@astryxdesign/cli 0.7.11 → 0.7.12-canary.07e325e

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 (143) hide show
  1. package/api/build/kit/rank.mjs +21 -4
  2. package/api/build/kit/words.d.mts +1 -0
  3. package/api/build/kit/words.mjs +1 -1
  4. package/api/component/__fixtures__/resolutions/modules.txt +5 -5
  5. package/api/docs/_adapter.d.mts +22 -0
  6. package/api/docs/_adapter.mjs +81 -3
  7. package/api/docs/docs.doc.mjs +5 -5
  8. package/api/docs/docs.type.d.mts +21 -0
  9. package/api/docs/docs.type.mjs +11 -0
  10. package/api/docs/list/list.d.mts +5 -1
  11. package/api/docs/list/list.mjs +72 -6
  12. package/api/docs/node/node.mjs +2 -40
  13. package/api/icon/_adapter.d.mts +3 -2
  14. package/api/icon/_adapter.mjs +8 -2
  15. package/api/icon/_authoring.d.mts +1 -0
  16. package/api/icon/_authoring.mjs +586 -66
  17. package/api/icon/_default-look.d.mts +155 -0
  18. package/api/icon/_default-look.mjs +474 -0
  19. package/api/icon/_records.d.mts +1 -1
  20. package/api/icon/_records.mjs +1 -0
  21. package/api/icon/add/add.mjs +224 -38
  22. package/api/icon/icon.type.d.mts +22 -2
  23. package/api/icon/icon.type.mjs +6 -2
  24. package/api/icon/iconAdd.doc.mjs +2 -2
  25. package/api/icon/iconNewDefinition.doc.mjs +3 -2
  26. package/api/icon/iconNewSet.doc.mjs +4 -4
  27. package/api/icon/search/search.mjs +10 -9
  28. package/api/index.d.mts +1 -0
  29. package/api/index.mjs +1 -0
  30. package/api/integration/add-helpers.d.mts +11 -1
  31. package/api/integration/add-helpers.mjs +5 -2
  32. package/api/integration/authoring-checks.d.mts +0 -2
  33. package/api/integration/authoring-checks.mjs +1 -6
  34. package/api/logger.mjs +2 -1
  35. package/api/render/_adapter.mjs +9 -0
  36. package/api/render/render.doc.mjs +2 -2
  37. package/api/search/_adapter.d.mts +22 -1
  38. package/api/search/_adapter.mjs +37 -20
  39. package/api/search/exportSearchIndex.doc.d.mts +10 -0
  40. package/api/search/exportSearchIndex.doc.mjs +58 -0
  41. package/api/search/rankSearchIndex.doc.d.mts +10 -0
  42. package/api/search/rankSearchIndex.doc.mjs +79 -0
  43. package/api/search/search-index.d.mts +44 -0
  44. package/api/search/search-index.mjs +270 -0
  45. package/api/search/search.type.d.mts +28 -0
  46. package/api/search/search.type.mjs +17 -0
  47. package/api/swizzle/_adapter.d.mts +1 -0
  48. package/api/swizzle/_adapter.mjs +4 -1
  49. package/api/swizzle/_moduleGraph.d.mts +178 -0
  50. package/api/swizzle/_moduleGraph.mjs +903 -0
  51. package/api/swizzle/copy/copy.d.mts +2 -43
  52. package/api/swizzle/copy/copy.mjs +287 -315
  53. package/api/swizzle/swizzle.d.mts +0 -2
  54. package/api/swizzle/swizzle.doc.mjs +13 -4
  55. package/api/swizzle/swizzle.mjs +3 -7
  56. package/api/swizzle/swizzle.type.d.mts +7 -1
  57. package/api/swizzle/swizzle.type.mjs +4 -2
  58. package/api/template/template.mjs +1 -0
  59. package/assets/discover/official-packages.json +36 -0
  60. package/assets/docs/browser-support.doc.mjs +2 -2
  61. package/assets/docs/styling-overview.doc.mjs +6 -2
  62. package/assets/docs/tree/icon-sets.doc.mjs +11 -5
  63. package/assets/docs/tree/render-pages.doc.mjs +2 -2
  64. package/assets/docs/tree/tailwind.doc.mjs +41 -1
  65. package/assets/docs/tree/type-scale.doc.mjs +19 -2
  66. package/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.doc.mjs +14 -0
  67. package/assets/templates/blocks/components/Calendar/useCalendarConstraintsHookUsage.tsx +146 -0
  68. package/assets/templates/blocks/components/Calendar/useCalendarNavigationHookUsage.doc.mjs +14 -0
  69. package/assets/templates/blocks/components/Calendar/useCalendarNavigationHookUsage.tsx +173 -0
  70. package/assets/templates/blocks/components/Hooks/useInputStatusIconHookUsage.tsx +1 -0
  71. package/assets/templates/blocks/components/Hooks/useInteractiveRoleHookUsage.doc.mjs +14 -0
  72. package/assets/templates/blocks/components/Hooks/useInteractiveRoleHookUsage.tsx +56 -0
  73. package/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.doc.mjs +2 -2
  74. package/assets/templates/blocks/components/Hooks/useStreamingTextHookUsage.tsx +66 -10
  75. package/assets/templates/blocks/components/Link/useLinkifyHookUsage.doc.mjs +14 -0
  76. package/assets/templates/blocks/components/Link/useLinkifyHookUsage.tsx +39 -0
  77. package/assets/templates/blocks/components/PowerSearch/usePowerSearchConfigHookUsage.doc.mjs +14 -0
  78. package/assets/templates/blocks/components/PowerSearch/usePowerSearchConfigHookUsage.tsx +83 -0
  79. package/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.doc.mjs +14 -0
  80. package/assets/templates/blocks/components/Table/RowsVirtualizationHookUsage.tsx +35 -0
  81. package/assets/templates/blocks/components/Table/TableRowIndexTable.doc.mjs +1 -1
  82. package/assets/templates/blocks/components/Table/TableRowIndexTable.tsx +2 -2
  83. package/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/useTableColumnSettingsStateHookUsage.tsx +97 -0
  85. package/assets/templates/pages/course-detail/page.tsx +699 -0
  86. package/assets/templates/pages/course-detail/template.doc.mjs +37 -0
  87. package/assets/templates/pages/file-explorer/page.tsx +103 -79
  88. package/assets/templates/pages/table-filter/page.tsx +15 -23
  89. package/assets/templates/pages/table-grouped/page.tsx +160 -232
  90. package/assets/templates/pages/table-grouped/template.doc.mjs +0 -2
  91. package/assets/templates/pages/table-inbox/page.tsx +3 -6
  92. package/assets/templates/pages/theme-showcase/page.tsx +724 -792
  93. package/assets/templates/pages/theme-showcase/template.doc.mjs +4 -5
  94. package/assets/templates/themes/butter/butterTheme.ts +2 -2
  95. package/assets/templates/themes/stone/stoneTheme.ts +1 -1
  96. package/assets/templates/themes/y2k/y2kTheme.ts +1 -1
  97. package/authoring/doctypes/template/type.ts +1 -0
  98. package/clients/cli/commands/docs.doc.mjs +5 -1
  99. package/clients/cli/commands/docs.mjs +30 -2
  100. package/clients/cli/commands/experimental/icon.mjs +31 -10
  101. package/clients/cli/commands/experimental-icon-add.doc.mjs +1 -1
  102. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +2 -1
  103. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +2 -2
  104. package/clients/cli/commands/swizzle.doc.mjs +12 -3
  105. package/clients/cli/commands/swizzle.mjs +33 -9
  106. package/clients/cli/lib/resolve-theme.mjs +16 -7
  107. package/foundation/discovery/component-loader.d.mts +1 -1
  108. package/foundation/discovery/doc-types.mjs +9 -2
  109. package/foundation/discovery/hook-discovery.mjs +31 -8
  110. package/foundation/discovery/icon-ranking.d.mts +27 -3
  111. package/foundation/discovery/icon-ranking.mjs +125 -8
  112. package/foundation/discovery/icon-set-checks.mjs +44 -35
  113. package/foundation/discovery/icon-set-discovery.d.mts +13 -0
  114. package/foundation/discovery/icon-set-discovery.mjs +25 -0
  115. package/foundation/discovery/icon-set-writer.d.mts +238 -16
  116. package/foundation/discovery/icon-set-writer.mjs +676 -79
  117. package/foundation/discovery/module-exports.d.mts +3 -2
  118. package/foundation/discovery/module-exports.mjs +167 -37
  119. package/foundation/doc-compiler/import.d.mts +5 -1
  120. package/foundation/doc-compiler/import.mjs +40 -6
  121. package/foundation/fs/import-url.d.mts +20 -0
  122. package/foundation/fs/import-url.mjs +22 -0
  123. package/foundation/fs/module-loader.d.mts +24 -3
  124. package/foundation/fs/module-loader.mjs +69 -47
  125. package/foundation/fs/paths.d.mts +2 -1
  126. package/foundation/fs/paths.mjs +3 -4
  127. package/foundation/render/charts.d.mts +59 -0
  128. package/foundation/render/charts.mjs +216 -0
  129. package/foundation/render/embedded-imports.d.mts +7 -7
  130. package/foundation/render/embedded-imports.mjs +63 -54
  131. package/foundation/render/page-worker.mjs +339 -52
  132. package/foundation/render/render-page.mjs +26 -10
  133. package/foundation/render/ts-paths.d.mts +63 -0
  134. package/foundation/render/ts-paths.mjs +138 -0
  135. package/foundation/response/error-codes.doc.mjs +2 -2
  136. package/foundation/response/error-codes.mjs +3 -2
  137. package/foundation/text/levenshtein.d.mts +6 -1
  138. package/foundation/text/levenshtein.mjs +25 -9
  139. package/foundation/text/shell-arg.d.mts +14 -0
  140. package/foundation/text/shell-arg.mjs +17 -0
  141. package/foundation/text/suggest-order.d.mts +8 -1
  142. package/foundation/text/suggest-order.mjs +72 -6
  143. package/package.json +7 -6
