@fastkit/icon-font-gen 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,7 @@ import type webfont from 'webfont';
5
5
 
6
6
  export declare function ceateIconFontConfig(options: IconFontConfig): IconFontConfig;
7
7
 
8
- export declare function cli(): void;
8
+ export declare function cli(): Promise<void>;
9
9
 
10
10
  export declare const DEFAULT_CONFIG_FILENAME = "icon-font.config";
11
11
 
@@ -1,12 +1,10 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var nodeUtil = require('@fastkit/node-util');
5
- var fs = require('fs-extra');
6
- var chokidar = require('chokidar');
7
- var ev = require('@fastkit/ev');
8
- var tinyLogger = require('@fastkit/tiny-logger');
9
- var cac = require('cac');
1
+ import path from 'path';
2
+ import { installPackage, HashComparator, findPackageDir, esbuildRequire } from '@fastkit/node-util';
3
+ import fs from 'fs-extra';
4
+ import chokidar from 'chokidar';
5
+ import { EV } from '@fastkit/ev';
6
+ import { TinyLogger, createTinyError } from '@fastkit/tiny-logger';
7
+ import { cac } from 'cac';
10
8
 
11
9
  const ICON_FONT_FORMATS = [
12
10
  'eot',
@@ -53,7 +51,7 @@ async function resolveRawIconFontEntry(rootDir, rawEntry) {
53
51
  };
54
52
  }
55
53
  function findOrInstallMDI() {
56
- return nodeUtil.installPackage('@mdi/svg', { dev: true });
54
+ return installPackage('@mdi/svg', { dev: true });
57
55
  }
58
56
  const DEFAULT_CONFIG_FILENAME = 'icon-font.config';
59
57
  const DEFAULT_DEST_DIRNAME = '.icon-font';
@@ -62,8 +60,8 @@ function ceateIconFontConfig(options) {
62
60
  }
63
61
 
64
62
  const name = 'icon-font-gen';
65
- const logger = new tinyLogger.TinyLogger(name);
66
- const IconFontGenError = tinyLogger.createTinyError(name);
63
+ const logger = new TinyLogger(name);
64
+ const IconFontGenError = createTinyError(name);
67
65
 
