@astryxdesign/cli 0.7.11-canary.ec945c9 → 0.7.11

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/api/build/kit/rank.mjs +4 -21
  3. package/api/build/kit/words.d.mts +0 -1
  4. package/api/build/kit/words.mjs +1 -1
  5. package/api/icon/_adapter.d.mts +2 -3
  6. package/api/icon/_adapter.mjs +2 -8
  7. package/api/icon/_authoring.d.mts +0 -1
  8. package/api/icon/_authoring.mjs +66 -586
  9. package/api/icon/_records.d.mts +1 -1
  10. package/api/icon/_records.mjs +0 -1
  11. package/api/icon/add/add.mjs +38 -224
  12. package/api/icon/icon.type.d.mts +2 -22
  13. package/api/icon/icon.type.mjs +2 -6
  14. package/api/icon/iconAdd.doc.mjs +2 -2
  15. package/api/icon/iconNewDefinition.doc.mjs +2 -3
  16. package/api/icon/iconNewSet.doc.mjs +4 -4
  17. package/api/icon/search/search.mjs +9 -10
  18. package/api/integration/add-helpers.d.mts +1 -11
  19. package/api/integration/add-helpers.mjs +2 -5
  20. package/api/integration/authoring-checks.d.mts +2 -0
  21. package/api/integration/authoring-checks.mjs +6 -1
  22. package/api/logger.mjs +1 -2
  23. package/api/swizzle/_adapter.d.mts +0 -1
  24. package/api/swizzle/_adapter.mjs +1 -4
  25. package/api/swizzle/copy/copy.d.mts +43 -2
  26. package/api/swizzle/copy/copy.mjs +314 -194
  27. package/api/swizzle/swizzle.d.mts +2 -0
  28. package/api/swizzle/swizzle.doc.mjs +4 -8
  29. package/api/swizzle/swizzle.mjs +7 -3
  30. package/api/swizzle/swizzle.type.d.mts +1 -1
  31. package/api/swizzle/swizzle.type.mjs +2 -2
  32. package/assets/discover/official-packages.json +0 -12
  33. package/assets/docs/tree/icon-sets.doc.mjs +5 -11
  34. package/assets/templates/pages/file-explorer/page.tsx +79 -103
  35. package/assets/templates/pages/table-grouped/page.tsx +232 -160
  36. package/assets/templates/pages/table-grouped/template.doc.mjs +2 -0
  37. package/assets/templates/pages/theme-showcase/page.tsx +792 -724
  38. package/assets/templates/pages/theme-showcase/template.doc.mjs +5 -4
  39. package/clients/cli/commands/experimental/icon.mjs +10 -31
  40. package/clients/cli/commands/experimental-icon-add.doc.mjs +1 -1
  41. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +1 -2
  42. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +2 -2
  43. package/clients/cli/commands/swizzle.doc.mjs +3 -6
  44. package/clients/cli/commands/swizzle.mjs +9 -8
  45. package/foundation/discovery/component-loader.d.mts +1 -1
  46. package/foundation/discovery/doc-types.mjs +2 -9
  47. package/foundation/discovery/icon-ranking.d.mts +3 -27
  48. package/foundation/discovery/icon-ranking.mjs +8 -125
  49. package/foundation/discovery/icon-set-checks.mjs +35 -44
  50. package/foundation/discovery/icon-set-discovery.d.mts +0 -13
  51. package/foundation/discovery/icon-set-discovery.mjs +0 -25
  52. package/foundation/discovery/icon-set-writer.d.mts +16 -238
  53. package/foundation/discovery/icon-set-writer.mjs +79 -676
  54. package/foundation/discovery/module-exports.d.mts +2 -3
  55. package/foundation/discovery/module-exports.mjs +37 -167
  56. package/foundation/fs/paths.d.mts +1 -2
  57. package/foundation/fs/paths.mjs +4 -3
  58. package/package.json +6 -6
  59. package/api/icon/_default-look.d.mts +0 -155
  60. package/api/icon/_default-look.mjs +0 -474
  61. package/api/swizzle/_moduleGraph.d.mts +0 -162
  62. package/api/swizzle/_moduleGraph.mjs +0 -754
  63. package/foundation/text/shell-arg.d.mts +0 -14
  64. package/foundation/text/shell-arg.mjs +0 -17
