new changes

This commit is contained in:
Niranjan
2026-04-07 05:05:28 +05:30
parent 7c070224bd
commit a18bba15f2
29975 changed files with 3247495 additions and 2761 deletions

View File

@@ -0,0 +1,193 @@
## [15.0.1](https://github.com/nfroidure/svgicons2svgfont/compare/v15.0.0...v15.0.1) (2025-02-26)
### Bug Fixes
* replace deprecated transformation-matrix-js ([118572c](https://github.com/nfroidure/svgicons2svgfont/commit/118572c009f3e3e06da5eea0dac48e3cc296913b))
# [15.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v14.0.2...v15.0.0) (2024-11-07)
### Bug Fixes
* **tests:** fix results folder creation ([6fcbc1e](https://github.com/nfroidure/svgicons2svgfont/commit/6fcbc1e9c7cf157e783527a1861c762733b3cfbb))
### Code Refactoring
* **cli:** uniformize CLI args style ([04e54a8](https://github.com/nfroidure/svgicons2svgfont/commit/04e54a8824d83575c7d4d17537e31c7c7425f83f)), closes [#167](https://github.com/nfroidure/svgicons2svgfont/issues/167)
### BREAKING CHANGES
* **cli:** CLI usages will need an update
## [14.0.2](https://github.com/nfroidure/svgicons2svgfont/compare/v14.0.1...v14.0.2) (2024-09-08)
### Bug Fixes
* fix circles convertion when no cx/cy ([13d9caf](https://github.com/nfroidure/svgicons2svgfont/commit/13d9caf999242490289c2ef0c22780120cdc030b)), closes [#162](https://github.com/nfroidure/svgicons2svgfont/issues/162)
## [14.0.1](https://github.com/nfroidure/svgicons2svgfont/compare/v14.0.0...v14.0.1) (2024-08-01)
### Bug Fixes
* **bin:** fix script mod eoutput to avoid logging unecessary data ([2ef67d3](https://github.com/nfroidure/svgicons2svgfont/commit/2ef67d320ef31e01d4ad4eab996adf9eb1386358))
# [14.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v13.0.0...v14.0.0) (2024-07-30)
# [13.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v12.0.0...v13.0.0) (2024-07-30)
### Bug Fixes
* **tests:** fix ci tests ([9c4152f](https://github.com/nfroidure/svgicons2svgfont/commit/9c4152f42c465db06841fd46ba02c55d4c2d6cdc))
### Code Refactoring
* **core:** complete rewrite with Typescript and modern node APIs ([e84a5ce](https://github.com/nfroidure/svgicons2svgfont/commit/e84a5ceca5c3b73662d986ffbfcadabbe8b766d8)), closes [#169](https://github.com/nfroidure/svgicons2svgfont/issues/169) [#129](https://github.com/nfroidure/svgicons2svgfont/issues/129) [#91](https://github.com/nfroidure/svgicons2svgfont/issues/91)
### BREAKING CHANGES
* **core:** Requires Node 20.11+ and ESM
# [12.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v11.0.0...v12.0.0) (2022-05-28)
# [11.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.6...v11.0.0) (2022-05-28)
### Bug Fixes
* **core:** fix the metapak setup ([66a6274](https://github.com/nfroidure/svgicons2svgfont/commit/66a6274d2917979298a96fc7597ceb68d1689b83))
* **deps:** remove unused dependencies, move devDependencies where they belong to ([ecc3d87](https://github.com/nfroidure/svgicons2svgfont/commit/ecc3d8736df9d7dbb4116475c8bc1b062bd70565))
<a name="10.0.6"></a>
# [10.0.6](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.5...v10.0.6) (2022-03-12)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.6
<a name="10.0.5"></a>
# [10.0.5](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.4...v10.0.5) (2021-09-10)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.5
<a name="10.0.4"></a>
# [10.0.4](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.4...v10.0.4) (2021-06-02)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.4
<a name="10.0.3"></a>
# [10.0.3](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.2...v10.0.3) (2021-06-02)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.3
<a name="10.0.2"></a>
# [10.0.2](https://github.com/nfroidure/svgicons2svgfont/compare/v10.0.1...v10.0.2) (2021-05-20)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.2
<a name="10.0.1"></a>
# [10.0.1](https://github.com/nfroidure/svgicons2svgfont/compare/v9.2.0...v10.0.1) (2021-05-13)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.1
<a name="10.0.0"></a>
# [10.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v9.2.0...v10.0.0) (2021-05-12)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v10.0.0
<a name="9.2.0"></a>
# [9.2.0](https://github.com/nfroidure/svgicons2svgfont/compare/v9.1.0...v9.2.0) (2021-04-24)
https://github.com/nfroidure/svgicons2svgfont/releases/tag/v9.2.0
<a name="9.1.0"></a>
# [9.1.0](https://github.com/nfroidure/svgicons2svgfont/compare/v9.0.3...v9.1.0) (2019-06-01)
### Bug Fixes
* NaN in d attribute when shape has rx, but ry attribute doesn't present ([72c5520](https://github.com/nfroidure/svgicons2svgfont/commit/72c5520))
### Features
* Add options.metadataProvider option + API doc ([3343d33](https://github.com/nfroidure/svgicons2svgfont/commit/3343d33))
<a name="9.0.3"></a>
## [9.0.3](https://github.com/nfroidure/svgicons2svgfont/compare/v9.0.2...v9.0.3) (2018-06-02)
<a name="9.0.2"></a>
## [9.0.2](https://github.com/nfroidure/svgicons2svgfont/compare/v9.0.1...v9.0.2) (2018-02-26)
<a name="9.0.1"></a>
## [9.0.1](https://github.com/nfroidure/svgicons2svgfont/compare/v9.0.0...v9.0.1) (2018-02-26)
<a name="9.0.0"></a>
# [9.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v8.0.0...v9.0.0) (2018-02-15)
<a name="8.0.0"></a>
# [8.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v7.0.0...v8.0.0) (2017-12-03)
<a name="7.0.2"></a>
## [7.0.2](https://github.com/nfroidure/svgicons2svgfont/compare/v7.0.0...v7.0.2) (2017-09-22)
<a name="7.0.1"></a>
## [7.0.1](https://github.com/nfroidure/svgicons2svgfont/compare/v7.0.0...v7.0.1) (2017-08-24)
<a name="7.0.0"></a>
# [7.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v6.0.0...v7.0.0) (2017-08-24)
<a name="6.1.0"></a>
# [6.1.0](https://github.com/nfroidure/svgicons2svgfont/compare/v6.0.0...v6.1.0) (2017-08-22)
<a name="6.0.0"></a>
# [6.0.0](https://github.com/nfroidure/svgicons2svgfont/compare/v5.0.2...v6.0.0) (2017-07-15)
### Bug Fixes
* **ScaledIcons:** Icons using a scaled viewbow weren't rendering as expected ([44e3dd6](https://github.com/nfroidure/svgicons2svgfont/commit/44e3dd6)), closes [#73](https://github.com/nfroidure/svgicons2svgfont/issues/73)

View File

@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright © 2017 Nicolas Froidure
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,300 @@
[//]: # ( )
[//]: # (This file is automatically generated by a `metapak`)
[//]: # (module. Do not change it except between the)
[//]: # (`content:start/end` flags, your changes would)
[//]: # (be overridden.)
[//]: # ( )
# svgicons2svgfont
> Read a set of SVG icons and output a SVG font
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/nfroidure/svgicons2svgfont/blob/main/LICENSE)
[//]: # (::contents:start)
`svgicons2svgfont` is a simple tool to merge multiple icons to an SVG font.
'rect', 'line', 'circle', 'ellipsis', 'polyline' and 'polygon' shapes will be
converted to pathes. Multiple pathes will be merged.
Transform attributes support is currenly experimental,
[report issues if any](https://github.com/nfroidure/svgicons2svgfont/issues/6).
You can test this library with the
[frontend generator](http://nfroidure.github.io/svgiconfont/).
You may want to convert fonts to icons, if so use
[svgfont2svgicons](https://github.com/nfroidure/svgfont2svgicons).
## Usage
### In your scripts
```js
import { SVGIcons2SVGFontStream } from 'svgicons2svgfont';
import { createReadStream, createWriteStream } from 'node:fs';
const fontStream = new SVGIcons2SVGFontStream({
fontName: 'hello',
});
// Setting the font destination
fontStream
.pipe(createWriteStream('fonts/hello.svg'))
.on('finish', function () {
console.log('Font successfully created!');
})
.on('error', function (err) {
console.log(err);
});
// Writing glyphs
const glyph1 = createReadStream('icons/icon1.svg');
glyph1.metadata = {
unicode: ['\uE001\uE002'],
name: 'icon1',
};
fontStream.write(glyph1);
// Multiple unicode values are possible
const glyph2 = createReadStream('icons/icon1.svg');
glyph2.metadata = {
unicode: ['\uE002', '\uEA02'],
name: 'icon2',
};
fontStream.write(glyph2);
// Either ligatures are available
const glyph3 = createReadStream('icons/icon1.svg');
glyph3.metadata = {
unicode: ['\uE001\uE002'],
name: 'icon1-icon2',
};
fontStream.write(glyph3);
// Do not forget to end the stream
fontStream.end();
```
## Debugging
To debug, simply use the following env var: `DEBUG=svgicons2svgfont`.
## CLI interface
All options are available except the `log` one by using this pattern:
`--{LOWER_CASE(optionName)}={optionValue}`.
```sh
svgicons2svgfont --fontName=hello -o font/destination/file.svg icons/directory/*.svg
```
Note that you won't be able to customize icon names or icons unicodes by passing
options but by using the following convention to name your icons files:
`${icon.unicode}-${icon.name}.svg` where `icon.unicode` is a comma separated
list of unicode strings (ex: 'uEA01,uE001,uE001uE002', note that the last string
is in fact a ligature).
There is a few more options for the CLI interface, you can list all of them:
```sh
npx svgicons2svgfont --help
```
Gives:
```txt
Usage: svgicons2svgfont [options] <icons ...>
Options:
-V, --version output the version number
-v, --verbose tell me everything!
-o, --output [/dev/stdout] file to write output to
-f, --fontName [value] the font family name you want [iconfont]
-i, --fontId [value] the font id you want [fontName]
-st, --style [value] the font style you want
-we, --weight [value] the font weight you want
-w, --fixedWidth creates a monospace font of the width of the largest input icon
-c, --centerHorizontally calculate the bounds of a glyph and center it horizontally
-y, --centerVertically centers the glyphs vertically in the generated font.
-n, --normalize normalize icons by scaling them to the height of the highest icon
-p, --preserveAspectRatio used with normalize to scale down glyph if the SVG width is greater than the height
-h, --height [value] the output font height [MAX(icons.height)] (icons will be scaled so the highest has
this height)
-r, --round [value] setup the SVG path rounding [10e12]
-d, --descent [value] the font descent [0]
-a, --ascent [value] the font ascent [height - descent]
-s, --startUnicode [value] the start unicode code point for unprefixed files [0xEA01]
-u, --prependUnicode prefix files with their automatically allocated unicode code point
-m, --metadata content of the metadata tag
--help display help for command
```
## API
### new SVGIcons2SVGFontStream(options)
#### options.fontName
Type: `String` Default value: `'iconfont'`
The font family name you want.
#### options.fontId
Type: `String` Default value: the options.fontName value
The font id you want.
#### options.fontStyle
Type: `String` Default value: `''`
The font style you want.
#### options.fontWeight
Type: `String` Default value: `''`
The font weight you want.
#### options.fixedWidth
Type: `Boolean` Default value: `false`
Creates a monospace font of the width of the largest input icon.
#### options.centerHorizontally
Type: `Boolean` Default value: `false`
Calculate the bounds of a glyph and center it horizontally.
#### options.centerVertically
Type: `Boolean` Default value: `false`
Centers the glyphs vertically in the generated font.
#### options.normalize
Type: `Boolean` Default value: `false`
Normalize icons by scaling them to the height of the highest icon.
#### options.preserveAspectRatio
Type: `Boolean` Default value: `false`
Used with normalize to scale down glyph if the SVG width is greater than the
height.
#### options.fontHeight
Type: `Number` Default value: `MAX(icons.height)` The outputted font height
(defaults to the height of the highest input icon).
#### options.round
Type: `Number` Default value: `10e12` Setup SVG path rounding.
#### options.descent
Type: `Number` Default value: `0`
The font descent. It is usefull to fix the font baseline yourself.
**Warning:** The descent is a positive value!
#### options.ascent
Type: `Number` Default value: `fontHeight - descent`
The font ascent. Use this options only if you know what you're doing. A suitable
value for this is computed for you.
#### options.metadata
Type: `String` Default value: `undefined`
The font [metadata](http://www.w3.org/TR/SVG/metadata.html). You can set any
character data in but it is the be suited place for a copyright mention.
#### options.metadataProvider
Type:
`(file: string, cb: (err: any, metadata: {file: string, name: string, unicode: string[], renamed: boolean}) => void`
Default value: `require('svgicons2svgfont/src/metadata')(options)`
A function which determines the metadata for an icon. It takes a parameter
`file` with an icon svg and should return icon metadata (asynchronously) via the
callback function. You can use this function to provide custom logic for svg to
codepoint mapping.
| | |
| ------------------ | ---------------------------------------------------------------------------------------- |
| `metadata.path` | The path to the icon file. (The original `file` param is the file was not moved.) |
| `metadata.name` | The name of the icon |
| `metadata.unicode` | The unicode codepoints corresponding to this glyph. Each should be a 1-codepoint string. |
| `metadata.renamed` | Wether the original file was moved (e.g. to prefix it with its unicode codepoint) |
#### options.log
Type: `Function` Default value: `console.log`
Allows you to provide your own logging function. Set to `function(){}` to
disable logging.
## Build systems
### Grunt plugins
[grunt-svgicons2svgfont](https://github.com/nfroidure/grunt-svgicons2svgfont)
and [grunt-webfont](https://github.com/sapegin/grunt-webfont).
### Gulp plugins
Try [gulp-iconfont](https://github.com/nfroidure/gulp-iconfont) and
[gulp-svgicons2svgfont](https://github.com/nfroidure/gulp-svgicons2svgfont).
### Stylus plugin
Use [stylus-iconfont](https://www.npmjs.org/package/stylus-iconfont).
### Mimosa plugin
Use
[mimosa-svgs-to-iconfonts](https://www.npmjs.org/package/mimosa-svgs-to-iconfonts).
## CLI alternatives
You can combine this plugin's CLI interface with
[svg2ttf](https://www.npmjs.com/package/svg2ttf),
[ttf2eot](https://www.npmjs.com/package/ttf2eot),
[ttf2woff](https://www.npmjs.com/package/ttf2woff) and
[ttf2woff2](https://www.npmjs.com/package/ttf2woff2). You can also use
[webfonts-generator](https://www.npmjs.com/package/webfonts-generator).
## Stats
[![NPM](https://nodei.co/npm/svgicons2svgfont.png?downloads=true&stars=true)](https://nodei.co/npm/svgicons2svgfont/)
[![NPM](https://nodei.co/npm-dl/svgicons2svgfont.png)](https://nodei.co/npm/svgicons2svgfont/)
## Contributing
Feel free to push your code if you agree with publishing under the MIT license.
# License
[MIT](https://github.com/nfroidure/svgicons2svgfont/blob/master/LICENSE)
[//]: # (::contents:end)
# Authors
- [Nicolas Froidure](http://insertafter.com/en/index.html)
- [Adrian Leonhard](https://github.com/NaridaL)
- [Vinicius Teixeira](https://github.com/vinicius0026)
# License
[MIT](https://github.com/nfroidure/svgicons2svgfont/blob/main/LICENSE)

View File

@@ -0,0 +1,102 @@
#! /usr/bin/env node
import { program } from 'commander';
import { createWriteStream } from 'node:fs';
import { join } from 'node:path';
import { argv, exit, stdout } from 'node:process';
import { error } from 'node:console';
import { readFile } from 'node:fs/promises';
import { glob } from 'glob';
import { SVGIcons2SVGFontStream } from '../dist/index.js';
import { SVGIconsDirStream } from '../dist/iconsdir.js';
const { version } = JSON.parse((await readFile(join(import.meta.dirname, '..', 'package.json'))).toString());
program
.storeOptionsAsProperties(true)
.version(version)
.usage('[options] <icons ...>')
.option('-v, --verbose', 'tell me everything!')
.option('-o, --output [/dev/stdout]', 'file to write output to')
.option('-f, --fontName [value]', 'the font family name you want [iconfont]')
.option('-i, --fontId [value]', 'the font id you want [fontName]')
.option('-st, --style [value]', 'the font style you want')
.option('-we, --weight [value]', 'the font weight you want')
.option(
'-w, --fixedWidth',
'creates a monospace font of the width of the largest input icon'
)
.option(
'-c, --centerHorizontally',
'calculate the bounds of a glyph and center it horizontally'
)
.option(
'-y, --centerVertically',
'centers the glyphs vertically in the generated font.'
)
.option(
'-n, --normalize',
'normalize icons by scaling them to the height of the highest icon'
)
.option(
'-p, --preserveAspectRatio',
'used with normalize to scale down glyph if the SVG width is greater than the height'
)
.option(
'-h, --height [value]',
'the output font height [MAX(icons.height)] (icons will be scaled so the highest has this height)',
parseInt
)
.option(
'-r, --round [value]',
'setup the SVG path rounding [10e12]',
parseFloat
)
.option('-d, --descent [value]', 'the font descent [0]', parseInt)
.option(
'-a, --ascent [value]',
'the font ascent [height - descent]',
parseInt
)
.option(
'-s, --startUnicode [value]',
'the start unicode code point for' + ' unprefixed files [0xEA01]',
parseInt
)
.option(
'-u, --prependUnicode',
'prefix files with their automatically' + ' allocated unicode code point',
parseInt
)
.option('-m, --metadata', 'content of the metadata tag')
.parse(argv);
if (!program.args.length) {
error('No icons specified!');
exit(1);
}
const files = program.args.flatMap((file) => glob.sync(file));
const options = program.opts();
new SVGIconsDirStream(files, {
startUnicode: options.startUnicode,
prependUnicode: options.prependUnicode,
})
.pipe(
new SVGIcons2SVGFontStream({
fontName: options.fontName,
fontId: options.fontId,
fixedWidth: options.fixedwidth,
centerHorizontally: options.centerHorizontally,
centerVertically: options.centerVertically,
normalize: options.normalize,
preserveAspectRatio: options.preserveAspectRatio,
fontHeight: options.height,
round: options.round,
descent: options.descent,
ascent: options.ascent,
metadata: options.metadata,
})
)
.pipe(options.output ? createWriteStream(options.output) : stdout);

View File

@@ -0,0 +1 @@
export declare function fileSorter(fileA: any, fileB: any): number;

View File

@@ -0,0 +1,16 @@
const testExpression = /(^|\/|\\)(?:((?:u[0-9a-f]{4,6},?)+)-)(.+)\.svg$/i;
export function fileSorter(fileA, fileB) {
const hasUnicodeA = testExpression.test(fileA);
const hasUnicodeB = testExpression.test(fileB);
if (hasUnicodeA == hasUnicodeB) {
// just compare alphabetically
const fileA_ = fileA.substr(0, fileA.lastIndexOf('.'));
const fileB_ = fileB.substr(0, fileB.lastIndexOf('.'));
return fileA_ < fileB_ ? -1 : 1;
}
else {
// map true to 0, because we want it to be first
return (hasUnicodeA ? 0 : 1) - (hasUnicodeB ? 0 : 1);
}
}
//# sourceMappingURL=filesorter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"filesorter.js","sourceRoot":"","sources":["../src/filesorter.ts"],"names":[],"mappings":"AAAA,MAAM,cAAc,GAAG,kDAAkD,CAAC;AAE1E,MAAM,UAAU,UAAU,CAAC,KAAK,EAAE,KAAK;IACrC,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/C,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAE/C,IAAI,WAAW,IAAI,WAAW,EAAE,CAAC;QAC/B,8BAA8B;QAC9B,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;QACvD,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;QACvD,OAAO,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClC,CAAC;SAAM,CAAC;QACN,gDAAgD;QAChD,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,CAAC;AACH,CAAC"}

View File

@@ -0,0 +1,19 @@
import { Readable } from 'node:stream';
import { getMetadataService, FileMetadata, MetadataServiceOptions } from './metadata.js';
export type SVGIconsDirStreamOptions = {
metadataProvider: ReturnType<typeof getMetadataService>;
};
export type SVGIconStream = Readable & {
metadata: Pick<FileMetadata, 'name' | 'unicode'>;
};
declare class SVGIconsDirStream extends Readable {
private _options;
gotFilesInfos: boolean;
fileInfos: FileMetadata[];
dir: string;
constructor(dir: string[], options: Partial<SVGIconsDirStreamOptions & MetadataServiceOptions>);
_getFilesInfos(files: any): void;
_pushSVGIcons(): void;
_read(): void;
}
export { SVGIconsDirStream };

View File

@@ -0,0 +1,93 @@
import { Readable } from 'node:stream';
import { createReadStream, readdir } from 'node:fs';
import { fileSorter } from './filesorter.js';
import { getMetadataService, } from './metadata.js';
import debug from 'debug';
const warn = debug('svgicons2svgfont');
class SVGIconsDirStream extends Readable {
_options;
gotFilesInfos = false;
fileInfos = [];
dir;
constructor(dir, options) {
super({ objectMode: true });
this._options = {
metadataProvider: options.metadataProvider || getMetadataService(options),
};
if (dir instanceof Array) {
this.dir = '';
this._getFilesInfos(dir);
}
else {
this.dir = dir;
}
}
_getFilesInfos(files) {
let filesProcessed = 0;
this.fileInfos = [];
// Ensure prefixed files come first
files = files.slice(0).sort(fileSorter);
files.forEach((file) => {
this._options.metadataProvider((this.dir ? this.dir + '/' : '') + file, (err, metadata) => {
filesProcessed++;
if (err) {
this.emit('error', err);
}
if (metadata) {
if (metadata.renamed) {
warn(' - Saved codepoint: ' +
'u' +
metadata.unicode[0]
.codePointAt(0)
?.toString(16)
.toUpperCase() +
' for the glyph "' +
metadata.name +
'"');
}
this.fileInfos.push(metadata);
}
if (files.length === filesProcessed) {
// Reorder files
this.fileInfos.sort((infosA, infosB) => infosA.unicode[0] > infosB.unicode[0] ? 1 : -1);
// Mark directory as processed
this.gotFilesInfos = true;
// Start processing
this._pushSVGIcons();
}
});
});
}
_pushSVGIcons() {
let fileInfo;
let svgIconStream;
while (this.fileInfos.length) {
fileInfo = this.fileInfos.shift();
svgIconStream = createReadStream(fileInfo.path);
svgIconStream.metadata = {
name: fileInfo.name,
unicode: fileInfo.unicode,
};
if (!this.push(svgIconStream)) {
return;
}
}
this.push(null);
}
_read() {
if (this.dir) {
readdir(this.dir, (err, files) => {
if (err) {
this.emit('error', err);
}
this._getFilesInfos(files);
});
return;
}
if (this.gotFilesInfos) {
this._pushSVGIcons();
}
}
}
export { SVGIconsDirStream };
//# sourceMappingURL=iconsdir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"iconsdir.js","sourceRoot":"","sources":["../src/iconsdir.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,39 @@
import { Transform } from 'stream';
import { SVGPathData } from 'svg-pathdata';
export { fileSorter } from './filesorter.js';
export * from './iconsdir.js';
export * from './metadata.js';
export type SVGIcons2SVGFontStreamOptions = {
fontName: string;
fontId: string;
fixedWidth: boolean;
descent: number;
ascent?: number;
round: number;
metadata: string;
usePathBounds: boolean;
normalize?: boolean;
preserveAspectRatio?: boolean;
centerHorizontally?: boolean;
centerVertically?: boolean;
fontWeight?: number;
fontHeight?: number;
fontStyle?: string;
callback?: (glyphs: Glyph[]) => void;
};
export type Glyph = {
name: string;
width: number;
height: number;
defaultHeight?: number;
defaultWidth?: number;
unicode: string[];
paths?: SVGPathData[];
};
export declare class SVGIcons2SVGFontStream extends Transform {
private _options;
glyphs: Glyph[];
constructor(options: Partial<SVGIcons2SVGFontStreamOptions>);
_transform(svgIconStream: any, _unused: any, svgIconStreamCallback: any): void;
_flush(svgFontFlushCallback: any): void;
}

View File

@@ -0,0 +1,379 @@
import { Transform } from 'stream';
import Sax from 'sax';
import { SVGPathData } from 'svg-pathdata';
import svgShapesToPath from './svgshapes2svgpath.js';
import { scale, translate, compose, fromDefinition, fromTransformAttribute, } from 'transformation-matrix';
import { YError } from 'yerror';
import debug from 'debug';
const warn = debug('svgicons2svgfont');
export { fileSorter } from './filesorter.js';
export * from './iconsdir.js';
export * from './metadata.js';
function matrixFromTransformAttribute(transformAttributeString) {
return compose(fromDefinition(fromTransformAttribute(transformAttributeString)));
}
// Rendering
function tagShouldRender(curTag, parents) {
let values;
return !parents.some((tag) => {
if ('undefined' !== typeof tag.attributes.display &&
'none' === tag.attributes.display.toLowerCase()) {
return true;
}
if ('undefined' !== typeof tag.attributes.width &&
0 === parseFloat(tag.attributes.width)) {
return true;
}
if ('undefined' !== typeof tag.attributes.height &&
0 === parseFloat(tag.attributes.height)) {
return true;
}
if ('undefined' !== typeof tag.attributes.viewBox) {
values = tag.attributes.viewBox.split(/\s*,*\s|\s,*\s*|,/);
if (0 === parseFloat(values[2]) || 0 === parseFloat(values[3])) {
return true;
}
}
return false;
});
}
// According to the document (http://www.w3.org/TR/SVG/painting.html#FillProperties)
// fill <paint> none|currentColor|inherit|<color>
// [<icccolor>]|<funciri> (not support yet)
function getTagColor(currTag, parents) {
const defaultColor = 'black';
const fillVal = currTag.attributes.fill;
let color;
const parentsLength = parents.length;
if ('none' === fillVal) {
return color;
}
if ('currentColor' === fillVal) {
return defaultColor;
}
if ('inherit' === fillVal) {
if (0 === parentsLength) {
return defaultColor;
}
return getTagColor(parents[parentsLength - 1], parents.slice(0, parentsLength - 1));
// this might be null.
// For example: <svg ><path fill="inherit" /> </svg>
// in this case getTagColor should return null
// recursive call, the bottom element should be svg,
// and svg didn't fill color, so just return null
}
return fillVal;
}
export class SVGIcons2SVGFontStream extends Transform {
_options;
glyphs;
constructor(options) {
super({ objectMode: true });
this.glyphs = [];
this._options = {
...options,
fontName: options.fontName || 'iconfont',
fontId: options.fontId || options.fontName || 'iconfont',
fixedWidth: options.fixedWidth || false,
descent: options.descent || 0,
round: options.round || 10e12,
metadata: options.metadata || '',
usePathBounds: options.usePathBounds || false,
};
}
_transform(svgIconStream, _unused, svgIconStreamCallback) {
// Parsing each icons asynchronously
const saxStream = Sax.createStream(true);
const parents = [];
const transformStack = [];
function applyTransform(d) {
const last = transformStack[transformStack.length - 1];
if (!last)
return new SVGPathData(d);
return new SVGPathData(d).matrix(last.a, last.b, last.c, last.d, last.e, last.f);
}
const glyph = svgIconStream.metadata || {};
// init width and height os they aren't undefined if <svg> isn't renderable
glyph.width = 0;
glyph.height = 1;
glyph.paths = [];
this.glyphs.push(glyph);
if ('string' !== typeof glyph.name) {
this.emit('error', new Error(`Please provide a name for the glyph at index ${this.glyphs.length - 1}`));
}
if (this.glyphs.some((anotherGlyph) => anotherGlyph !== glyph && anotherGlyph.name === glyph.name)) {
this.emit('error', new Error(`The glyph name "${glyph.name}" must be unique.`));
}
if (glyph.unicode &&
glyph.unicode instanceof Array &&
glyph.unicode.length) {
if (glyph.unicode.some((unicodeA, i) => glyph.unicode.some((unicodeB, j) => i !== j && unicodeA === unicodeB))) {
this.emit('error', new Error(`Given codepoints for the glyph "${glyph.name}" contain duplicates.`));
}
}
else if ('string' !== typeof glyph.unicode) {
this.emit('error', new Error(`Please provide a codepoint for the glyph "${glyph.name}"`));
}
if (this.glyphs.some((anotherGlyph) => anotherGlyph !== glyph && anotherGlyph.unicode === glyph.unicode)) {
this.emit('error', new Error(`The glyph "${glyph.name}" codepoint seems to be used already elsewhere.`));
}
saxStream.on('opentag', (tag) => {
let values;
let color;
parents.push(tag);
try {
const currentTransform = transformStack[transformStack.length - 1];
if ('undefined' !== typeof tag.attributes.transform) {
const transform = matrixFromTransformAttribute(tag.attributes.transform);
transformStack.push(compose([currentTransform, transform].filter(Boolean)));
}
else {
transformStack.push(currentTransform);
}
// Checking if any parent rendering is disabled and exit if so
if (!tagShouldRender(tag, parents)) {
return;
}
// Save the view size
if ('svg' === tag.name) {
if ('viewBox' in tag.attributes) {
values = tag.attributes.viewBox.split(/\s*,*\s|\s,*\s*|,/);
const dX = parseFloat(values[0]);
const dY = parseFloat(values[1]);
const width = parseFloat(values[2]);
const height = parseFloat(values[3]);
// use the viewBox width/height if not specified explictly
glyph.width =
'width' in tag.attributes
? parseFloat(tag.attributes.width)
: width;
glyph.height =
'height' in tag.attributes
? parseFloat(tag.attributes.height)
: height;
transformStack[transformStack.length - 1] = compose([
transformStack[transformStack.length - 1],
translate(-dX, -dY),
scale(glyph.width / width, glyph.height / height),
].filter(Boolean));
}
else {
if ('width' in tag.attributes) {
glyph.width = parseFloat(tag.attributes.width);
}
else {
warn(`⚠️ - Glyph "${glyph.name}" has no width attribute, using current glyph horizontal bounds.`);
glyph.defaultWidth = true;
}
if ('height' in tag.attributes) {
glyph.height = parseFloat(tag.attributes.height);
}
else {
warn(`⚠️ - Glyph "${glyph.name}" has no height attribute, using current glyph vertical bounds.`);
glyph.defaultHeight = true;
}
}
}
else if ('clipPath' === tag.name) {
// Clipping path unsupported
warn(`🤷 - Found a clipPath element in the icon "${glyph.name}" the result may be different than expected.`);
}
else if ('rect' === tag.name && 'none' !== tag.attributes.fill) {
glyph.paths.push(applyTransform(svgShapesToPath.rectToPath(tag.attributes)));
}
else if ('line' === tag.name && 'none' !== tag.attributes.fill) {
warn(`🤷 - Found a line element in the icon "${glyph.name}" the result could be different than expected.`);
glyph.paths.push(applyTransform(svgShapesToPath.lineToPath(tag.attributes)));
}
else if ('polyline' === tag.name && 'none' !== tag.attributes.fill) {
warn(`🤷 - Found a polyline element in the icon "${glyph.name}" the result could be different than expected.`);
glyph.paths.push(applyTransform(svgShapesToPath.polylineToPath(tag.attributes)));
}
else if ('polygon' === tag.name && 'none' !== tag.attributes.fill) {
glyph.paths.push(applyTransform(svgShapesToPath.polygonToPath(tag.attributes)));
}
else if (['circle', 'ellipse'].includes(tag.name) &&
'none' !== tag.attributes.fill) {
glyph.paths.push(applyTransform(svgShapesToPath.circleToPath(tag.attributes)));
}
else if ('path' === tag.name &&
tag.attributes.d &&
'none' !== tag.attributes.fill) {
glyph.paths.push(applyTransform(tag.attributes.d));
}
// According to http://www.w3.org/TR/SVG/painting.html#SpecifyingPaint
// Map attribute fill to color property
if ('none' !== tag.attributes.fill) {
color = getTagColor(tag, parents);
if ('undefined' !== typeof color) {
glyph.color = color;
}
}
}
catch (err) {
this.emit('error', new Error(`Got an error parsing the glyph "${glyph.name}": ${err?.message}.`));
}
});
saxStream.on('error', (err) => {
this.emit('error', err);
});
saxStream.on('closetag', () => {
transformStack.pop();
parents.pop();
});
saxStream.on('end', () => {
svgIconStreamCallback();
});
svgIconStream.pipe(saxStream);
}
_flush(svgFontFlushCallback) {
this.glyphs.forEach((glyph) => {
if (glyph.defaultHeight ||
glyph.defaultWidth ||
this._options.usePathBounds) {
const glyphPath = new SVGPathData('');
(glyph.paths || []).forEach((path) => {
glyphPath.commands.push(...path.commands);
});
const bounds = glyphPath.getBounds();
if (glyph.defaultHeight || this._options.usePathBounds) {
glyph.height = bounds.maxY - bounds.minY;
}
if (glyph.defaultWidth || this._options.usePathBounds) {
glyph.width = bounds.maxX - bounds.minX;
}
}
});
const maxGlyphHeight = this.glyphs.reduce((curMax, glyph) => Math.max(curMax, glyph.height), 0);
const maxGlyphWidth = this.glyphs.reduce((curMax, glyph) => Math.max(curMax, glyph.width), 0);
const fontHeight = this._options.fontHeight || maxGlyphHeight;
let fontWidth = maxGlyphWidth;
if (this._options.normalize) {
fontWidth = this.glyphs.reduce((curMax, glyph) => Math.max(curMax, (fontHeight / glyph.height) * glyph.width), 0);
}
else if (this._options.fontHeight) {
// even if normalize is off, we need to scale the fontWidth if we have a custom fontHeight
fontWidth *= fontHeight / maxGlyphHeight;
}
this._options.ascent =
'undefined' !== typeof this._options.ascent
? this._options.ascent
: fontHeight - this._options.descent;
if (!this._options.normalize &&
fontHeight >
(1 < this.glyphs.length
? this.glyphs.reduce((curMin, glyph) => Math.min(curMin, glyph.height), Infinity)
: this.glyphs[0].height)) {
warn('🤷 - The provided icons do not have the same heights. This could lead' +
' to unexpected results. Using the normalize option may help.');
}
if (1000 > fontHeight) {
warn('🤷 - A fontHeight of at least than 1000 is recommended, otherwise ' +
'further steps (rounding in svg2ttf) could lead to ugly results.' +
' Use the fontHeight option to scale icons.');
}
// Output the SVG file
// (find a SAX parser that allows modifying SVG on the fly)
this.push('<?xml version="1.0" standalone="no"?>\n' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >\n' +
'<svg xmlns="http://www.w3.org/2000/svg">\n' +
(this._options.metadata
? '<metadata>' + this._options.metadata + '</metadata>\n'
: '') +
'<defs>\n' +
' <font id="' +
this._options.fontId +
'" horiz-adv-x="' +
fontWidth +
'">\n' +
' <font-face font-family="' +
this._options.fontName +
'"\n' +
' units-per-em="' +
fontHeight +
'" ascent="' +
this._options.ascent +
'"\n' +
' descent="' +
this._options.descent +
'"' +
(this._options.fontWeight
? '\n font-weight="' + this._options.fontWeight + '"'
: '') +
(this._options.fontStyle
? '\n font-style="' + this._options.fontStyle + '"'
: '') +
' />\n' +
' <missing-glyph horiz-adv-x="0" />\n');
this.glyphs.forEach((glyph) => {
const ratio = this._options.normalize
? fontHeight /
(this._options.preserveAspectRatio && glyph.width > glyph.height
? glyph.width
: glyph.height)
: fontHeight / maxGlyphHeight;
if (!isFinite(ratio)) {
throw new YError('E_BAD_COMPUTED_RATIO', ratio);
}
glyph.width *= ratio;
glyph.height *= ratio;
const glyphPath = new SVGPathData('');
if (this._options.fixedWidth) {
glyph.width = fontWidth;
}
const yOffset = glyph.height - this._options.descent;
let glyphPathTransform = {
a: 1,
b: 0,
c: 0,
d: -1,
e: 0,
f: yOffset,
}; // ySymmetry
if (1 !== ratio) {
glyphPathTransform = compose(glyphPathTransform, scale(ratio, ratio));
}
(glyph.paths || []).forEach((path) => {
glyphPath.commands.push(...path
.toAbs()
.matrix(glyphPathTransform.a, glyphPathTransform.b, glyphPathTransform.c, glyphPathTransform.d, glyphPathTransform.e, glyphPathTransform.f).commands);
});
const bounds = (this._options.centerHorizontally || this._options.centerVertically) &&
glyphPath.getBounds();
if (this._options.centerHorizontally && bounds && 'maxX' in bounds) {
glyphPath.translate((glyph.width - (bounds.maxX - bounds.minX)) / 2 - bounds.minX);
}
if (this._options.centerVertically && bounds && 'maxX' in bounds) {
glyphPath.translate(0, (fontHeight - (bounds.maxY - bounds.minY)) / 2 -
bounds.minY -
this._options.descent);
}
delete glyph.paths;
const d = glyphPath.round(this._options.round).encode();
glyph.unicode.forEach((unicode, i) => {
const unicodeStr = [...unicode]
.map((char) => '&#x' + char.codePointAt(0).toString(16).toUpperCase() + ';')
.join('');
this.push(' <glyph glyph-name="' +
glyph.name +
(0 === i ? '' : '-' + i) +
'"\n' +
' unicode="' +
unicodeStr +
'"\n' +
' horiz-adv-x="' +
glyph.width +
'" d="' +
d +
'" />\n');
});
});
this.push(' </font>\n' + '</defs>\n' + '</svg>\n');
warn('✅ - Font created');
if ('function' === typeof this._options.callback) {
this._options.callback(this.glyphs);
}
svgFontFlushCallback();
}
}
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
export type MetadataServiceOptions = {
prependUnicode: boolean;
startUnicode: number;
};
export type FileMetadata = {
path: string;
name: string;
unicode: string[] | string;
renamed: boolean;
};
declare function getMetadataService(options?: Partial<MetadataServiceOptions>): (file: string, cb: (error: Error | null, metadata?: FileMetadata) => void) => void;
export { getMetadataService };

View File

@@ -0,0 +1,70 @@
import { join, dirname, basename } from 'node:path';
import { rename } from 'node:fs';
function getMetadataService(options = {}) {
const usedUnicodes = [];
// Default options
const _options = {
prependUnicode: !!options.prependUnicode,
startUnicode: 'number' === typeof options.startUnicode ? options.startUnicode : 0xea01,
};
return function getMetadataFromFile(file, cb) {
const fileBasename = basename(file);
const metadata = {
path: file,
name: '',
unicode: [],
renamed: false,
};
const matches = fileBasename.match(/^(?:((?:u[0-9a-f]{4,6},?)+)-)?(.+)\.svg$/i);
metadata.name =
matches && matches[2] ? matches[2] : 'icon' + _options.startUnicode;
if (matches && matches[1]) {
metadata.unicode = matches[1].split(',').map((match) => {
match = match.substring(1);
return match
.split('u')
.map((code) => String.fromCodePoint(parseInt(code, 16)))
.join('');
});
if (-1 !== usedUnicodes.indexOf(metadata.unicode[0])) {
cb(new Error('The unicode codepoint of the glyph ' +
metadata.name +
' seems to be already used by another glyph.'));
return;
}
usedUnicodes.push(...metadata.unicode);
}
else {
do {
metadata.unicode[0] = String.fromCodePoint(_options.startUnicode++);
} while (usedUnicodes.includes(metadata.unicode[0]));
usedUnicodes.push(metadata.unicode[0]);
if (_options.prependUnicode) {
metadata.renamed = true;
metadata.path = join(dirname(file), 'u' +
metadata.unicode[0].codePointAt(0)?.toString(16).toUpperCase() +
'-' +
fileBasename);
rename(file, metadata.path, (err) => {
if (err) {
cb(new Error('Could not save codepoint: ' +
'u' +
metadata.unicode[0]
.codePointAt(0)
?.toString(16)
.toUpperCase() +
' for ' +
fileBasename));
return;
}
cb(null, metadata);
});
}
}
if (!metadata.renamed) {
setImmediate(() => cb(null, metadata));
}
};
}
export { getMetadataService };
//# sourceMappingURL=metadata.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../src/metadata.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,13 @@
declare const svgShapesToPath: {
rectToPath: typeof svgShapesToPathRectToPath;
polylineToPath: typeof svgShapesToPathPolylineToPath;
lineToPath: typeof svgShapesToPathLineToPath;
circleToPath: typeof svgShapesToPathCircleToPath;
polygonToPath: typeof svgShapesToPathPolygonToPath;
};
export default svgShapesToPath;
declare function svgShapesToPathRectToPath(attributes: any): string;
declare function svgShapesToPathPolylineToPath(attributes: any): string;
declare function svgShapesToPathLineToPath(attributes: any): string;
declare function svgShapesToPathCircleToPath(attributes: any): string;
declare function svgShapesToPathPolygonToPath(attributes: any): string;

View File

@@ -0,0 +1,113 @@
const svgShapesToPath = {
rectToPath: svgShapesToPathRectToPath,
polylineToPath: svgShapesToPathPolylineToPath,
lineToPath: svgShapesToPathLineToPath,
circleToPath: svgShapesToPathCircleToPath,
polygonToPath: svgShapesToPathPolygonToPath,
};
export default svgShapesToPath;
// Shapes helpers (should also move elsewhere)
function svgShapesToPathRectToPath(attributes) {
const x = 'undefined' !== typeof attributes.x ? parseFloat(attributes.x) : 0;
const y = 'undefined' !== typeof attributes.y ? parseFloat(attributes.y) : 0;
const width = 'undefined' !== typeof attributes.width ? parseFloat(attributes.width) : 0;
const height = 'undefined' !== typeof attributes.height
? parseFloat(attributes.height)
: 0;
const rx = 'undefined' !== typeof attributes.rx
? parseFloat(attributes.rx)
: 'undefined' !== typeof attributes.ry
? parseFloat(attributes.ry)
: 0;
const ry = 'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : rx;
return ('' +
// start at the left corner
'M' +
(x + rx) +
' ' +
y +
// top line
'h' +
(width - rx * 2) +
// upper right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry : '') +
// Draw right side
'v' +
(height - ry * 2) +
// Draw bottom right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry : '') +
// Down the down side
'h' +
(width - rx * 2) * -1 +
// Draw bottom right corner
(rx || ry
? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry * -1
: '') +
// Down the left side
'v' +
(height - ry * 2) * -1 +
// Draw bottom right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry * -1 : '') +
// Close path
'z');
}
function svgShapesToPathPolylineToPath(attributes) {
return 'M' + attributes.points;
}
function svgShapesToPathLineToPath(attributes) {
// Move to the line start
return ('' +
'M' +
(parseFloat(attributes.x1) || 0).toString(10) +
' ' +
(parseFloat(attributes.y1) || 0).toString(10) +
' ' +
((parseFloat(attributes.x1) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.y1) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.x2) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.y2) || 0) + 1).toString(10) +
' ' +
(parseFloat(attributes.x2) || 0).toString(10) +
' ' +
(parseFloat(attributes.y2) || 0).toString(10) +
'Z');
}
function svgShapesToPathCircleToPath(attributes) {
const cx = parseFloat(attributes.cx || 0);
const cy = parseFloat(attributes.cy || 0);
const rx = 'undefined' !== typeof attributes.rx
? parseFloat(attributes.rx)
: parseFloat(attributes.r);
const ry = 'undefined' !== typeof attributes.ry
? parseFloat(attributes.ry)
: parseFloat(attributes.r);
// use two A commands because one command which returns to origin is invalid
return ('' +
'M' +
(cx - rx) +
',' +
cy +
'A' +
rx +
',' +
ry +
' 0,0,0 ' +
(cx + rx) +
',' +
cy +
'A' +
rx +
',' +
ry +
' 0,0,0 ' +
(cx - rx) +
',' +
cy);
}
function svgShapesToPathPolygonToPath(attributes) {
return 'M' + attributes.points + 'Z';
}
//# sourceMappingURL=svgshapes2svgpath.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"svgshapes2svgpath.js","sourceRoot":"","sources":["../src/svgshapes2svgpath.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,65 @@
import { describe, test, expect } from '@jest/globals';
import { readFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
try {
await mkdir(join('fixtures', 'results'));
}
catch (err) {
// empty
}
describe('Testing CLI', () => {
test('should work for simple SVG', async () => {
const command = `${'node' + ' '}${join('bin', 'svgicons2svgfont.js')} -o ${join('fixtures', 'results', 'originalicons-cli.svg')} -s 0xE001` + ` ${join('fixtures', 'icons', 'originalicons', '*.svg')}`;
await promisify(exec)(command);
expect(await readFile(join('fixtures', 'results', 'originalicons-cli.svg'), {
encoding: 'utf8',
})).toEqual(await readFile(join('fixtures', 'expected', 'originalicons-cli.svg'), {
encoding: 'utf8',
}));
});
test('should work for more than 32 SVG icons', async () => {
const command = 'node' +
' ' +
join('bin', 'svgicons2svgfont.js') +
' -o ' +
join('fixtures', 'results', 'lotoficons-cli.svg') +
' -s 0xE001' +
' -r 1e4' +
' ' +
join('fixtures', 'icons', 'cleanicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'hiddenpathesicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'multipathicons', 'kikoolol.svg') +
' ' +
join('fixtures', 'icons', 'originalicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'realicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'roundedcorners', '*.svg') +
' ' +
join('fixtures', 'icons', 'shapeicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'tocentericons', '*.svg');
await promisify(exec)(command);
expect(await readFile(join('fixtures', 'results', 'lotoficons-cli.svg'), {
encoding: 'utf8',
})).toEqual(await readFile(join('fixtures', 'expected', 'lotoficons-cli.svg'), {
encoding: 'utf8',
}));
});
describe('with nested icons', () => {
test('should work', async () => {
const command = `${'node' + ' '}${join('bin', 'svgicons2svgfont.js')} -o ${join('fixtures', 'results', 'nestedicons-cli.svg')} ${join('fixtures', 'icons', 'nestedicons', '*.svg')}`;
await promisify(exec)(command);
expect(await readFile(join('fixtures', 'results', 'nestedicons-cli.svg'), {
encoding: 'utf8',
})).toEqual(await readFile(join('fixtures', 'expected', 'nestedicons-cli.svg'), {
encoding: 'utf8',
}));
});
});
});
//# sourceMappingURL=cli.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"cli.test.js","sourceRoot":"","sources":["../../src/tests/cli.test.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,79 @@
import { describe, test, expect } from '@jest/globals';
import { fileSorter } from '../filesorter.js';
describe('fileSorter', () => {
test('should sort files per filename', () => {
expect([
'/var/plop/c.svg',
'/var/plop/a.svg',
'/var/plop/A.svg',
'/var/plop/C.svg',
'/var/plop/B.svg',
'/var/plop/b.svg',
].sort(fileSorter)).toEqual([
'/var/plop/A.svg',
'/var/plop/B.svg',
'/var/plop/C.svg',
'/var/plop/a.svg',
'/var/plop/b.svg',
'/var/plop/c.svg',
]);
});
test('should sort files per codepoints', () => {
expect([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE06-C.svg',
'/var/plop/uAE04-B.svg',
'/var/plop/uAE05-b.svg',
].sort(fileSorter)).toEqual([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE04-B.svg',
'/var/plop/uAE05-b.svg',
'/var/plop/uAE06-C.svg',
]);
});
test('should put codepoints first', () => {
expect([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/C.svg',
'/var/plop/B.svg',
'/var/plop/b.svg',
].sort(fileSorter)).toEqual([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/B.svg',
'/var/plop/C.svg',
'/var/plop/b.svg',
]);
});
test('should work with the @pinin files', () => {
expect([
'bell-disabled.svg',
'bell-disabled-o.svg',
'bell-o.svg',
'UEA01-calendar-agenda.svg',
'UEA02-calendar-alert.svg',
'UEA03-calendar.svg',
'uEA04-bookmark-favorite.svg',
'uEA05-bookmark-o.svg',
'uEA06-bookmark.svg',
].sort(fileSorter)).toEqual([
'UEA01-calendar-agenda.svg',
'UEA02-calendar-alert.svg',
'UEA03-calendar.svg',
'uEA04-bookmark-favorite.svg',
'uEA05-bookmark-o.svg',
'uEA06-bookmark.svg',
'bell-disabled.svg',
'bell-disabled-o.svg',
'bell-o.svg',
]);
});
});
//# sourceMappingURL=filesorter.test.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"filesorter.test.js","sourceRoot":"","sources":["../../src/tests/filesorter.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,QAAQ,CAAC,YAAY,EAAE,GAAG,EAAE;IAC1B,IAAI,CAAC,gCAAgC,EAAE,GAAG,EAAE;QAC1C,MAAM,CACJ;YACE,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;SAClB,CAAC,IAAI,CAAC,UAAU,CAAC,CACnB,CAAC,OAAO,CAAC;YACR,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;SAClB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,kCAAkC,EAAE,GAAG,EAAE;QAC5C,MAAM,CACJ;YACE,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;SACxB,CAAC,IAAI,CAAC,UAAU,CAAC,CACnB,CAAC,OAAO,CAAC;YACR,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;SACxB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,6BAA6B,EAAE,GAAG,EAAE;QACvC,MAAM,CACJ;YACE,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;SAClB,CAAC,IAAI,CAAC,UAAU,CAAC,CACnB,CAAC,OAAO,CAAC;YACR,uBAAuB;YACvB,uBAAuB;YACvB,uBAAuB;YACvB,iBAAiB;YACjB,iBAAiB;YACjB,iBAAiB;SAClB,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,mCAAmC,EAAE,GAAG,EAAE;QAC7C,MAAM,CACJ;YACE,mBAAmB;YACnB,qBAAqB;YACrB,YAAY;YACZ,2BAA2B;YAC3B,0BAA0B;YAC1B,oBAAoB;YACpB,6BAA6B;YAC7B,sBAAsB;YACtB,oBAAoB;SACrB,CAAC,IAAI,CAAC,UAAU,CAAC,CACnB,CAAC,OAAO,CAAC;YACR,2BAA2B;YAC3B,0BAA0B;YAC1B,oBAAoB;YACpB,6BAA6B;YAC7B,sBAAsB;YACtB,oBAAoB;YACpB,mBAAmB;YACnB,qBAAqB;YACrB,YAAY;SACb,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,553 @@
import { describe, test, expect } from '@jest/globals';
import assert from 'assert';
import fs from 'node:fs';
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { SVGIcons2SVGFontStream } from '../index.js';
import { SVGIconsDirStream } from '../iconsdir.js';
import streamtest from 'streamtest';
import { BufferStream } from 'bufferstreams';
try {
await mkdir(join('fixtures', 'results'));
}
catch (err) {
// empty
}
const codepoint = JSON.parse(fs.readFileSync('./fixtures/expected/test-codepoint.json').toString());
// Helpers
async function generateFontToFile(options, fileSuffix, startUnicode, files) {
const dest = join('fixtures', 'results', `${options.fontName + (fileSuffix || '')}.svg`);
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
options.log = () => { };
options.round = options.round || 1e3;
const svgFontStream = new SVGIcons2SVGFontStream(options);
svgFontStream.pipe(fs.createWriteStream(dest)).on('finish', () => {
try {
expect(fs.readFileSync(dest, { encoding: 'utf8' })).toEqual(fs.readFileSync(join('fixtures', 'expected', `${options.fontName + (fileSuffix || '')}.svg`), { encoding: 'utf8' }));
resolve();
}
catch (err) {
reject(err);
}
});
new SVGIconsDirStream(files || join('fixtures', 'icons', options.fontName), {
startUnicode: startUnicode || 0xe001,
}).pipe(svgFontStream);
return await promise;
}
async function generateFontToMemory(options, files, startUnicode) {
options.log = () => { };
options.round = options.round || 1e3;
options.callback = (glyphs) => {
const fontName = options.fontName;
expect(glyphs).toEqual(codepoint[fontName]);
};
const svgFontStream = new SVGIcons2SVGFontStream(options);
const promise = bufferStream(svgFontStream);
new SVGIconsDirStream(files || join('fixtures', 'icons', options.fontName), {
startUnicode: startUnicode || 0xe001,
}).pipe(svgFontStream);
expect((await promise).toString()).toEqual(fs.readFileSync(join('fixtures', 'expected', `${options.fontName}.svg`), {
encoding: 'utf8',
}));
}
// Tests
describe('Generating fonts to files', () => {
test('should work for simple SVG', async () => {
await generateFontToFile({
fontName: 'originalicons',
});
});
test('should work for simple fixedWidth and normalize option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fixedWidth: true,
normalize: true,
}, 'n');
});
test('should work for simple SVG', async () => {
await generateFontToFile({
fontName: 'cleanicons',
});
});
test('should work for simple SVG and custom ascent', async () => {
await generateFontToFile({
fontName: 'cleanicons',
ascent: 100,
}, '-ascent');
});
test('should work for simple SVG and custom properties', async () => {
await generateFontToFile({
fontName: 'cleanicons',
fontStyle: 'italic',
fontWeight: 'bold',
}, '-stw');
});
test('should work for codepoint mapped SVG icons', async () => {
await generateFontToFile({
fontName: 'prefixedicons',
callback: () => { },
});
});
test('should work with multipath SVG icons', async () => {
await generateFontToFile({
fontName: 'multipathicons',
});
});
test('should work with simple shapes SVG icons', async () => {
await generateFontToFile({
fontName: 'shapeicons',
});
});
test('should work with variable height icons', async () => {
await generateFontToFile({
fontName: 'variableheighticons',
});
});
test('should work with variable height icons and the normalize option', async () => {
await generateFontToFile({
fontName: 'variableheighticons',
normalize: true,
}, 'n');
});
test('should work with variable height icons, the normalize option and the preserveAspectRatio option', async () => {
await generateFontToFile({
fontName: 'variableheighticons',
normalize: true,
preserveAspectRatio: true,
}, 'np');
});
test('should work with variable width icons', async () => {
await generateFontToFile({
fontName: 'variablewidthicons',
});
});
test('should work with centered variable width icons and the fixed width option', async () => {
await generateFontToFile({
fontName: 'variablewidthicons',
fixedWidth: true,
centerHorizontally: true,
}, 'n');
});
test('should calculate bounds when not specified in the svg file', async () => {
await generateFontToFile({
fontName: 'calcbounds',
});
});
test('should work with a font id', async () => {
await generateFontToFile({
fontName: 'variablewidthicons',
fixedWidth: true,
centerHorizontally: true,
fontId: 'plop',
}, 'id');
});
test('should work with scaled icons', async () => {
await generateFontToFile({
fontName: 'scaledicons',
fixedWidth: true,
centerHorizontally: true,
fontId: 'plop',
});
});
test('should not display hidden paths', async () => {
await generateFontToFile({
fontName: 'hiddenpathesicons',
});
});
test('should work with real world icons', async () => {
await generateFontToFile({
fontName: 'realicons',
});
});
test('should work with rendering test SVG icons', async () => {
await generateFontToFile({
fontName: 'rendricons',
});
});
test('should work with a single SVG icon', async () => {
await generateFontToFile({
fontName: 'singleicon',
});
});
test('should work with transformed SVG icons', async () => {
await generateFontToFile({
fontName: 'transformedicons',
});
});
test('should work when horizontally centering SVG icons', async () => {
await generateFontToFile({
fontName: 'tocentericons',
centerHorizontally: true,
});
});
test('should work when vertically centering SVG icons', async () => {
await generateFontToFile({
fontName: 'toverticalcentericons',
centerVertically: true,
});
});
test('should work with a icons with path with fill none', async () => {
await generateFontToFile({
fontName: 'pathfillnone',
});
});
test('should work with shapes with rounded corners', async () => {
await generateFontToFile({
fontName: 'roundedcorners',
});
});
test('should work with realworld icons', async () => {
await generateFontToFile({
fontName: 'realworld',
});
});
test('should work with a lot of icons', async () => {
await generateFontToFile({
fontName: 'lotoficons',
}, '', 0, [
'fixtures/icons/cleanicons/account.svg',
'fixtures/icons/cleanicons/arrow-down.svg',
'fixtures/icons/cleanicons/arrow-left.svg',
'fixtures/icons/cleanicons/arrow-right.svg',
'fixtures/icons/cleanicons/arrow-up.svg',
'fixtures/icons/cleanicons/basket.svg',
'fixtures/icons/cleanicons/close.svg',
'fixtures/icons/cleanicons/minus.svg',
'fixtures/icons/cleanicons/plus.svg',
'fixtures/icons/cleanicons/search.svg',
'fixtures/icons/hiddenpathesicons/sound--off.svg',
'fixtures/icons/hiddenpathesicons/sound--on.svg',
'fixtures/icons/multipathicons/kikoolol.svg',
'fixtures/icons/originalicons/mute.svg',
'fixtures/icons/originalicons/sound.svg',
'fixtures/icons/originalicons/speaker.svg',
'fixtures/icons/realicons/diegoliv.svg',
'fixtures/icons/realicons/hannesjohansson.svg',
'fixtures/icons/realicons/roelvanhitum.svg',
'fixtures/icons/realicons/safety-icon.svg',
'fixtures/icons/realicons/sb-icon.svg',
'fixtures/icons/realicons/settings-icon.svg',
'fixtures/icons/realicons/track-icon.svg',
'fixtures/icons/realicons/web-icon.svg',
'fixtures/icons/roundedcorners/roundedrect.svg',
'fixtures/icons/shapeicons/circle.svg',
'fixtures/icons/shapeicons/ellipse.svg',
'fixtures/icons/shapeicons/lines.svg',
'fixtures/icons/shapeicons/polygon.svg',
'fixtures/icons/shapeicons/polyline.svg',
'fixtures/icons/shapeicons/rect.svg',
'fixtures/icons/tocentericons/bottomleft.svg',
'fixtures/icons/tocentericons/center.svg',
'fixtures/icons/tocentericons/topright.svg',
]);
});
test('should work with rotated rectangle icon', async () => {
await generateFontToFile({
fontName: 'rotatedrectangle',
});
});
/**
* Issue #6
* icon by @paesku
* https://github.com/nfroidure/svgicons2svgfont/issues/6#issuecomment-125545925
*/
test('should work with complicated nested transforms', async () => {
await generateFontToFile({
fontName: 'paesku',
round: 1e3,
});
});
/**
* Issue #76
* https://github.com/nfroidure/svgicons2svgfont/issues/76#issue-259831969
*/
test('should work with transform=translate(x) without y', async () => {
await generateFontToFile({
fontName: 'translatex',
round: 1e3,
});
});
test('should work with skew', async () => {
await generateFontToFile({
fontName: 'skew',
});
});
test('should work when only rx is present', async () => {
await generateFontToFile({
fontName: 'onlywithrx',
});
});
test('should work when only ry is present', async () => {
await generateFontToFile({
fontName: 'onlywithry',
});
});
});
describe('Generating fonts to memory', () => {
test('should work for simple SVG', async () => {
await generateFontToMemory({
fontName: 'originalicons',
});
});
test('should work for simple SVG', async () => {
await generateFontToMemory({
fontName: 'cleanicons',
});
});
test('should work for codepoint mapped SVG icons', async () => {
await generateFontToMemory({
fontName: 'prefixedicons',
});
});
test('should work with multipath SVG icons', async () => {
await generateFontToMemory({
fontName: 'multipathicons',
});
});
test('should work with simple shapes SVG icons', async () => {
await generateFontToMemory({
fontName: 'shapeicons',
});
});
});
describe('Using options', () => {
test('should work with fixedWidth option set to true', async () => {
await generateFontToFile({
fontName: 'originalicons',
fixedWidth: true,
}, '2');
});
test('should work with custom fontHeight option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
}, '3');
});
test('should work with custom descent option', async () => {
await generateFontToFile({
fontName: 'originalicons',
descent: 200,
}, '4');
});
test('should work with fixedWidth set to true and with custom fontHeight option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true,
}, '5');
});
test('should work with fixedWidth and centerHorizontally set to true and with' +
' custom fontHeight option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
}, '6');
});
test('should work with fixedWidth, normalize and centerHorizontally set to' +
' true and with custom fontHeight option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fontHeight: 800,
normalize: true,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
}, '7');
});
test('should work with fixedWidth, normalize and centerHorizontally set to' +
' true and with a large custom fontHeight option', async () => {
await generateFontToFile({
fontName: 'originalicons',
fontHeight: 5000,
normalize: true,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
}, '8');
});
test('should work with nested icons', async () => {
await generateFontToFile({
fontName: 'nestedicons',
}, '', 0xea01);
});
});
describe('Passing code points', () => {
test('should work with multiple unicode values for a single icon', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: 'account',
unicode: ['\uE001', '\uE002'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal(await promise, fs.readFileSync(join('fixtures', 'expected', 'cleanicons-multi.svg'), {
encoding: 'utf8',
}));
});
test('should work with ligatures', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: 'account',
unicode: ['\uE001\uE002'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal(await promise, fs.readFileSync(join('fixtures', 'expected', 'cleanicons-lig.svg'), {
encoding: 'utf8',
}));
});
test('should work with high code points', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: 'account',
unicode: ['\u{1f63a}'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal((await promise).toString(), fs.readFileSync(join('fixtures', 'expected', 'cleanicons-high.svg'), {
encoding: 'utf8',
}));
});
});
describe('Providing bad glyphs', () => {
test('should fail when not providing glyph name', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: undefined,
unicode: '\uE001',
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Please provide a name for the glyph at index 0');
})
.write(svgIconStream);
});
test('should fail when not providing codepoints', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: 'test',
unicode: undefined,
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Please provide a codepoint for the glyph "test"');
})
.write(svgIconStream);
});
test('should fail when providing unicode value with duplicates', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002', '\uE002'],
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Given codepoints for the glyph "test" contain duplicates.');
})
.write(svgIconStream);
});
test('should fail when providing the same codepoint twice', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
const svgIconStream2 = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
const svgFontStream = new SVGIcons2SVGFontStream({
round: 1e3,
});
svgIconStream.metadata = {
name: 'test',
unicode: '\uE002',
};
svgIconStream2.metadata = {
name: 'test2',
unicode: '\uE002',
};
svgFontStream.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'The glyph "test2" codepoint seems to be used already elsewhere.');
});
svgFontStream.write(svgIconStream);
svgFontStream.write(svgIconStream2);
});
test('should fail when providing the same name twice', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
const svgIconStream2 = fs.createReadStream(join('fixtures', 'icons', 'cleanicons', 'account.svg'));
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
svgIconStream.metadata = {
name: 'test',
unicode: '\uE001',
};
svgIconStream2.metadata = {
name: 'test',
unicode: '\uE002',
};
svgFontStream.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'The glyph name "test" must be unique.');
});
svgFontStream.write(svgIconStream);
svgFontStream.write(svgIconStream2);
});
test('should fail when providing bad pathdata', async () => {
const svgIconStream = fs.createReadStream(join('fixtures', 'icons', 'badicons', 'pathdata.svg'));
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002'],
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'Got an error parsing the glyph "test":' +
' Expected a flag, got "20" at index "23".');
})
.on('end', () => { })
.write(svgIconStream);
});
test('should fail when providing bad XML', async () => {
const svgIconStream = streamtest.fromChunks([
Buffer.from('bad'),
Buffer.from('xml'),
]);
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002'],
};
let firstError = true;
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
if (firstError) {
firstError = false;
assert.equal(err.message, 'Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: b');
}
})
.write(svgIconStream);
});
});
async function bufferStream(readableStream) {
return await new Promise((resolve, reject) => {
readableStream.pipe(new BufferStream((err, buf) => {
if (err) {
return reject(err);
}
resolve(buf);
}));
});
}
//# sourceMappingURL=index.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,167 @@
import { describe, test, expect } from '@jest/globals';
import { writeFile, readFile, unlink } from 'node:fs/promises';
import { promisify } from 'node:util';
import { getMetadataService } from '../metadata.js';
import { YError } from 'yerror';
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
try {
await mkdir(join('fixtures', 'results'));
}
catch (err) {
// empty
}
describe('Metadata service', () => {
describe('for code generation', () => {
test('should extract right unicodes from files', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/hello.svg');
expect(infos).toEqual({
path: '/var/plop/hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
});
test('should append unicodes to files when the option is set', async () => {
const metadataService = getMetadataService({
prependUnicode: true,
});
await writeFile(join('fixtures', 'results', 'plop.svg'), 'plop', 'utf-8');
const infos = await promisify(metadataService)(join('fixtures', 'results', 'plop.svg'));
expect(infos).toEqual({
path: join('fixtures', 'results', 'uEA01-plop.svg'),
name: 'plop',
unicode: [String.fromCharCode(0xea01)],
renamed: true,
});
expect(await readFile(join('fixtures', 'results', 'uEA01-plop.svg'))).toBeTruthy();
unlink(join('fixtures', 'results', 'uEA01-plop.svg'));
try {
await readFile(join('fixtures', 'results', 'plop.svg'));
throw new YError('E_UNEXPECTED_SUCCESS');
}
catch (err) {
expect(err.code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
});
test('should log file rename errors', async () => {
const metadataService = getMetadataService({
prependUnicode: true,
startUnicode: 0xea02,
});
try {
await promisify(metadataService)(join('fixtures', 'results', 'plop.svg'));
throw new YError('E_UNEXPECTED_SUCCESS');
}
catch (err) {
expect(err).toBeTruthy();
expect(err.code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
try {
await readFile(join('fixtures', 'results', 'uEA02-plop.svg'));
throw new YError('E_UNEXPECTED_SUCCESS');
}
catch (err) {
expect(err.code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
});
});
describe('for code extraction', () => {
test('should work for simple codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/u0001-hello.svg');
expect(infos).toEqual({
path: '/var/plop/u0001-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001)],
renamed: false,
});
});
test('should work for several codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/u0001,u0002-hello.svg');
expect(infos).toEqual({
path: '/var/plop/u0001,u0002-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001), String.fromCharCode(0x0002)],
renamed: false,
});
});
test('should work for higher codepoint codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/u1F63A-hello.svg');
expect(infos).toEqual({
path: '/var/plop/u1F63A-hello.svg',
name: 'hello',
unicode: [String.fromCodePoint(0x1f63a)],
renamed: false,
});
});
test('should work for ligature codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/u0001u0002-hello.svg');
expect(infos).toEqual({
path: '/var/plop/u0001u0002-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001) + String.fromCharCode(0x0002)],
renamed: false,
});
});
test('should work for nested codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/u0001u0002,u0001-hello.svg');
expect(infos).toEqual({
path: '/var/plop/u0001u0002,u0001-hello.svg',
name: 'hello',
unicode: [
String.fromCharCode(0x0001) + String.fromCharCode(0x0002),
String.fromCharCode(0x0001),
],
renamed: false,
});
});
test('should not set the same codepoint twice', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/uEA01-hello.svg');
expect(infos).toEqual({
path: '/var/plop/uEA01-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
const infos2 = await promisify(metadataService)('/var/plop/plop.svg');
expect(infos2).toEqual({
path: '/var/plop/plop.svg',
name: 'plop',
unicode: [String.fromCharCode(0xea02)],
renamed: false,
});
});
test('should not set the same codepoint twice with different cases', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/UEA01-hello.svg');
expect(infos).toEqual({
path: '/var/plop/UEA01-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
const infos2 = await promisify(metadataService)('/var/plop/uEA02-hello.svg');
expect(infos2).toEqual({
path: '/var/plop/uEA02-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea02)],
renamed: false,
});
const infos3 = await promisify(metadataService)('/var/plop/bell-o.svg');
expect(infos3).toEqual({
path: '/var/plop/bell-o.svg',
name: 'bell-o',
unicode: [String.fromCharCode(0xea03)],
renamed: false,
});
});
});
});
//# sourceMappingURL=metadata.test.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
import commander from './index.js';
// wrapper to provide named exports for ESM.
export const {
program,
createCommand,
createArgument,
createOption,
CommanderError,
InvalidArgumentError,
InvalidOptionArgumentError, // deprecated old name
Command,
Argument,
Option,
Help,
} = commander;

View File

@@ -0,0 +1,24 @@
const { Argument } = require('./lib/argument.js');
const { Command } = require('./lib/command.js');
const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
const { Help } = require('./lib/help.js');
const { Option } = require('./lib/option.js');
exports.program = new Command();
exports.createCommand = (name) => new Command(name);
exports.createOption = (flags, description) => new Option(flags, description);
exports.createArgument = (name, description) => new Argument(name, description);
/**
* Expose classes
*/
exports.Command = Command;
exports.Option = Option;
exports.Argument = Argument;
exports.Help = Help;
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated

View File

@@ -0,0 +1,149 @@
const { InvalidArgumentError } = require('./error.js');
class Argument {
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @param {string} name
* @param {string} [description]
*/
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.required = true;
this._name = name.slice(1, -1);
break;
case '[': // e.g. [optional]
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && this._name.slice(-3) === '...') {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
this.required = false;
return this;
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Argument} arg
* @return {string}
* @private
*/
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
/**
* CommanderError class
*/
class CommanderError extends Error {
/**
* Constructs the CommanderError class
* @param {number} exitCode suggested exit code which could be used with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
*/
constructor(exitCode, code, message) {
super(message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
this.nestedError = undefined;
}
}
/**
* InvalidArgumentError class
*/
class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(message) {
super(1, 'commander.invalidArgument', message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;

View File

@@ -0,0 +1,520 @@
const { humanReadableArgName } = require('./argument.js');
/**
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
* @typedef { import("./argument.js").Argument } Argument
* @typedef { import("./command.js").Command } Command
* @typedef { import("./option.js").Option } Option
*/
// Although this is a class, methods are static in style to allow override using subclass or just functions.
class Help {
constructor() {
this.helpWidth = undefined;
this.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
*
* @param {Command} cmd
* @returns {Command[]}
*/
visibleCommands(cmd) {
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
const helpCommand = cmd._getHelpCommand();
if (helpCommand && !helpCommand._hidden) {
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
// @ts-ignore: because overloaded return type
return a.name().localeCompare(b.name());
});
}
return visibleCommands;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(a, b) {
const getSortKey = (option) => {
// WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
return option.short
? option.short.replace(/^-/, '')
: option.long.replace(/^--/, '');
};
return getSortKey(a).localeCompare(getSortKey(b));
}
/**
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleOptions(cmd) {
const visibleOptions = cmd.options.filter((option) => !option.hidden);
// Built-in help option.
const helpOption = cmd._getHelpOption();
if (helpOption && !helpOption.hidden) {
// Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
if (!removeShort && !removeLong) {
visibleOptions.push(helpOption); // no changes needed
} else if (helpOption.long && !removeLong) {
visibleOptions.push(
cmd.createOption(helpOption.long, helpOption.description),
);
} else if (helpOption.short && !removeShort) {
visibleOptions.push(
cmd.createOption(helpOption.short, helpOption.description),
);
}
}
if (this.sortOptions) {
visibleOptions.sort(this.compareOptions);
}
return visibleOptions;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(cmd) {
if (!this.showGlobalOptions) return [];
const globalOptions = [];
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
const visibleOptions = ancestorCmd.options.filter(
(option) => !option.hidden,
);
globalOptions.push(...visibleOptions);
}
if (this.sortOptions) {
globalOptions.sort(this.compareOptions);
}
return globalOptions;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(cmd) {
// Side effect! Apply the legacy descriptions before the arguments are displayed.
if (cmd._argsDescription) {
cmd.registeredArguments.forEach((argument) => {
argument.description =
argument.description || cmd._argsDescription[argument.name()] || '';
});
}
// If there are any arguments with a description then return all the arguments.
if (cmd.registeredArguments.find((argument) => argument.description)) {
return cmd.registeredArguments;
}
return [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(cmd) {
// Legacy. Ignores custom usage string, and nested commands.
const args = cmd.registeredArguments
.map((arg) => humanReadableArgName(arg))
.join(' ');
return (
cmd._name +
(cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
(cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
(args ? ' ' + args : '')
);
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(option) {
return option.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(argument) {
return argument.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(cmd, helper) {
return helper.visibleCommands(cmd).reduce((max, command) => {
return Math.max(max, helper.subcommandTerm(command).length);
}, 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(cmd, helper) {
return helper.visibleOptions(cmd).reduce((max, option) => {
return Math.max(max, helper.optionTerm(option).length);
}, 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(cmd, helper) {
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
return Math.max(max, helper.optionTerm(option).length);
}, 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(cmd, helper) {
return helper.visibleArguments(cmd).reduce((max, argument) => {
return Math.max(max, helper.argumentTerm(argument).length);
}, 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(cmd) {
// Usage
let cmdName = cmd._name;
if (cmd._aliases[0]) {
cmdName = cmdName + '|' + cmd._aliases[0];
}
let ancestorCmdNames = '';
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
}
return ancestorCmdNames + cmdName + ' ' + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.summary() || cmd.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(option) {
const extraInfo = [];
if (option.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (option.defaultValue !== undefined) {
// default for boolean and negated more for programmer than end user,
// but show true/false for boolean option as may be for hand-rolled env or config processing.
const showDefault =
option.required ||
option.optional ||
(option.isBoolean() && typeof option.defaultValue === 'boolean');
if (showDefault) {
extraInfo.push(
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
);
}
}
// preset for boolean and negated are more for programmer than end user
if (option.presetArg !== undefined && option.optional) {
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
}
if (option.envVar !== undefined) {
extraInfo.push(`env: ${option.envVar}`);
}
if (extraInfo.length > 0) {
return `${option.description} (${extraInfo.join(', ')})`;
}
return option.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(argument) {
const extraInfo = [];
if (argument.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (argument.defaultValue !== undefined) {
extraInfo.push(
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
);
}
if (extraInfo.length > 0) {
const extraDescripton = `(${extraInfo.join(', ')})`;
if (argument.description) {
return `${argument.description} ${extraDescripton}`;
}
return extraDescripton;
}
return argument.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(cmd, helper) {
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth || 80;
const itemIndentWidth = 2;
const itemSeparatorWidth = 2; // between term and description
function formatItem(term, description) {
if (description) {
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
return helper.wrap(
fullText,
helpWidth - itemIndentWidth,
termWidth + itemSeparatorWidth,
);
}
return term;
}
function formatList(textArray) {
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
}
// Usage
let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.wrap(commandDescription, helpWidth, 0),
'',
]);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return formatItem(
helper.argumentTerm(argument),
helper.argumentDescription(argument),
);
});
if (argumentList.length > 0) {
output = output.concat(['Arguments:', formatList(argumentList), '']);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return formatItem(
helper.optionTerm(option),
helper.optionDescription(option),
);
});
if (optionList.length > 0) {
output = output.concat(['Options:', formatList(optionList), '']);
}
if (this.showGlobalOptions) {
const globalOptionList = helper
.visibleGlobalOptions(cmd)
.map((option) => {
return formatItem(
helper.optionTerm(option),
helper.optionDescription(option),
);
});
if (globalOptionList.length > 0) {
output = output.concat([
'Global Options:',
formatList(globalOptionList),
'',
]);
}
}
// Commands
const commandList = helper.visibleCommands(cmd).map((cmd) => {
return formatItem(
helper.subcommandTerm(cmd),
helper.subcommandDescription(cmd),
);
});
if (commandList.length > 0) {
output = output.concat(['Commands:', formatList(commandList), '']);
}
return output.join('\n');
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(cmd, helper) {
return Math.max(
helper.longestOptionTermLength(cmd, helper),
helper.longestGlobalOptionTermLength(cmd, helper),
helper.longestSubcommandTermLength(cmd, helper),
helper.longestArgumentTermLength(cmd, helper),
);
}
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*
* @param {string} str
* @param {number} width
* @param {number} indent
* @param {number} [minColumnWidth=40]
* @return {string}
*
*/
wrap(str, width, indent, minColumnWidth = 40) {
// Full \s characters, minus the linefeeds.
const indents =
' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
// Detect manually wrapped and indented strings by searching for line break followed by spaces.
const manualIndent = new RegExp(`[\\n][${indents}]+`);
if (str.match(manualIndent)) return str;
// Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
const columnWidth = width - indent;
if (columnWidth < minColumnWidth) return str;
const leadingStr = str.slice(0, indent);
const columnText = str.slice(indent).replace('\r\n', '\n');
const indentString = ' '.repeat(indent);
const zeroWidthSpace = '\u200B';
const breaks = `\\s${zeroWidthSpace}`;
// Match line end (so empty lines don't collapse),
// or as much text as will fit in column, or excess text up to first break.
const regex = new RegExp(
`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
'g',
);
const lines = columnText.match(regex) || [];
return (
leadingStr +
lines
.map((line, i) => {
if (line === '\n') return ''; // preserve empty lines
return (i > 0 ? indentString : '') + line.trimEnd();
})
.join('\n')
);
}
}
exports.Help = Help;

View File

@@ -0,0 +1,330 @@
const { InvalidArgumentError } = require('./error.js');
class Option {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags, description) {
this.flags = flags;
this.description = description || '';
this.required = flags.includes('<'); // A value must be supplied when the option is specified.
this.optional = flags.includes('['); // A value is optional when the option is specified.
// variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
const optionFlags = splitOptionFlags(flags);
this.short = optionFlags.shortFlag;
this.long = optionFlags.longFlag;
this.negate = false;
if (this.long) {
this.negate = this.long.startsWith('--no-');
}
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.presetArg = undefined;
this.envVar = undefined;
this.parseArg = undefined;
this.hidden = false;
this.argChoices = undefined;
this.conflictsWith = [];
this.implied = undefined;
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Option}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
*
* @param {*} arg
* @return {Option}
*/
preset(arg) {
this.presetArg = arg;
return this;
}
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
*
* @param {(string | string[])} names
* @return {Option}
*/
conflicts(names) {
this.conflictsWith = this.conflictsWith.concat(names);
return this;
}
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*
* @param {object} impliedOptionValues
* @return {Option}
*/
implies(impliedOptionValues) {
let newImplied = impliedOptionValues;
if (typeof impliedOptionValues === 'string') {
// string is not documented, but easy mistake and we can do what user probably intended.
newImplied = { [impliedOptionValues]: true };
}
this.implied = Object.assign(this.implied || {}, newImplied);
return this;
}
/**
* Set environment variable to check for option value.
*
* An environment variable is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*
* @param {string} name
* @return {Option}
*/
env(name) {
this.envVar = name;
return this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(mandatory = true) {
this.mandatory = !!mandatory;
return this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(hide = true) {
this.hidden = !!hide;
return this;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
if (this.long) {
return this.long.replace(/^--/, '');
}
return this.short.replace(/^-/, '');
}
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*
* @return {string}
*/
attributeName() {
return camelcase(this.name().replace(/^no-/, ''));
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(arg) {
return this.short === arg || this.long === arg;
}
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*
* @return {boolean}
* @package
*/
isBoolean() {
return !this.required && !this.optional && !this.negate;
}
}
/**
* This class is to make it easier to work with dual options, without changing the existing
* implementation. We support separate dual options for separate positive and negative options,
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
* use cases, but is tricky for others where we want separate behaviours despite
* the single shared option value.
*/
class DualOptions {
/**
* @param {Option[]} options
*/
constructor(options) {
this.positiveOptions = new Map();
this.negativeOptions = new Map();
this.dualOptions = new Set();
options.forEach((option) => {
if (option.negate) {
this.negativeOptions.set(option.attributeName(), option);
} else {
this.positiveOptions.set(option.attributeName(), option);
}
});
this.negativeOptions.forEach((value, key) => {
if (this.positiveOptions.has(key)) {
this.dualOptions.add(key);
}
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(value, option) {
const optionKey = option.attributeName();
if (!this.dualOptions.has(optionKey)) return true;
// Use the value to deduce if (probably) came from the option.
const preset = this.negativeOptions.get(optionKey).presetArg;
const negativeValue = preset !== undefined ? preset : false;
return option.negate === (negativeValue === value);
}
}
/**
* Convert string from kebab-case to camelCase.
*
* @param {string} str
* @return {string}
* @private
*/
function camelcase(str) {
return str.split('-').reduce((str, word) => {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Split the short and long flag out of something like '-m,--mixed <value>'
*
* @private
*/
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
// Use original very loose parsing to maintain backwards compatibility for now,
// which allowed for example unintended `-sw, --short-word` [sic].
const flagParts = flags.split(/[ |,]+/);
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
shortFlag = flagParts.shift();
longFlag = flagParts.shift();
// Add support for lone short flag without significantly changing parsing!
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
shortFlag = longFlag;
longFlag = undefined;
}
return { shortFlag, longFlag };
}
exports.Option = Option;
exports.DualOptions = DualOptions;

View File

@@ -0,0 +1,101 @@
const maxDistance = 3;
function editDistance(a, b) {
// https://en.wikipedia.org/wiki/DamerauLevenshtein_distance
// Calculating optimal string alignment distance, no substring is edited more than once.
// (Simple implementation.)
// Quick early exit, return worst case.
if (Math.abs(a.length - b.length) > maxDistance)
return Math.max(a.length, b.length);
// distance between prefix substrings of a and b
const d = [];
// pure deletions turn a into empty string
for (let i = 0; i <= a.length; i++) {
d[i] = [i];
}
// pure insertions turn empty string into b
for (let j = 0; j <= b.length; j++) {
d[0][j] = j;
}
// fill matrix
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
let cost = 1;
if (a[i - 1] === b[j - 1]) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(
d[i - 1][j] + 1, // deletion
d[i][j - 1] + 1, // insertion
d[i - 1][j - 1] + cost, // substitution
);
// transposition
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
}
return d[a.length][b.length];
}
/**
* Find close matches, restricted to same number of edits.
*
* @param {string} word
* @param {string[]} candidates
* @returns {string}
*/
function suggestSimilar(word, candidates) {
if (!candidates || candidates.length === 0) return '';
// remove possible duplicates
candidates = Array.from(new Set(candidates));
const searchingOptions = word.startsWith('--');
if (searchingOptions) {
word = word.slice(2);
candidates = candidates.map((candidate) => candidate.slice(2));
}
let similar = [];
let bestDistance = maxDistance;
const minSimilarity = 0.4;
candidates.forEach((candidate) => {
if (candidate.length <= 1) return; // no one character guesses
const distance = editDistance(word, candidate);
const length = Math.max(word.length, candidate.length);
const similarity = (length - distance) / length;
if (similarity > minSimilarity) {
if (distance < bestDistance) {
// better edit distance, throw away previous worse matches
bestDistance = distance;
similar = [candidate];
} else if (distance === bestDistance) {
similar.push(candidate);
}
}
});
similar.sort((a, b) => a.localeCompare(b));
if (searchingOptions) {
similar = similar.map((candidate) => `--${candidate}`);
}
if (similar.length > 1) {
return `\n(Did you mean one of ${similar.join(', ')}?)`;
}
if (similar.length === 1) {
return `\n(Did you mean ${similar[0]}?)`;
}
return '';
}
exports.suggestSimilar = suggestSimilar;

View File

@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}

View File

@@ -0,0 +1,84 @@
{
"name": "commander",
"version": "12.1.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser",
"cli",
"argument",
"args",
"argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/tj/commander.js.git"
},
"scripts": {
"check": "npm run check:type && npm run check:lint && npm run check:format",
"check:format": "prettier --check .",
"check:lint": "eslint .",
"check:type": "npm run check:type:js && npm run check:type:ts",
"check:type:ts": "tsd && tsc -p tsconfig.ts.json",
"check:type:js": "tsc -p tsconfig.js.json",
"fix": "npm run fix:lint && npm run fix:format",
"fix:format": "prettier --write .",
"fix:lint": "eslint --fix .",
"test": "jest && npm run check:type:ts",
"test-all": "jest && npm run test-esm && npm run check",
"test-esm": "node ./tests/esm-imports-test.mjs"
},
"files": [
"index.js",
"lib/*.js",
"esm.mjs",
"typings/index.d.ts",
"typings/esm.d.mts",
"package-support.json"
],
"type": "commonjs",
"main": "./index.js",
"exports": {
".": {
"require": {
"types": "./typings/index.d.ts",
"default": "./index.js"
},
"import": {
"types": "./typings/esm.d.mts",
"default": "./esm.mjs"
},
"default": "./index.js"
},
"./esm.mjs": {
"types": "./typings/esm.d.mts",
"import": "./esm.mjs"
}
},
"devDependencies": {
"@eslint/js": "^8.56.0",
"@types/jest": "^29.2.4",
"@types/node": "^20.2.5",
"eslint": "^8.30.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.3.0",
"eslint-plugin-jsdoc": "^48.1.0",
"globals": "^13.24.0",
"jest": "^29.3.1",
"prettier": "^3.2.5",
"prettier-plugin-jsdoc": "^1.3.0",
"ts-jest": "^29.0.3",
"tsd": "^0.31.0",
"typescript": "^5.0.4",
"typescript-eslint": "^7.0.1"
},
"types": "typings/index.d.ts",
"engines": {
"node": ">=18"
},
"support": true
}

View File

@@ -0,0 +1,3 @@
// Just reexport the types from cjs
// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.
export * from './index.js';

View File

@@ -0,0 +1,969 @@
// Type definitions for commander
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
/* eslint-disable @typescript-eslint/method-signature-style */
/* eslint-disable @typescript-eslint/no-explicit-any */
// This is a trick to encourage editor to suggest the known literals while still
// allowing any BaseType value.
// References:
// - https://github.com/microsoft/TypeScript/issues/29729
// - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts
// - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts
type LiteralUnion<LiteralType, BaseType extends string | number> =
| LiteralType
| (BaseType & Record<never, never>);
export class CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
/**
* Constructs the CommanderError class
* @param exitCode - suggested exit code which could be used with process.exit
* @param code - an id string representing the error
* @param message - human-readable description of the error
*/
constructor(exitCode: number, code: string, message: string);
}
export class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param message - explanation of why argument is invalid
*/
constructor(message: string);
}
export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
export interface ErrorOptions {
// optional parameter for error()
/** an id string representing the error */
code?: string;
/** suggested exit code which could be used with process.exit */
exitCode?: number;
}
export class Argument {
description: string;
required: boolean;
variadic: boolean;
defaultValue?: any;
defaultValueDescription?: string;
argChoices?: string[];
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*/
constructor(arg: string, description?: string);
/**
* Return argument name.
*/
name(): string;
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default(value: unknown, description?: string): this;
/**
* Set the custom handler for processing CLI command arguments into argument values.
*/
argParser<T>(fn: (value: string, previous: T) => T): this;
/**
* Only allow argument value to be one of choices.
*/
choices(values: readonly string[]): this;
/**
* Make argument required.
*/
argRequired(): this;
/**
* Make argument optional.
*/
argOptional(): this;
}
export class Option {
flags: string;
description: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
variadic: boolean;
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
short?: string;
long?: string;
negate: boolean;
defaultValue?: any;
defaultValueDescription?: string;
presetArg?: unknown;
envVar?: string;
parseArg?: <T>(value: string, previous: T) => T;
hidden: boolean;
argChoices?: string[];
constructor(flags: string, description?: string);
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default(value: unknown, description?: string): this;
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* ```ts
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
* ```
*/
preset(arg: unknown): this;
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* ```ts
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
* ```
*/
conflicts(names: string | string[]): this;
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*/
implies(optionValues: OptionValues): this;
/**
* Set environment variable to check for option value.
*
* An environment variables is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*/
env(name: string): this;
/**
* Set the custom handler for processing CLI option arguments into option values.
*/
argParser<T>(fn: (value: string, previous: T) => T): this;
/**
* Whether the option is mandatory and must have a value after parsing.
*/
makeOptionMandatory(mandatory?: boolean): this;
/**
* Hide option in help.
*/
hideHelp(hide?: boolean): this;
/**
* Only allow option value to be one of choices.
*/
choices(values: readonly string[]): this;
/**
* Return option name.
*/
name(): string;
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*/
attributeName(): string;
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*/
isBoolean(): boolean;
}
export class Help {
/** output helpWidth, long lines are wrapped to fit */
helpWidth?: number;
sortSubcommands: boolean;
sortOptions: boolean;
showGlobalOptions: boolean;
constructor();
/** Get the command term to show in the list of subcommands. */
subcommandTerm(cmd: Command): string;
/** Get the command summary to show in the list of subcommands. */
subcommandDescription(cmd: Command): string;
/** Get the option term to show in the list of options. */
optionTerm(option: Option): string;
/** Get the option description to show in the list of options. */
optionDescription(option: Option): string;
/** Get the argument term to show in the list of arguments. */
argumentTerm(argument: Argument): string;
/** Get the argument description to show in the list of arguments. */
argumentDescription(argument: Argument): string;
/** Get the command usage to be displayed at the top of the built-in help. */
commandUsage(cmd: Command): string;
/** Get the description for the command. */
commandDescription(cmd: Command): string;
/** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
visibleCommands(cmd: Command): Command[];
/** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
visibleOptions(cmd: Command): Option[];
/** Get an array of the visible global options. (Not including help.) */
visibleGlobalOptions(cmd: Command): Option[];
/** Get an array of the arguments which have descriptions. */
visibleArguments(cmd: Command): Argument[];
/** Get the longest command term length. */
longestSubcommandTermLength(cmd: Command, helper: Help): number;
/** Get the longest option term length. */
longestOptionTermLength(cmd: Command, helper: Help): number;
/** Get the longest global option term length. */
longestGlobalOptionTermLength(cmd: Command, helper: Help): number;
/** Get the longest argument term length. */
longestArgumentTermLength(cmd: Command, helper: Help): number;
/** Calculate the pad width from the maximum term length. */
padWidth(cmd: Command, helper: Help): number;
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*/
wrap(
str: string,
width: number,
indent: number,
minColumnWidth?: number,
): string;
/** Generate the built-in help text. */
formatHelp(cmd: Command, helper: Help): string;
}
export type HelpConfiguration = Partial<Help>;
export interface ParseOptions {
from: 'node' | 'electron' | 'user';
}
export interface HelpContext {
// optional parameter for .help() and .outputHelp()
error: boolean;
}
export interface AddHelpTextContext {
// passed to text function used with .addHelpText()
error: boolean;
command: Command;
}
export interface OutputConfiguration {
writeOut?(str: string): void;
writeErr?(str: string): void;
getOutHelpWidth?(): number;
getErrHelpWidth?(): number;
outputError?(str: string, write: (str: string) => void): void;
}
export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
// The source is a string so author can define their own too.
export type OptionValueSource =
| LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string>
| undefined;
export type OptionValues = Record<string, any>;
export class Command {
args: string[];
processedArgs: any[];
readonly commands: readonly Command[];
readonly options: readonly Option[];
readonly registeredArguments: readonly Argument[];
parent: Command | null;
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): this;
/**
* Get the program version.
*/
version(): string | undefined;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(
nameAndArgs: string,
opts?: CommandOptions,
): ReturnType<this['createCommand']>;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns `this` command for chaining
*/
command(
nameAndArgs: string,
description: string,
opts?: ExecutableCommandOptions,
): this;
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*/
createCommand(name?: string): Command;
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @returns `this` command for chaining
*/
addCommand(cmd: Command, opts?: CommandOptions): this;
/**
* Factory routine to create a new unattached argument.
*
* See .argument() for creating an attached argument, which uses this routine to
* create the argument. You can override createArgument to return a custom argument.
*/
createArgument(name: string, description?: string): Argument;
/**
* Define argument syntax for command.
*
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @example
* ```
* program.argument('<input-file>');
* program.argument('[output-file]');
* ```
*
* @returns `this` command for chaining
*/
argument<T>(
flags: string,
description: string,
fn: (value: string, previous: T) => T,
defaultValue?: T,
): this;
argument(name: string, description?: string, defaultValue?: unknown): this;
/**
* Define argument syntax for command, adding a prepared argument.
*
* @returns `this` command for chaining
*/
addArgument(arg: Argument): this;
/**
* Define argument syntax for command, adding multiple at once (without descriptions).
*
* See also .argument().
*
* @example
* ```
* program.arguments('<cmd> [env]');
* ```
*
* @returns `this` command for chaining
*/
arguments(names: string): this;
/**
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
*
* @example
* ```ts
* program.helpCommand('help [cmd]');
* program.helpCommand('help [cmd]', 'show help');
* program.helpCommand(false); // suppress default help command
* program.helpCommand(true); // add help command even if no subcommands
* ```
*/
helpCommand(nameAndArgs: string, description?: string): this;
helpCommand(enable: boolean): this;
/**
* Add prepared custom help command.
*/
addHelpCommand(cmd: Command): this;
/** @deprecated since v12, instead use helpCommand */
addHelpCommand(nameAndArgs: string, description?: string): this;
/** @deprecated since v12, instead use helpCommand */
addHelpCommand(enable?: boolean): this;
/**
* Add hook for life cycle event.
*/
hook(
event: HookEvent,
listener: (
thisCommand: Command,
actionCommand: Command,
) => void | Promise<void>,
): this;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never | void): this;
/**
* Display error message and exit (or call exitOverride).
*/
error(message: string, errorOptions?: ErrorOptions): never;
/**
* You can customise the help with a subclass of Help by overriding createHelp,
* or by overriding Help properties using configureHelp().
*/
createHelp(): Help;
/**
* You can customise the help by overriding Help properties using configureHelp(),
* or with a subclass of Help by overriding createHelp().
*/
configureHelp(configuration: HelpConfiguration): this;
/** Get configuration */
configureHelp(): HelpConfiguration;
/**
* The default output goes to stdout and stderr. You can customise this for special
* applications. You can also customise the display of errors by overriding outputError.
*
* The configuration properties are all functions:
* ```
* // functions to change where being written, stdout and stderr
* writeOut(str)
* writeErr(str)
* // matching functions to specify width for wrapping help
* getOutHelpWidth()
* getErrHelpWidth()
* // functions based on what is being written out
* outputError(str, write) // used for displaying errors, and not used for displaying help
* ```
*/
configureOutput(configuration: OutputConfiguration): this;
/** Get configuration */
configureOutput(): OutputConfiguration;
/**
* Copy settings that are useful to have in common across root command and subcommands.
*
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
*/
copyInheritedSettings(sourceCommand: Command): this;
/**
* Display the help or a custom message after an error occurs.
*/
showHelpAfterError(displayHelp?: boolean | string): this;
/**
* Display suggestion of similar commands for unknown commands, or options for unknown options.
*/
showSuggestionAfterError(displaySuggestion?: boolean): this;
/**
* Register callback `fn` for the command.
*
* @example
* ```
* program
* .command('serve')
* .description('start service')
* .action(function() {
* // do work here
* });
* ```
*
* @returns `this` command for chaining
*/
action(fn: (...args: any[]) => void | Promise<void>): this;
/**
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
*
* See the README for more details, and see also addOption() and requiredOption().
*
* @example
*
* ```js
* program
* .option('-p, --pepper', 'add pepper')
* .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
* ```
*
* @returns `this` command for chaining
*/
option(
flags: string,
description?: string,
defaultValue?: string | boolean | string[],
): this;
option<T>(
flags: string,
description: string,
parseArg: (value: string, previous: T) => T,
defaultValue?: T,
): this;
/** @deprecated since v7, instead use choices or a custom function */
option(
flags: string,
description: string,
regexp: RegExp,
defaultValue?: string | boolean | string[],
): this;
/**
* Define a required option, which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
*/
requiredOption(
flags: string,
description?: string,
defaultValue?: string | boolean | string[],
): this;
requiredOption<T>(
flags: string,
description: string,
parseArg: (value: string, previous: T) => T,
defaultValue?: T,
): this;
/** @deprecated since v7, instead use choices or a custom function */
requiredOption(
flags: string,
description: string,
regexp: RegExp,
defaultValue?: string | boolean | string[],
): this;
/**
* Factory routine to create a new unattached option.
*
* See .option() for creating an attached option, which uses this routine to
* create the option. You can override createOption to return a custom option.
*/
createOption(flags: string, description?: string): Option;
/**
* Add a prepared Option.
*
* See .option() and .requiredOption() for creating and attaching an option in a single call.
*/
addOption(option: Option): this;
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @returns `this` command for chaining
*/
storeOptionsAsProperties<T extends OptionValues>(): this & T;
storeOptionsAsProperties<T extends OptionValues>(
storeAsProperties: true,
): this & T;
storeOptionsAsProperties(storeAsProperties?: boolean): this;
/**
* Retrieve option value.
*/
getOptionValue(key: string): any;
/**
* Store option value.
*/
setOptionValue(key: string, value: unknown): this;
/**
* Store option value and where the value came from.
*/
setOptionValueWithSource(
key: string,
value: unknown,
source: OptionValueSource,
): this;
/**
* Get source of option value.
*/
getOptionValueSource(key: string): OptionValueSource | undefined;
/**
* Get source of option value. See also .optsWithGlobals().
*/
getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
/**
* Alter parsing of short flags with optional values.
*
* @example
* ```
* // for `.option('-f,--flag [value]'):
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
* ```
*
* @returns `this` command for chaining
*/
combineFlagAndOptionalValue(combine?: boolean): this;
/**
* Allow unknown options on the command line.
*
* @returns `this` command for chaining
*/
allowUnknownOption(allowUnknown?: boolean): this;
/**
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
*
* @returns `this` command for chaining
*/
allowExcessArguments(allowExcess?: boolean): this;
/**
* Enable positional options. Positional means global options are specified before subcommands which lets
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
*
* The default behaviour is non-positional and global options may appear anywhere on the command line.
*
* @returns `this` command for chaining
*/
enablePositionalOptions(positional?: boolean): this;
/**
* Pass through options that come after command-arguments rather than treat them as command-options,
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
* positional options to have been enabled on the program (parent commands).
*
* The default behaviour is non-positional and options may appear before or after command-arguments.
*
* @returns `this` command for chaining
*/
passThroughOptions(passThrough?: boolean): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async.
*
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
*
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
* - `'user'`: just user arguments
*
* @example
* ```
* program.parse(); // parse process.argv and auto-detect electron and special node flags
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
* ```
*
* @returns `this` command for chaining
*/
parse(argv?: readonly string[], parseOptions?: ParseOptions): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
*
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
* - `'user'`: just user arguments
*
* @example
* ```
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
* ```
*
* @returns Promise
*/
parseAsync(
argv?: readonly string[],
parseOptions?: ParseOptions,
): Promise<this>;
/**
* Parse options from `argv` removing known options,
* and return argv split into operands and unknown arguments.
*
* argv => operands, unknown
* --known kkk op => [op], []
* op --known kkk => [op], []
* sub --unknown uuu op => [sub], [--unknown uuu op]
* sub -- --unknown uuu op => [sub --unknown uuu op], []
*/
parseOptions(argv: string[]): ParseOptionsResult;
/**
* Return an object containing local option values as key-value pairs
*/
opts<T extends OptionValues>(): T;
/**
* Return an object containing merged local and global option values as key-value pairs.
*/
optsWithGlobals<T extends OptionValues>(): T;
/**
* Set the description.
*
* @returns `this` command for chaining
*/
description(str: string): this;
/** @deprecated since v8, instead use .argument to add command argument with description */
description(str: string, argsDescription: Record<string, string>): this;
/**
* Get the description.
*/
description(): string;
/**
* Set the summary. Used when listed as subcommand of parent.
*
* @returns `this` command for chaining
*/
summary(str: string): this;
/**
* Get the summary.
*/
summary(): string;
/**
* Set an alias for the command.
*
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
alias(alias: string): this;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set aliases for the command.
*
* Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
aliases(aliases: readonly string[]): this;
/**
* Get aliases for the command.
*/
aliases(): string[];
/**
* Set the command usage.
*
* @returns `this` command for chaining
*/
usage(str: string): this;
/**
* Get the command usage.
*/
usage(): string;
/**
* Set the name of the command.
*
* @returns `this` command for chaining
*/
name(str: string): this;
/**
* Get the name of the command.
*/
name(): string;
/**
* Set the name of the command from script filename, such as process.argv[1],
* or require.main.filename, or __filename.
*
* (Used internally and public although not documented in README.)
*
* @example
* ```ts
* program.nameFromFilename(require.main.filename);
* ```
*
* @returns `this` command for chaining
*/
nameFromFilename(filename: string): this;
/**
* Set the directory for searching for executable subcommands of this command.
*
* @example
* ```ts
* program.executableDir(__dirname);
* // or
* program.executableDir('subcommands');
* ```
*
* @returns `this` command for chaining
*/
executableDir(path: string): this;
/**
* Get the executable search directory.
*/
executableDir(): string | null;
/**
* Output help information for this command.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*
*/
outputHelp(context?: HelpContext): void;
/** @deprecated since v7 */
outputHelp(cb?: (str: string) => string): void;
/**
* Return command help documentation.
*/
helpInformation(context?: HelpContext): string;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command. Pass in false
* to disable the built-in help option.
*/
helpOption(flags?: string | boolean, description?: string): this;
/**
* Supply your own option to use for the built-in help option.
* This is an alternative to using helpOption() to customise the flags and description etc.
*/
addHelpOption(option: Option): this;
/**
* Output help information and exit.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*/
help(context?: HelpContext): never;
/** @deprecated since v7 */
help(cb?: (str: string) => string): never;
/**
* Add additional text to be displayed with the built-in help.
*
* Position is 'before' or 'after' to affect just this command,
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
*/
addHelpText(position: AddHelpTextPosition, text: string): this;
addHelpText(
position: AddHelpTextPosition,
text: (context: AddHelpTextContext) => string,
): this;
/**
* Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
*/
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface CommandOptions {
hidden?: boolean;
isDefault?: boolean;
/** @deprecated since v7, replaced by hidden */
noHelp?: boolean;
}
export interface ExecutableCommandOptions extends CommandOptions {
executableFile?: string;
}
export interface ParseOptionsResult {
operands: string[];
unknown: string[];
}
export function createCommand(name?: string): Command;
export function createOption(flags: string, description?: string): Option;
export function createArgument(name: string, description?: string): Argument;
export const program: Command;

View File

@@ -0,0 +1,190 @@
{
"metapak": {
"configs": [
"main",
"readme",
"tsesm",
"jest",
"eslint",
"codeclimate",
"ghactions"
],
"data": {
"files": "'src/**/*.ts'",
"testsFiles": "'src/**/*.test.ts'",
"distFiles": "'dist/**/*.js'",
"ignore": [
"dist",
"fixtures/results"
],
"bundleFiles": [
"dist",
"src",
"bin"
]
}
},
"name": "svgicons2svgfont",
"version": "15.0.1",
"description": "Read a set of SVG icons and output a SVG font",
"homepage": "https://github.com/nfroidure/svgicons2svgfont",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"scripts": {
"build": "rimraf 'dist' && tsc --outDir dist",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s && git add CHANGELOG.md",
"cli": "env NODE_ENV=${NODE_ENV:-cli}",
"cover": "npm run jest -- --coverage",
"cz": "env NODE_ENV=${NODE_ENV:-cli} git cz",
"format": "npm run prettier",
"jest": "NODE_OPTIONS=--experimental-vm-modules NODE_ENV=test jest",
"lint": "eslint 'src/**/*.ts'",
"metapak": "metapak",
"precz": "npm run build && npm t && npm run lint && npm run metapak -- -s",
"prettier": "prettier --write 'src/**/*.ts'",
"preversion": "npm run build && npm t && npm run lint && npm run metapak -- -s",
"rebuild": "swc ./src -s -d dist -C jsc.target=es2022",
"test": "npm run jest",
"type-check": "tsc --pretty --noEmit",
"version": "npm run changelog"
},
"repository": {
"type": "git",
"url": "git://github.com/nfroidure/svgicons2svgfont"
},
"keywords": [
"SVG",
"icons",
"font",
"creation",
"fonts"
],
"engines": {
"node": ">=20.11.1"
},
"dependencies": {
"@types/sax": "^1.2.7",
"commander": "^12.1.0",
"debug": "^4.3.6",
"glob": "^11.0.0",
"sax": "^1.4.1",
"svg-pathdata": "^7.0.0",
"transformation-matrix": "^3.0.0",
"yerror": "^8.0.0"
},
"devDependencies": {
"@eslint/js": "^9.7.0",
"@swc/cli": "^0.4.0",
"@swc/core": "^1.6.13",
"@swc/helpers": "^0.5.12",
"@swc/jest": "^0.2.36",
"bufferstreams": "^4.0.0",
"commitizen": "^4.3.0",
"conventional-changelog-cli": "^5.0.0",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^9.7.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.6.0",
"eslint-plugin-prettier": "^5.1.3",
"jest": "^29.7.0",
"metapak": "^6.0.1",
"metapak-nfroidure": "^18.2.0",
"prettier": "^3.3.3",
"rimraf": "^6.0.1",
"streamtest": "^3.0.1",
"typescript": "^5.5.3",
"typescript-eslint": "^7.16.0"
},
"author": {
"name": "Nicolas Froidure",
"email": "nicolas.froidure@insertafter.com",
"url": "http://insertafter.com/en/index.html"
},
"contributors": [
{
"name": "Adrian Leonhard",
"email": "adrianleonhard@gmail.com",
"url": "https://github.com/NaridaL"
},
{
"name": "Vinicius Teixeira",
"email": "vinicius0026@gmail.com",
"url": "https://github.com/vinicius0026"
}
],
"license": "MIT",
"bugs": {
"url": "https://github.com/nfroidure/svgicons2svgfont/issues"
},
"bin": {
"svgicons2svgfont": "bin/svgicons2svgfont.js"
},
"files": [
"dist",
"src",
"bin",
"LICENSE",
"README.md",
"CHANGELOG.md"
],
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"greenkeeper": {
"ignore": [
"commitizen",
"cz-conventional-changelog",
"conventional-changelog-cli",
"typescript",
"rimraf",
"@swc/cli",
"@swc/core",
"@swc/helpers",
"jest",
"@swc/jest",
"eslint",
"prettier",
"eslint-config-prettier",
"eslint-plugin-prettier",
"typescript-eslint"
]
},
"jest": {
"coverageReporters": [
"lcov"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"roots": [
"<rootDir>/src"
],
"transform": {
"^.+\\.tsx?$": [
"@swc/jest",
{}
]
},
"testEnvironment": "node",
"moduleNameMapper": {
"(.+)\\.js": "$1"
},
"extensionsToTreatAsEsm": [
".ts"
],
"prettierPath": null
},
"prettier": {
"semi": true,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "all",
"proseWrap": "always"
},
"overrides": {
"eslint": "^9.7.0"
}
}

View File

@@ -0,0 +1,16 @@
const testExpression = /(^|\/|\\)(?:((?:u[0-9a-f]{4,6},?)+)-)(.+)\.svg$/i;
export function fileSorter(fileA, fileB) {
const hasUnicodeA = testExpression.test(fileA);
const hasUnicodeB = testExpression.test(fileB);
if (hasUnicodeA == hasUnicodeB) {
// just compare alphabetically
const fileA_ = fileA.substr(0, fileA.lastIndexOf('.'));
const fileB_ = fileB.substr(0, fileB.lastIndexOf('.'));
return fileA_ < fileB_ ? -1 : 1;
} else {
// map true to 0, because we want it to be first
return (hasUnicodeA ? 0 : 1) - (hasUnicodeB ? 0 : 1);
}
}

View File

@@ -0,0 +1,122 @@
import { Readable } from 'node:stream';
import { createReadStream, readdir } from 'node:fs';
import { fileSorter } from './filesorter.js';
import {
getMetadataService,
FileMetadata,
MetadataServiceOptions,
} from './metadata.js';
import debug from 'debug';
const warn = debug('svgicons2svgfont');
export type SVGIconsDirStreamOptions = {
metadataProvider: ReturnType<typeof getMetadataService>;
};
export type SVGIconStream = Readable & {
metadata: Pick<FileMetadata, 'name' | 'unicode'>;
};
class SVGIconsDirStream extends Readable {
private _options: SVGIconsDirStreamOptions & Partial<MetadataServiceOptions>;
gotFilesInfos: boolean = false;
fileInfos: FileMetadata[] = [];
dir: string;
constructor(
dir: string[],
options: Partial<SVGIconsDirStreamOptions & MetadataServiceOptions>,
) {
super({ objectMode: true });
this._options = {
metadataProvider: options.metadataProvider || getMetadataService(options),
};
if (dir instanceof Array) {
this.dir = '';
this._getFilesInfos(dir);
} else {
this.dir = dir;
}
}
_getFilesInfos(files) {
let filesProcessed = 0;
this.fileInfos = [];
// Ensure prefixed files come first
files = files.slice(0).sort(fileSorter);
files.forEach((file) => {
this._options.metadataProvider(
(this.dir ? this.dir + '/' : '') + file,
(err, metadata) => {
filesProcessed++;
if (err) {
this.emit('error', err);
}
if (metadata) {
if (metadata.renamed) {
warn(
' - Saved codepoint: ' +
'u' +
metadata.unicode[0]
.codePointAt(0)
?.toString(16)
.toUpperCase() +
' for the glyph "' +
metadata.name +
'"',
);
}
this.fileInfos.push(metadata);
}
if (files.length === filesProcessed) {
// Reorder files
this.fileInfos.sort((infosA, infosB) =>
infosA.unicode[0] > infosB.unicode[0] ? 1 : -1,
);
// Mark directory as processed
this.gotFilesInfos = true;
// Start processing
this._pushSVGIcons();
}
},
);
});
}
_pushSVGIcons() {
let fileInfo: FileMetadata;
let svgIconStream: SVGIconStream;
while (this.fileInfos.length) {
fileInfo = this.fileInfos.shift() as FileMetadata;
svgIconStream = createReadStream(
fileInfo.path,
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: fileInfo.name,
unicode: fileInfo.unicode,
};
if (!this.push(svgIconStream)) {
return;
}
}
this.push(null);
}
_read() {
if (this.dir) {
readdir(this.dir, (err, files) => {
if (err) {
this.emit('error', err);
}
this._getFilesInfos(files);
});
return;
}
if (this.gotFilesInfos) {
this._pushSVGIcons();
}
}
}
export { SVGIconsDirStream };

View File

@@ -0,0 +1,580 @@
import { Transform } from 'stream';
import Sax from 'sax';
import { SVGPathData } from 'svg-pathdata';
import svgShapesToPath from './svgshapes2svgpath.js';
import {
type Matrix,
scale,
translate,
compose,
fromDefinition,
fromTransformAttribute,
} from 'transformation-matrix';
import { YError } from 'yerror';
import debug from 'debug';
const warn = debug('svgicons2svgfont');
export { fileSorter } from './filesorter.js';
export * from './iconsdir.js';
export * from './metadata.js';
function matrixFromTransformAttribute(transformAttributeString): Matrix {
return compose(
fromDefinition(fromTransformAttribute(transformAttributeString)),
);
}
// Rendering
function tagShouldRender(curTag, parents) {
let values;
return !parents.some((tag) => {
if (
'undefined' !== typeof tag.attributes.display &&
'none' === tag.attributes.display.toLowerCase()
) {
return true;
}
if (
'undefined' !== typeof tag.attributes.width &&
0 === parseFloat(tag.attributes.width)
) {
return true;
}
if (
'undefined' !== typeof tag.attributes.height &&
0 === parseFloat(tag.attributes.height)
) {
return true;
}
if ('undefined' !== typeof tag.attributes.viewBox) {
values = tag.attributes.viewBox.split(/\s*,*\s|\s,*\s*|,/);
if (0 === parseFloat(values[2]) || 0 === parseFloat(values[3])) {
return true;
}
}
return false;
});
}
// According to the document (http://www.w3.org/TR/SVG/painting.html#FillProperties)
// fill <paint> none|currentColor|inherit|<color>
// [<icccolor>]|<funciri> (not support yet)
function getTagColor(currTag, parents) {
const defaultColor = 'black';
const fillVal = currTag.attributes.fill;
let color;
const parentsLength = parents.length;
if ('none' === fillVal) {
return color;
}
if ('currentColor' === fillVal) {
return defaultColor;
}
if ('inherit' === fillVal) {
if (0 === parentsLength) {
return defaultColor;
}
return getTagColor(
parents[parentsLength - 1],
parents.slice(0, parentsLength - 1),
);
// this might be null.
// For example: <svg ><path fill="inherit" /> </svg>
// in this case getTagColor should return null
// recursive call, the bottom element should be svg,
// and svg didn't fill color, so just return null
}
return fillVal;
}
export type SVGIcons2SVGFontStreamOptions = {
fontName: string;
fontId: string;
fixedWidth: boolean;
descent: number;
ascent?: number;
round: number;
metadata: string;
usePathBounds: boolean;
normalize?: boolean;
preserveAspectRatio?: boolean;
centerHorizontally?: boolean;
centerVertically?: boolean;
fontWeight?: number;
fontHeight?: number;
fontStyle?: string;
callback?: (glyphs: Glyph[]) => void;
};
export type Glyph = {
name: string;
width: number;
height: number;
defaultHeight?: number;
defaultWidth?: number;
unicode: string[];
paths?: SVGPathData[];
};
export class SVGIcons2SVGFontStream extends Transform {
private _options: SVGIcons2SVGFontStreamOptions;
glyphs: Glyph[];
constructor(options: Partial<SVGIcons2SVGFontStreamOptions>) {
super({ objectMode: true });
this.glyphs = [];
this._options = {
...options,
fontName: options.fontName || 'iconfont',
fontId: options.fontId || options.fontName || 'iconfont',
fixedWidth: options.fixedWidth || false,
descent: options.descent || 0,
round: options.round || 10e12,
metadata: options.metadata || '',
usePathBounds: options.usePathBounds || false,
};
}
_transform(svgIconStream, _unused, svgIconStreamCallback) {
// Parsing each icons asynchronously
const saxStream = Sax.createStream(true);
const parents: (Sax.Tag | Sax.QualifiedTag)[] = [];
const transformStack: Matrix[] = [];
function applyTransform(d) {
const last = transformStack[transformStack.length - 1];
if (!last) return new SVGPathData(d);
return new SVGPathData(d).matrix(
last.a,
last.b,
last.c,
last.d,
last.e,
last.f,
);
}
const glyph = svgIconStream.metadata || {};
// init width and height os they aren't undefined if <svg> isn't renderable
glyph.width = 0;
glyph.height = 1;
glyph.paths = [];
this.glyphs.push(glyph);
if ('string' !== typeof glyph.name) {
this.emit(
'error',
new Error(
`Please provide a name for the glyph at index ${
this.glyphs.length - 1
}`,
),
);
}
if (
this.glyphs.some(
(anotherGlyph) =>
anotherGlyph !== glyph && anotherGlyph.name === glyph.name,
)
) {
this.emit(
'error',
new Error(`The glyph name "${glyph.name}" must be unique.`),
);
}
if (
glyph.unicode &&
glyph.unicode instanceof Array &&
glyph.unicode.length
) {
if (
glyph.unicode.some((unicodeA, i) =>
glyph.unicode.some((unicodeB, j) => i !== j && unicodeA === unicodeB),
)
) {
this.emit(
'error',
new Error(
`Given codepoints for the glyph "${glyph.name}" contain duplicates.`,
),
);
}
} else if ('string' !== typeof glyph.unicode) {
this.emit(
'error',
new Error(`Please provide a codepoint for the glyph "${glyph.name}"`),
);
}
if (
this.glyphs.some(
(anotherGlyph) =>
anotherGlyph !== glyph && anotherGlyph.unicode === glyph.unicode,
)
) {
this.emit(
'error',
new Error(
`The glyph "${glyph.name}" codepoint seems to be used already elsewhere.`,
),
);
}
saxStream.on('opentag', (tag) => {
let values;
let color;
parents.push(tag);
try {
const currentTransform = transformStack[transformStack.length - 1];
if ('undefined' !== typeof tag.attributes.transform) {
const transform = matrixFromTransformAttribute(
tag.attributes.transform,
);
transformStack.push(
compose([currentTransform, transform].filter(Boolean)),
);
} else {
transformStack.push(currentTransform);
}
// Checking if any parent rendering is disabled and exit if so
if (!tagShouldRender(tag, parents)) {
return;
}
// Save the view size
if ('svg' === tag.name) {
if ('viewBox' in tag.attributes) {
values = (tag.attributes.viewBox as string).split(
/\s*,*\s|\s,*\s*|,/,
);
const dX = parseFloat(values[0]);
const dY = parseFloat(values[1]);
const width = parseFloat(values[2]);
const height = parseFloat(values[3]);
// use the viewBox width/height if not specified explictly
glyph.width =
'width' in tag.attributes
? parseFloat(tag.attributes.width as string)
: width;
glyph.height =
'height' in tag.attributes
? parseFloat(tag.attributes.height as string)
: height;
transformStack[transformStack.length - 1] = compose(
[
transformStack[transformStack.length - 1],
translate(-dX, -dY),
scale(glyph.width / width, glyph.height / height),
].filter(Boolean),
);
} else {
if ('width' in tag.attributes) {
glyph.width = parseFloat(tag.attributes.width as string);
} else {
warn(
`⚠️ - Glyph "${glyph.name}" has no width attribute, using current glyph horizontal bounds.`,
);
glyph.defaultWidth = true;
}
if ('height' in tag.attributes) {
glyph.height = parseFloat(tag.attributes.height as string);
} else {
warn(
`⚠️ - Glyph "${glyph.name}" has no height attribute, using current glyph vertical bounds.`,
);
glyph.defaultHeight = true;
}
}
} else if ('clipPath' === tag.name) {
// Clipping path unsupported
warn(
`🤷 - Found a clipPath element in the icon "${glyph.name}" the result may be different than expected.`,
);
} else if ('rect' === tag.name && 'none' !== tag.attributes.fill) {
glyph.paths.push(
applyTransform(svgShapesToPath.rectToPath(tag.attributes)),
);
} else if ('line' === tag.name && 'none' !== tag.attributes.fill) {
warn(
`🤷 - Found a line element in the icon "${glyph.name}" the result could be different than expected.`,
);
glyph.paths.push(
applyTransform(svgShapesToPath.lineToPath(tag.attributes)),
);
} else if ('polyline' === tag.name && 'none' !== tag.attributes.fill) {
warn(
`🤷 - Found a polyline element in the icon "${glyph.name}" the result could be different than expected.`,
);
glyph.paths.push(
applyTransform(svgShapesToPath.polylineToPath(tag.attributes)),
);
} else if ('polygon' === tag.name && 'none' !== tag.attributes.fill) {
glyph.paths.push(
applyTransform(svgShapesToPath.polygonToPath(tag.attributes)),
);
} else if (
['circle', 'ellipse'].includes(tag.name) &&
'none' !== tag.attributes.fill
) {
glyph.paths.push(
applyTransform(svgShapesToPath.circleToPath(tag.attributes)),
);
} else if (
'path' === tag.name &&
tag.attributes.d &&
'none' !== tag.attributes.fill
) {
glyph.paths.push(applyTransform(tag.attributes.d));
}
// According to http://www.w3.org/TR/SVG/painting.html#SpecifyingPaint
// Map attribute fill to color property
if ('none' !== tag.attributes.fill) {
color = getTagColor(tag, parents);
if ('undefined' !== typeof color) {
glyph.color = color;
}
}
} catch (err) {
this.emit(
'error',
new Error(
`Got an error parsing the glyph "${glyph.name}": ${(err as Error)?.message}.`,
),
);
}
});
saxStream.on('error', (err) => {
this.emit('error', err);
});
saxStream.on('closetag', () => {
transformStack.pop();
parents.pop();
});
saxStream.on('end', () => {
svgIconStreamCallback();
});
svgIconStream.pipe(saxStream);
}
_flush(svgFontFlushCallback) {
this.glyphs.forEach((glyph) => {
if (
glyph.defaultHeight ||
glyph.defaultWidth ||
this._options.usePathBounds
) {
const glyphPath = new SVGPathData('');
(glyph.paths || []).forEach((path) => {
glyphPath.commands.push(...path.commands);
});
const bounds = glyphPath.getBounds();
if (glyph.defaultHeight || this._options.usePathBounds) {
glyph.height = bounds.maxY - bounds.minY;
}
if (glyph.defaultWidth || this._options.usePathBounds) {
glyph.width = bounds.maxX - bounds.minX;
}
}
});
const maxGlyphHeight = this.glyphs.reduce(
(curMax, glyph) => Math.max(curMax, glyph.height),
0,
);
const maxGlyphWidth = this.glyphs.reduce(
(curMax, glyph) => Math.max(curMax, glyph.width),
0,
);
const fontHeight = this._options.fontHeight || maxGlyphHeight;
let fontWidth = maxGlyphWidth;
if (this._options.normalize) {
fontWidth = this.glyphs.reduce(
(curMax, glyph) =>
Math.max(curMax, (fontHeight / glyph.height) * glyph.width),
0,
);
} else if (this._options.fontHeight) {
// even if normalize is off, we need to scale the fontWidth if we have a custom fontHeight
fontWidth *= fontHeight / maxGlyphHeight;
}
this._options.ascent =
'undefined' !== typeof this._options.ascent
? this._options.ascent
: fontHeight - this._options.descent;
if (
!this._options.normalize &&
fontHeight >
(1 < this.glyphs.length
? this.glyphs.reduce(
(curMin, glyph) => Math.min(curMin, glyph.height),
Infinity,
)
: this.glyphs[0].height)
) {
warn(
'🤷 - The provided icons do not have the same heights. This could lead' +
' to unexpected results. Using the normalize option may help.',
);
}
if (1000 > fontHeight) {
warn(
'🤷 - A fontHeight of at least than 1000 is recommended, otherwise ' +
'further steps (rounding in svg2ttf) could lead to ugly results.' +
' Use the fontHeight option to scale icons.',
);
}
// Output the SVG file
// (find a SAX parser that allows modifying SVG on the fly)
this.push(
'<?xml version="1.0" standalone="no"?>\n' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >\n' +
'<svg xmlns="http://www.w3.org/2000/svg">\n' +
(this._options.metadata
? '<metadata>' + this._options.metadata + '</metadata>\n'
: '') +
'<defs>\n' +
' <font id="' +
this._options.fontId +
'" horiz-adv-x="' +
fontWidth +
'">\n' +
' <font-face font-family="' +
this._options.fontName +
'"\n' +
' units-per-em="' +
fontHeight +
'" ascent="' +
this._options.ascent +
'"\n' +
' descent="' +
this._options.descent +
'"' +
(this._options.fontWeight
? '\n font-weight="' + this._options.fontWeight + '"'
: '') +
(this._options.fontStyle
? '\n font-style="' + this._options.fontStyle + '"'
: '') +
' />\n' +
' <missing-glyph horiz-adv-x="0" />\n',
);
this.glyphs.forEach((glyph) => {
const ratio = this._options.normalize
? fontHeight /
(this._options.preserveAspectRatio && glyph.width > glyph.height
? glyph.width
: glyph.height)
: fontHeight / maxGlyphHeight;
if (!isFinite(ratio)) {
throw new YError('E_BAD_COMPUTED_RATIO', ratio);
}
glyph.width *= ratio;
glyph.height *= ratio;
const glyphPath = new SVGPathData('');
if (this._options.fixedWidth) {
glyph.width = fontWidth;
}
const yOffset = glyph.height - this._options.descent;
let glyphPathTransform: Matrix = {
a: 1,
b: 0,
c: 0,
d: -1,
e: 0,
f: yOffset,
}; // ySymmetry
if (1 !== ratio) {
glyphPathTransform = compose(glyphPathTransform, scale(ratio, ratio));
}
(glyph.paths || []).forEach((path) => {
glyphPath.commands.push(
...path
.toAbs()
.matrix(
glyphPathTransform.a,
glyphPathTransform.b,
glyphPathTransform.c,
glyphPathTransform.d,
glyphPathTransform.e,
glyphPathTransform.f,
).commands,
);
});
const bounds =
(this._options.centerHorizontally || this._options.centerVertically) &&
glyphPath.getBounds();
if (this._options.centerHorizontally && bounds && 'maxX' in bounds) {
glyphPath.translate(
(glyph.width - (bounds.maxX - bounds.minX)) / 2 - bounds.minX,
);
}
if (this._options.centerVertically && bounds && 'maxX' in bounds) {
glyphPath.translate(
0,
(fontHeight - (bounds.maxY - bounds.minY)) / 2 -
bounds.minY -
this._options.descent,
);
}
delete glyph.paths;
const d = glyphPath.round(this._options.round).encode();
glyph.unicode.forEach((unicode, i) => {
const unicodeStr = [...unicode]
.map(
(char) =>
'&#x' + char.codePointAt(0)!.toString(16).toUpperCase() + ';',
)
.join('');
this.push(
' <glyph glyph-name="' +
glyph.name +
(0 === i ? '' : '-' + i) +
'"\n' +
' unicode="' +
unicodeStr +
'"\n' +
' horiz-adv-x="' +
glyph.width +
'" d="' +
d +
'" />\n',
);
});
});
this.push(' </font>\n' + '</defs>\n' + '</svg>\n');
warn('✅ - Font created');
if ('function' === typeof this._options.callback) {
this._options.callback(this.glyphs);
}
svgFontFlushCallback();
}
}

View File

@@ -0,0 +1,104 @@
import { join, dirname, basename } from 'node:path';
import { rename } from 'node:fs';
export type MetadataServiceOptions = {
prependUnicode: boolean;
startUnicode: number;
};
export type FileMetadata = {
path: string;
name: string;
unicode: string[] | string;
renamed: boolean;
};
function getMetadataService(options: Partial<MetadataServiceOptions> = {}) {
const usedUnicodes = [] as string[];
// Default options
const _options: MetadataServiceOptions = {
prependUnicode: !!options.prependUnicode,
startUnicode:
'number' === typeof options.startUnicode ? options.startUnicode : 0xea01,
};
return function getMetadataFromFile(
file: string,
cb: (error: Error | null, metadata?: FileMetadata) => void,
) {
const fileBasename = basename(file);
const metadata: FileMetadata = {
path: file,
name: '',
unicode: [],
renamed: false,
};
const matches = fileBasename.match(
/^(?:((?:u[0-9a-f]{4,6},?)+)-)?(.+)\.svg$/i,
);
metadata.name =
matches && matches[2] ? matches[2] : 'icon' + _options.startUnicode;
if (matches && matches[1]) {
metadata.unicode = matches[1].split(',').map((match) => {
match = match.substring(1);
return match
.split('u')
.map((code) => String.fromCodePoint(parseInt(code, 16)))
.join('');
});
if (-1 !== usedUnicodes.indexOf(metadata.unicode[0])) {
cb(
new Error(
'The unicode codepoint of the glyph ' +
metadata.name +
' seems to be already used by another glyph.',
),
);
return;
}
usedUnicodes.push(...metadata.unicode);
} else {
do {
(metadata.unicode as string[])[0] = String.fromCodePoint(
_options.startUnicode++,
);
} while (usedUnicodes.includes(metadata.unicode[0]));
usedUnicodes.push(metadata.unicode[0]);
if (_options.prependUnicode) {
metadata.renamed = true;
metadata.path = join(
dirname(file),
'u' +
metadata.unicode[0].codePointAt(0)?.toString(16).toUpperCase() +
'-' +
fileBasename,
);
rename(file, metadata.path, (err) => {
if (err) {
cb(
new Error(
'Could not save codepoint: ' +
'u' +
metadata.unicode[0]
.codePointAt(0)
?.toString(16)
.toUpperCase() +
' for ' +
fileBasename,
),
);
return;
}
cb(null, metadata);
});
}
}
if (!metadata.renamed) {
setImmediate(() => cb(null, metadata));
}
};
}
export { getMetadataService };

View File

@@ -0,0 +1,132 @@
const svgShapesToPath = {
rectToPath: svgShapesToPathRectToPath,
polylineToPath: svgShapesToPathPolylineToPath,
lineToPath: svgShapesToPathLineToPath,
circleToPath: svgShapesToPathCircleToPath,
polygonToPath: svgShapesToPathPolygonToPath,
};
export default svgShapesToPath;
// Shapes helpers (should also move elsewhere)
function svgShapesToPathRectToPath(attributes) {
const x = 'undefined' !== typeof attributes.x ? parseFloat(attributes.x) : 0;
const y = 'undefined' !== typeof attributes.y ? parseFloat(attributes.y) : 0;
const width =
'undefined' !== typeof attributes.width ? parseFloat(attributes.width) : 0;
const height =
'undefined' !== typeof attributes.height
? parseFloat(attributes.height)
: 0;
const rx =
'undefined' !== typeof attributes.rx
? parseFloat(attributes.rx)
: 'undefined' !== typeof attributes.ry
? parseFloat(attributes.ry)
: 0;
const ry =
'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : rx;
return (
'' +
// start at the left corner
'M' +
(x + rx) +
' ' +
y +
// top line
'h' +
(width - rx * 2) +
// upper right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry : '') +
// Draw right side
'v' +
(height - ry * 2) +
// Draw bottom right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry : '') +
// Down the down side
'h' +
(width - rx * 2) * -1 +
// Draw bottom right corner
(rx || ry
? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry * -1
: '') +
// Down the left side
'v' +
(height - ry * 2) * -1 +
// Draw bottom right corner
(rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry * -1 : '') +
// Close path
'z'
);
}
function svgShapesToPathPolylineToPath(attributes) {
return 'M' + attributes.points;
}
function svgShapesToPathLineToPath(attributes) {
// Move to the line start
return (
'' +
'M' +
(parseFloat(attributes.x1) || 0).toString(10) +
' ' +
(parseFloat(attributes.y1) || 0).toString(10) +
' ' +
((parseFloat(attributes.x1) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.y1) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.x2) || 0) + 1).toString(10) +
' ' +
((parseFloat(attributes.y2) || 0) + 1).toString(10) +
' ' +
(parseFloat(attributes.x2) || 0).toString(10) +
' ' +
(parseFloat(attributes.y2) || 0).toString(10) +
'Z'
);
}
function svgShapesToPathCircleToPath(attributes) {
const cx = parseFloat(attributes.cx || 0);
const cy = parseFloat(attributes.cy || 0);
const rx =
'undefined' !== typeof attributes.rx
? parseFloat(attributes.rx)
: parseFloat(attributes.r);
const ry =
'undefined' !== typeof attributes.ry
? parseFloat(attributes.ry)
: parseFloat(attributes.r);
// use two A commands because one command which returns to origin is invalid
return (
'' +
'M' +
(cx - rx) +
',' +
cy +
'A' +
rx +
',' +
ry +
' 0,0,0 ' +
(cx + rx) +
',' +
cy +
'A' +
rx +
',' +
ry +
' 0,0,0 ' +
(cx - rx) +
',' +
cy
);
}
function svgShapesToPathPolygonToPath(attributes) {
return 'M' + attributes.points + 'Z';
}

View File

@@ -0,0 +1,98 @@
import { describe, test, expect } from '@jest/globals';
import { readFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { exec } from 'node:child_process';
import { promisify } from 'node:util';
try {
await mkdir(join('fixtures', 'results'));
} catch (err) {
// empty
}
describe('Testing CLI', () => {
test('should work for simple SVG', async () => {
const command =
`${'node' + ' '}${join('bin', 'svgicons2svgfont.js')} -o ${join(
'fixtures',
'results',
'originalicons-cli.svg',
)} -s 0xE001` + ` ${join('fixtures', 'icons', 'originalicons', '*.svg')}`;
await promisify(exec)(command);
expect(
await readFile(join('fixtures', 'results', 'originalicons-cli.svg'), {
encoding: 'utf8',
}),
).toEqual(
await readFile(join('fixtures', 'expected', 'originalicons-cli.svg'), {
encoding: 'utf8',
}),
);
});
test('should work for more than 32 SVG icons', async () => {
const command =
'node' +
' ' +
join('bin', 'svgicons2svgfont.js') +
' -o ' +
join('fixtures', 'results', 'lotoficons-cli.svg') +
' -s 0xE001' +
' -r 1e4' +
' ' +
join('fixtures', 'icons', 'cleanicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'hiddenpathesicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'multipathicons', 'kikoolol.svg') +
' ' +
join('fixtures', 'icons', 'originalicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'realicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'roundedcorners', '*.svg') +
' ' +
join('fixtures', 'icons', 'shapeicons', '*.svg') +
' ' +
join('fixtures', 'icons', 'tocentericons', '*.svg');
await promisify(exec)(command);
expect(
await readFile(join('fixtures', 'results', 'lotoficons-cli.svg'), {
encoding: 'utf8',
}),
).toEqual(
await readFile(join('fixtures', 'expected', 'lotoficons-cli.svg'), {
encoding: 'utf8',
}),
);
});
describe('with nested icons', () => {
test('should work', async () => {
const command = `${'node' + ' '}${join(
'bin',
'svgicons2svgfont.js',
)} -o ${join(
'fixtures',
'results',
'nestedicons-cli.svg',
)} ${join('fixtures', 'icons', 'nestedicons', '*.svg')}`;
await promisify(exec)(command);
expect(
await readFile(join('fixtures', 'results', 'nestedicons-cli.svg'), {
encoding: 'utf8',
}),
).toEqual(
await readFile(join('fixtures', 'expected', 'nestedicons-cli.svg'), {
encoding: 'utf8',
}),
);
});
});
});

View File

@@ -0,0 +1,90 @@
import { describe, test, expect } from '@jest/globals';
import { fileSorter } from '../filesorter.js';
describe('fileSorter', () => {
test('should sort files per filename', () => {
expect(
[
'/var/plop/c.svg',
'/var/plop/a.svg',
'/var/plop/A.svg',
'/var/plop/C.svg',
'/var/plop/B.svg',
'/var/plop/b.svg',
].sort(fileSorter),
).toEqual([
'/var/plop/A.svg',
'/var/plop/B.svg',
'/var/plop/C.svg',
'/var/plop/a.svg',
'/var/plop/b.svg',
'/var/plop/c.svg',
]);
});
test('should sort files per codepoints', () => {
expect(
[
'/var/plop/uAE01-c.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE06-C.svg',
'/var/plop/uAE04-B.svg',
'/var/plop/uAE05-b.svg',
].sort(fileSorter),
).toEqual([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE04-B.svg',
'/var/plop/uAE05-b.svg',
'/var/plop/uAE06-C.svg',
]);
});
test('should put codepoints first', () => {
expect(
[
'/var/plop/uAE01-c.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/C.svg',
'/var/plop/B.svg',
'/var/plop/b.svg',
].sort(fileSorter),
).toEqual([
'/var/plop/uAE01-c.svg',
'/var/plop/uAE02-A.svg',
'/var/plop/uAE03-a.svg',
'/var/plop/B.svg',
'/var/plop/C.svg',
'/var/plop/b.svg',
]);
});
test('should work with the @pinin files', () => {
expect(
[
'bell-disabled.svg',
'bell-disabled-o.svg',
'bell-o.svg',
'UEA01-calendar-agenda.svg',
'UEA02-calendar-alert.svg',
'UEA03-calendar.svg',
'uEA04-bookmark-favorite.svg',
'uEA05-bookmark-o.svg',
'uEA06-bookmark.svg',
].sort(fileSorter),
).toEqual([
'UEA01-calendar-agenda.svg',
'UEA02-calendar-alert.svg',
'UEA03-calendar.svg',
'uEA04-bookmark-favorite.svg',
'uEA05-bookmark-o.svg',
'uEA06-bookmark.svg',
'bell-disabled.svg',
'bell-disabled-o.svg',
'bell-o.svg',
]);
});
});

View File

@@ -0,0 +1,775 @@
import { describe, test, expect } from '@jest/globals';
import assert from 'assert';
import { Readable } from 'node:stream';
import fs from 'node:fs';
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { SVGIcons2SVGFontStream } from '../index.js';
import { SVGIconsDirStream, type SVGIconStream } from '../iconsdir.js';
import streamtest from 'streamtest';
import { BufferStream } from 'bufferstreams';
try {
await mkdir(join('fixtures', 'results'));
} catch (err) {
// empty
}
const codepoint = JSON.parse(
fs.readFileSync('./fixtures/expected/test-codepoint.json').toString(),
);
// Helpers
async function generateFontToFile(options, fileSuffix?, startUnicode?, files?) {
const dest = join(
'fixtures',
'results',
`${options.fontName + (fileSuffix || '')}.svg`,
);
let resolve;
let reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
options.log = () => {};
options.round = options.round || 1e3;
const svgFontStream = new SVGIcons2SVGFontStream(options);
svgFontStream.pipe(fs.createWriteStream(dest)).on('finish', () => {
try {
expect(fs.readFileSync(dest, { encoding: 'utf8' })).toEqual(
fs.readFileSync(
join(
'fixtures',
'expected',
`${options.fontName + (fileSuffix || '')}.svg`,
),
{ encoding: 'utf8' },
),
);
resolve();
} catch (err) {
reject(err);
}
});
new SVGIconsDirStream(files || join('fixtures', 'icons', options.fontName), {
startUnicode: startUnicode || 0xe001,
}).pipe(svgFontStream);
return await promise;
}
async function generateFontToMemory(options, files?, startUnicode?) {
options.log = () => {};
options.round = options.round || 1e3;
options.callback = (glyphs) => {
const fontName = options.fontName;
expect(glyphs).toEqual(codepoint[fontName]);
};
const svgFontStream = new SVGIcons2SVGFontStream(options);
const promise = bufferStream(svgFontStream);
new SVGIconsDirStream(files || join('fixtures', 'icons', options.fontName), {
startUnicode: startUnicode || 0xe001,
}).pipe(svgFontStream);
expect((await promise).toString()).toEqual(
fs.readFileSync(join('fixtures', 'expected', `${options.fontName}.svg`), {
encoding: 'utf8',
}),
);
}
// Tests
describe('Generating fonts to files', () => {
test('should work for simple SVG', async () => {
await generateFontToFile({
fontName: 'originalicons',
});
});
test('should work for simple fixedWidth and normalize option', async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fixedWidth: true,
normalize: true,
},
'n',
);
});
test('should work for simple SVG', async () => {
await generateFontToFile({
fontName: 'cleanicons',
});
});
test('should work for simple SVG and custom ascent', async () => {
await generateFontToFile(
{
fontName: 'cleanicons',
ascent: 100,
},
'-ascent',
);
});
test('should work for simple SVG and custom properties', async () => {
await generateFontToFile(
{
fontName: 'cleanicons',
fontStyle: 'italic',
fontWeight: 'bold',
},
'-stw',
);
});
test('should work for codepoint mapped SVG icons', async () => {
await generateFontToFile({
fontName: 'prefixedicons',
callback: () => {},
});
});
test('should work with multipath SVG icons', async () => {
await generateFontToFile({
fontName: 'multipathicons',
});
});
test('should work with simple shapes SVG icons', async () => {
await generateFontToFile({
fontName: 'shapeicons',
});
});
test('should work with variable height icons', async () => {
await generateFontToFile({
fontName: 'variableheighticons',
});
});
test('should work with variable height icons and the normalize option', async () => {
await generateFontToFile(
{
fontName: 'variableheighticons',
normalize: true,
},
'n',
);
});
test('should work with variable height icons, the normalize option and the preserveAspectRatio option', async () => {
await generateFontToFile(
{
fontName: 'variableheighticons',
normalize: true,
preserveAspectRatio: true,
},
'np',
);
});
test('should work with variable width icons', async () => {
await generateFontToFile({
fontName: 'variablewidthicons',
});
});
test('should work with centered variable width icons and the fixed width option', async () => {
await generateFontToFile(
{
fontName: 'variablewidthicons',
fixedWidth: true,
centerHorizontally: true,
},
'n',
);
});
test('should calculate bounds when not specified in the svg file', async () => {
await generateFontToFile({
fontName: 'calcbounds',
});
});
test('should work with a font id', async () => {
await generateFontToFile(
{
fontName: 'variablewidthicons',
fixedWidth: true,
centerHorizontally: true,
fontId: 'plop',
},
'id',
);
});
test('should work with scaled icons', async () => {
await generateFontToFile({
fontName: 'scaledicons',
fixedWidth: true,
centerHorizontally: true,
fontId: 'plop',
});
});
test('should not display hidden paths', async () => {
await generateFontToFile({
fontName: 'hiddenpathesicons',
});
});
test('should work with real world icons', async () => {
await generateFontToFile({
fontName: 'realicons',
});
});
test('should work with rendering test SVG icons', async () => {
await generateFontToFile({
fontName: 'rendricons',
});
});
test('should work with a single SVG icon', async () => {
await generateFontToFile({
fontName: 'singleicon',
});
});
test('should work with transformed SVG icons', async () => {
await generateFontToFile({
fontName: 'transformedicons',
});
});
test('should work when horizontally centering SVG icons', async () => {
await generateFontToFile({
fontName: 'tocentericons',
centerHorizontally: true,
});
});
test('should work when vertically centering SVG icons', async () => {
await generateFontToFile({
fontName: 'toverticalcentericons',
centerVertically: true,
});
});
test('should work with a icons with path with fill none', async () => {
await generateFontToFile({
fontName: 'pathfillnone',
});
});
test('should work with shapes with rounded corners', async () => {
await generateFontToFile({
fontName: 'roundedcorners',
});
});
test('should work with realworld icons', async () => {
await generateFontToFile({
fontName: 'realworld',
});
});
test('should work with a lot of icons', async () => {
await generateFontToFile(
{
fontName: 'lotoficons',
},
'',
0,
[
'fixtures/icons/cleanicons/account.svg',
'fixtures/icons/cleanicons/arrow-down.svg',
'fixtures/icons/cleanicons/arrow-left.svg',
'fixtures/icons/cleanicons/arrow-right.svg',
'fixtures/icons/cleanicons/arrow-up.svg',
'fixtures/icons/cleanicons/basket.svg',
'fixtures/icons/cleanicons/close.svg',
'fixtures/icons/cleanicons/minus.svg',
'fixtures/icons/cleanicons/plus.svg',
'fixtures/icons/cleanicons/search.svg',
'fixtures/icons/hiddenpathesicons/sound--off.svg',
'fixtures/icons/hiddenpathesicons/sound--on.svg',
'fixtures/icons/multipathicons/kikoolol.svg',
'fixtures/icons/originalicons/mute.svg',
'fixtures/icons/originalicons/sound.svg',
'fixtures/icons/originalicons/speaker.svg',
'fixtures/icons/realicons/diegoliv.svg',
'fixtures/icons/realicons/hannesjohansson.svg',
'fixtures/icons/realicons/roelvanhitum.svg',
'fixtures/icons/realicons/safety-icon.svg',
'fixtures/icons/realicons/sb-icon.svg',
'fixtures/icons/realicons/settings-icon.svg',
'fixtures/icons/realicons/track-icon.svg',
'fixtures/icons/realicons/web-icon.svg',
'fixtures/icons/roundedcorners/roundedrect.svg',
'fixtures/icons/shapeicons/circle.svg',
'fixtures/icons/shapeicons/ellipse.svg',
'fixtures/icons/shapeicons/lines.svg',
'fixtures/icons/shapeicons/polygon.svg',
'fixtures/icons/shapeicons/polyline.svg',
'fixtures/icons/shapeicons/rect.svg',
'fixtures/icons/tocentericons/bottomleft.svg',
'fixtures/icons/tocentericons/center.svg',
'fixtures/icons/tocentericons/topright.svg',
],
);
});
test('should work with rotated rectangle icon', async () => {
await generateFontToFile({
fontName: 'rotatedrectangle',
});
});
/**
* Issue #6
* icon by @paesku
* https://github.com/nfroidure/svgicons2svgfont/issues/6#issuecomment-125545925
*/
test('should work with complicated nested transforms', async () => {
await generateFontToFile({
fontName: 'paesku',
round: 1e3,
});
});
/**
* Issue #76
* https://github.com/nfroidure/svgicons2svgfont/issues/76#issue-259831969
*/
test('should work with transform=translate(x) without y', async () => {
await generateFontToFile({
fontName: 'translatex',
round: 1e3,
});
});
test('should work with skew', async () => {
await generateFontToFile({
fontName: 'skew',
});
});
test('should work when only rx is present', async () => {
await generateFontToFile({
fontName: 'onlywithrx',
});
});
test('should work when only ry is present', async () => {
await generateFontToFile({
fontName: 'onlywithry',
});
});
});
describe('Generating fonts to memory', () => {
test('should work for simple SVG', async () => {
await generateFontToMemory({
fontName: 'originalicons',
});
});
test('should work for simple SVG', async () => {
await generateFontToMemory({
fontName: 'cleanicons',
});
});
test('should work for codepoint mapped SVG icons', async () => {
await generateFontToMemory({
fontName: 'prefixedicons',
});
});
test('should work with multipath SVG icons', async () => {
await generateFontToMemory({
fontName: 'multipathicons',
});
});
test('should work with simple shapes SVG icons', async () => {
await generateFontToMemory({
fontName: 'shapeicons',
});
});
});
describe('Using options', () => {
test('should work with fixedWidth option set to true', async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fixedWidth: true,
},
'2',
);
});
test('should work with custom fontHeight option', async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fontHeight: 800,
},
'3',
);
});
test('should work with custom descent option', async () => {
await generateFontToFile(
{
fontName: 'originalicons',
descent: 200,
},
'4',
);
});
test('should work with fixedWidth set to true and with custom fontHeight option', async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true,
},
'5',
);
});
test(
'should work with fixedWidth and centerHorizontally set to true and with' +
' custom fontHeight option',
async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fontHeight: 800,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
},
'6',
);
},
);
test(
'should work with fixedWidth, normalize and centerHorizontally set to' +
' true and with custom fontHeight option',
async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fontHeight: 800,
normalize: true,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
},
'7',
);
},
);
test(
'should work with fixedWidth, normalize and centerHorizontally set to' +
' true and with a large custom fontHeight option',
async () => {
await generateFontToFile(
{
fontName: 'originalicons',
fontHeight: 5000,
normalize: true,
fixedWidth: true,
centerHorizontally: true,
round: 1e5,
},
'8',
);
},
);
test('should work with nested icons', async () => {
await generateFontToFile(
{
fontName: 'nestedicons',
},
'',
0xea01,
);
});
});
describe('Passing code points', () => {
test('should work with multiple unicode values for a single icon', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'account',
unicode: ['\uE001', '\uE002'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal(
await promise,
fs.readFileSync(join('fixtures', 'expected', 'cleanicons-multi.svg'), {
encoding: 'utf8',
}),
);
});
test('should work with ligatures', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'account',
unicode: ['\uE001\uE002'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal(
await promise,
fs.readFileSync(join('fixtures', 'expected', 'cleanicons-lig.svg'), {
encoding: 'utf8',
}),
);
});
test('should work with high code points', async () => {
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'account',
unicode: ['\u{1f63a}'],
};
const promise = bufferStream(svgFontStream);
svgFontStream.write(svgIconStream);
svgFontStream.end();
assert.equal(
(await promise).toString(),
fs.readFileSync(join('fixtures', 'expected', 'cleanicons-high.svg'), {
encoding: 'utf8',
}),
);
});
});
describe('Providing bad glyphs', () => {
test('should fail when not providing glyph name', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: undefined as unknown as string,
unicode: '\uE001',
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(
err.message,
'Please provide a name for the glyph at index 0',
);
})
.write(svgIconStream);
});
test('should fail when not providing codepoints', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'test',
unicode: undefined as unknown as string[],
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(
err.message,
'Please provide a codepoint for the glyph "test"',
);
})
.write(svgIconStream);
});
test('should fail when providing unicode value with duplicates', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002', '\uE002'],
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(
err.message,
'Given codepoints for the glyph "test" contain duplicates.',
);
})
.write(svgIconStream);
});
test('should fail when providing the same codepoint twice', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
const svgIconStream2 = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
const svgFontStream = new SVGIcons2SVGFontStream({
round: 1e3,
});
svgIconStream.metadata = {
name: 'test',
unicode: '\uE002',
};
svgIconStream2.metadata = {
name: 'test2',
unicode: '\uE002',
};
svgFontStream.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(
err.message,
'The glyph "test2" codepoint seems to be used already elsewhere.',
);
});
svgFontStream.write(svgIconStream);
svgFontStream.write(svgIconStream2);
});
test('should fail when providing the same name twice', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
const svgIconStream2 = fs.createReadStream(
join('fixtures', 'icons', 'cleanicons', 'account.svg'),
) as unknown as SVGIconStream;
const svgFontStream = new SVGIcons2SVGFontStream({ round: 1e3 });
svgIconStream.metadata = {
name: 'test',
unicode: '\uE001',
};
svgIconStream2.metadata = {
name: 'test',
unicode: '\uE002',
};
svgFontStream.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(err.message, 'The glyph name "test" must be unique.');
});
svgFontStream.write(svgIconStream);
svgFontStream.write(svgIconStream2);
});
test('should fail when providing bad pathdata', async () => {
const svgIconStream = fs.createReadStream(
join('fixtures', 'icons', 'badicons', 'pathdata.svg'),
) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002'],
};
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
assert.equal(
err.message,
'Got an error parsing the glyph "test":' +
' Expected a flag, got "20" at index "23".',
);
})
.on('end', () => {})
.write(svgIconStream);
});
test('should fail when providing bad XML', async () => {
const svgIconStream = streamtest.fromChunks([
Buffer.from('bad'),
Buffer.from('xml'),
]) as unknown as SVGIconStream;
svgIconStream.metadata = {
name: 'test',
unicode: ['\uE002'],
};
let firstError = true;
new SVGIcons2SVGFontStream({ round: 1e3 })
.on('error', (err) => {
assert.equal(err instanceof Error, true);
if (firstError) {
firstError = false;
assert.equal(
err.message,
'Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: b',
);
}
})
.write(svgIconStream);
});
});
async function bufferStream(readableStream: Readable) {
return await new Promise<Buffer>((resolve, reject) => {
readableStream.pipe(
new BufferStream((err, buf) => {
if (err) {
return reject(err);
}
resolve(buf);
}),
);
});
}

View File

@@ -0,0 +1,215 @@
import { describe, test, expect } from '@jest/globals';
import { writeFile, readFile, unlink } from 'node:fs/promises';
import { promisify } from 'node:util';
import { getMetadataService } from '../metadata.js';
import { YError } from 'yerror';
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
try {
await mkdir(join('fixtures', 'results'));
} catch (err) {
// empty
}
describe('Metadata service', () => {
describe('for code generation', () => {
test('should extract right unicodes from files', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)('/var/plop/hello.svg');
expect(infos).toEqual({
path: '/var/plop/hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
});
test('should append unicodes to files when the option is set', async () => {
const metadataService = getMetadataService({
prependUnicode: true,
});
await writeFile(join('fixtures', 'results', 'plop.svg'), 'plop', 'utf-8');
const infos = await promisify(metadataService)(
join('fixtures', 'results', 'plop.svg'),
);
expect(infos).toEqual({
path: join('fixtures', 'results', 'uEA01-plop.svg'),
name: 'plop',
unicode: [String.fromCharCode(0xea01)],
renamed: true,
});
expect(
await readFile(join('fixtures', 'results', 'uEA01-plop.svg')),
).toBeTruthy();
unlink(join('fixtures', 'results', 'uEA01-plop.svg'));
try {
await readFile(join('fixtures', 'results', 'plop.svg'));
throw new YError('E_UNEXPECTED_SUCCESS');
} catch (err) {
expect((err as YError).code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
});
test('should log file rename errors', async () => {
const metadataService = getMetadataService({
prependUnicode: true,
startUnicode: 0xea02,
});
try {
await promisify(metadataService)(
join('fixtures', 'results', 'plop.svg'),
);
throw new YError('E_UNEXPECTED_SUCCESS');
} catch (err) {
expect(err).toBeTruthy();
expect((err as YError).code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
try {
await readFile(join('fixtures', 'results', 'uEA02-plop.svg'));
throw new YError('E_UNEXPECTED_SUCCESS');
} catch (err) {
expect((err as YError).code === 'E_UNEXPECTED_SUCCESS').toBeFalsy();
}
});
});
describe('for code extraction', () => {
test('should work for simple codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/u0001-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/u0001-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001)],
renamed: false,
});
});
test('should work for several codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/u0001,u0002-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/u0001,u0002-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001), String.fromCharCode(0x0002)],
renamed: false,
});
});
test('should work for higher codepoint codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/u1F63A-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/u1F63A-hello.svg',
name: 'hello',
unicode: [String.fromCodePoint(0x1f63a)],
renamed: false,
});
});
test('should work for ligature codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/u0001u0002-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/u0001u0002-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0x0001) + String.fromCharCode(0x0002)],
renamed: false,
});
});
test('should work for nested codes', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/u0001u0002,u0001-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/u0001u0002,u0001-hello.svg',
name: 'hello',
unicode: [
String.fromCharCode(0x0001) + String.fromCharCode(0x0002),
String.fromCharCode(0x0001),
],
renamed: false,
});
});
test('should not set the same codepoint twice', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/uEA01-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/uEA01-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
const infos2 = await promisify(metadataService)('/var/plop/plop.svg');
expect(infos2).toEqual({
path: '/var/plop/plop.svg',
name: 'plop',
unicode: [String.fromCharCode(0xea02)],
renamed: false,
});
});
test('should not set the same codepoint twice with different cases', async () => {
const metadataService = getMetadataService();
const infos = await promisify(metadataService)(
'/var/plop/UEA01-hello.svg',
);
expect(infos).toEqual({
path: '/var/plop/UEA01-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea01)],
renamed: false,
});
const infos2 = await promisify(metadataService)(
'/var/plop/uEA02-hello.svg',
);
expect(infos2).toEqual({
path: '/var/plop/uEA02-hello.svg',
name: 'hello',
unicode: [String.fromCharCode(0xea02)],
renamed: false,
});
const infos3 = await promisify(metadataService)('/var/plop/bell-o.svg');
expect(infos3).toEqual({
path: '/var/plop/bell-o.svg',
name: 'bell-o',
unicode: [String.fromCharCode(0xea03)],
renamed: false,
});
});
});
});