@@ -40,30 +40,6 @@ function getJiti() {
40
40
  return jitiInstance;
41
41
  }
42
42
 
43
- /**
44
- * Node treats `.js` as ESM only inside the nearest package scope whose
45
- * package.json declares `"type": "module"`; no package.json defaults to
46
- * CommonJS.
47
- * @param {string} file
48
- * @returns {boolean}
49
- */
50
- function isCommonJsFile(file) {
51
- let dir = path.dirname(file);
52
- for (;;) {
53
- const packageJson = path.join(dir, 'package.json');
54
- if (fs.existsSync(packageJson)) {
55
- try {
56
- return JSON.parse(fs.readFileSync(packageJson, 'utf-8')).type !== 'module';
57
- } catch {
58
- return true;
59
- }
60
- }
61
- const parent = path.dirname(dir);
62
- if (parent === dir) return true;
63
- dir = parent;
64
- }
65
- }
66
-
67
43
  let loadsInFlight = 0;
68
44
  /** @type {typeof process.stdout.write | undefined} */
69
45
  let realStdoutWrite;
@@ -104,9 +80,9 @@ async function withStdoutOnStderr(load) {
104
80
  /**
105
81
  * Import a user-authored module. `.ts` is loaded via jiti; `.mjs`/`.js` use
106
82
  * native dynamic import for ordinary cached reads. A fresh `.ts` read uses a
107
- * no-cache jiti instance. A fresh CommonJS `.js` read evicts and reloads through
108
- * `require`; an ESM `.js` or `.mjs` read uses a cache-busted file URL. The
109
- * nearest package.json `type` decides `.js`, matching Node's package scopes.
83
+ * no-cache jiti instance. Any other fresh read drops the module from the
84
+ * require cache and imports a cache-busted file URL. Node then chooses its
85
+ * format as for the first read, so a fresh read gives what a first read gives.
110
86
  * Normal loads retain module caching. `fresh` rereads a file that changed
111
87
  * during this process: one a codemod rewrote, or an edited doc file (the doc
112
88
  * importers in ../doc-compiler/import.mjs read each change once).
@@ -251,31 +227,77 @@ async function importModule(file, fresh) {
251
227
  if (fresh && file.endsWith('.ts')) {
252
228
  return await createJiti(import.meta.url, {moduleCache: false}).import(file);
253
229
  }
254
- if (fresh && file.endsWith('.js') && isCommonJsFile(file)) {
255
- const resolved = requireFromHere.resolve(file);
256
- delete requireFromHere.cache[resolved];
257
- const value = requireFromHere(file);
258
- if (
259
- value != null &&
260
- typeof value === 'object' &&
261
- value.__esModule === true &&
262
- Object.prototype.hasOwnProperty.call(value, 'default')
263
- ) {
264
- return value;
265
- }
266
- return {
267
- ...(value != null && typeof value === 'object' ? value : {}),
268
- default: value,
269
- };
270
- }
271
230
  if (file.endsWith('.ts')) {
272
231
  return await getJiti().import(file);
273
232
  }
274
233
  const url = pathToFileURL(file);
275
- if (fresh) {
276
- url.searchParams.set('astryx-fresh', String(++freshImportNonce));
234
+ if (!fresh) return await readInTurn(file, () => import(url.href));
235
+ // Node chooses the format again, as for the first import: a package's
236
+ // "type", the extension, or the source's syntax. The query names a new ES
237
+ // module. A CommonJS module also needs its cache entry gone.
238
+ url.searchParams.set('astryx-fresh', String(++freshImportNonce));
239
+ return await readFreshInTurn(file, () => import(url.href));
240
+ }
241
+
242
+ /**
243
+ * The name Node's CommonJS cache gives `file`: its real path, so a link and
244
+ * its target name one entry. A file that does not resolve keeps its path.
245
+ * @param {string} file absolute path
246
+ * @returns {string}
247
+ */
248
+ function cacheKey(file) {
249
+ try {
250
+ return requireFromHere.resolve(file);
251
+ } catch {
252
+ return file;
277
253
  }
278
- return await import(url.href);
254
+ }
255
+
256
+ /**
257
+ * Each file's latest read, by its cache name, settled once that read ends.
258
+ * @type {Map<string, Promise<void>>}
259
+ */
260
+ const readsInProgress = new Map();
261
+
262
+ /**
263
+ * Run `read`, an import of `file`, once the imports of `file` started before
264
+ * it have ended. Imports of other files do not wait. A fresh read removes the
265
+ * file from Node's CommonJS cache. A CommonJS import still in progress needs
266
+ * that entry until it ends.
267
+ * @template T
268
+ * @param {string} file absolute path
269
+ * @param {() => Promise<T>} read
270
+ * @returns {Promise<T>}
271
+ */
272
+ export function readInTurn(file, read) {
273
+ const key = cacheKey(file);
274
+ const before = readsInProgress.get(key) ?? Promise.resolve();
275
+ const result = before.then(read);
276
+ const ended = result.then(
277
+ () => {},
278
+ () => {},
279
+ );
280
+ readsInProgress.set(key, ended);
281
+ void ended.then(() => {
282
+ if (readsInProgress.get(key) === ended) readsInProgress.delete(key);
283
+ });
284
+ return result;
285
+ }
286
+
287
+ /**
288
+ * Run `read`, a fresh import of `file`, in the file's turn (`readInTurn`),
289
+ * once the file is gone from Node's CommonJS cache. A new URL names a new ES
290
+ * module only, so a CommonJS module also needs its cache entry gone.
291
+ * @template T
292
+ * @param {string} file absolute path
293
+ * @param {() => Promise<T>} read
294
+ * @returns {Promise<T>}
295
+ */
296
+ export function readFreshInTurn(file, read) {
297
+ return readInTurn(file, () => {
298
+ delete requireFromHere.cache[cacheKey(file)];
299
+ return read();
300
+ });
279
301
  }
280
302
 
281
303
 
@@ -166,7 +166,8 @@ export function discoverExternalPackages(startDir?: string): {
166
166
  }[];
167
167
  /**
168
168
  * List available component directories in packages/core/src.
169
- * Returns directory names that contain Astryx*.tsx files.
169
+ * Component directories are capitalized (`Button`, `Dialog`); lowercase
170
+ * directories hold shared infrastructure and are never listed.
170
171
  * @param {string} coreDir
171
172
  */
172
173
  export function listComponents(coreDir: string): string[];
@@ -854,7 +854,8 @@ export function discoverExternalPackages(startDir = process.cwd()) {
854
854
 
855
855
  /**
856
856
  * List available component directories in packages/core/src.
857
- * Returns directory names that contain Astryx*.tsx files.
857
+ * Component directories are capitalized (`Button`, `Dialog`); lowercase
858
+ * directories hold shared infrastructure and are never listed.
858
859
  * @param {string} coreDir
859
860
  */
860
861
  export function listComponents(coreDir) {
@@ -865,9 +866,7 @@ export function listComponents(coreDir) {
865
866
  return entries
866
867
  .filter(e => {
867
868
  if (!e.isDirectory()) return false;
868
- // Skip non-component dirs
869
- if (['hooks', 'theme', 'utils'].includes(e.name)) return false;
870
- return true;
869
+ return /^[A-Z]/.test(e.name);
871
870
  })
872
871
  .map(e => e.name)
873
872
  .sort();
@@ -0,0 +1,59 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * The size a ResponsiveContainer starts at: its own numbers where it has
6
+ * them. Otherwise the width follows the height: six times it for a
7
+ * sparkline, which sits in a narrow card or a table cell, and two and a half
8
+ * times it for a taller chart. The drawing then scales to the width the
9
+ * page gives it, so its text stays near its own size in most layouts.
10
+ * @param {{width?: unknown, height?: unknown, aspect?: unknown}} props
11
+ * @returns {{width: number, height: number}}
12
+ */
13
+ export function chartSize({ width, height, aspect }: {
14
+ width?: unknown;
15
+ height?: unknown;
16
+ aspect?: unknown;
17
+ }): {
18
+ width: number;
19
+ height: number;
20
+ };
21
+ /**
22
+ * Mark each container chart whose legend is vertical and on one side with
23
+ * that side, and whether it sits at the bottom or the middle, for
24
+ * {@link CHART_CSS}. A vertically centered legend has a `top` near the
25
+ * middle (no room is kept for it in a container chart). A vertical legend
26
+ * centered across takes its own row, as a horizontal one does.
27
+ * @param {any} root the element the charts were drawn in
28
+ */
29
+ export function markLegends(root: any): void;
30
+ /**
31
+ * Give this thread the small document a chart draws in: no layout, no
32
+ * motion, and no frames to wait for.
33
+ * @returns {Promise<void>}
34
+ */
35
+ export function chartDocument(): Promise<void>;
36
+ /**
37
+ * @file Charts in a rendered page. A recharts chart draws only after its
38
+ * effects run, and a ResponsiveContainer measures its parent in a browser, so
39
+ * a server render leaves them empty. The render worker draws each one again
40
+ * in a small document, at the size the container starts at, and puts the
41
+ * drawing in its place.
42
+ *
43
+ * @input The chart elements the server render set aside.
44
+ * @output Their markup, and the CSS that lets a drawn chart fit its width.
45
+ * @position foundation/render — read by page-worker.mjs and render-page.mjs.
46
+ */
47
+ /** The global the render worker installs to set charts aside. SYNC: page-worker.mjs assigns it by this name. */
48
+ export const CHART_GLOBAL: "__astryxRenderChart";
49
+ /** The recharts exports that draw a chart, besides ResponsiveContainer. */
50
+ export const CHART_ROOTS: Set<string>;
51
+ /**
52
+ * A chart drawn at its starting size scales to the width the page gives it
53
+ * and keeps its shape, so it never overflows its card. Its legend stays out
54
+ * of the scaled picture, so its text never covers the chart however narrow
55
+ * the page is. A horizontal legend takes its own row under the picture, or
56
+ * above it when it asks for the top. A vertical legend on one side sits
57
+ * beside the picture, on that side.
58
+ */
59
+ export const CHART_CSS: string;
@@ -0,0 +1,216 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Charts in a rendered page. A recharts chart draws only after its
5
+ * effects run, and a ResponsiveContainer measures its parent in a browser, so
6
+ * a server render leaves them empty. The render worker draws each one again
7
+ * in a small document, at the size the container starts at, and puts the
8
+ * drawing in its place.
9
+ *
10
+ * @input The chart elements the server render set aside.
11
+ * @output Their markup, and the CSS that lets a drawn chart fit its width.
12
+ * @position foundation/render — read by page-worker.mjs and render-page.mjs.
13
+ */
14
+
15
+ /** The global the render worker installs to set charts aside. SYNC: page-worker.mjs assigns it by this name. */
16
+ export const CHART_GLOBAL = '__astryxRenderChart';
17
+
18
+ /** The recharts exports that draw a chart, besides ResponsiveContainer. */
19
+ export const CHART_ROOTS = new Set([
20
+ 'AreaChart',
21
+ 'BarChart',
22
+ 'ComposedChart',
23
+ 'FunnelChart',
24
+ 'LineChart',
25
+ 'PieChart',
26
+ 'RadarChart',
27
+ 'RadialBarChart',
28
+ 'Sankey',
29
+ 'ScatterChart',
30
+ 'SunburstChart',
31
+ 'Treemap',
32
+ ]);
33
+
34
+ /** Widest starting size for a chart its page lets fill the width. */
35
+ const CHART_MAX_WIDTH = 800;
36
+
37
+ /** Height of a chart that names none. */
38
+ const CHART_HEIGHT = 300;
39
+
40
+ /** Height up to which a chart counts as a sparkline. */
41
+ const SPARKLINE_HEIGHT = 60;
42
+
43
+ /**
44
+ * The size a ResponsiveContainer starts at: its own numbers where it has
45
+ * them. Otherwise the width follows the height: six times it for a
46
+ * sparkline, which sits in a narrow card or a table cell, and two and a half
47
+ * times it for a taller chart. The drawing then scales to the width the
48
+ * page gives it, so its text stays near its own size in most layouts.
49
+ * @param {{width?: unknown, height?: unknown, aspect?: unknown}} props
50
+ * @returns {{width: number, height: number}}
51
+ */
52
+ export function chartSize({width, height, aspect}) {
53
+ const ratio = typeof aspect === 'number' && aspect > 0 ? aspect : null;
54
+ const w = typeof width === 'number' && width > 0 ? width : null;
55
+ const h =
56
+ typeof height === 'number' && height > 0
57
+ ? height
58
+ : ratio
59
+ ? (w ?? CHART_MAX_WIDTH) / ratio
60
+ : CHART_HEIGHT;
61
+ return {
62
+ width:
63
+ w ??
64
+ (ratio
65
+ ? h * ratio
66
+ : Math.min(CHART_MAX_WIDTH, Math.round(h * (h <= SPARKLINE_HEIGHT ? 6 : 2.5)))),
67
+ height: h,
68
+ };
69
+ }
70
+
71
+ /**
72
+ * A chart drawn at its starting size scales to the width the page gives it
73
+ * and keeps its shape, so it never overflows its card. Its legend stays out
74
+ * of the scaled picture, so its text never covers the chart however narrow
75
+ * the page is. A horizontal legend takes its own row under the picture, or
76
+ * above it when it asks for the top. A vertical legend on one side sits
77
+ * beside the picture, on that side.
78
+ */
79
+ export const CHART_CSS =
80
+ '.recharts-responsive-container{width:100%}' +
81
+ '.recharts-responsive-container>.recharts-wrapper{width:100%!important;height:auto!important;display:flex;flex-direction:column}' +
82
+ // Only the chart's own picture scales; a legend's icons keep their size.
83
+ '.recharts-responsive-container>.recharts-wrapper>svg.recharts-surface{width:100%!important;height:auto!important}' +
84
+ '.recharts-responsive-container>.recharts-wrapper>.recharts-legend-wrapper{position:static!important;width:auto!important;height:auto!important}' +
85
+ '.recharts-responsive-container>.recharts-wrapper:not([data-legend-side])>.recharts-legend-wrapper[style*="bottom"]{order:1}' +
86
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]{flex-direction:row;align-items:flex-start}' +
87
+ // A side is physical, as in a chart of fixed size: a right-to-left page
88
+ // reverses the row so the legend stays on the side it asked for.
89
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]:dir(rtl){flex-direction:row-reverse}' +
90
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side][data-legend-middle]{align-items:center}' +
91
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side][data-legend-bottom]{align-items:flex-end}' +
92
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]>svg.recharts-surface{flex:1 1 0;min-width:0}' +
93
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]>.recharts-legend-wrapper{flex:none}' +
94
+ // recharts puts the legend before the picture; one on the right goes after it.
95
+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side="right"]>.recharts-legend-wrapper{order:1}';
96
+
97
+ /**
98
+ * Mark each container chart whose legend is vertical and on one side with
99
+ * that side, and whether it sits at the bottom or the middle, for
100
+ * {@link CHART_CSS}. A vertically centered legend has a `top` near the
101
+ * middle (no room is kept for it in a container chart). A vertical legend
102
+ * centered across takes its own row, as a horizontal one does.
103
+ * @param {any} root the element the charts were drawn in
104
+ */
105
+ export function markLegends(root) {
106
+ for (const wrapper of root.querySelectorAll('.recharts-responsive-container > .recharts-wrapper')) {
107
+ const legend = wrapper.querySelector(':scope > .recharts-legend-wrapper');
108
+ if (!legend) continue;
109
+ const vertical = [...legend.querySelectorAll('.recharts-legend-item')].some(item =>
110
+ /display:\s*block/.test(item.getAttribute('style') ?? ''),
111
+ );
112
+ if (!vertical) continue;
113
+ const style = legend.getAttribute('style') ?? '';
114
+ // recharts places a right-aligned legend with `right`, a left-aligned one
115
+ // at the chart's left margin, and a centered one half way across.
116
+ const width = Number(wrapper.getAttribute('width'));
117
+ const left = Number(/(?:^|;)\s*left\s*:\s*(-?[\d.]+)px/.exec(style)?.[1]);
118
+ const side = /(?:^|;)\s*right\s*:/.test(style)
119
+ ? 'right'
120
+ : Number.isFinite(left) && width > 0 && left < width * 0.2
121
+ ? 'left'
122
+ : null;
123
+ if (!side) continue;
124
+ wrapper.setAttribute('data-legend-side', side);
125
+ const top = Number(/(?:^|;)\s*top\s*:\s*(-?[\d.]+)px/.exec(style)?.[1]);
126
+ const height = Number(wrapper.getAttribute('height'));
127
+ if (/(?:^|;)\s*bottom\s*:/.test(style)) wrapper.setAttribute('data-legend-bottom', '');
128
+ else if (top > 0 && height > 0 && top > height * 0.2) wrapper.setAttribute('data-legend-middle', '');
129
+ }
130
+ }
131
+
132
+ /**
133
+ * The box a legend would measure in a browser, estimated from its items, so
134
+ * a chart of fixed size keeps room for it where its props place it: rows for
135
+ * a horizontal legend, one line per item for a vertical one. A chart sized by
136
+ * its container keeps no room, because its legend takes its own row.
137
+ * @param {any} el the legend wrapper
138
+ */
139
+ function legendBox(el) {
140
+ if (el.closest?.('.recharts-responsive-container')) return box(0, 0);
141
+ const items = [...el.querySelectorAll('.recharts-legend-item')];
142
+ const widths = items.map(item => 14 + 4 + 7 * (item.textContent ?? '').length + 10);
143
+ const vertical = items.some(item => /display:\s*block/.test(item.getAttribute('style') ?? ''));
144
+ if (vertical) return box(Math.max(0, ...widths), 20 * items.length + 10);
145
+ // A row as wide as the legend's own width holds the items it can; the rest
146
+ // wrap onto more rows.
147
+ const total = widths.reduce((a, b) => a + b, 0);
148
+ const room = Number(/(?:^|;)\s*width\s*:\s*([\d.]+)px/.exec(el.getAttribute('style') ?? '')?.[1]);
149
+ const rows = room > 0 ? Math.max(1, Math.ceil(total / room)) : 1;
150
+ return box(Math.min(total, room > 0 ? room : total), 24 * rows);
151
+ }
152
+
153
+ /** @param {number} width @param {number} height */
154
+ const box = (width, height) => ({x: 0, y: 0, top: 0, left: 0, right: width, bottom: height, width, height});
155
+
156
+ /** Font size of text that names none, as an axis tick's. */
157
+ const TEXT_SIZE = 14;
158
+
159
+ /**
160
+ * The box recharts' measurement span would measure: its text at its font
161
+ * size, about 0.6 em per character and 1.2 em high.
162
+ * @param {any} el
163
+ */
164
+ function textBox(el) {
165
+ const fromStyle = el.style?.fontSize ?? /(?:^|;)\s*font-size\s*:\s*([^;]+)/.exec(el.getAttribute?.('style') ?? '')?.[1];
166
+ const size = Number.parseFloat(String(fromStyle ?? '')) || TEXT_SIZE;
167
+ return box(Math.round(String(el.textContent ?? '').length * size * 0.6), Math.round(size * 1.2));
168
+ }
169
+
170
+ /**
171
+ * Give this thread the small document a chart draws in: no layout, no
172
+ * motion, and no frames to wait for.
173
+ * @returns {Promise<void>}
174
+ */
175
+ export async function chartDocument() {
176
+ const {parseHTML} = await import('linkedom');
177
+ const {window} = parseHTML('<!doctype html><html><head></head><body></body></html>');
178
+ const g = /** @type {any} */ (globalThis);
179
+ const quiet = () => ({
180
+ matches: true,
181
+ addEventListener() {},
182
+ removeEventListener() {},
183
+ addListener() {},
184
+ removeListener() {},
185
+ });
186
+ Object.assign(window, {
187
+ matchMedia: quiet,
188
+ // Every style property reads as empty, as for an element with no CSS.
189
+ getComputedStyle: () => new Proxy({getPropertyValue: () => ''}, {get: (o, k) => (k in o ? /** @type {any} */ (o)[k] : '')}),
190
+ requestAnimationFrame: (/** @type {(t: number) => void} */ cb) => setTimeout(() => cb(Date.now()), 0),
191
+ cancelAnimationFrame: (/** @type {any} */ id) => clearTimeout(id),
192
+ ResizeObserver: class {
193
+ observe() {}
194
+ unobserve() {}
195
+ disconnect() {}
196
+ },
197
+ });
198
+ g.window = window;
199
+ g.document = window.document;
200
+ g.matchMedia = window.matchMedia;
201
+ g.getComputedStyle = window.getComputedStyle;
202
+ g.requestAnimationFrame = window.requestAnimationFrame;
203
+ g.cancelAnimationFrame = window.cancelAnimationFrame;
204
+ g.ResizeObserver = window.ResizeObserver;
205
+ // Nothing is laid out, so every box measures zero, except a legend's and
206
+ // the span recharts measures text with, which are estimated: the chart
207
+ // keeps room for its legend, and lays out its axis labels as in a browser.
208
+ Object.defineProperty(window.Element.prototype, 'getBoundingClientRect', {
209
+ configurable: true,
210
+ writable: true,
211
+ value() {
212
+ if (this.getAttribute?.('id') === 'recharts_measurement_span') return textBox(this);
213
+ return String(this.getAttribute?.('class') ?? '').includes('recharts-legend-wrapper') ? legendBox(this) : box(0, 0);
214
+ },
215
+ });
216
+ }
@@ -23,12 +23,12 @@ export function importSpecifiers(source: string, file: string): string[];
23
23
  */
