Skip to content

Commit

Permalink
Update everything to the latest.
Browse files Browse the repository at this point in the history
BREAKING: now requires node 18.
BREAKING: now requires node's built-in fetch.
moved to latest @cto.af lint rules and fixed.
using beta nock to get native fetch support.
  • Loading branch information
hildjj committed Dec 11, 2024
1 parent e9ac56b commit 456cb70
Show file tree
Hide file tree
Showing 16 changed files with 2,752 additions and 1,747 deletions.
11 changes: 11 additions & 0 deletions .c8rc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"reporter": [
"text",
"lcov"
],
"exclude": [
"**/test/**",
"**/node_modules/**",
"ava.config.cjs"
]
}
17 changes: 0 additions & 17 deletions .eslintrc.js

This file was deleted.

32 changes: 8 additions & 24 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ name: Tests

on:
push:
branches:
- 'main'
branches: [main]
pull_request:
branches: [main]

Expand All @@ -13,39 +12,24 @@ jobs:

strategy:
matrix:
node-version: [16, 18, 20]
node-version: [18, 20, 22, 23]
platform: [ubuntu-latest]

runs-on: ${{ matrix.platform }}

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
submodules: true
- name: Install pnpm
uses: pnpm/[email protected]
with:
version: 7.14.0
run_install: true
- run: corepack enable
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'pnpm'
- name: Test ${{ matrix.node-version }}
run: npm run coverage
- name: Coveralls Parallel
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.github_token }}
flag-name: node-${{ matrix.node-version }}
parallel: true
finish:
needs: build
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/github-action@master
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
with:
github-token: ${{ secrets.github_token }}
parallel-finished: true
token: ${{ secrets.CODECOV_TOKEN }}
30 changes: 30 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Publish Package to npmjs
on:
release:
types: [published]
workflow_call:
secrets:
NPM_TOKEN:
required: true

jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- run: corepack enable
- uses: actions/setup-node@v4
with:
node-version: '22.x'
registry-url: 'https://registry.npmjs.org'
cache: pnpm
- run: pnpm i -r
- run: npm run test
- run: npm run lint
- run: npm pkg delete devDependencies scripts packageManager
- run: npm publish --access public --provenance
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
6 changes: 6 additions & 0 deletions .ncurc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"dep": ["prod", "dev", "packageManager"],
"reject": [
"rimraf"
]
}
8 changes: 4 additions & 4 deletions .ncurc.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'
'use strict';

module.exports = {
reject: [
"node-fetch"
]
}
'node-fetch',
],
};
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ Call the WebSequenceDiagram.com API.
Example:

```js
const wsd = require('websequencediagrams')
const fs = require('fs')

;(async() => {
const [buf, typ] = await wsd.diagram('Alice->Bob: message', 'modern-blue', 'png')
console.log('Received MIME type:', typ)
fs.writeFile('my.png', buf)
})()
const wsd = require('websequencediagrams');
const fs = require('node:fs');

(async() => {
const [buf, typ] = await wsd.diagram('Alice->Bob: message', 'modern-blue', 'png');
console.log('Received MIME type:', typ);
fs.writeFile('my.png', buf);
})();
```

### .diagram(text, style, output_type)
Expand Down
2 changes: 1 addition & 1 deletion bin/wsd_get
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const {argv} = yargs
alias: 'r',
desc: 'WebSequenceDiagrams root URL',
type: 'string',
default: 'https://websequencediagrams.com',
default: 'https://www.websequencediagrams.com',
},
key: {
alias: 'k',
Expand Down
7 changes: 7 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import base from '@cto.af/eslint-config';
import markdown from '@cto.af/eslint-config/markdown.js';

export default [
...base,
...markdown,
];
48 changes: 22 additions & 26 deletions lib/fileStream.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
'use strict'
'use strict';

const fs = require('fs')
const path = require('path')
const util = require('util')
const {Buffer} = require('buffer')
const stat = util.promisify(fs.stat)
const readdir = util.promisify(fs.readdir)
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const path = require('node:path');
const {Buffer} = require('node:buffer');

/**
* Promisified stream for a file. Can be replaced with fs.promises one day.
Expand All @@ -17,12 +15,12 @@ class FileStream {
* @param {string} [name='-'] File name, or '-' for stdin.
*/
constructor(name = '-') {
this.name = name
this.name = name;
if (name === '-') {
this.stream = process.stdin
process.stdin.resume()
this.stream = process.stdin;
process.stdin.resume();
} else {
this.stream = fs.createReadStream(name)
this.stream = fs.createReadStream(name);
}
}

Expand All @@ -33,13 +31,11 @@ class FileStream {
*/
read() {
return new Promise((resolve, reject) => {
const bufs = []
this.stream.on('error', er => {
reject(er)
})
this.stream.on('data', data => bufs.push(data))
this.stream.on('end', () => resolve(Buffer.concat(bufs)))
})
const bufs = [];
this.stream.on('error', reject);
this.stream.on('data', data => bufs.push(data));
this.stream.on('end', () => resolve(Buffer.concat(bufs)));
});
}