68
66
  const DEFAULT_OPTIONS = {
69
67
  formats: ['woff2'],
@@ -115,7 +113,7 @@ async function generateEntry(entry) {
115
113
  // @TODO support empty prefix
116
114
  // const namePrefix = options.name;
117
115
  const cssPrefix = `icon-${options.prefix}`;
118
- const hash = new nodeUtil.HashComparator(options.src, options.dest);
116
+ const hash = new HashComparator(options.src, options.dest);
119
117
  const srcHash = await hash.hasChanged();
120
118
  if (!srcHash) {
121
119
  logger.info(`Has not chaged files. Skip process. >>> ${options.src}`);
@@ -242,7 +240,7 @@ async function generate(opts) {
242
240
  const entries = results.map(({ entry }) => entry);
243
241
  await generateIndex(opts.dest, entries);
244
242
  }
245
- class IconFontRunnerItem extends ev.EV {
243
+ class IconFontRunnerItem extends EV {
246
244
  entry;
247
245
  ctx;
248
246
  _resolveEntryPromise;
@@ -290,7 +288,7 @@ class IconFontRunnerItem extends ev.EV {
290
288
  }
291
289
  }
292
290
  }
293
- class IconFontRunner extends ev.EV {
291
+ class IconFontRunner extends EV {
294
292
  items = [];
295
293
  dest;
296
294
  // private _opts: IconFontOptions;
@@ -329,9 +327,8 @@ class IconFontRunner extends ev.EV {
329
327
  }
330
328
  }
331
329
 
332
- const { version } = require('../package.json');
333
- function cli() {
334
- const cli = cac.cac('icon-font');
330
+ async function cli() {
331
+ const cli = cac('icon-font');
335
332
  cli
336
333
  .option('-d, --dest <string>', 'Destination for generated fonts.', {
337
334
  default: path.join(process.cwd(), `${DEFAULT_DEST_DIRNAME}`),
@@ -349,14 +346,14 @@ Path of the configuration file. (default: [your package directory]${path.sep}${D
349
346
  `.trim())
350
347
  .action(async (configPath, options) => {
351
348
  if (!configPath) {
352
- const pkgDir = await nodeUtil.findPackageDir();
349
+ const pkgDir = await findPackageDir();
353
350
  if (!pkgDir) {
354
351
  throw new IconFontGenError('missing package directory.');
355
352
  }
356
353
  configPath = path.join(pkgDir, DEFAULT_CONFIG_FILENAME);
357
354
  }
358
355
  const dest = path.resolve(options.dest);
359
- const mod = await nodeUtil.esbuildRequire(configPath);
356
+ const mod = await esbuildRequire(configPath);
360
357
  const config = mod.exports.default;
361
358
  await generate({
362
359
  ...config,
@@ -364,21 +361,8 @@ Path of the configuration file. (default: [your package directory]${path.sep}${D
364
361
  });
365
362
  });
366
363
  cli.help();
367
- cli.version(version);
364
+ cli.version("0.10.1");
368
365
  cli.parse();
369
366
  }
370
367
 
371
- exports.DEFAULT_CONFIG_FILENAME = DEFAULT_CONFIG_FILENAME;
372
- exports.DEFAULT_DEST_DIRNAME = DEFAULT_DEST_DIRNAME;
373
- exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
374
- exports.ICON_FONT_FORMATS = ICON_FONT_FORMATS;
375
- exports.ICON_FONT_FORMAT_MAP = ICON_FONT_FORMAT_MAP;
376
- exports.IconFontRunner = IconFontRunner;
377
- exports.IconFontRunnerItem = IconFontRunnerItem;
378
- exports.ceateIconFontConfig = ceateIconFontConfig;
379
- exports.cli = cli;
380
- exports.generate = generate;
381
- exports.generateEntry = generateEntry;
382
- exports.generateIndex = generateIndex;
383
- exports.mergeDefaults = mergeDefaults;
384
- exports.resolveRawIconFontEntry = resolveRawIconFontEntry;
368
+ export { DEFAULT_CONFIG_FILENAME, DEFAULT_DEST_DIRNAME, DEFAULT_OPTIONS, ICON_FONT_FORMATS, ICON_FONT_FORMAT_MAP, IconFontRunner, IconFontRunnerItem, ceateIconFontConfig, cli, generate, generateEntry, generateIndex, mergeDefaults, resolveRawIconFontEntry };
package/lib/cli.mjs ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { cli } from '@fastkit/icon-font-gen';
3
+
4
+ cli();
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "@fastkit/icon-font-gen",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "A tool to generate icon web fonts and their definitions Type-safe for your application.",
5
5
  "buildOptions": {
6
- "name": "IconFont",
7
- "formats": [
8
- "cjs"
9
- ]
6
+ "name": "IconFont"
10
7
  },
11
8
  "_docs": {
12
9
  "scope": "",
@@ -16,13 +13,14 @@
16
13
  "ja": "アプリケーションのためにアイコンWebフォントとその定義をTypeセーフに生成するツール。"
17
14
  }
18
15
  },
19
- "main": "index.js",
20
16
  "bin": {
21
- "icon-font": "lib/cli.js"
17
+ "icon-font": "lib/cli.mjs"
18
+ },
19
+ "main": "./dist/icon-font-gen.mjs",
20
+ "exports": {
21
+ ".": "./dist/icon-font-gen.mjs"
22
22
  },
23
- "module": "dist/icon-font-gen.mjs",
24
23
  "files": [
25
- "index.js",
26
24
  "lib",
27
25
  "dist"
28
26
  ],
@@ -42,10 +40,10 @@
42
40
  },
43
41
  "homepage": "https://github.com/dadajam4/fastkit/tree/main/packages/icon-font-gen#readme",
44
42
  "dependencies": {
45
- "@fastkit/ev": "0.10.0",
46
- "@fastkit/icon-font": "0.10.0",
47
- "@fastkit/node-util": "0.10.0",
48
- "@fastkit/tiny-logger": "0.10.0",
43
+ "@fastkit/ev": "0.10.1",
44
+ "@fastkit/icon-font": "0.10.1",
45
+ "@fastkit/node-util": "0.10.1",
46
+ "@fastkit/tiny-logger": "0.10.1",
49
47
  "cac": "^6.7.11",
50
48
  "chokidar": "^3.5.0",
51
49
  "fs-extra": "^11.1.0",
@@ -1,384 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var nodeUtil = require('@fastkit/node-util');
5
- var fs = require('fs-extra');
6
- var chokidar = require('chokidar');
7
- var ev = require('@fastkit/ev');
8
- var tinyLogger = require('@fastkit/tiny-logger');
9
- var cac = require('cac');
10
-
11
- const ICON_FONT_FORMATS = [
12
- 'eot',
13
- 'woff',
14
- 'woff2',
15
- 'svg',
16
- 'ttf',
17
- ];
18
- const ICON_FONT_FORMAT_MAP = {
19
- eot: 'embedded-opentype',
20
- woff2: 'woff2',
21
- woff: 'woff',
22
- ttf: 'truetype',
23
- svg: 'svg',
24
- };
25
- async function resolveRawIconFontEntry(rootDir, rawEntry) {
26
- const entry = {
27
- ...rawEntry,
28
- };
29
- // mdi support
30
- if (entry.src === '@mdi') {
31
- const installedDir = await findOrInstallMDI();
32
- entry.src = path.join(installedDir, 'svg');
33
- if (entry.fontHeight == null) {
34
- entry.fontHeight = 512;
35
- }
36
- if (entry.descent == null) {
37
- entry.descent = 64;
38
- }
39
- if (entry.name == null) {
40
- entry.name = 'mdi';
41
- }
42
- }
43
- const name = entry.name || path.basename(entry.src);
44
- const fontName = entry.fontName || `${name}-icon`;
45
- const dest = path.join(rootDir, name);
46
- const prefix = entry.disablePrefix ? '' : `${name}-`;
47
- return {
48
- ...entry,
49
- name,
50
- fontName,
51
- prefix,
52
- dest,
53
- };
54
- }
55
- function findOrInstallMDI() {
56
- return nodeUtil.installPackage('@mdi/svg', { dev: true });
57
- }
58
- const DEFAULT_CONFIG_FILENAME = 'icon-font.config';
59
- const DEFAULT_DEST_DIRNAME = '.icon-font';
60
- function ceateIconFontConfig(options) {
61
- return options;
62
- }
63
-
64
- const name = 'icon-font-gen';
65
- const logger = new tinyLogger.TinyLogger(name);
66
- const IconFontGenError = tinyLogger.createTinyError(name);
67
-
68
- const DEFAULT_OPTIONS = {
69
- formats: ['woff2'],
70
- fixedWidth: true,
71
- normalize: true,
72
- };
73
- const BANNER = `
74
- /**
75
- * This is auto generated file.
76
- * Do not edit !!!
77
- *
78
- * @see: https://github.com/dadajam4/fastkit/tree/main/packages/icon-font-gen
79
- */
80
- `.trim();
81
- function mergeDefaults(entry) {
82
- return {
83
- ...DEFAULT_OPTIONS,
84
- ...entry,
85
- };
86
- }
87
- async function generateTS(entry, ids) {
88
- const code = `
89
- /* eslint-disable */
90
- // @ts-nocheck
91
- ${BANNER}
92
- import type { IconName, IconNameMap } from '@fastkit/icon-font';
93
- import { registerIconNames } from '@fastkit/icon-font';
94
- declare module "@fastkit/icon-font" {
95
- export interface IconNameMap {
96
- ${ids.map((id) => ` '${id}': true,`).join('\n')}
97
- }
98
- }
99
- export const ICON_NAMES = registerIconNames([
100
- ${ids.map((id) => `'${id}'`).join(',\n ')}
101
- ]);
102
- export type { IconName, IconNameMap } from '@fastkit/icon-font';
103
- `.trim();
104
- const fileName = `${entry.name || 'icons'}.ts`;
105
- const dest = path.resolve(entry.dest, fileName);
106
- await fs.writeFile(dest, code);
107
- return {
108
- fileName,
109
- dest,
110
- code,
111
- };
112
- }
113
- async function generateEntry(entry) {
114
- const options = mergeDefaults(entry);
115
- // @TODO support empty prefix
116
- // const namePrefix = options.name;
117
- const cssPrefix = `icon-${options.prefix}`;
118
- const hash = new nodeUtil.HashComparator(options.src, options.dest);
119
- const srcHash = await hash.hasChanged();
120
- if (!srcHash) {
121
- logger.info(`Has not chaged files. Skip process. >>> ${options.src}`);
122
- return { entry };
123
- }
124
- await fs.ensureDir(options.dest);
125
- const { webfont } = await import('webfont');
126
- // const { startUnicode = 0xea01 } = options;
127
- const { startUnicode = 0xba01 } = options;
128
- let i = startUnicode;
129
- const result = await webfont({
130
- files: options.src,
131
- fontName: options.fontName,
132
- formats: options.formats,
133
- fixedWidth: options.fixedWidth,
134
- centerHorizontally: options.centerHorizontally,
135
- normalize: options.normalize,
136
- fontHeight: options.fontHeight,
137
- round: options.round,
138
- descent: options.descent,
139
- addHashInFontUrl: options.addHashInFontUrl,
140
- glyphTransformFn: (obj) => {
141
- const char = String.fromCodePoint(i);
142
- obj.unicode = [char];
143
- i++;
144
- return obj;
145
- },
146
- });
147
- const buildedFormats = [];
148
- ICON_FONT_FORMATS.forEach((format) => {
149
- const code = result[format];
150
- if (code) {
151
- buildedFormats.push({ format, code });
152
- }
153
- });
154
- await Promise.all(buildedFormats.map(({ format, code }) => {
155
- return fs.writeFile(path.join(options.dest, `${options.name}.${format}`), code);
156
- }));
157
- const glyphs = [];
158
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
159
- result.glyphsData.forEach(({ metadata }) => {
160
- if (!metadata)
161
- return;
162
- const { name, unicode } = metadata;
163
- if (!unicode) {
164
- return;
165
- }
166
- const code = unicode[0].charCodeAt(0).toString(16);
167
- glyphs.push({ name, code });
168
- });
169
- const urlPath = options.absolutePath ? options.dest : '.';
170
- const hashSuffix = options.addHashInFontUrl ? `?${Date.now()}` : '';
171
- const src = buildedFormats
172
- .map(({ format }) => {
173
- return `url("${urlPath}/${options.name}.${format}${hashSuffix}") format("${ICON_FONT_FORMAT_MAP[format]}")`;
174
- })
175
- .join(',');
176
- const cssCode = `/* stylelint-disable */
177
- @font-face {
178
- font-family: "${options.fontName}";
179
- font-display: block;
180
- font-style: normal;
181
- font-weight: 400;
182
- src: ${src};
183
- }
184
-
185
- i[class^="${cssPrefix}"]:before, i[class*=" ${cssPrefix}"]:before {
186
- font-family: ${options.fontName} !important;
187
- font-style: normal;
188
- font-weight: normal !important;
189
- font-variant: normal;
190
- text-transform: none;
191
- text-rendering: auto;
192
- line-height: 1;
193
- -webkit-font-smoothing: antialiased;
194
- -moz-osx-font-smoothing: grayscale;
195
- }
196
- ${glyphs
197
- .map(({ name, code }) => {
198
- return `
199
- .${cssPrefix}${name}:before { content: "\\${code}"; }
200
- `;
201
- })
202
- .join('\n')}
203
- `;
204
- await fs.writeFile(path.join(options.dest, `${options.name}.css`), cssCode);
205
- // const prefix = options.prefix ? `${options.prefix}-` : '';
206
- const ids = glyphs.map(({ name }) => `${options.prefix}${name}`);
207
- await generateTS(options, ids);
208
- await hash.commit(srcHash);
209
- return {
210
- entry,
211
- result,
212
- };
213
- }
214
- async function generateIndex(dest, entries) {
215
- const names = entries.map(({ name }) => name);
216
- const tsCode = `
217
- /* eslint-disable */
218
- // @ts-nocheck
219
- import './index.css';
220
- ${BANNER}
221
- ${names
222
- .map((name, index) =>
223
- // `import { IconName as IconName_${index}, IconNameMap as IconNameMap_${index} } from './${name}/${name}';`,
224
- `import './${name}/${name}';`)
225
- .join('\n')}
226
- export type { IconName } from '@fastkit/icon-font';
227
- export { ICON_NAMES } from '@fastkit/icon-font';
228
- `.trim();
229
- const tsDest = path.join(dest, 'index.ts');
230
- await fs.writeFile(tsDest, tsCode);
231
- const cssCode = `
232
- /* stylelint-disable */
233
- ${BANNER}
234
- ${names.map((name) => `@import './${name}/${name}.css';`).join('\n')}
235
- `.trim();
236
- const cssDest = path.join(dest, 'index.css');
237
- await fs.writeFile(cssDest, cssCode);
238
- }
239
- async function generate(opts) {
240
- await fs.emptyDir(opts.dest);
241
- const results = await Promise.all(opts.entries.map((entry) => resolveRawIconFontEntry(opts.dest, entry).then((entry) => generateEntry(entry))));
242
- const entries = results.map(({ entry }) => entry);
243
- await generateIndex(opts.dest, entries);
244
- }
245
- class IconFontRunnerItem extends ev.EV {
246
- entry;
247
- ctx;
248
- _resolveEntryPromise;
249
- _watcher = null;
250
- watchMode;
251
- // get name() {
252
- // return this.entry.name;
253
- // }
254
- constructor(ctx, entry, watch = false) {
255
- super();
256
- this.ctx = ctx;
257
- this.entry = entry;
258
- this.watchMode = watch;
259
- this.build = this.build.bind(this);
260
- }
261
- async run() {
262
- const result = await this.build();
263
- if (this.watchMode && !this._watcher) {
264
- const watchDir = path.resolve(this.entry.src);
265
- this._watcher = chokidar.watch(watchDir, { ignoreInitial: true });
266
- this._watcher.on('all', this.build);
267
- }
268
- return result;
269
- }
270
- resolveEntry() {
271
- if (!this._resolveEntryPromise) {
272
- this._resolveEntryPromise = resolveRawIconFontEntry(this.ctx.dest, this.entry);
273
- }
274
- return this._resolveEntryPromise;
275
- }
276
- async build() {
277
- const entry = await this.resolveEntry();
278
- const result = await generateEntry(entry);
279
- this.emit('build', result);
280
- return { entry };
281
- }
282
- destroy() {
283
- if (this._watcher) {
284
- this._watcher.close();
285
- this._watcher = null;
286
- }
287
- this.offAll();
288
- if (this.ctx) {
289
- delete this.ctx;
290
- }
291
- }
292
- }
293
- class IconFontRunner extends ev.EV {
294
- items = [];
295
- dest;
296
- // private _opts: IconFontOptions;
297
- // private entries: IconFontEntry[] = [];
298
- constructor(opts, watch) {
299
- super();
300
- // this._opts = opts;
301
- this.dest = opts.dest;
302
- // this.entries = opts.entries.map((entry) =>
303
- // resolveRawIconFontEntry(this.outputDir, entry),
304
- // );
305
- opts.entries.forEach((entry) => {
306
- const item = new IconFontRunnerItem(this, entry, watch);
307
- item.on('build', (result) => {
308
- this.emit('build', { item, result });
309
- });
310
- this.items.push(item);
311
- });
312
- }
313
- async buildIndex() {
314
- const entries = await Promise.all(this.items.map((item) => item.resolveEntry()));
315
- return generateIndex(this.dest, entries);
316
- }
317
- async run() {
318
- await fs.ensureDir(this.dest);
319
- await Promise.all([
320
- this.buildIndex(),
321
- Promise.all(this.items.map((item) => item.run())),
322
- ]);
323
- }
324
- destroy() {
325
- this.items.forEach((item) => item.destroy());
326
- this.items.length = 0;
327
- this.offAll();
328
- delete this._opts;
329
- }
330
- }
331
-
332
- const { version } = require('../package.json');
333
- function cli() {
334
- const cli = cac.cac('icon-font');
335
- cli
336
- .option('-d, --dest <string>', 'Destination for generated fonts.', {
337
- default: path.join(process.cwd(), `${DEFAULT_DEST_DIRNAME}`),
338
- })
339
- .command('[config file path]', `
340
- Path of the configuration file. (default: [your package directory]${path.sep}${DEFAULT_CONFIG_FILENAME})
341
- You must export default <IconFontConfig>.
342
-
343
- e.g.
344
- \`\`\`
345
- import { ceateIconFontConfig } from '@fastkit/icon-font-gen';
346
-
347
- export default ceateIconFontConfig({ ... });
348
- \`\`\`
349
- `.trim())
350
- .action(async (configPath, options) => {
351
- if (!configPath) {
352
- const pkgDir = await nodeUtil.findPackageDir();
353
- if (!pkgDir) {
354
- throw new IconFontGenError('missing package directory.');
355
- }
356
- configPath = path.join(pkgDir, DEFAULT_CONFIG_FILENAME);
357
- }
358
- const dest = path.resolve(options.dest);
359
- const mod = await nodeUtil.esbuildRequire(configPath);
360
- const config = mod.exports.default;
361
- await generate({
362
- ...config,
363
- dest,
364
- });
365
- });
366
- cli.help();
367
- cli.version(version);
368
- cli.parse();
369
- }
370
-
371
- exports.DEFAULT_CONFIG_FILENAME = DEFAULT_CONFIG_FILENAME;
372
- exports.DEFAULT_DEST_DIRNAME = DEFAULT_DEST_DIRNAME;
373
- exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
374
- exports.ICON_FONT_FORMATS = ICON_FONT_FORMATS;
375
- exports.ICON_FONT_FORMAT_MAP = ICON_FONT_FORMAT_MAP;
376
- exports.IconFontRunner = IconFontRunner;
377
- exports.IconFontRunnerItem = IconFontRunnerItem;
378
- exports.ceateIconFontConfig = ceateIconFontConfig;
379
- exports.cli = cli;
380
- exports.generate = generate;
381
- exports.generateEntry = generateEntry;
382
- exports.generateIndex = generateIndex;
383
- exports.mergeDefaults = mergeDefaults;
384
- exports.resolveRawIconFontEntry = resolveRawIconFontEntry;
package/index.js DELETED
@@ -1,6 +0,0 @@
1
- 'use strict';
2
- if (process.env.NODE_ENV === 'production') {
3
- module.exports = require('./dist/icon-font-gen.cjs.prod.js');
4
- } else {
5
- module.exports = require('./dist/icon-font-gen.cjs.js');
6
- }
package/lib/cli.js DELETED
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env node
2
- const path = require('path');
3
- const { cli } = require(path.resolve(__dirname, '../dist/icon-font-gen.cjs'));
4
- cli();