24
24
  export function assetRefsIn(text: string): string[];
25
25
  /**
26
- * Path aliases (`compilerOptions.paths`) of the project that holds `dir`, as
27
- * absolute prefixes: `"@/*": ["./src/*"]` becomes `["@/", "<root>/src/"]`.
26
+ * The path aliases (`compilerOptions.paths`) of the project that holds
27
+ * `dir`, by TypeScript's rules (see ts-paths.mjs).
28
28
  * @param {string} dir
29
- * @returns {[string, string][]}
29
+ * @returns {import('./ts-paths.mjs').PathPattern[]}
30
30
  */
31
- export function receivingAliases(dir: string): [string, string][];
31
+ export function receivingAliases(dir: string): import("./ts-paths.mjs").PathPattern[];
32
32
  /**
33
33
  * @typedef {object} Reach
34
34
  * @property {boolean} relative - Reached by a relative import (or it is the
@@ -40,8 +40,8 @@ export function receivingAliases(dir: string): [string, string][];
40
40
  * The embedded files the page reaches through its imports.
41
41
  * @param {{path: string, base64: string}[]} files the embedded files, page
42
42
  * first; every path appears once (callers refuse duplicates first)
43
- * @param {{aliases?: [string, string][]}} [options] the receiving project's
44
- * path aliases, absolute (see receivingAliases)
43
+ * @param {{aliases?: import('./ts-paths.mjs').PathPattern[]}} [options] the
44
+ * receiving project's path aliases (see receivingAliases)
45
45
  * @returns {{reached: Map<string, Reach>, missing: string[]}} the reached
46
46
  * tree paths, and the relative imports the file does not carry
47
47
  */