/**
Expand All @@ -53,19 +49,19 @@ class FileStream {
const streams = await Promise.all(names.map(async n => {
if (n === '-') {
// Prevent stat() throwing
return new FileStream()
return new FileStream();
}
const stats = await stat(n)
const stats = await fsp.stat(n);
if (stats.isDirectory()) {
const dir = await readdir(n)
const dir = await fsp.readdir(n);
return dir
.filter(f => f.endsWith('.wsd'))
.map(fn => new FileStream(path.join(n, fn)))
.map(fn => new FileStream(path.join(n, fn)));
}
return new FileStream(n)
}))
return streams.flat()
return new FileStream(n);
}));
return streams.flat();
}
}

module.exports = FileStream
module.exports = FileStream;
83 changes: 40 additions & 43 deletions lib/wsd.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict'
'use strict';

const fetch = require('node-fetch')
const {Buffer} = require('buffer')
const {Buffer} = require('node:buffer');
const {version} = require('../package.json');

const defaultRoot = 'http://www.websequencediagrams.com'
const defaultRoot = 'https://www.websequencediagrams.com';
const styles = [
'default',
'earth',
Expand All @@ -17,7 +17,7 @@ const styles = [
'magazine',
'vs2010',
'patent',
]
];

/**
* API for WebSequenceDiagrams.
Expand All @@ -37,56 +37,52 @@ class WSD {
* formats include: 'png', 'svg', or 'pdf'. 'pdf' requires a paid
* account.
* @param {string} [apikey] API key for non-free usage.
* @param {string} [root='http://www.websequencediagrams.com'] Root URL for
* @param {string} [root='https://www.websequencediagrams.com'] Root URL for
* the service.
* @returns {Promise<string>} The URL for the diagram.
*/
// eslint-disable-next-line max-params
static async diagramURL(
message, style = 'default',
message,
style = 'default',
format = 'png',
apikey = null,
root = defaultRoot
) {
if (message instanceof Buffer) {
message = message.toString('utf8')
}
const msg = Buffer.isBuffer(message) ? message.toString('utf8') : message;
if (WSD.styles.indexOf(style) === -1) {
throw new Error(`Unknown style: ${style}`)
throw new Error(`Unknown style: ${style}`);
}
if (['png', 'pdf', 'svg'].indexOf(format) === -1) {
throw new Error(`Unknown format: ${format}`)
throw new Error(`Unknown format: ${format}`);
}

const query = new URLSearchParams(apikey ?
{
apiVersion: '1',
message,
style,
format,
apikey,
} :
{
apiVersion: '1',
message,
style,
format,
})
const res = await fetch(`${root}/index.php`, {
const query = new URLSearchParams({
apiVersion: '1',
message: msg,
style,
format,
...(apikey ? {apikey} : {}),
});

const u = new URL('index.php', root);
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const res = await fetch(u, {
method: 'POST',
body: query,
})
redirect: 'error',
headers: {
'user-agent': `node-websequencediagrams/${version}`,
},
});
if (res.status !== 200) {
throw new Error(`HTTP Error: ${res.status}`)
}
const jres = await res.json()
if (!jres.errors) {
throw new Error(`Invalid JSON response: ${jres}`)
throw new Error(`${res.status} ${res.statusText}: ${res.headers.get('status')}`);
}
if (jres.errors.length > 0) {
throw new Error(jres.errors.join(', '))
const jres = await res.json();
if (jres.errors?.length > 0) {
throw new Error(jres.errors.join(', '));
}
return `${root}/${jres.img}`
return new URL(jres.img, root).toString();
}

/**
Expand All @@ -107,13 +103,14 @@ class WSD {
*/
// eslint-disable-next-line max-params
static async diagram(description, style, format, apikey, root) {
const u = await WSD.diagramURL(description, style, format, apikey, root)
const res = await fetch(u)
const ct = res.headers.get('content-type')
const buf = await res.buffer()
return [buf, ct]
const u = await WSD.diagramURL(description, style, format, apikey, root);
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const res = await fetch(u);
const ct = res.headers.get('content-type');
const buf = await res.arrayBuffer();
return [Buffer.from(buf), ct];
}
}
WSD.styles = styles
WSD.styles = styles;

module.exports = WSD
module.exports = WSD;
Loading

0 comments on commit 456cb70

Please sign in to comment.