@@ -1,754 +0,0 @@
1
- // Copyright (c) Meta Platforms, Inc. and affiliates.
2
-
3
- /**
4
- * @file swizzle.copy module graph — decides, for each module a component
5
- * reaches, whether the copy imports it from the owner package's public
6
- * exports or carries it in the output.
7
- *
8
- * @input the owner package's source root and `exports` map, the component folder
9
- * @output the files the copy holds, each with its rewritten source
10
- * @position api/swizzle adapter helper; the copy leaf reaches it through _adapter.mjs
11
- */
12
-
13
- import * as fs from 'node:fs';
14
- import * as path from 'node:path';
15
- import {parse} from '@babel/parser';
16
- import {
17
- inspectPackageExport,
18
- sourceExportTarget,
19
- } from '../../foundation/discovery/package-exports.mjs';
20
- import {
21
- moduleExportOrigins,
22
- resolveLocalModule,
23
- } from '../../foundation/discovery/module-exports.mjs';
24
- import {
25
- allTargets,
26
- isRecord,
27
- subpathDeclaration,
28
- } from '../../foundation/integrations/exports-subpaths.mjs';
29
-
30
- /** The extensions an extensionless import may name, in resolution order. */
31
- const CODE_FILE = /\.[cm]?[jt]sx?$/;
32
- const DECLARATION_FILE = /\.d\.[cm]?ts$/;
33
- const STYLEX_FILE = /\.stylex\.[cm]?[jt]sx?$/;
34
-
35
- /** @param {string} file */
36
- const toPosix = file => file.split(path.sep).join('/');
37
-
38
- /**
39
- * The file an import names, or null when no file is there.
40
- * @param {string} fromFile absolute path of the importing file
41
- * @param {string} specifier a relative specifier
42
- * @param {Map<string, string|null>} cache resolutions already made in this copy
43
- * @returns {string|null}
44
- */
45
- function resolveRelative(fromFile, specifier, cache) {
46
- const base = path.resolve(path.dirname(fromFile), specifier);
47
- const known = cache.get(base);
48
- if (known !== undefined) return known;
49
- const found = resolveLocalModule(specifier, fromFile);
50
- cache.set(base, found);
51
- return found;
52
- }
53
-
54
- /**
55
- * @typedef {object} ImportSpecifier
56
- * @property {string} imported the exported name (`default` for a default import)
57
- * @property {string} local
58
- * @property {boolean} typeOnly
59
- *
60
- * @typedef {object} ModuleReference
61
- * @property {'named'|'namespace'|'sideEffect'|'dynamic'|'reexportAll'|'reexportNamed'} kind
62
- * @property {string} source the specifier as written
63
- * @property {number} start statement (or, for `import()`, string literal) start
64
- * @property {number} end
65
- * @property {boolean} typeOnly the whole statement is `import type` / `export type`
66
- * @property {ImportSpecifier[]} specifiers
67
- * @property {string} [namespace] the local name of `* as X`
68
- *
69
- * @typedef {object} ParsedModule
70
- * @property {string} code
71
- * @property {ModuleReference[]} references
72
- * @property {Set<string>} declares names the module declares and exports
73
-
74
- */
75
-
76
- /**
77
- * A module's source and every module reference in it: static imports and
78
- * re-exports, `import()` calls, and `import('…')` types.
79
- * @param {string} file
80
- * @returns {ParsedModule}
81
- */
82
- function parseModule(file) {
83
- const code = fs.readFileSync(file, 'utf-8');
84
- /** @type {ParsedModule} */
85
- const parsed = {code, references: [], declares: new Set()};
86
- if (!CODE_FILE.test(file)) return parsed;
87
- const ast = parse(code, {
88
- sourceType: 'module',
89
- errorRecovery: true,
90
- plugins: /\.[cm]?tsx?$/.test(file) ? ['typescript', 'jsx'] : ['jsx'],
91
- });
92
- const {references} = parsed;
93
- // Babel's node types mark positions optional; a parsed file always has them.
94
- for (const node of /** @type {any[]} */ (ast.program.body)) {
95
- for (const d of node.declaration?.declarations ?? [node.declaration]) {
96
- if (node.type === 'ExportNamedDeclaration' && d?.id?.name)
97
- parsed.declares.add(d.id.name);
98
- }
99
- if (node.type === 'ImportDeclaration') {
100
- const typeOnly = node.importKind === 'type';
101
- const base = {
102
- source: node.source.value,
103
- start: node.start,
104
- end: node.end,
105
- typeOnly,
106
- };
107
- const namespace = node.specifiers.find(
108
- (/** @type {any} */ s) => s.type === 'ImportNamespaceSpecifier',
109
- );
110
- const named = node.specifiers.filter(
111
- (/** @type {any} */ s) => s.type !== 'ImportNamespaceSpecifier',
112
- );
113
- if (node.specifiers.length === 0) {
114
- references.push({...base, kind: 'sideEffect', specifiers: []});
115
- } else if (namespace && named.length === 0) {
116
- references.push({
117
- ...base,
118
- kind: 'namespace',
119
- specifiers: [],
120
- namespace: namespace.local.name,
121
- });
122
- } else if (!namespace) {
123
- references.push({
124
- ...base,
125
- kind: 'named',
126
- specifiers: named.map((/** @type {any} */ s) => ({
127
- imported:
128
- s.type === 'ImportDefaultSpecifier'
129
- ? 'default'
130
- : s.imported.type === 'StringLiteral'
131
- ? s.imported.value
132
- : s.imported.name,
133
- local: s.local.name,
134
- typeOnly: typeOnly || s.importKind === 'type',
135
- })),
136
- });
137
- } else {
138
- // `import X, * as Y from` names the whole module.
139
- references.push({...base, kind: 'namespace', specifiers: []});
140
- }
141
- } else if (node.type === 'ExportAllDeclaration') {
142
- references.push({
143
- kind: 'reexportAll',
144
- source: node.source.value,
145
- start: node.start,
146
- end: node.end,
147
- typeOnly: node.exportKind === 'type',
148
- specifiers: [],
149
- });
150
- } else if (node.type === 'ExportNamedDeclaration' && node.source) {
151
- const typeOnly = node.exportKind === 'type';
152
- references.push({
153
- kind: 'reexportNamed',
154
- source: node.source.value,
155
- start: node.start,
156
- end: node.end,
157
- typeOnly,
158
- specifiers: node.specifiers.map((/** @type {any} */ s) => ({
159
- imported: s.type === 'ExportNamespaceSpecifier' ? '*' : s.local.name,
160
- local:
161
- s.exported.type === 'StringLiteral'
162
- ? s.exported.value
163
- : s.exported.name,
164
- typeOnly: typeOnly || s.exportKind === 'type',
165
- })),
166
- });
167
- }
168
- }
169
- visitDynamicReferences(ast.program, literal => {
170
- references.push({
171
- kind: 'dynamic',
172
- source: literal.value,
173
- start: literal.start,
174
- end: literal.end,
175
- typeOnly: false,
176
- specifiers: [],
177
- });
178
- });
179
- return parsed;
180
- }
181
-
182
- /**
183
- * Call `onLiteral` with the string literal of every `import('…')` call and
184
- * `import('…')` type under a node.
185
- * @param {any} node
186
- * @param {(literal: {value: string, start: number, end: number}) => void} onLiteral
187
- */
188
- function visitDynamicReferences(node, onLiteral) {
189
- if (node == null || typeof node !== 'object') return;
190
- if (Array.isArray(node)) {
191
- for (const child of node) visitDynamicReferences(child, onLiteral);
192
- return;
193
- }
194
- if (
195
- node.type === 'CallExpression' &&
196
- node.callee?.type === 'Import' &&
197
- node.arguments[0]?.type === 'StringLiteral'
198
- ) {
199
- onLiteral(node.arguments[0]);
200
- } else if (
201
- node.type === 'ImportExpression' &&
202
- node.source?.type === 'StringLiteral'
203
- ) {
204
- onLiteral(node.source);
205
- } else if (node.type === 'TSImportType') {
206
- const literal =
207
- node.argument?.type === 'TSLiteralType'
208
- ? node.argument.literal
209
- : node.argument;
210
- if (literal?.type === 'StringLiteral') onLiteral(literal);
211
- }
212
- for (const key of Object.keys(node)) {
213
- if (
214
- key === 'loc' ||
215
- key === 'leadingComments' ||
216
- key === 'trailingComments' ||
217
- key === 'innerComments'
218
- )
219
- continue;
220
- const value = node[key];
221
- if (value && typeof value === 'object')
222
- visitDynamicReferences(value, onLiteral);
223
- }
224
- }
225
-
226
- /**
227
- * @typedef {'value' | 'type'} ExportKind `value` reads runtime exports only;
228
- * `type` reads type-only exports too
229
- *
230
- * @typedef {(file: string, kind: ExportKind) => Map<string, {file: string, name: string}>} OriginsOf
231
- * every name a module exports, with where it is declared
232
- *
233
- * @typedef {Map<string, Array<{subpath: string, name: string}>>} ExportersByOrigin
234
- * `file#name` of a declaration -> the subpaths that export it, and as what
235
- *
236
- * @typedef {object} PublicSurface
237
- * @property {Record<ExportKind, ExportersByOrigin>} byOrigin the subpaths
238
- * that export each declaration as a value, and as a value or a type
239
- * @property {Map<string, string>} byFile source file -> the subpath that
240
- * exports exactly that file
241
- * @property {Record<string, unknown>|undefined} exportsField
242
- */
243
-
244
- /**
245
- * Every public subpath of a package with the source file under `root` that
246
- * the shared export readers give it. `./internal/*` is never public.
247
- * @param {{exports?: unknown}} pkg
248
- * @param {string} packageDir
249
- * @param {string} root
250
- * @returns {Array<[string, string]>}
251
- */
252
- function exportedSourceFiles(pkg, packageDir, root) {
253
- const exportsField = pkg.exports;
254
- const subpathMap =
255
- isRecord(exportsField) &&
256
- Object.keys(exportsField).some(key => key.startsWith('.'));
257
- const candidates = new Set(['.']);
258
- if (subpathMap) {
259
- for (const [key, value] of Object.entries(exportsField)) {
260
- if (!key.includes('*')) {
261
- candidates.add(key);
262
- continue;
263
- }
264
- for (const subpath of wildcardSubpaths(packageDir, root, key, value)) {
265
- candidates.add(subpath);
266
- }
267
- }
268
- }
269
- /** @type {Array<[string, string]>} */
270
- const found = [];
271
- for (const subpath of candidates) {
272
- if (/^\.\/internal(\/|$)/.test(subpath)) continue;
273
- const inspected = inspectPackageExport(pkg, packageDir, subpath);
274
- if (!inspected.exported) continue;
275
- const file =
276
- sourceExportTarget(pkg, packageDir, subpath) ?? inspected.target;
277
- if (
278
- file &&
279
- file.startsWith(root + path.sep) &&
280
- !DECLARATION_FILE.test(file)
281
- ) {
282
- found.push([subpath, file]);
283
- }
284
- }
285
- return found;
286
- }
287
-
288
- /**
289
- * The subpaths a `*` key names: one per file its target patterns match.
290
- * @param {string} packageDir
291
- * @param {string} root
292
- * @param {string} key
293
- * @param {unknown} value
294
- * @returns {string[]}
295
- */
296
- function wildcardSubpaths(packageDir, root, key, value) {
297
- /** @type {string[]} */
298
- const subpaths = [];
299
- for (const pattern of allTargets(value)) {
300
- if (!pattern.startsWith('./') || !pattern.includes('*')) continue;
301
- const fixed = pattern.slice(2, pattern.indexOf('*'));
302
- const base = path.resolve(
303
- packageDir,
304
- fixed.slice(0, fixed.lastIndexOf('/') + 1),
305
- );
306
- if (!base.startsWith(root) || !fs.existsSync(base)) continue;
307
- for (const entry of fs.readdirSync(base, {
308
- recursive: true,
309
- withFileTypes: true,
310
- })) {
311
- if (!entry.isFile()) continue;
312
- const file = path.join(entry.parentPath, entry.name);
313
- if (path.relative(base, file).split(path.sep).includes('node_modules'))
314
- continue;
315
- const rel = toPosix(path.relative(packageDir, file));
316
- if (!rel.startsWith(fixed)) continue;
317
- const rest = rel.slice(fixed.length);
318
- for (let end = 1; end <= rest.length; end++) {
319
- const star = rest.slice(0, end);
320
- if (pattern.slice(2).replaceAll('*', star) === rel) {
321
- subpaths.push(key.replace('*', star));
322
- break;
323
- }
324
- }
325
- }
326
- }
327
- return subpaths;
328
- }
329
-
330
- /**
331
- * The owner package's public surface, read from its `exports` map: each
332
- * subpath with a `source` condition under the source root, and the
333
- * declarations it exports. `./internal/*` subpaths are not public.
334
- * @param {string} packageDir
335
- * @param {string} srcRoot
336
- * @param {OriginsOf} originsOf
337
- * @returns {PublicSurface}
338
- */
339
- function publicSurfaceOf(packageDir, srcRoot, originsOf) {
340
- /** @type {{exports?: unknown}} */
341
- let pkg;
342
- try {
343
- pkg = JSON.parse(
344
- fs.readFileSync(path.join(packageDir, 'package.json'), 'utf-8'),
345
- );
346
- } catch {
347
- pkg = {};
348
- }
349
- const exportsField =
350
- pkg.exports && typeof pkg.exports === 'object'
351
- ? /** @type {Record<string, unknown>} */ (pkg.exports)
352
- : undefined;
353
- /** @type {PublicSurface['byOrigin']} */
354
- const byOrigin = {value: new Map(), type: new Map()};
355
- /** @type {PublicSurface['byFile']} */
356
- const byFile = new Map();
357
- for (const [subpath, sourceFile] of exportedSourceFiles(
358
- pkg,
359
- packageDir,
360
- srcRoot,
361
- )) {
362
- byFile.set(sourceFile, subpath);
363
- if (!CODE_FILE.test(sourceFile)) continue;
364
- for (const kind of /** @type {const} */ (['value', 'type'])) {
365
- for (const [name, origin] of originsOf(sourceFile, kind)) {
366
- const key = `${origin.file}#${origin.name}`;
367
- const list = byOrigin[kind].get(key) ?? [];
368
- list.push({subpath, name});
369
- byOrigin[kind].set(key, list);
370
- }
371
- }
372
- }
373
- return {byOrigin, byFile, exportsField};
374
- }
375
-
376
- /**
377
- * A specifier that is either fixed (a public subpath) or computed from where
378
- * two copied files land.
379
- * @typedef {string | {from: string, to: string}} SpecifierChoice
380
- *
381
- * @typedef {object} PlannedEdit
382
- * @property {number} start
383
- * @property {number} end
384
- * @property {(specifierOf: (choice: SpecifierChoice) => string) => string} render
385
- *
386
- * @typedef {object} CopyPlan
387
- * @property {Map<string, {code: string, edits: PlannedEdit[]}>} files every
388
- * file the copy holds (absolute source path), with the edits its imports need
389
- * @property {Map<string, Set<string>>} dependsOn file -> carried files its
390
- * computed specifiers point at
391
- */
392
-
393
- /**
394
- * Follow a component's module graph from its entry files and decide what the
395
- * copy holds. A module inside the component folder is copied. A module
396
- * outside it is reached through the owner package's public exports when every
397
- * name taken from it is public there; otherwise the module that defines the
398
- * name is copied, and imported by relative path. Tests, stories and docs are
399
- * never reached, so they are never copied.
400
- *
401
- * @param {object} options
402
- * @param {string} options.packageDir the owner package root
403
- * @param {string} options.srcRoot its source root
404
- * @param {string} options.componentDir
405
- * @param {string} options.ownerPackage
406
- * @param {string[]} options.entries absolute entry files of the component
407
- * @returns {CopyPlan}
408
- */
409
- export function planCopy({
410
- packageDir,
411
- srcRoot,
412
- componentDir,
413
- ownerPackage,
414
- entries,
415
- }) {
416
- // Every read is cached for this copy only, so a later copy sees the
417
- // package as it is then.
418
- const exportMemos = {value: new Map(), type: new Map()};
419
- /** @type {OriginsOf} */
420
- const originsOf = (file, kind) =>
421
- moduleExportOrigins(file, {
422
- types: kind === 'type',
423
- memo: exportMemos[kind],
424
- });
425
- /** @param {string} file @param {string} name */
426
- const originOf = (file, name) => originsOf(file, 'type').get(name) ?? null;
427
- /**
428
- * The subpaths that export a module's export: as a value when the import
429
- * takes a value, since a type-only export is erased at runtime.
430
- * @param {string} file
431
- * @param {string} name
432
- * @param {boolean} typeOnly
433
- */
434
- const exportersOf = (file, name, typeOnly) => {
435
- const origin = originOf(file, name);
436
- if (!origin) return [];
437
- const kind = typeOnly ? 'type' : 'value';
438
- return surface.byOrigin[kind].get(`${origin.file}#${origin.name}`) ?? [];
439
- };
440
- /**
441
- * The name a module exports one of its own bindings under, or null.
442
- * @param {{file: string, name: string}} origin
443
- */
444
- const exportNameOf = origin => {
445
- for (const [name, found] of originsOf(origin.file, 'type')) {
446
- if (found.file === origin.file && found.name === origin.name) return name;
447
- }
448
- return null;
449
- };
450
- /** @type {Map<string, string|null>} */
451
- const resolutions = new Map();
452
- const surface = publicSurfaceOf(packageDir, srcRoot, originsOf);
453
- /** @type {CopyPlan['files']} */
454
- const files = new Map();
455
- /** @type {CopyPlan['dependsOn']} */
456
- const dependsOn = new Map();
457
- const queue = [...entries];
458
- const queued = new Set(queue);
459
- /** @param {string} file */
460
- const enqueue = file => {
461
- if (!queued.has(file)) {
462
- queued.add(file);
463
- queue.push(file);
464
- }
465
- };
466
- /** @param {string} file */
467
- const inComponent = file => file.startsWith(componentDir + path.sep);
468
- /** @param {string} file */
469
- const inSource = file => file.startsWith(srcRoot + path.sep);
470
-
471
- /**
472
- * The subpath that exports every name a module exports, with the same
473
- * definition. An exactly exported file is its own subpath.
474
- * @param {string} file
475
- * @returns {string|null}
476
- */
477
- const subpathCoveringModule = file => {
478
- const exact = surface.byFile.get(file);
479
- if (exact) return exact;
480
- const names = [...originsOf(file, 'type').keys()];
481
- if (names.length === 0) return null;
482
- const values = originsOf(file, 'value');
483
- const options = names.map(name =>
484
- exportersOf(file, name, !values.has(name))
485
- .filter(o => o.name === name)
486
- .map(o => o.subpath),
487
- );
488
- const common = options.reduce((acc, list) =>
489
- acc.filter(s => list.includes(s)),
490
- );
491
- return STYLEX_FILE.test(file) ? null : pickSubpath(common, file);
492
- };
493
-
494
- /**
495
- * The public subpath to take a name from. A StyleX module is imported by
496
- * its own exported path, because the StyleX compiler resolves styles and
497
- * variables from the real module; when that path is not exported, there is
498
- * no public import.
499
- * @param {string[]} subpaths subpaths that export the name
500
- * @param {string} target the module the import names
501
- * @param {string} [originFile] the module that defines the name
502
- * @returns {string|null}
503
- */
504
- const choosePublic = (subpaths, target, originFile) => {
505
- const exact = originFile ? surface.byFile.get(originFile) : undefined;
506
- if (exact && subpaths.includes(exact)) return exact;
507
- if (
508
- STYLEX_FILE.test(target) ||
509
- (originFile && STYLEX_FILE.test(originFile))
510
- )
511
- return null;
512
- return pickSubpath(subpaths, target);
513
- };
514
-
515
- /**
516
- * Prefer the subpath of the module's top folder, then the package root.
517
- * @param {string[]} subpaths
518
- * @param {string} file
519
- * @returns {string|null}
520
- */
521
- const pickSubpath = (subpaths, file) => {
522
- if (subpaths.length === 0) return null;
523
- const top = `./${toPosix(path.relative(srcRoot, file)).split('/')[0]}`;
524
- return (
525
- subpaths.find(s => s === top) ??
526
- subpaths.find(s => s === '.') ??
527
- [...subpaths].sort((a, b) => a.length - b.length)[0]
528
- );
529
- };
530
-
531
- /** @param {string} subpath */
532
- const publicSpecifier = subpath =>
533
- subpath === '.' ? ownerPackage : `${ownerPackage}/${subpath.slice(2)}`;
534
-
535
- /**
536
- * Carry a module in the copy.
537
- * @param {string} from
538
- * @param {string} to
539
- * @returns {SpecifierChoice}
540
- */
541
- const carry = (from, to) => {
542
- enqueue(to);
543
- const deps = dependsOn.get(from) ?? new Set();
544
- deps.add(to);
545
- dependsOn.set(from, deps);
546
- return {from, to};
547
- };
548
-
549
- while (queue.length > 0) {
550
- const file = /** @type {string} */ (queue.shift());
551
- const parsed = parseModule(file);
552
- /** @type {PlannedEdit[]} */
553
- const edits = [];
554
- files.set(file, {code: parsed.code, edits});
555
- if (!CODE_FILE.test(file)) continue;
556
- for (const ref of parsed.references) {
557
- if (!ref.source.startsWith('.')) continue;
558
- const target = resolveRelative(file, ref.source, resolutions);
559
- // A dangling import is left for the build to report.
560
- if (!target) continue;
561
- if (inComponent(target)) {
562
- // Files of the component keep their relative imports of each other.
563
- if (inComponent(file)) enqueue(target);
564
- else edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
565
- continue;
566
- }
567
- if (!CODE_FILE.test(target) || !inSource(target)) {
568
- // An asset, such as `../../locales/en.json` or a stylesheet, that the
569
- // package exports by its own path is imported from the package.
570
- const subpath = `./${toPosix(path.relative(packageDir, target))}`;
571
- if (
572
- subpathDeclaration(surface.exportsField, subpath).state === 'declared'
573
- ) {
574
- edits.push(
575
- sourceEdit(parsed.code, ref, `${ownerPackage}/${subpath.slice(2)}`),
576
- );
577
- continue;
578
- }
579
- // An unexported asset in the source is carried; one outside it is
580
- // left for the build to report.
581
- if (!inSource(target)) continue;
582
- edits.push(sourceEdit(parsed.code, ref, carry(file, target)));
583
- continue;
584
- }
585
- edits.push(planReference(file, parsed.code, ref, target));
586
- }
587
- }
588
- return {files, dependsOn};
589
-
590
- /**
591
- * Decide one reference that leaves the component folder.
592
- * @param {string} file
593
- * @param {string} code
594
- * @param {ModuleReference} ref
595
- * @param {string} target
596
- * @returns {PlannedEdit}
597
- */
598
- function planReference(file, code, ref, target) {
599
- if (ref.kind !== 'named' && ref.kind !== 'reexportNamed') {
600
- const covering = subpathCoveringModule(target);
601
- return sourceEdit(
602
- code,
603
- ref,
604
- covering ? publicSpecifier(covering) : carry(file, target),
605
- );
606
- }
607
- /** @type {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} */
608
- const groups = [];
609
- /** @param {SpecifierChoice} choice @param {ImportSpecifier} spec */
610
- const add = (choice, spec) => {
611
- const same = groups.find(g =>
612
- typeof choice === 'string'
613
- ? g.choice === choice
614
- : typeof g.choice !== 'string' && g.choice.to === choice.to,
615
- );
616
- if (same) same.specs.push(spec);
617
- else groups.push({choice, specs: [spec]});
618
- };
619
- for (const spec of ref.specifiers) {
620
- if (spec.imported === '*') {
621
- const covering = subpathCoveringModule(target);
622
- add(covering ? publicSpecifier(covering) : carry(file, target), spec);
623
- continue;
624
- }
625
- const origin = originOf(target, spec.imported);
626
- const publicOptions = exportersOf(target, spec.imported, spec.typeOnly);
627
- const chosen = choosePublic(
628
- publicOptions.map(o => o.subpath),
629
- target,
630
- origin?.file,
631
- );
632
- if (chosen) {
633
- const exported = /** @type {{name: string}} */ (
634
- publicOptions.find(o => o.subpath === chosen)
635
- ).name;
636
- add(publicSpecifier(chosen), {...spec, imported: exported});
637
- } else {
638
- // Take the name from the module that defines it, so the copy carries
639
- // that module and not a whole barrel. An origin names a binding, so
640
- // the import uses the name that module exports it under.
641
- // A module that declares the name itself, even as an alias, is carried.
642
- const definingExport =
643
- origin &&
644
- origin.file !== target &&
645
- inSource(origin.file) &&
646
- !parseModule(target).declares.has(spec.imported)
647
- ? exportNameOf(origin)
648
- : null;
649
- if (origin && definingExport != null) {
650
- add(carry(file, origin.file), {...spec, imported: definingExport});
651
- } else {
652
- add(carry(file, target), spec);
653
- }
654
- }
655
- }
656
- // One source and the same names: keep the statement as written and swap
657
- // only its specifier.
658
- const unchangedNames =
659
- groups.length === 1 &&
660
- groups[0].specs.every(
661
- (spec, i) => spec.imported === ref.specifiers[i].imported,
662
- );
663
- if (unchangedNames) return sourceEdit(code, ref, groups[0].choice);
664
- return {
665
- start: ref.start,
666
- end: ref.end,
667
- render: specifierOf => renderStatements(ref, groups, specifierOf),
668
- };
669
- }
670
- }
671
-
672
- /**
673
- * An edit that replaces only the string literal of a reference.
674
- * @param {string} code
675
- * @param {ModuleReference} ref
676
- * @param {SpecifierChoice} choice
677
- * @returns {PlannedEdit}
678
- */
679
- function sourceEdit(code, ref, choice) {
680
- const slice = code.slice(ref.start, ref.end);
681
- const quoted = new RegExp(
682
- `(['"])${ref.source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\1`,
683
- );
684
- const m = slice.match(quoted);
685
- const at = m && m.index != null ? ref.start + m.index : ref.start;
686
- const length = m ? m[0].length : 0;
687
- const quote = m ? m[1] : "'";
688
- return {
689
- start: at,
690
- end: at + length,
691
- render: specifierOf =>
692
- m ? `${quote}${specifierOf(choice)}${quote}` : slice,
693
- };
694
- }
695
-
696
- /**
697
- * The statements that replace one named import or re-export, one per source.
698
- * @param {ModuleReference} ref
699
- * @param {Array<{choice: SpecifierChoice, specs: ImportSpecifier[]}>} groups
700
- * @param {(choice: SpecifierChoice) => string} specifierOf
701
- */
702
- function renderStatements(ref, groups, specifierOf) {
703
- const keyword = ref.kind === 'reexportNamed' ? 'export' : 'import';
704
- const statements = [];
705
- for (const {choice, specs} of groups) {
706
- const specifier = specifierOf(choice);
707
- const star = specs.find(s => s.imported === '*');
708
- if (star) statements.push(`export * as ${star.local} from '${specifier}';`);
709
- const named = specs.filter(s => s.imported !== '*');
710
- if (named.length === 0) continue;
711
- const allType = ref.typeOnly || named.every(s => s.typeOnly);
712
- const parts = named.map(s => {
713
- const prefix = !allType && s.typeOnly ? 'type ' : '';
714
- return s.imported === s.local
715
- ? `${prefix}${s.local}`
716
- : `${prefix}${s.imported} as ${s.local}`;
717
- });
718
- const head = `${keyword} ${allType ? 'type ' : ''}`;
719
- const oneLine = `${head}{${parts.join(', ')}} from '${specifier}';`;
720
- statements.push(
721
- oneLine.length <= 80
722
- ? oneLine
723
- : `${head}{\n${parts.map(p => ` ${p},`).join('\n')}\n} from '${specifier}';`,
724
- );
725
- }
726
- return statements.join('\n');
727
- }
728
-
729
- /**
730
- * The source of a planned file with its edits applied.
731
- * @param {{code: string, edits: PlannedEdit[]}} planned
732
- * @param {(choice: SpecifierChoice) => string} specifierOf
733
- */
734
- export function renderFile(planned, specifierOf) {
735
- let out = planned.code;
736
- for (const edit of [...planned.edits].sort((a, b) => b.start - a.start)) {
737
- out =
738
- out.slice(0, edit.start) + edit.render(specifierOf) + out.slice(edit.end);
739
- }
740
- return out;
741
- }
742
-
743
- /**
744
- * The relative specifier from one written file to another.
745
- * @param {string} fromDest
746
- * @param {string} toDest
747
- */
748
- export function relativeSpecifierBetween(fromDest, toDest) {
749
- let rel = toPosix(path.relative(path.dirname(fromDest), toDest));
750
- rel = DECLARATION_FILE.test(toDest)
751
- ? rel.replace(/\.d\.[cm]?ts$/, '')
752
- : rel.replace(/\.(?:[cm]?[jt]sx?)$/, '');
753
- return rel.startsWith('.') ? rel : `./${rel}`;
754
- }