@@ -49,7 +49,7 @@ export function reachableFiles(files: {
49
49
  path: string;
50
50
  base64: string;
51
51
  }[], { aliases }?: {
52
- aliases?: [string, string][];
52
+ aliases?: import("./ts-paths.mjs").PathPattern[];
53
53
  }): {
54
54
  reached: Map<string, Reach>;
55
55
  missing: string[];
@@ -18,6 +18,7 @@ import * as path from 'node:path';
18
18
  import {parse} from '@babel/parser';
19
19
  import {PAGE_EXTENSIONS} from './embedded-files.mjs';
20
20
  import postcss from 'postcss';
21
+ import {matchPath, readPathsIn} from './ts-paths.mjs';
21
22
  import {isAssetPath} from './assets.mjs';
22
23
 
23
24
  /**
@@ -131,41 +132,17 @@ function scanModule(source, file) {
131
132
  }
132
133
 
133
134
  /**
134
- * Path aliases (`compilerOptions.paths`) of the project that holds `dir`, as
135
- * absolute prefixes: `"@/*": ["./src/*"]` becomes `["@/", "<root>/src/"]`.
135
+ * The path aliases (`compilerOptions.paths`) of the project that holds
136
+ * `dir`, by TypeScript's rules (see ts-paths.mjs).
136
137
  * @param {string} dir
137
- * @returns {[string, string][]}
138
+ * @returns {import('./ts-paths.mjs').PathPattern[]}
138
139
  */
139
140
  export function receivingAliases(dir) {
140
141
  let d = dir;
141
142
  while (!fs.existsSync(d) && path.dirname(d) !== d) d = path.dirname(d);
142
143
  for (;;) {
143
- for (const name of ['tsconfig.json', 'jsconfig.json']) {
144
- const file = path.join(d, name);
145
- if (!fs.existsSync(file)) continue;
146
- try {
147
- const text = fs
148
- .readFileSync(file, 'utf8')
149
- .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
150
- .replace(/,(\s*[}\]])/g, '$1');
151
- const options = JSON.parse(text)?.compilerOptions ?? {};
152
- const base = path.resolve(d, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
153
- /** @type {[string, string][]} */
154
- const out = [];
155
- for (const [key, targets] of Object.entries(options.paths ?? {})) {
156
- const target = Array.isArray(targets) ? targets[0] : undefined;
157
- if (typeof target !== 'string') continue;
158
- if (key.endsWith('/*') && target.endsWith('/*')) {
159
- out.push([key.slice(0, -1), `${path.resolve(base, target.slice(0, -2))}${path.sep}`]);
160
- } else if (!key.includes('*') && !target.includes('*')) {
161
- out.push([key, path.resolve(base, target)]);
162
- }
163
- }
164
- return out;
165
- } catch {
166
- return [];
167
- }
168
- }
144
+ const found = readPathsIn(d);
145
+ if (found) return found;
169
146
  if (fs.existsSync(path.join(d, 'package.json'))) return [];
170
147
  const up = path.dirname(d);
171
148
  if (up === d) return [];
@@ -185,8 +162,8 @@ export function receivingAliases(dir) {
185
162
  * The embedded files the page reaches through its imports.
186
163
  * @param {{path: string, base64: string}[]} files the embedded files, page
187
164
  * first; every path appears once (callers refuse duplicates first)
188
- * @param {{aliases?: [string, string][]}} [options] the receiving project's
189
- * path aliases, absolute (see receivingAliases)
165
+ * @param {{aliases?: import('./ts-paths.mjs').PathPattern[]}} [options] the
166
+ * receiving project's path aliases (see receivingAliases)
190
167
  * @returns {{reached: Map<string, Reach>, missing: string[]}} the reached
191
168
  * tree paths, and the relative imports the file does not carry
192
169
  */
@@ -285,29 +262,61 @@ export function reachableFiles(files, {aliases = []} = {}) {
285
262
  if (fresh) queue.push(target);
286
263
  continue;
287
264
  }
288
- for (const [key, aliasTarget] of aliases) {
289
- const named = key.endsWith('/') ? bare.startsWith(key) : bare === key;
290
- if (!named) continue;
291
- // A wildcard alias names a path under its target; an exact alias
292
- // (`"@theme": ["./src/theme.ts"]`) names its target file itself.
293
- const exactExt = key.endsWith('/') ? '' : path.extname(aliasTarget);
294
- const rest = key.endsWith('/')
295
- ? bare.slice(key.length)
296
- : path.basename(aliasTarget, exactExt);
297
- const hit = rest ? bySuffix(rest) : null;
298
- if (!hit) break;
299
- const target = hit.path;
300
- // The alias names the module without its extension or index file;
301
- // the file keeps both: `@/c/Header` -> `<alias target>/c/Header.tsx`.
302
- const abs = key.endsWith('/')
303
- ? aliasTarget + hit.tail
304
- : exactExt
305
- ? aliasTarget
306
- : aliasTarget + hit.tail.slice(rest.length);
307
- const {r, fresh} = reach(target);
308
- r.aliased.add(abs);
309
- if (fresh) queue.push(target);
310
- break;
265
+ const match = matchPath(aliases, bare);
266
+ if (match) {
267
+ // Each target in order: the file the alias names, matched in the
268
+ // tree by the path's tail, and placed where this project's target
269
+ // puts it (`@/c/Header` -> `<target>/c/Header.tsx`). The target whose
270
+ // folders match the most whole segments of the sent path above the
271
+ // file wins; with no match, the first target does.
272
+ /** @type {{abs: string, hit: {path: string, tail: string}, score: number}[]} */
273
+ const options = [];
274
+ for (const target of match.pattern.targets) {
275
+ const named = target.replace('*', match.capture);
276
+ const ext = path.extname(named);
277
+ const star = target.indexOf('*');
278
+ // The tail starts at the path segment that holds the `*`, so text
279
+ // before it (`icons/icon-*`) is part of the file name.
280
+ const cut = star === -1 ? -1 : target.lastIndexOf(path.sep, star) + 1;
281
+ const rest = (star === -1 ? path.basename(named, ext) : target.slice(cut).replace('*', match.capture))
282
+ .split(path.sep)
283
+ .join('/')
284
+ .replace(/^\/+/, '');
285
+ const hit = rest ? bySuffix(rest) : null;
286
+ if (!hit) continue;
287
+ // The file keeps its own extension or index: `<target>/c/Header` ->
288
+ // `<target>/c/Header.tsx`.
289
+ const abs =
290
+ star !== -1
291
+ ? target.slice(0, cut) + hit.tail
292
+ : ext
293
+ ? named
294
+ : named + hit.tail.slice(rest.length);
295
+ // The folders that hold the target's `*` (or, for a target with
296
+ // none, the target's own folders), against the folders of the sent
297
+ // path above the part the alias named, from the nearest up.
298
+ const targetFolders = (star === -1 ? path.dirname(named) : target.slice(0, cut)).split(path.sep).filter(Boolean);
299
+ const sentTail = hit.tail;
300
+ const sentFolders = hit.path.slice(0, hit.path.length - sentTail.length).split('/').filter(Boolean);
301
+ let score = 0;
302
+ while (
303
+ score < sentFolders.length &&
304
+ score < targetFolders.length &&
305
+ sentFolders[sentFolders.length - 1 - score] === targetFolders[targetFolders.length - 1 - score]
306
+ ) {
307
+ score += 1;
308
+ }
309
+ options.push({abs, hit, score});
310
+ }
311
+ const chosen = options.reduce(
312
+ (/** @type {(typeof options)[number] | undefined} */ best, o) => (!best || o.score > best.score ? o : best),
313
+ undefined,
314
+ );
315
+ if (chosen) {
316
+ const {r, fresh} = reach(chosen.hit.path);
317
+ r.aliased.add(chosen.abs);
318
+ if (fresh) queue.push(chosen.hit.path);
319
+ }
311
320
  }
312
321
  }
313
322
  }