@astryxdesign/cli 0.7.13 → 0.7.14-canary.108f354

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 (164) hide show
  1. package/README.md +18 -18
  2. package/api/component/__fixtures__/resolutions/modules.txt +1 -1
  3. package/api/doctor/doctor.mjs +3 -7
  4. package/api/experimental.d.mts +2 -0
  5. package/api/experimental.mjs +12 -0
  6. package/api/icon/_adapter.d.mts +10 -0
  7. package/api/icon/_adapter.mjs +31 -2
  8. package/api/icon/_authoring.d.mts +2 -1
  9. package/api/icon/_authoring.mjs +91 -6
  10. package/api/icon/_options.mjs +1 -0
  11. package/api/icon/_records.d.mts +18 -0
  12. package/api/icon/_records.mjs +26 -0
  13. package/api/icon/add/add.mjs +7 -1
  14. package/api/icon/definitions/definitions.d.mts +12 -0
  15. package/api/icon/definitions/definitions.mjs +83 -0
  16. package/api/icon/icon.doc.mjs +5 -4
  17. package/api/icon/icon.mjs +5 -16
  18. package/api/icon/icon.type.d.mts +29 -2
  19. package/api/icon/icon.type.mjs +17 -3
  20. package/api/icon/iconAdd.doc.mjs +1 -1
  21. package/api/icon/iconMap.doc.mjs +2 -2
  22. package/api/icon/iconNewSet.doc.mjs +8 -2
  23. package/api/icon/map/map.mjs +21 -2
  24. package/api/icon/new-set/new-set.mjs +14 -2
  25. package/api/icon/search/search.mjs +2 -15
  26. package/api/icon/use/use.mjs +4 -3
  27. package/api/integration/validate-integration.mjs +6 -1
  28. package/api/integration/validate-integration.type.d.mts +12 -0
  29. package/api/integration/validate-integration.type.mjs +5 -0
  30. package/api/theme-edit/_adapter.d.mts +116 -0
  31. package/api/theme-edit/_adapter.mjs +1683 -0
  32. package/api/theme-edit/_catalog.d.mts +59 -0
  33. package/api/theme-edit/_catalog.mjs +564 -0
  34. package/api/theme-edit/_check.d.mts +49 -0
  35. package/api/theme-edit/_check.mjs +845 -0
  36. package/api/theme-edit/_color.d.mts +29 -0
  37. package/api/theme-edit/_color.mjs +300 -0
  38. package/api/theme-edit/_compiler.d.mts +61 -0
  39. package/api/theme-edit/_compiler.mjs +522 -0
  40. package/api/theme-edit/_css-properties.d.mts +10 -0
  41. package/api/theme-edit/_css-properties.mjs +556 -0
  42. package/api/theme-edit/_parts.d.mts +111 -0
  43. package/api/theme-edit/_parts.mjs +409 -0
  44. package/api/theme-edit/_png.d.mts +40 -0
  45. package/api/theme-edit/_png.mjs +187 -0
  46. package/api/theme-edit/_preview.d.mts +121 -0
  47. package/api/theme-edit/_preview.mjs +720 -0
  48. package/api/theme-edit/_project.d.mts +83 -0
  49. package/api/theme-edit/_project.mjs +289 -0
  50. package/api/theme-edit/_settings.d.mts +222 -0
  51. package/api/theme-edit/_settings.mjs +861 -0
  52. package/api/theme-edit/_tables.d.mts +132 -0
  53. package/api/theme-edit/_tables.mjs +700 -0
  54. package/api/theme-edit/theme-edit.d.mts +93 -0
  55. package/api/theme-edit/theme-edit.mjs +145 -0
  56. package/api/theme-edit/theme-edit.type.d.mts +413 -0
  57. package/api/theme-edit/theme-edit.type.mjs +233 -0
  58. package/api/theme-edit/themeEditHow.doc.d.mts +6 -0
  59. package/api/theme-edit/themeEditHow.doc.mjs +88 -0
  60. package/api/theme-edit/themeEditNew.doc.d.mts +6 -0
  61. package/api/theme-edit/themeEditNew.doc.mjs +89 -0
  62. package/api/theme-edit/themeEditPreviewAdd.doc.d.mts +6 -0
  63. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +100 -0
  64. package/api/theme-edit/themeEditPreviewApp.doc.d.mts +6 -0
  65. package/api/theme-edit/themeEditPreviewApp.doc.mjs +84 -0
  66. package/api/theme-edit/themeEditPreviewList.doc.d.mts +6 -0
  67. package/api/theme-edit/themeEditPreviewList.doc.mjs +53 -0
  68. package/api/theme-edit/themeEditPreviewRemove.doc.d.mts +6 -0
  69. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +66 -0
  70. package/api/theme-edit/themeEditSet.doc.d.mts +6 -0
  71. package/api/theme-edit/themeEditSet.doc.mjs +165 -0
  72. package/api/theme-edit/themeEditShow.doc.d.mts +6 -0
  73. package/api/theme-edit/themeEditShow.doc.mjs +86 -0
  74. package/api/theme-edit/themeEditUndo.doc.d.mts +6 -0
  75. package/api/theme-edit/themeEditUndo.doc.mjs +124 -0
  76. package/assets/docs/color.doc.mjs +5 -5
  77. package/assets/docs/tree/icon-sets.doc.mjs +6 -2
  78. package/assets/docs/tree/tokens-border.doc.mjs +1 -1
  79. package/assets/docs/tree/tokens-color.doc.mjs +2 -2
  80. package/assets/docs/tree/tokens-data.doc.mjs +2 -2
  81. package/assets/docs/tree/tokens-duration.doc.mjs +1 -1
  82. package/assets/docs/tree/tokens-ease.doc.mjs +1 -1
  83. package/assets/docs/tree/tokens-focus.doc.mjs +1 -1
  84. package/assets/docs/tree/tokens-font-weight.doc.mjs +1 -1
  85. package/assets/docs/tree/tokens-radius.doc.mjs +1 -1
  86. package/assets/docs/tree/tokens-shadow.doc.mjs +1 -1
  87. package/assets/docs/tree/tokens-size.doc.mjs +1 -1
  88. package/assets/docs/tree/tokens-spacing.doc.mjs +1 -1
  89. package/assets/docs/tree/tokens-syntax.doc.mjs +1 -1
  90. package/assets/docs/tree/tokens-text-size.doc.mjs +1 -1
  91. package/assets/docs/tree/tokens-type-scale.doc.mjs +1 -1
  92. package/assets/docs/tree/tokens-typography.doc.mjs +1 -1
  93. package/assets/icons/definitions/bank.doc.mjs +1 -1
  94. package/assets/icons/definitions/save.doc.mjs +1 -1
  95. package/assets/preview-app/README.md +6 -0
  96. package/assets/preview-app/css.d.ts +5 -0
  97. package/assets/preview-app/gitignore +1 -0
  98. package/assets/preview-app/next.config.mjs +6 -0
  99. package/assets/preview-app/package.json +23 -0
  100. package/assets/preview-app/src/app/globals.css +5 -0
  101. package/assets/preview-app/src/app/layout.tsx +21 -0
  102. package/assets/preview-app/src/app/page.tsx +94 -0
  103. package/assets/preview-app/src/app/providers.tsx +16 -0
  104. package/assets/preview-app/tsconfig.json +27 -0
  105. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider01ShippedLocale.doc.mjs +2 -1
  106. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider02Overrides.doc.mjs +2 -1
  107. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider03RtlDirection.doc.mjs +2 -1
  108. package/assets/templates/blocks/components/InternationalizationProvider/InternationalizationProvider04Calendar.doc.mjs +2 -1
  109. package/assets/templates/blocks/components/Text/useTruncationHookUsage.doc.mjs +14 -0
  110. package/assets/templates/blocks/components/Text/useTruncationHookUsage.tsx +112 -0
  111. package/authoring/doctypes/_schema.d.mts +1 -0
  112. package/authoring/doctypes/_schema.mjs +1 -0
  113. package/authoring/doctypes/command/command.doc.mjs +7 -0
  114. package/authoring/doctypes/command/type.ts +3 -0
  115. package/authoring/doctypes/icon-set/parse.d.mts +7 -0
  116. package/authoring/doctypes/icon-set/parse.mjs +18 -8
  117. package/clients/cli/commands/doctor.mjs +33 -3
  118. package/clients/cli/commands/experimental/icon.mjs +67 -14
  119. package/clients/cli/commands/experimental/index.mjs +2 -0
  120. package/clients/cli/commands/experimental/theme.mjs +684 -0
  121. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +7 -1
  122. package/clients/cli/commands/experimental-icon.doc.mjs +3 -2
  123. package/clients/cli/commands/experimental-theme-add.doc.mjs +78 -0
  124. package/clients/cli/commands/experimental-theme-compile.doc.mjs +97 -0
  125. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +84 -0
  126. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +66 -0
  127. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +121 -0
  128. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +66 -0
  129. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +104 -0
  130. package/clients/cli/commands/experimental-theme-editor.doc.mjs +49 -0
  131. package/clients/cli/commands/experimental-theme-eject.doc.mjs +71 -0
  132. package/clients/cli/commands/experimental-theme-list.doc.mjs +49 -0
  133. package/clients/cli/commands/experimental-theme-palette-generate.doc.mjs +73 -0
  134. package/clients/cli/commands/experimental-theme-palette.doc.mjs +37 -0
  135. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +86 -0
  136. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +66 -0
  137. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +48 -0
  138. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +59 -0
  139. package/clients/cli/commands/experimental-theme-preview.doc.mjs +40 -0
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +55 -0
  141. package/clients/cli/commands/experimental-theme-targets.doc.mjs +61 -0
  142. package/clients/cli/commands/experimental-theme-template.doc.mjs +61 -0
  143. package/clients/cli/commands/experimental-theme-use.doc.mjs +55 -0
  144. package/clients/cli/commands/experimental-theme.doc.mjs +57 -0
  145. package/clients/cli/commands/experimental.doc.mjs +10 -3
  146. package/clients/cli/commands/theme.mjs +101 -34
  147. package/clients/cli/index.mjs +18 -0
  148. package/clients/cli/lib/define-command.mjs +3 -0
  149. package/foundation/discovery/icon-set-checks.d.mts +16 -1
  150. package/foundation/discovery/icon-set-checks.mjs +68 -7
  151. package/foundation/discovery/icon-set-discovery.d.mts +21 -6
  152. package/foundation/discovery/icon-set-discovery.mjs +17 -8
  153. package/foundation/discovery/template-icon-meanings.d.mts +39 -0
  154. package/foundation/discovery/template-icon-meanings.mjs +95 -0
  155. package/foundation/discovery/theming-targets.d.mts +6 -0
  156. package/foundation/discovery/theming-targets.mjs +33 -0
  157. package/foundation/response/error-codes.d.mts +12 -1
  158. package/foundation/response/error-codes.doc.mjs +66 -0
  159. package/foundation/response/error-codes.mjs +55 -0
  160. package/foundation/response/response-types.doc.mjs +55 -0
  161. package/foundation/text/template-meanings-line.d.mts +16 -0
  162. package/foundation/text/template-meanings-line.mjs +37 -0
  163. package/foundation/xle/browser.d.mts +2 -2
  164. package/package.json +6 -6
@@ -0,0 +1,409 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file What each themeable part reads, derived from the installed Core
5
+ * itself: render a catalog of every component on the server with the
6
+ * project's own React (the machinery of `astryx experimental render`), then
7
+ * join each element's classes to the rules in Core's shipped stylesheet.
8
+ * The result names, for every part, the CSS properties it sets and the
9
+ * public tokens that feed each one (under which variant or state), the parts
10
+ * inside it, the variant values seen, and the real text-on-background pairs.
11
+ *
12
+ * It needs no browser. It is cached per Core version (and stylesheet) under
13
+ * node_modules/.cache/astryx-theme/, so it is built once per install.
14
+ *
15
+ * @position api/theme-edit — part data for the checks, and `how`
16
+ */
17
+
18
+ import * as fs from 'node:fs';
19
+ import * as path from 'node:path';
20
+ import {AstryxError} from '../error.mjs';
21
+ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
22
+ import {importPathOf} from './_project.mjs';
23
+ import {renderPage, RenderError} from '../../foundation/render/render-page.mjs';
24
+ import {
25
+ EXTRA,
26
+ OPEN_OVERLAYS,
27
+ SAMPLE_PAGE,
28
+ elementNames,
29
+ pageSource,
30
+ } from './_catalog.mjs';
31
+
32
+ /** Bump when the shape of the cached part data changes. */
33
+ const PART_DATA_VERSION = 3;
34
+
35
+ /**
36
+ * @typedef {object} PartRecord
37
+ * @property {Record<string, {tokens: Record<string, string[]>, values: string[]}>} own - property -> tokens (with conditions) and raw values
38
+ * @property {Record<string, string[]>} inside - tokens read by unnamed elements inside the part -> properties
39
+ * @property {Record<string, string[]>} attrs - data attributes seen on the part
40
+ * @property {string[]} contains - parts rendered inside it
41
+ */
42
+
43
+ /**
44
+ * @typedef {{target: string | null, tokens: string[], raw: string | null}} PaintSide
45
+ * @typedef {{text: string, fg: PaintSide, bg: PaintSide, sample: string}} TextPair
46
+ * @typedef {{version: number, coreKey: string, map: Record<string, PartRecord>, pairs: TextPair[], rendered: number, items: number}} PartData
47
+ */
48
+
49
+ /**
50
+ * The catalog: each component with playground defaults once per visual
51
+ * variant value, the hand-made extras, and the sample page.
52
+ * @param {import('./_project.mjs').ThemeProject} project
53
+ * @returns {{items: import('./_catalog.mjs').CatalogItem[], imports: Record<string, string>}}
54
+ */
55
+ export function catalogItems(project) {
56
+ /** @type {import('./_catalog.mjs').CatalogItem[]} */
57
+ const items = [];
58
+ for (const [name, info] of Object.entries(project.components)) {
59
+ const defaults = /** @type {any} */ (info.defaults);
60
+ if (!defaults || typeof defaults !== 'object') continue;
61
+ const values = info.targets[0]?.values ?? {};
62
+ /** @type {Array<Record<string, string>>} */
63
+ const variants = [{}];
64
+ for (const p of ['variant', 'status', 'color'])
65
+ for (const v of values[p] ?? []) variants.push({[p]: v});
66
+ for (const v of variants.slice(0, 16)) {
67
+ const label = Object.values(v).join(' ');
68
+ items.push({
69
+ name,
70
+ label,
71
+ tree: {__element: name, props: {...defaults, ...v}},
72
+ });
73
+ }
74
+ }
75
+ for (const [name, list] of [...EXTRA, ...OPEN_OVERLAYS])
76
+ for (const [label, tree] of list) items.push({name, label, tree});
77
+ /** @type {Record<string, string>} */
78
+ const imports = {};
79
+ for (const n of elementNames([items.map(i => i.tree), SAMPLE_PAGE])) {
80
+ const spec = importPathOf(project, n);
81
+ if (spec) imports[n] = spec;
82
+ }
83
+ return {items, imports};
84
+ }
85
+
86
+ /**
87
+ * The folder generated pages render from: inside the project but outside
88
+ * node_modules, so the render compiles them and their stylesheet imports as
89
+ * the project's own. It is removed after each render.
90
+ * @param {import('./_project.mjs').ThemeProject} project
91
+ */
92
+ export const renderDir = project =>
93
+ path.join(project.cwd, 'themes', '.astryx-render');
94
+
95
+ /**
96
+ * Render a generated page module and give its HTML and markup (the body,
97
+ * without the embedded source block).
98
+ * @param {import('./_project.mjs').ThemeProject} project
99
+ * @param {string} file name inside the render folder
100
+ * @param {string} source
101
+ * @param {Array<{name: string, from: string}>} [extra] files copied beside it
102
+ * @returns {Promise<{html: string, markup: string}>}
103
+ */
104
+ export async function renderGenerated(project, file, source, extra = []) {
105
+ const dir = renderDir(project);
106
+ fs.mkdirSync(dir, {recursive: true});
107
+ const entry = path.join(dir, file);
108
+ fs.writeFileSync(entry, source);
109
+ for (const x of extra) {
110
+ fs.mkdirSync(path.dirname(path.join(dir, x.name)), {recursive: true});
111
+ fs.copyFileSync(x.from, path.join(dir, x.name));
112
+ }
113
+ try {
114
+ const page = await renderPage(entry, {title: file.replace(/\.[^.]+$/, '')});
115
+ const body = page.html.slice(page.html.indexOf('<body>') + 6);
116
+ const end = body.indexOf('<script type=');
117
+ return {html: page.html, markup: end >= 0 ? body.slice(0, end) : body};
118
+ } catch (e) {
119
+ if (e instanceof RenderError) {
120
+ const missing = e.code === 'ERR_RENDER_MISSING_DEPENDENCY';
121
+ throw new AstryxError(
122
+ `Could not render the components with this project's React: ${e.message}${missing ? ' The theme command renders components on the server, so react and react-dom must be installed.' : ''}`,
123
+ [],
124
+ missing
125
+ ? ERROR_CODES.ERR_RENDER_MISSING_DEPENDENCY
126
+ : ERROR_CODES.ERR_RENDER_FAILED,
127
+ );
128
+ }
129
+ throw e;
130
+ } finally {
131
+ fs.rmSync(dir, {recursive: true, force: true});
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The part data for the installed Core, from the cache or built now.
137
+ * @param {import('./_project.mjs').ThemeProject} project
138
+ * @returns {Promise<PartData>}
139
+ */
140
+ export async function partData(project) {
141
+ const file = path.join(project.cacheDir, 'parts.json');
142
+ try {
143
+ const cached = JSON.parse(fs.readFileSync(file, 'utf8'));
144
+ if (
145
+ cached.version === PART_DATA_VERSION &&
146
+ cached.coreKey === project.coreKey
147
+ )
148
+ return cached;
149
+ } catch {
150
+ // Not built yet, or unreadable: build it.
151
+ }
152
+ const data = await buildPartData(project);
153
+ try {
154
+ fs.mkdirSync(project.cacheDir, {recursive: true});
155
+ fs.writeFileSync(file, JSON.stringify(data));
156
+ } catch {
157
+ // A read-only node_modules: build it again next time.
158
+ }
159
+ return data;
160
+ }
161
+
162
+ /**
163
+ * Build the part data: render the catalog, then walk its markup.
164
+ * @param {import('./_project.mjs').ThemeProject} project
165
+ * @returns {Promise<PartData>}
166
+ */
167
+ async function buildPartData(project) {
168
+ const {items, imports} = catalogItems(project);
169
+ const all = [...items, {name: 'sample-page', label: '', tree: SAMPLE_PAGE}];
170
+ const {markup} = await renderGenerated(
171
+ project,
172
+ 'catalog.mjs',
173
+ pageSource({items: all, imports, theme: null, layout: 'catalog'}),
174
+ );
175
+ let css = '';
176
+ try {
177
+ css = fs.readFileSync(
178
+ project.req.resolve('@astryxdesign/core/astryx.css'),
179
+ 'utf8',
180
+ );
181
+ } catch {
182
+ // No stylesheet: every part reads nothing.
183
+ }
184
+ const tokens = new Set(Object.keys(project.core.tokenDefaults ?? {}));
185
+ const result = walkMarkup(markup, declarations(css), tokens);
186
+ return {
187
+ version: PART_DATA_VERSION,
188
+ coreKey: project.coreKey,
189
+ ...result,
190
+ rendered: (markup.match(/<section data-cat=/g) ?? []).length,
191
+ items: all.length,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Atomic class -> its declarations, with the condition (pseudo-class,
197
+ * attribute) each one applies under.
198
+ * @param {string} css
199
+ * @returns {Map<string, Array<{prop: string, value: string, cond: string}>>}
200
+ */
201
+ export function declarations(css) {
202
+ /** @type {Map<string, Array<{prop: string, value: string, cond: string}>>} */
203
+ const decls = new Map();
204
+ for (const m of css.matchAll(
205
+ /\.(x[a-z0-9]+)((?:\.x[a-z0-9]+|[:[][^{]*)?)\{([^{}]*)\}/g,
206
+ )) {
207
+ const [, cls, rest, body] = m;
208
+ const cond = rest
209
+ .replace(/\.x[a-z0-9]+/g, '')
210
+ .replace(/:not\(#\\#\)/g, '')
211
+ .replace(/:where\([^)]*\)\)?/g, '')
212
+ .trim();
213
+ for (const d of body.split(';')) {
214
+ const i = d.indexOf(':');
215
+ if (i < 0) continue;
216
+ const prop = d.slice(0, i).trim();
217
+ const value = d.slice(i + 1).trim();
218
+ if (!prop) continue;
219
+ const list = decls.get(cls) ?? [];
220
+ list.push({prop, value, cond});
221
+ decls.set(cls, list);
222
+ }
223
+ }
224
+ return decls;
225
+ }
226
+
227
+ const VOID = new Set([
228
+ 'area',
229
+ 'base',
230
+ 'br',
231
+ 'col',
232
+ 'embed',
233
+ 'hr',
234
+ 'img',
235
+ 'input',
236
+ 'link',
237
+ 'meta',
238
+ 'source',
239
+ 'track',
240
+ 'wbr',
241
+ ]);
242
+
243
+ /** @param {string} v */
244
+ const refs = v => [...v.matchAll(/var\((--[a-zA-Z0-9_-]+)/g)].map(m => m[1]);
245
+
246
+ /**
247
+ * The public tokens a value reads, following private variables set on the
248
+ * element or its ancestors.
249
+ * @param {string} v
250
+ * @param {Record<string, string>} env
251
+ * @param {Set<string>} tokens
252
+ * @param {Set<string>} [seen]
253
+ * @param {number} [depth]
254
+ * @returns {Set<string>}
255
+ */
256
+ function expand(v, env, tokens, seen = new Set(), depth = 0) {
257
+ /** @type {Set<string>} */
258
+ const out = new Set();
259
+ for (const r of refs(v)) {
260
+ if (tokens.has(r)) out.add(r);
261
+ else if (env[r] && !seen.has(r) && depth < 8) {
262
+ seen.add(r);
263
+ for (const t of expand(env[r], env, tokens, seen, depth + 1)) out.add(t);
264
+ }
265
+ }
266
+ return out;
267
+ }
268
+
269
+ /**
270
+ * Walk server-rendered markup: for each element, its classes' declarations
271
+ * become what its part reads; text records the color pair it sits on.
272
+ * @param {string} html
273
+ * @param {ReturnType<typeof declarations>} decls
274
+ * @param {Set<string>} tokens
275
+ * @returns {{map: Record<string, PartRecord>, pairs: TextPair[]}}
276
+ */
277
+ export function walkMarkup(html, decls, tokens) {
278
+ /** @type {Record<string, {own: Record<string, {tokens: Record<string, Set<string>>, values: Set<string>}>, inside: Record<string, Set<string>>, attrs: Record<string, Set<string>>, contains: Set<string>}>} */
279
+ const map = {};
280
+ /** @type {Array<{env: Record<string, string>, target: string | null, fg: PaintSide | null, bg: PaintSide | null}>} */
281
+ const stack = [{env: {}, target: null, fg: null, bg: null}];
282
+ /** @type {Map<string, TextPair>} */
283
+ const pairs = new Map();
284
+ let inSample = false;
285
+ for (const m of html.matchAll(
286
+ /([^<]+)|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*?)(\/?)>/g,
287
+ )) {
288
+ const [, text, close, tag, attrs, selfClose] = m;
289
+ if (text !== undefined) {
290
+ const top = stack[stack.length - 1];
291
+ const t = text.trim();
292
+ if (t && top.target && top.fg && top.bg && !/^skip to/i.test(t)) {
293
+ const k = `${top.target}|${top.fg.target}:${top.fg.tokens.join('+') || top.fg.raw}|${top.bg.target}:${top.bg.tokens.join('+') || top.bg.raw}`;
294
+ pairs.set(k, {
295
+ text: top.target,
296
+ fg: top.fg,
297
+ bg: top.bg,
298
+ sample: t.slice(0, 30),
299
+ });
300
+ }
301
+ continue;
302
+ }
303
+ if (!close && tag === 'section')
304
+ inSample = /data-cat="sample-page"/.test(attrs);
305
+ if (close) {
306
+ if (stack.length > 1) stack.pop();
307
+ continue;
308
+ }
309
+ void inSample;
310
+ const cls = (/class="([^"]*)"/.exec(attrs)?.[1] ?? '')
311
+ .split(/\s+/)
312
+ .filter(Boolean);
313
+ const dataAttrs = Object.fromEntries(
314
+ [
315
+ ...attrs.matchAll(
316
+ /data-(variant|status|size|selected|state|elevation|tone|color|level|weight)="([^"]*)"/g,
317
+ ),
318
+ ].map(x => [x[1], x[2]]),
319
+ );
320
+ const parent = stack[stack.length - 1];
321
+ const env = {...parent.env};
322
+ const own = cls.flatMap(c => decls.get(c) ?? []);
323
+ for (const d of own)
324
+ if (d.prop.startsWith('--') && !d.cond) env[d.prop] = d.value;
325
+ const named = cls.filter(
326
+ c => c.startsWith('astryx-') && !c.startsWith('astryx-theme'),
327
+ );
328
+ const target = named[0]?.slice(7) ?? parent.target;
329
+ const ownsTarget = named.length > 0;
330
+ if (target) {
331
+ const T = (map[target] ??= {
332
+ own: {},
333
+ inside: {},
334
+ attrs: {},
335
+ contains: new Set(),
336
+ });
337
+ if (ownsTarget)
338
+ for (const [k, v] of Object.entries(dataAttrs))
339
+ (T.attrs[k] ??= new Set()).add(v);
340
+ const cond0 = Object.entries(dataAttrs)
341
+ .map(([k, v]) => `${k}=${v}`)
342
+ .join(',');
343
+ for (const d of own) {
344
+ if (d.prop.startsWith('--')) continue;
345
+ const toks = expand(d.value, env, tokens);
346
+ const cond = [cond0, d.cond].filter(Boolean).join(' ');
347
+ if (ownsTarget) {
348
+ const P = (T.own[d.prop] ??= {tokens: {}, values: new Set()});
349
+ P.values.add(
350
+ d.value.length > 80 ? `${d.value.slice(0, 80)}...` : d.value,
351
+ );
352
+ for (const t of toks)
353
+ (P.tokens[t] ??= new Set()).add(cond || 'always');
354
+ } else for (const t of toks) (T.inside[t] ??= new Set()).add(d.prop);
355
+ }
356
+ }
357
+ let fg = parent.fg;
358
+ let bg = parent.bg;
359
+ for (const d of own) {
360
+ if (d.cond) continue;
361
+ if (
362
+ d.prop === 'color' &&
363
+ !/^(inherit|currentcolor|unset|initial)$/i.test(d.value)
364
+ ) {
365
+ const t = [...expand(d.value, env, tokens)];
366
+ fg = {target, tokens: t, raw: t.length ? null : d.value};
367
+ }
368
+ if (d.prop === 'background-color') {
369
+ const t = [...expand(d.value, env, tokens)];
370
+ if (t.length || !/transparent/.test(d.value))
371
+ bg = {target, tokens: t, raw: t.length ? null : d.value};
372
+ }
373
+ }
374
+ if (ownsTarget && target)
375
+ for (const anc of stack)
376
+ if (anc.target && anc.target !== target)
377
+ map[anc.target].contains.add(target);
378
+ if (!selfClose && !VOID.has(tag.toLowerCase()))
379
+ stack.push({env, target, fg, bg});
380
+ }
381
+ /** @type {Record<string, PartRecord>} */
382
+ const out = {};
383
+ for (const [t, v] of Object.entries(map)) {
384
+ out[t] = {
385
+ own: Object.fromEntries(
386
+ Object.entries(v.own).map(([p, x]) => [
387
+ p,
388
+ {
389
+ tokens: Object.fromEntries(
390
+ Object.entries(x.tokens).map(([k, s]) => [
391
+ k,
392
+ [...s].slice(0, 12),
393
+ ]),
394
+ ),
395
+ values: [...x.values].slice(0, 6),
396
+ },
397
+ ]),
398
+ ),
399
+ inside: Object.fromEntries(
400
+ Object.entries(v.inside).map(([k, s]) => [k, [...s]]),
401
+ ),
402
+ attrs: Object.fromEntries(
403
+ Object.entries(v.attrs).map(([k, s]) => [k, [...s]]),
404
+ ),
405
+ contains: [...v.contains],
406
+ };
407
+ }
408
+ return {map: out, pairs: [...pairs.values()]};
409
+ }
@@ -0,0 +1,40 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /** @typedef {{width: number, height: number, rgba: Uint8Array}} Picture */
5
+ /**
6
+ * Decode a PNG file's bytes. Interlaced pictures are refused.
7
+ * @param {Buffer} bytes
8
+ * @returns {Picture}
9
+ */
10
+ export function decodePng(bytes: Buffer): Picture;
11
+ /**
12
+ * The exact color at each point.
13
+ * @param {Picture} pic
14
+ * @param {Array<{x: number, y: number}>} points
15
+ * @returns {Array<{at: string, color: string | null}>}
16
+ */
17
+ export function colorsAt(pic: Picture, points: Array<{
18
+ x: number;
19
+ y: number;
20
+ }>): Array<{
21
+ at: string;
22
+ color: string | null;
23
+ }>;
24
+ /**
25
+ * The main colors of a picture: every second pixel bucketed to 5 bits per
26
+ * channel, biggest share first, each with where it sits.
27
+ * @param {Picture} pic
28
+ * @param {number} count
29
+ * @returns {Array<{color: string, share: number, where: string}>}
30
+ */
31
+ export function mainColors(pic: Picture, count: number): Array<{
32
+ color: string;
33
+ share: number;
34
+ where: string;
35
+ }>;
36
+ export type Picture = {
37
+ width: number;
38
+ height: number;
39
+ rgba: Uint8Array;
40
+ };
@@ -0,0 +1,187 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Read a PNG in plain Node: decompress with zlib, undo the row
5
+ * filters, and give RGBA pixels. Then the main colors of a picture, or the
6
+ * exact color at given points.
7
+ * @position api/theme-edit — pure helpers for `experimental theme editor how <picture.png>`
8
+ */
9
+
10
+ import * as zlib from 'node:zlib';
11
+
12
+ const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
13
+
14
+ /** @typedef {{width: number, height: number, rgba: Uint8Array}} Picture */
15
+
16
+ /**
17
+ * Decode a PNG file's bytes. Interlaced pictures are refused.
18
+ * @param {Buffer} bytes
19
+ * @returns {Picture}
20
+ */
21
+ export function decodePng(bytes) {
22
+ if (bytes.length < 8 || !bytes.subarray(0, 8).equals(SIGNATURE))
23
+ throw new Error('not a PNG file');
24
+ let pos = 8;
25
+ let width = 0;
26
+ let height = 0;
27
+ let depth = 0;
28
+ let colorType = 0;
29
+ let interlace = 0;
30
+ /** @type {Buffer | null} */
31
+ let palette = null;
32
+ /** @type {Buffer | null} */
33
+ let alpha = null;
34
+ /** @type {Buffer[]} */
35
+ const data = [];
36
+ while (pos + 8 <= bytes.length) {
37
+ const length = bytes.readUInt32BE(pos);
38
+ const type = bytes.toString('latin1', pos + 4, pos + 8);
39
+ const body = bytes.subarray(pos + 8, pos + 8 + length);
40
+ pos += 12 + length;
41
+ if (type === 'IHDR') {
42
+ width = body.readUInt32BE(0);
43
+ height = body.readUInt32BE(4);
44
+ depth = body[8];
45
+ colorType = body[9];
46
+ interlace = body[12];
47
+ } else if (type === 'PLTE') palette = body;
48
+ else if (type === 'tRNS') alpha = body;
49
+ else if (type === 'IDAT') data.push(body);
50
+ else if (type === 'IEND') break;
51
+ }
52
+ if (!width || !height) throw new Error('the PNG has no header');
53
+ if (interlace) throw new Error('interlaced PNG files are not supported');
54
+ const channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[colorType];
55
+ if (!channels || ![1, 2, 4, 8, 16].includes(depth))
56
+ throw new Error('unsupported PNG color format');
57
+ const raw = zlib.inflateSync(Buffer.concat(data));
58
+ const bitsPerPixel = channels * depth;
59
+ const stride = Math.ceil((width * bitsPerPixel) / 8);
60
+ const bpp = Math.max(1, bitsPerPixel >> 3);
61
+ const rows = Buffer.alloc(stride * height);
62
+ for (let y = 0; y < height; y++) {
63
+ const filter = raw[y * (stride + 1)];
64
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
65
+ const out = rows.subarray(y * stride, (y + 1) * stride);
66
+ const prev = y > 0 ? rows.subarray((y - 1) * stride, y * stride) : null;
67
+ for (let x = 0; x < stride; x++) {
68
+ const a = x >= bpp ? out[x - bpp] : 0;
69
+ const b = prev ? prev[x] : 0;
70
+ const c = prev && x >= bpp ? prev[x - bpp] : 0;
71
+ let v = line[x];
72
+ if (filter === 1) v += a;
73
+ else if (filter === 2) v += b;
74
+ else if (filter === 3) v += (a + b) >> 1;
75
+ else if (filter === 4) {
76
+ const p = a + b - c;
77
+ const pa = Math.abs(p - a);
78
+ const pb = Math.abs(p - b);
79
+ const pc = Math.abs(p - c);
80
+ v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
81
+ }
82
+ out[x] = v & 255;
83
+ }
84
+ }
85
+ const rgba = new Uint8Array(width * height * 4);
86
+ const max = (1 << depth) - 1;
87
+ /** @param {number} y @param {number} i sample index in the row */
88
+ const sample = (y, i) => {
89
+ const row = y * stride;
90
+ if (depth === 8) return rows[row + i];
91
+ if (depth === 16) return rows[row + i * 2];
92
+ const bit = i * depth;
93
+ const byte = rows[row + (bit >> 3)];
94
+ const v = (byte >> (8 - depth - (bit & 7))) & max;
95
+ return colorType === 3 ? v : Math.round((v * 255) / max);
96
+ };
97
+ for (let y = 0; y < height; y++) {
98
+ for (let x = 0; x < width; x++) {
99
+ const o = (y * width + x) * 4;
100
+ const s = x * channels;
101
+ if (colorType === 3) {
102
+ const idx = sample(y, s);
103
+ rgba[o] = palette?.[idx * 3] ?? 0;
104
+ rgba[o + 1] = palette?.[idx * 3 + 1] ?? 0;
105
+ rgba[o + 2] = palette?.[idx * 3 + 2] ?? 0;
106
+ rgba[o + 3] = alpha && idx < alpha.length ? alpha[idx] : 255;
107
+ } else if (colorType === 0 || colorType === 4) {
108
+ const g = sample(y, s);
109
+ rgba[o] = rgba[o + 1] = rgba[o + 2] = g;
110
+ rgba[o + 3] = colorType === 4 ? sample(y, s + 1) : 255;
111
+ } else {
112
+ rgba[o] = sample(y, s);
113
+ rgba[o + 1] = sample(y, s + 1);
114
+ rgba[o + 2] = sample(y, s + 2);
115
+ rgba[o + 3] = colorType === 6 ? sample(y, s + 3) : 255;
116
+ }
117
+ }
118
+ }
119
+ return {width, height, rgba};
120
+ }
121
+
122
+ /** @param {number} v */
123
+ const hx = v => Math.round(v).toString(16).padStart(2, '0');
124
+
125
+ /**
126
+ * The exact color at each point.
127
+ * @param {Picture} pic
128
+ * @param {Array<{x: number, y: number}>} points
129
+ * @returns {Array<{at: string, color: string | null}>}
130
+ */
131
+ export function colorsAt(pic, points) {
132
+ return points.map(({x, y}) => {
133
+ if (x < 0 || y < 0 || x >= pic.width || y >= pic.height)
134
+ return {at: `${x},${y}`, color: null};
135
+ const i = (y * pic.width + x) * 4;
136
+ return {
137
+ at: `${x},${y}`,
138
+ color: `#${hx(pic.rgba[i])}${hx(pic.rgba[i + 1])}${hx(pic.rgba[i + 2])}`,
139
+ };
140
+ });
141
+ }
142
+
143
+ /**
144
+ * The main colors of a picture: every second pixel bucketed to 5 bits per
145
+ * channel, biggest share first, each with where it sits.
146
+ * @param {Picture} pic
147
+ * @param {number} count
148
+ * @returns {Array<{color: string, share: number, where: string}>}
149
+ */
150
+ export function mainColors(pic, count) {
151
+ /** @type {Map<number, {n: number, r: number, g: number, b: number, x: number, y: number}>} */
152
+ const buckets = new Map();
153
+ for (let y = 0; y < pic.height; y += 2) {
154
+ for (let x = 0; x < pic.width; x += 2) {
155
+ const i = (y * pic.width + x) * 4;
156
+ const r = pic.rgba[i];
157
+ const g = pic.rgba[i + 1];
158
+ const b = pic.rgba[i + 2];
159
+ const k = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
160
+ let e = buckets.get(k);
161
+ if (!e) {
162
+ e = {n: 0, r: 0, g: 0, b: 0, x: 0, y: 0};
163
+ buckets.set(k, e);
164
+ }
165
+ e.n++;
166
+ e.r += r;
167
+ e.g += g;
168
+ e.b += b;
169
+ e.x += x;
170
+ e.y += y;
171
+ }
172
+ }
173
+ const total = [...buckets.values()].reduce((a, e) => a + e.n, 0) || 1;
174
+ return [...buckets.values()]
175
+ .sort((a, b) => b.n - a.n)
176
+ .slice(0, count)
177
+ .map(e => {
178
+ const cx = e.x / e.n / pic.width;
179
+ const cy = e.y / e.n / pic.height;
180
+ const where = `${cy < 0.15 ? 'top' : cy > 0.8 ? 'bottom' : 'middle'}${cx < 0.25 ? '-left' : cx > 0.75 ? '-right' : ''}`;
181
+ return {
182
+ color: `#${hx(e.r / e.n)}${hx(e.g / e.n)}${hx(e.b / e.n)}`,
183
+ share: Number(((100 * e.n) / total).toFixed(1)),
184
+ where,
185
+ };
186
+ });
187
+ }