@whzxc/agent-design-gallery 0.8.0 → 0.10.0
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.
- package/README.md +27 -1
- package/package.json +4 -1
- package/src/cli-output.mjs +40 -1
- package/src/cli.mjs +57 -8
- package/src/toolkit/arch-git.mjs +19 -0
- package/src/toolkit/build-store.mjs +6 -4
- package/src/toolkit/build-worker.mjs +5 -2
- package/src/toolkit/build.mjs +20 -5
- package/src/toolkit/commands.mjs +44 -14
- package/src/toolkit/config.mjs +6 -5
- package/src/toolkit/diff-inputs.mjs +5 -5
- package/src/toolkit/diff.mjs +14 -10
- package/src/toolkit/frame-document.mjs +6 -0
- package/src/toolkit/impact-eligibility.mjs +136 -0
- package/src/toolkit/impact-inputs.mjs +71 -0
- package/src/toolkit/impact-output.mjs +46 -0
- package/src/toolkit/impact-proof.mjs +67 -0
- package/src/toolkit/impact-selection.mjs +96 -0
- package/src/toolkit/impact.mjs +403 -0
- package/src/toolkit/implementation-map.mjs +129 -0
- package/src/toolkit/implementation-query.mjs +53 -0
- package/src/toolkit/index-store.mjs +99 -0
- package/src/toolkit/json-locations.mjs +28 -0
- package/src/toolkit/owner-authoring.mjs +39 -0
- package/src/toolkit/owner-colors.mjs +70 -0
- package/src/toolkit/owner-locators.mjs +73 -0
- package/src/toolkit/owner-observation.mjs +271 -0
- package/src/toolkit/owner-search.mjs +156 -0
- package/src/toolkit/owner.mjs +159 -0
- package/src/toolkit/project-index.mjs +188 -0
- package/src/toolkit/results.mjs +2 -2
- package/src/toolkit/runtime.d.ts +1 -1
- package/src/toolkit/runtime.mjs +1 -0
- package/src/toolkit/source-facts.mjs +25 -0
- package/src/toolkit/token-reachability.mjs +71 -0
- package/src/toolkit/tokens.mjs +9 -0
package/README.md
CHANGED
|
@@ -104,6 +104,14 @@ adg check
|
|
|
104
104
|
adg render surfaces/example --frame=default --scale=2
|
|
105
105
|
adg check --read-only
|
|
106
106
|
adg diff --base=HEAD --json
|
|
107
|
+
adg owner --file=ui/controls.tsx --symbol=Button --json
|
|
108
|
+
adg owner --text="Save changes" --locale=en --json
|
|
109
|
+
adg impact --source=design/components/badge.tsx --part=Badge --json
|
|
110
|
+
adg impact --token=--accent --json
|
|
111
|
+
adg impact --base=HEAD --json
|
|
112
|
+
adg render --impacted --base=HEAD --json
|
|
113
|
+
adg check --impacted --base=HEAD --read-only --json
|
|
114
|
+
adg diff --base=HEAD --impacted --json
|
|
107
115
|
```
|
|
108
116
|
|
|
109
117
|
`init` creates tokens, components/modules/surfaces, fixtures/art, editor configuration and ignore entries. A fresh library gets one `example.tsx` per production layer, composed downward with shared fixture data; existing libraries receive no demo sources. Existing authored files are preserved, declarations are refreshed, and missing ignore entries are appended. Starter configuration requires ADG 0.5.0 or newer. `check --read-only` skips declarations and build files for an audit. Projects do not install ADG as a dependency.
|
|
@@ -118,6 +126,24 @@ in both themes. Exit 0 is `identical`/`structural`, 1 is completed `changed`, an
|
|
|
118
126
|
incomplete execution. See [parts and classifier limits](docs/design-toolkit.md#git-frame-diff)
|
|
119
127
|
and the [JSON contract](docs/agent-interface.md#diff).
|
|
120
128
|
|
|
129
|
+
`adg owner` looks up design sources, parts, frames and tokens from an implementation
|
|
130
|
+
file/directory/glob, rendered text, absolute CSS color or token name. File lookup uses
|
|
131
|
+
optional [implementation.json mappings](docs/design-toolkit.md#implementation-mappings).
|
|
132
|
+
Text answers include literal-search `authoredIn` copy locations; token references remain
|
|
133
|
+
separate from computed paint. Both themes are searched by default. Broad color/token
|
|
134
|
+
answers can be around 100 KB; read `owners` first and narrow with `--theme`. See the
|
|
135
|
+
[owner JSON contract](docs/agent-interface.md#owner) for ranks, evidence and diagnostics.
|
|
136
|
+
|
|
137
|
+
`adg impact` lists conservative direct/transitive frame candidates from sources, parts, tokens,
|
|
138
|
+
implementation mappings or exact Git endpoints. It uses emitted provenance and lexical token
|
|
139
|
+
reachability, with compact optional `--explain` witnesses. Equal theme records and same-source frame records are grouped; noncandidates are counted.
|
|
140
|
+
Git queries freshly materialize both endpoints and prove equivalent closed rendering inputs for
|
|
141
|
+
this operation. Hypothetical queries remain candidate lookups. `render`, `check` and `diff` accept `--impacted --base=<rev>`;
|
|
142
|
+
check reports skipped evaluations as `not_checked` with partial coverage, while unqualified both-theme
|
|
143
|
+
diff counts fresh proofs. Query stdout cannot authorize a later skip. Architecture `render --base`
|
|
144
|
+
produces proposal overlays; `render --impacted --base` captures plain current frames. Zero-job runs
|
|
145
|
+
report zero work. See the [impact contract](docs/agent-interface.md#impact).
|
|
146
|
+
|
|
121
147
|
See the [toolkit contract](docs/design-toolkit.md) for source format and compare adapters, and the [changelog](CHANGELOG.md) for version changes. Node.js executes design modules at build time; open sources you trust.
|
|
122
148
|
|
|
123
149
|
## Architecture sources
|
|
@@ -150,7 +176,7 @@ The development server serves the checked-in frontend and `design/tokens.css` di
|
|
|
150
176
|
|
|
151
177
|
After a completed runtime or dependency milestone passes its relevant checks and required design approvals, maintainers update the global installation and verify the deployed viewer as part of delivery. Follow [local updates](docs/local-updates.md) for packing, installation, restart conditions and endpoint verification. Documentation-only, test-only and fixture-only commits skip this update.
|
|
152
178
|
|
|
153
|
-
Maintainers publish releases
|
|
179
|
+
Maintainers publish releases through [GitHub Actions](https://github.com/whzxc/agent-design-gallery/actions/workflows/publish.yml) using [npm trusted publishing](docs/npm-release.md). Local milestone updates can install a tarball without publishing or changing the package version.
|
|
154
180
|
|
|
155
181
|
See [ADG design](docs/design.md), [architecture](docs/architecture.md), and [performance](docs/performance.md). ARC's MIT-licensed gallery is the starting point; the MIT license and Lucide/Feather icon notices are retained in `LICENSE`.
|
|
156
182
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@whzxc/agent-design-gallery",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Local TSX design toolkit and SVG viewer",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,8 +32,11 @@
|
|
|
32
32
|
"prepack": "node tooling/package.mjs"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
+
"css-tree": "3.1.0",
|
|
36
|
+
"entities": "9.0.0",
|
|
35
37
|
"esbuild": "0.28.2",
|
|
36
38
|
"lucide": "1.70.0",
|
|
39
|
+
"parse5": "8.1.1",
|
|
37
40
|
"pele": "1.12.0",
|
|
38
41
|
"playwright": "1.64.1",
|
|
39
42
|
"tailwindcss": "4.3.4"
|
package/src/cli-output.mjs
CHANGED
|
@@ -15,6 +15,13 @@ export const errorCatalog = {
|
|
|
15
15
|
USAGE_INVALID: [2, 'help', 'Read command arguments.'],
|
|
16
16
|
CONFIG_INVALID: [2, 'check', 'Recheck after fixing configuration.'],
|
|
17
17
|
TOKENS_INVALID: [2, 'check', 'Recheck after repairing tokens.css.'],
|
|
18
|
+
OWNER_MAP_INVALID: [2, 'check', 'Recheck after repairing implementation.json.'],
|
|
19
|
+
OWNER_COLOR_INVALID: [2, 'owner-help', 'Supply an absolute supported CSS color or query a token name.'],
|
|
20
|
+
OWNER_INPUT_NOT_FOUND: [2, 'owner-help', 'Choose an existing in-project file or directory.'],
|
|
21
|
+
OWNER_UNSETTLED: [2, 'owner', 'Stabilize the named frame and resources before repeating the query.'],
|
|
22
|
+
OWNER_INDEX_CHANGED: [2, 'owner', 'Finish concurrent input edits before repeating the query.'],
|
|
23
|
+
IMPACT_INPUT_NOT_FOUND: [2, 'impact-help', 'Choose an existing design input, registered part or declared token.'],
|
|
24
|
+
IMPACT_INPUT_CHANGED: [2, 'impact', 'Finish concurrent input edits before repeating the query.'],
|
|
18
25
|
MIGRATION_REQUIRED: [2, 'migrate', 'Migrate the legacy project.'],
|
|
19
26
|
MIGRATION_CONFLICT: [2, 'migration', 'Inspect migration inputs before resolving the conflict.'],
|
|
20
27
|
VERSION_UNSATISFIED: [2, 'install', 'Install a version satisfying project requires.'],
|
|
@@ -69,7 +76,7 @@ export class CliError extends Error {
|
|
|
69
76
|
}
|
|
70
77
|
|
|
71
78
|
const canonicalCommands = new Set([
|
|
72
|
-
'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff',
|
|
79
|
+
'open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact',
|
|
73
80
|
'root add', 'root remove', 'root list', 'root scan',
|
|
74
81
|
'service install', 'service uninstall', 'service status', 'service logs', 'service migrate',
|
|
75
82
|
'help', 'version', 'adg',
|
|
@@ -104,6 +111,37 @@ export function nextActions(code, context = {}) {
|
|
|
104
111
|
case 'migrate-help': argv = helpArgv('migrate'); break;
|
|
105
112
|
case 'check-help': argv = helpArgv('check'); break;
|
|
106
113
|
case 'render-help': argv = helpArgv('render'); break;
|
|
114
|
+
case 'owner-help': argv = helpArgv('owner'); break;
|
|
115
|
+
case 'impact-help': argv = helpArgv('impact'); break;
|
|
116
|
+
case 'impact': {
|
|
117
|
+
if (['render', 'check', 'diff'].includes(context.command) && context.values?.impacted && typeof context.values.base === 'string') {
|
|
118
|
+
argv = ['adg', context.command, '--impacted'];
|
|
119
|
+
for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir', 'state-dir']) if (typeof context.values[key] === 'string') argv.push(`--${key}=${context.values[key]}`);
|
|
120
|
+
if (context.values['read-only']) argv.push('--read-only');
|
|
121
|
+
if (context.values.explain) argv.push('--explain');
|
|
122
|
+
argv.push('--json');
|
|
123
|
+
if (context.positionals?.length) argv.push('--', ...context.positionals);
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
if (context.command !== 'impact') { argv = helpArgv('impact'); break; }
|
|
127
|
+
const values = context.values ?? {};
|
|
128
|
+
argv = ['adg', 'impact'];
|
|
129
|
+
for (const key of ['source', 'part', 'token', 'file', 'line', 'symbol', 'base', 'head', 'theme', 'state-dir']) {
|
|
130
|
+
const inputs = Array.isArray(values[key]) ? values[key] : typeof values[key] === 'string' ? [values[key]] : [];
|
|
131
|
+
for (const value of inputs) argv.push(`--${key}=${value}`);
|
|
132
|
+
}
|
|
133
|
+
if (values.explain) argv.push('--explain');
|
|
134
|
+
argv.push('--json'); break;
|
|
135
|
+
}
|
|
136
|
+
case 'owner': {
|
|
137
|
+
const values = context.values ?? {};
|
|
138
|
+
if (context.command !== 'owner' || !['file', 'text', 'color', 'token'].some(key => typeof values[key] === 'string' && values[key].trim())) { argv = helpArgv('owner'); break; }
|
|
139
|
+
argv = ['adg', 'owner'];
|
|
140
|
+
for (const key of ['file', 'line', 'symbol', 'text', 'color', 'token', 'locale']) if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
|
|
141
|
+
if (values.contains) argv.push('--contains');
|
|
142
|
+
for (const key of ['theme', 'state-dir']) if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
|
|
143
|
+
argv.push('--json'); break;
|
|
144
|
+
}
|
|
107
145
|
case 'serve-help': argv = helpArgv('serve'); break;
|
|
108
146
|
case 'roots': argv = ['adg', 'root', 'list', ...state, '--json']; break;
|
|
109
147
|
case 'rotate': argv = ['adg', 'serve', '--rotate-key', ...state, '--json']; break;
|
|
@@ -124,6 +162,7 @@ export function nextActions(code, context = {}) {
|
|
|
124
162
|
for (const key of ['base', 'frame', 'theme', 'scale', 'out-dir']) {
|
|
125
163
|
if (typeof values[key] === 'string') argv.push(`--${key}=${values[key]}`);
|
|
126
164
|
}
|
|
165
|
+
if (values.impacted) argv.push('--impacted');
|
|
127
166
|
argv.push('--json');
|
|
128
167
|
if (context.positionals?.length) argv.push('--', ...context.positionals);
|
|
129
168
|
break;
|
package/src/cli.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { realpathSync } from 'node:fs';
|
|
|
6
6
|
import { VERSION, loadConfig } from './toolkit/config.mjs';
|
|
7
7
|
import { CliError, createOutput, withHumanOutput } from './cli-output.mjs';
|
|
8
8
|
|
|
9
|
-
export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff'];
|
|
9
|
+
export const commands = ['open', 'link', 'serve', 'root', 'service', 'migrate', 'init', 'check', 'render', 'compare', 'diff', 'owner', 'impact'];
|
|
10
10
|
const targetOptions = '[--asset=<path> [--frame=<name>] | --group=<name> | --layer=<name> | --tokens] [--mode=query|path] [--base=<rev>]';
|
|
11
11
|
const usage = {
|
|
12
12
|
open: `[directory] [--port=<n>] [--no-open] [--state-dir=<path>] ${targetOptions}`,
|
|
@@ -14,9 +14,11 @@ const usage = {
|
|
|
14
14
|
serve: '[--port=4310] [--state-dir=<path>] [--print-key | --rotate-key]',
|
|
15
15
|
service: 'install|uninstall|status|logs|migrate [--state-dir=<path>] [--port=4310]',
|
|
16
16
|
root: 'add <dir> [--depth=2] | remove <dir> | list | scan [dir] [--state-dir=<path>]',
|
|
17
|
-
migrate: '[project]', init: '', check: '[source...] [--read-only]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>]',
|
|
17
|
+
migrate: '[project]', init: '', check: '[source...] [--read-only] [--impacted --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--state-dir=<path>] [--explain]]', render: '[source...] [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--base=<rev>] [--impacted [--state-dir=<path>] [--explain]]',
|
|
18
18
|
compare: '<source> --frame=<name> [--fixture=<name>] [--region=<name> | --selector=<css> | --page] [--origin="<x> <y>"] [--click=<name>...] [--viewport=<w>x<h>] | --all',
|
|
19
|
-
diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json]',
|
|
19
|
+
diff: '[source...] --base=<rev> [--frame=<name>] [--theme=both|light|dark] [--scale=2] [--out-dir=<path>] [--json] [--impacted [--state-dir=<path>] [--explain]]',
|
|
20
|
+
owner: '(--file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --text=<text> [--contains] [--locale=<tag>] | --color=<css> | --token=<name>) [--theme=both|light|dark] [--state-dir=<path>] [--json]',
|
|
21
|
+
impact: '(--source=<path>... [--part=<name>] | --token=<name>... | --file=<path|directory|glob> [--line=<n>] [--symbol=<name>] | --base=<rev> [--head=<rev>]) [--theme=both|light|dark] [--explain] [--state-dir=<path>] [--json]',
|
|
20
22
|
};
|
|
21
23
|
const details = {
|
|
22
24
|
migrate: 'Rename a project configuration and runtime imports, update editor paths and ignore entries, remove old generated files and regenerate declarations. Refuses mixed config names; safe to run again.',
|
|
@@ -25,12 +27,20 @@ const details = {
|
|
|
25
27
|
root: 'Manage registered scan roots. add scans immediately. scan rescans registered roots only; depth is 0 through 3. Hidden directories, node_modules and Git worktrees are skipped.',
|
|
26
28
|
open: 'Browse TSX, Mermaid architecture sources and legacy SVG designs on an independent random-port server.', init: 'Create design sources, tokens and editor configuration without overwriting files.',
|
|
27
29
|
link: 'Print a clean ADG preview URL. Query mode isolates a target. Path mode locates it in the design hierarchy.',
|
|
28
|
-
check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --
|
|
30
|
+
check: 'Check import direction and every selected frame in both themes. --read-only skips generated types and build files. --impacted --base=<rev> evaluates scheduled current rows; proven rows remain not_checked with partial coverage.', render: 'Render selected frames as PNG. Defaults to both themes at 2×. --impacted --base=<rev> captures scheduled plain current frames and reports deletions, with operation-local proofs for skipped rows. Ordinary architecture --base produces proposal overlays; --impacted never does. --json prints completed captures and impact coverage, including zero-job runs.',
|
|
29
31
|
compare: 'Compare fixture text positions. Flags override Frame fixture and capture. --all writes a summary for every fixture frame.',
|
|
30
|
-
diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff. Writes before, after and difference PNGs plus report.json. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
|
|
32
|
+
diff: 'Compare the Git base and working-tree source/frame union. Existing frames require exact pixels and CSS/device size; added Frame parent declarations enable structural part evidence under diff.thresholds. Defaults to both themes at 2× and <configured output>/diff. Writes before, after and difference PNGs plus report.json. --impacted captures only scheduled rows; unqualified both-theme runs count fresh proofs toward full coverage. Required parents/support always capture. A structural batch requires all existing frames in both themes; source/frame/theme restrictions report partial coverage. Exit 0 identical/structural, 1 changed, 2 incomplete.',
|
|
33
|
+
owner: 'Find owning design sources, parts, frames and tokens from an implementation path, rendered text, absolute CSS color or token name. Paths resolve from the project root; quote globs. --line returns the containing export/anchor region, including unmapped exports; non-exported helpers belong to the preceding export. Text is NFC/whitespace normalized and exact unless --contains; --locale filters exact Frame locale annotations without translation. Colors use 8-bit sRGB RGBA equality. Owner evidence is scoped to the query: mappings for files, text runs for text, computed paint for colors and authored references for tokens. Text authoredIn lists literal-search copy candidates; escaped or concatenated strings may be missed. Color evidence may include compact same-element/property references. Defaults to both themes. Broad color/token JSON can be around 100 KB; read owners first and narrow with --theme. Empty, stale and ambiguous results exit 0; invalid/incomplete requests exit 2.',
|
|
34
|
+
impact: 'Query direct/transitive candidates from sources, named parts, tokens or implementation mappings, or compare exact Git endpoints. --base includes staged, unstaged and untracked working files; --head selects another exact commit. Hypothetical selectors cannot prove skips; token candidates assume unchanged Tailwind classification. Git mode freshly executes both endpoint source sets and compares eligible materialized inputs. Closure or occurrence absence never proves safety. Groups merge equal theme and same-source frame records; noncandidate proofs remain counts. --explain samples witnesses/digests without splitting groups. No browser launch. Render/check/diff --impacted compute their own operation-local proofs. Exit 0 completed, including empty/stale mappings; 2 invalid/incomplete.',
|
|
35
|
+
};
|
|
36
|
+
const helpExamples = {
|
|
37
|
+
impact: 'adg impact --source=design/components/badge.tsx --part=Badge --json\nadg impact --token=--accent --json\nadg impact --base=HEAD --json',
|
|
38
|
+
render: 'adg render --impacted --base=HEAD --json\nadg render arch/catalog.mmd --base=HEAD --json',
|
|
39
|
+
check: 'adg check --impacted --base=HEAD --read-only --json\nadg check --read-only --json',
|
|
40
|
+
diff: 'adg diff --base=HEAD --impacted --json',
|
|
31
41
|
};
|
|
32
42
|
export function help(command) {
|
|
33
|
-
if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare/diff problems, 2 usage/configuration/environment error.`;
|
|
43
|
+
if (command) return `Usage: adg ${command} ${usage[command]}\n\n${details[command]}${helpExamples[command] ? `\n\nExamples:\n${helpExamples[command]}` : ''}\n\n-h, --help Show help\nExit codes: 0 success, 1 check/compare/diff problems, 2 usage/configuration/environment error.`;
|
|
34
44
|
return `Usage: adg [open] [directory] [options]\n\n${commands.map(name => ` adg ${name} ${usage[name]}`).join('\n')}\n\nAny first argument that is not a command opens a directory. Use adg open check for a directory named check.\nRun adg <command> --help for details. -v, --version prints the installed version.`;
|
|
35
45
|
}
|
|
36
46
|
export function parseCli(args) {
|
|
@@ -39,20 +49,57 @@ export function parseCli(args) {
|
|
|
39
49
|
const explicit = commands.includes(args[0]), command = explicit ? args[0] : 'open';
|
|
40
50
|
const options = { help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' }, json: { type: 'boolean' } };
|
|
41
51
|
const locators = ['asset', 'frame', 'group', 'layer', 'mode', 'base'];
|
|
42
|
-
const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'] };
|
|
52
|
+
const strings = { open: ['port', 'state-dir', ...locators], link: locators, serve: ['port', 'state-dir'], root: ['depth', 'state-dir'], service: ['port', 'state-dir'], check: ['base', 'frame', 'theme', 'state-dir'], render: ['scale', 'frame', 'theme', 'out-dir', 'base', 'state-dir'], diff: ['base', 'frame', 'theme', 'scale', 'out-dir', 'state-dir'], compare: ['frame', 'fixture', 'region', 'selector', 'viewport', 'origin'], owner: ['file', 'text', 'color', 'token', 'line', 'symbol', 'locale', 'theme', 'state-dir'], impact: ['source', 'part', 'token', 'file', 'line', 'symbol', 'base', 'head', 'theme', 'state-dir'] };
|
|
43
53
|
for (const name of strings[command] ?? []) options[name] = { type: 'string' };
|
|
44
54
|
if (command === 'serve') for (const name of ['print-key', 'rotate-key']) options[name] = { type: 'boolean' };
|
|
45
55
|
if (command === 'open') options['no-open'] = { type: 'boolean' };
|
|
46
56
|
if (command === 'open' || command === 'link') options.tokens = { type: 'boolean' };
|
|
47
57
|
if (command === 'check') options['read-only'] = { type: 'boolean' };
|
|
58
|
+
if (['render', 'check', 'diff'].includes(command)) { options.impacted = { type: 'boolean' }; options.explain = { type: 'boolean' }; }
|
|
59
|
+
if (command === 'owner') options.contains = { type: 'boolean' };
|
|
60
|
+
if (command === 'impact') {
|
|
61
|
+
options.explain = { type: 'boolean' };
|
|
62
|
+
for (const name of ['source', 'token']) options[name].multiple = true;
|
|
63
|
+
}
|
|
48
64
|
if (command === 'compare') { options.all = { type: 'boolean' }; options.page = { type: 'boolean' }; }
|
|
49
65
|
if (command === 'compare') options.click = { type: 'string', multiple: true };
|
|
50
66
|
let parsed;
|
|
51
|
-
try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true }); }
|
|
67
|
+
try { parsed = parseArgs({ args: explicit ? args.slice(1) : args, options, allowPositionals: true, tokens: command === 'owner' || command === 'impact' }); }
|
|
52
68
|
catch (error) { throw new CliError('USAGE_INVALID', `${error.message}; run adg ${command} --help`); }
|
|
53
69
|
const { values, positionals } = parsed;
|
|
54
70
|
if (globalJson) values.json = true;
|
|
55
71
|
if (!values.help && !values.version) {
|
|
72
|
+
if (['render', 'check', 'diff'].includes(command)) {
|
|
73
|
+
if (!values.impacted && (values.explain !== undefined || values['state-dir'] !== undefined)) throw new CliError('USAGE_INVALID', '--explain and --state-dir require --impacted --base=<rev>.');
|
|
74
|
+
if (values.impacted && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', '--impacted requires --base=<rev>.');
|
|
75
|
+
if (command === 'check' && !values.impacted && ['base', 'frame', 'theme', 'state-dir', 'explain'].some(key => values[key] !== undefined)) throw new CliError('USAGE_INVALID', 'Check selection flags require --impacted --base=<rev>.');
|
|
76
|
+
}
|
|
77
|
+
if (command === 'impact') {
|
|
78
|
+
const kinds = ['source', 'token', 'file', 'base'].filter(key => values[key] !== undefined), seen = new Set();
|
|
79
|
+
for (const token of parsed.tokens) if (token.kind === 'option' && !['json', 'help', 'version', 'source', 'token'].includes(token.name)) {
|
|
80
|
+
if (seen.has(token.name)) throw new CliError('USAGE_INVALID', `Do not repeat --${token.name}; run adg impact --help.`);
|
|
81
|
+
seen.add(token.name);
|
|
82
|
+
}
|
|
83
|
+
if (positionals.length || kinds.length !== 1 || strings.impact.some(key => values[key] !== undefined && (Array.isArray(values[key]) ? values[key] : [values[key]]).some(value => !value.trim())) ||
|
|
84
|
+
values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme) ||
|
|
85
|
+
values.part !== undefined && (kinds[0] !== 'source' || values.source.length !== 1) ||
|
|
86
|
+
values.head !== undefined && kinds[0] !== 'base' ||
|
|
87
|
+
(values.line !== undefined || values.symbol !== undefined) && kinds[0] !== 'file' ||
|
|
88
|
+
values.line !== undefined && (!/^[1-9]\d*$/.test(values.line) || !Number.isSafeInteger(Number(values.line)))) throw new CliError('USAGE_INVALID', 'Choose one nonempty impact selector family and compatible options; run adg impact --help.');
|
|
89
|
+
}
|
|
90
|
+
if (command === 'owner') {
|
|
91
|
+
const kinds = ['file', 'text', 'color', 'token'].filter(key => values[key] !== undefined);
|
|
92
|
+
const seen = new Set();
|
|
93
|
+
for (const token of parsed.tokens) if (token.kind === 'option' && !['json', 'help', 'version'].includes(token.name)) {
|
|
94
|
+
if (seen.has(token.name)) throw new CliError('USAGE_INVALID', `Do not repeat --${token.name}; run adg owner --help.`);
|
|
95
|
+
seen.add(token.name);
|
|
96
|
+
}
|
|
97
|
+
if (positionals.length || kinds.length !== 1 || strings.owner.some(key => values[key] !== undefined && !values[key].trim()) ||
|
|
98
|
+
values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme) ||
|
|
99
|
+
(values.line !== undefined || values.symbol !== undefined) && kinds[0] !== 'file' ||
|
|
100
|
+
(values.contains !== undefined || values.locale !== undefined) && kinds[0] !== 'text' ||
|
|
101
|
+
values.line !== undefined && (!/^[1-9]\d*$/.test(values.line) || !Number.isSafeInteger(Number(values.line)))) throw new CliError('USAGE_INVALID', 'Choose one nonempty owner input and compatible options; run adg owner --help.');
|
|
102
|
+
}
|
|
56
103
|
if (command === 'diff' && (typeof values.base !== 'string' || !values.base.trim())) throw new CliError('USAGE_INVALID', 'Set --base to a Git revision; run adg diff --help.');
|
|
57
104
|
if ((command === 'init' && positionals.length) || (['open', 'migrate'].includes(command) && positionals.length > 1) || (command === 'compare' && (values.all ? positionals.length || values.frame : positionals.length !== 1 || !values.frame))) throw new CliError('USAGE_INVALID', `Invalid arguments; run adg ${command} --help`);
|
|
58
105
|
if (command === 'link' && positionals.length !== 1) throw new CliError('USAGE_INVALID', 'Expected one viewer URL. Run adg link --help.');
|
|
@@ -120,6 +167,8 @@ async function dispatch({ command, values, positionals }, cwd, output, serviceOp
|
|
|
120
167
|
return {data:values['print-key'] ? {action:'print-key',stateDirectory,key} : {action:'rotate-key',stateDirectory,rotated:true}};
|
|
121
168
|
}
|
|
122
169
|
const config = await loadConfig(cwd);
|
|
170
|
+
if (command === 'impact') return (await import('./toolkit/impact.mjs')).impact(config, { ...values, ...(values['state-dir'] !== undefined ? { 'state-dir': path.resolve(cwd, values['state-dir']) } : {}) }, { log: output.log });
|
|
171
|
+
if (command === 'owner') return (await import('./toolkit/owner.mjs')).owner(config, { ...values, ...(values['state-dir'] !== undefined ? { 'state-dir': path.resolve(cwd, values['state-dir']) } : {}) }, { log: output.log });
|
|
123
172
|
if (command === 'init') return { data: (await import('./toolkit/project.mjs')).init(config, output.log) };
|
|
124
173
|
if (command === 'compare') return (await import('./toolkit/compare.mjs')).compare(config, positionals, values, {log:output.log});
|
|
125
174
|
if (command === 'diff') return (await import('./toolkit/diff.mjs')).diff(config, positionals, values, { log: output.log });
|
package/src/toolkit/arch-git.mjs
CHANGED
|
@@ -150,6 +150,25 @@ export async function sourceRenames(base) {
|
|
|
150
150
|
}
|
|
151
151
|
return renames;
|
|
152
152
|
}
|
|
153
|
+
|
|
154
|
+
/** Actual endpoint changes; working-tree mode includes staged, unstaged and untracked paths. */
|
|
155
|
+
export async function revisionChanges(base, head = null) {
|
|
156
|
+
const fields = (await git(base.root, ['diff', '--name-status', '-z', '--find-renames', base.sha, ...(head ? [head.sha] : []), '--'])).split('\0');
|
|
157
|
+
const changes = [];
|
|
158
|
+
for (let i = 0; i < fields.length - 1;) {
|
|
159
|
+
const code = fields[i++], first = fields[i++];
|
|
160
|
+
if (code.startsWith('R') || code.startsWith('C')) {
|
|
161
|
+
const second = fields[i++];
|
|
162
|
+
changes.push(code.startsWith('R') ? { before: first, after: second, status: 'renamed' } : { before: null, after: second, status: 'added' });
|
|
163
|
+
} else changes.push({ before: code === 'A' ? null : first, after: code === 'D' ? null : first,
|
|
164
|
+
status: code === 'A' ? 'added' : code === 'D' ? 'deleted' : code === 'T' ? 'type_changed' : 'modified' });
|
|
165
|
+
}
|
|
166
|
+
if (!head) {
|
|
167
|
+
const names = (await git(base.root, ['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean);
|
|
168
|
+
for (const name of names) if (!changes.some(change => change.after === name)) changes.push({ before: null, after: name, status: 'added' });
|
|
169
|
+
}
|
|
170
|
+
return changes.sort((a, b) => (a.after ?? a.before) < (b.after ?? b.before) ? -1 : (a.after ?? a.before) > (b.after ?? b.before) ? 1 : 0);
|
|
171
|
+
}
|
|
153
172
|
export async function resolveBase(config, rev) {
|
|
154
173
|
if(typeof rev!=='string'||!rev.trim())throw new CliError('USAGE_INVALID', 'Set --base to a Git revision, for example HEAD.');
|
|
155
174
|
let root;
|
|
@@ -12,7 +12,7 @@ const aborted = () => Object.assign(new Error('Build superseded'), { name: 'Abor
|
|
|
12
12
|
const memoryLimit = 32 * 1024 * 1024, diskLimit = 256 * 1024 * 1024;
|
|
13
13
|
const workerLimit = 2, recycleAfter = 32;
|
|
14
14
|
|
|
15
|
-
class BuildPool {
|
|
15
|
+
export class BuildPool {
|
|
16
16
|
slots = new Set(); retiring = new Set(); queue = []; nextId = 0; closed = false;
|
|
17
17
|
counters = { attempts: 0, spawned: 0, recycled: 0, cancelled: 0 };
|
|
18
18
|
run(payload, signal) {
|
|
@@ -113,7 +113,7 @@ export async function createBuildStore({ config, cacheDirectory }) {
|
|
|
113
113
|
const workerConfig = { root: await realpath(config.root), design, output: config.output, sources: config.sources, arch:config.arch, check:config.check, ...(config.overlay?{overlay:config.overlay}:{}) };
|
|
114
114
|
const require = createRequire(import.meta.url);
|
|
115
115
|
const fingerprint = digest(Buffer.concat(await Promise.all([
|
|
116
|
-
...['../../package.json', './build.mjs', './runtime.mjs', './tokens.mjs', './text.mjs', './project.mjs', './build-worker.mjs', './build-store.mjs', './arch.mjs', './arch-browser.mjs', './browser.mjs'].map(file => new URL(file, import.meta.url)),
|
|
116
|
+
...['../../package.json', './build.mjs', './frame-document.mjs', './runtime.mjs', './tokens.mjs', './text.mjs', './project.mjs', './build-worker.mjs', './build-store.mjs', './arch.mjs', './arch-browser.mjs', './browser.mjs'].map(file => new URL(file, import.meta.url)),
|
|
117
117
|
...(config.overlay?['./arch-overlay.mjs','./arch-git.mjs'].map(file=>new URL(file,import.meta.url)):[]),
|
|
118
118
|
require.resolve('esbuild/package.json'), require.resolve('tailwindcss/package.json'),
|
|
119
119
|
].map(file => readFile(file)))));
|
|
@@ -238,10 +238,12 @@ export async function createBuildStore({ config, cacheDirectory }) {
|
|
|
238
238
|
const built = await pool.run({ config: workerConfig, name }, controller.signal); counters.builds++;
|
|
239
239
|
endQueue?.({frames: built.frames.length});
|
|
240
240
|
if (controller.signal.aborted || generation !== (generations.get(name) ?? 0)) throw aborted();
|
|
241
|
-
const payload = { frames: built.frames, css: built.css
|
|
241
|
+
const payload = { frames: built.frames, parts: built.parts, css: built.css,
|
|
242
|
+
...(built.tokenCss !== undefined ? { tokenCss: built.tokenCss, cssWithoutTokens: built.cssWithoutTokens,
|
|
243
|
+
cssBeforeTokens: built.cssBeforeTokens, cssAfterTokens: built.cssAfterTokens } : {}) };
|
|
242
244
|
const hash = digest(JSON.stringify({ path: name, component: !name.startsWith('surfaces/'), ...payload, ...(config.overlay?{base:config.overlay.sha,baseBlob:built.baseBlob}:{}), imports: built.imports }));
|
|
243
245
|
const entry = { path: name, hash, inputHash: inputHash(built.dependencyHashes,built.baseBlob), ...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies: built.dependencies, dependencyHashes: built.dependencyHashes,
|
|
244
|
-
frames: built.frames.map(({ html, ...frame }) => frame) };
|
|
246
|
+
parts: built.parts, frames: built.frames.map(({ html, ...frame }) => frame) };
|
|
245
247
|
if (old) unlinkEntry(old); entries.set(name, entry); link(entry); remember(hash, payload);
|
|
246
248
|
touch(hash);
|
|
247
249
|
await persist(hash, payload);
|
|
@@ -17,7 +17,7 @@ parentPort.on('message', async ({ id, config, name, type }) => {
|
|
|
17
17
|
if (shuttingDown) return;
|
|
18
18
|
try {
|
|
19
19
|
const snapshot = new Map();
|
|
20
|
-
const build = async browser => config.overlay && name.endsWith('.mmd') ? (await import('./arch-overlay.mjs')).buildOverlay(config,path.join(config.root,name),{base:config.overlay,browser,snapshot}) : buildSource(config, path.join(name.endsWith('.mmd')?config.root:config.design, name), { write: false, snapshot, browser });
|
|
20
|
+
const build = async browser => config.overlay && name.endsWith('.mmd') ? (await import('./arch-overlay.mjs')).buildOverlay(config,path.join(config.root,name),{base:config.overlay,browser,snapshot}) : buildSource(config, path.join(name.endsWith('.mmd')?config.root:config.design, name), { write: false, snapshot, browser, allowLegacy: config.allowLegacy ?? true });
|
|
21
21
|
const built = await (name.endsWith('.mmd') ? archBrowser.run(build) : build());
|
|
22
22
|
const frames = JSON.parse(JSON.stringify(built.frames.map(({ document, ...frame }) => frame)));
|
|
23
23
|
const dependencies = [...new Set(built.dependencies.map(file => path.relative(config.design, file).split(path.sep).join('/')))].sort();
|
|
@@ -25,7 +25,10 @@ parentPort.on('message', async ({ id, config, name, type }) => {
|
|
|
25
25
|
const bytes=snapshot.get(path.join(config.design,name));
|
|
26
26
|
return [name,createHash('sha256').update(bytes===null?'missing\0':'present\0').update(bytes??'').digest('hex')];
|
|
27
27
|
}));
|
|
28
|
-
if (!shuttingDown) parentPort.postMessage({ id, result: { frames,
|
|
28
|
+
if (!shuttingDown) parentPort.postMessage({ id, result: { frames, parts: built.parts ?? [], css: built.css,
|
|
29
|
+
...(built.tokenCss !== undefined ? { tokenCss: built.tokenCss, cssWithoutTokens: built.cssWithoutTokens,
|
|
30
|
+
cssBeforeTokens: built.cssBeforeTokens, cssAfterTokens: built.cssAfterTokens } : {}),
|
|
31
|
+
...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies, dependencyHashes }, heapBytes: process.memoryUsage().heapUsed });
|
|
29
32
|
} catch (error) {
|
|
30
33
|
const diagnostics=error.errors ?? error.cause?.errors ?? [];
|
|
31
34
|
// esbuild's onLoad error keeps transform diagnostics under detail.errors.
|
package/src/toolkit/build.mjs
CHANGED
|
@@ -6,8 +6,9 @@ import path from 'node:path';
|
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
7
|
import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
|
|
8
8
|
import { themeCss, parseTokens } from './tokens.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { componentOwner } from './runtime.mjs';
|
|
10
10
|
import { CliError, classifyError } from '../cli-output.mjs';
|
|
11
|
+
import { frameDocument } from './frame-document.mjs';
|
|
11
12
|
const require = createRequire(import.meta.url);
|
|
12
13
|
const runtime = fileURLToPath(new URL('./runtime.mjs', import.meta.url));
|
|
13
14
|
const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
|
|
@@ -17,6 +18,7 @@ const tailwind = path.dirname(require.resolve('tailwindcss/package.json'));
|
|
|
17
18
|
const sourceTransforms = new Map();
|
|
18
19
|
let transformBytes = 0;
|
|
19
20
|
const transformLimit = 8 * 1024 * 1024;
|
|
21
|
+
let evaluation = 0;
|
|
20
22
|
function forgetTransform(file) {
|
|
21
23
|
const entry = sourceTransforms.get(file);
|
|
22
24
|
if (entry) { transformBytes -= entry.bytes; sourceTransforms.delete(file); }
|
|
@@ -61,6 +63,10 @@ function trimTransforms() {
|
|
|
61
63
|
export function validateFrame(frame) {
|
|
62
64
|
if (!frame?.frame || typeof frame.name !== 'string' || !frame.name.trim()) throw Error('Default export must return named Frames');
|
|
63
65
|
for (const key of ['width', 'height']) if (frame[key] !== undefined && !(Number.isFinite(frame[key]) && frame[key] > 0)) throw Error(`Invalid Frame ${key}; use positive CSS pixels`);
|
|
66
|
+
if (frame.locale !== undefined) {
|
|
67
|
+
try { if (typeof frame.locale !== 'string' || !frame.locale.trim()) throw Error(); frame.locale = Intl.getCanonicalLocales(frame.locale)[0]; }
|
|
68
|
+
catch { throw Error('Invalid Frame locale; use a BCP 47 language tag.'); }
|
|
69
|
+
}
|
|
64
70
|
const parent = frame.parent;
|
|
65
71
|
if (parent !== undefined) {
|
|
66
72
|
if (!parent || typeof parent !== 'object' || Array.isArray(parent) ||
|
|
@@ -136,7 +142,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
136
142
|
// Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
|
|
137
143
|
throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
|
|
138
144
|
});
|
|
139
|
-
const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${
|
|
145
|
+
const mod = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}#${++evaluation}`);
|
|
140
146
|
if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
|
|
141
147
|
const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
|
|
142
148
|
if (!frames.length) throw Error(`${relative(config,file)}: default export must return at least one Frame`);
|
|
@@ -148,10 +154,19 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
148
154
|
const tokenSource = read(path.join(base,'tokens.css'),'utf8'), tokens = snapshot ? parseTokens(tokenSource) : loadTokens(config);
|
|
149
155
|
const compiler = await compile(`${readFileSync(path.join(tailwind,'theme.css'),'utf8')}\n${themeCss(tokens)}\n${readFileSync(path.join(tailwind,'preflight.css'),'utf8')}\n@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));\n@tailwind utilities;`);
|
|
150
156
|
const classes = [...new Set(frames.flatMap(f => [...f.html.matchAll(/\bclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/))))];
|
|
151
|
-
const
|
|
157
|
+
const utilities = compiler.build(classes);
|
|
158
|
+
const defaults = 'html,body{margin:0;font-family:var(--font-ui);color:var(--text);background:var(--canvas)}[data-adg-frame]{display:flex;align-items:flex-start;position:relative;background:var(--canvas)}[data-adg-frame]>*,svg{flex-shrink:0} @media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}';
|
|
159
|
+
const css = `${utilities}\n${tokenSource}\n${defaults}`;
|
|
152
160
|
for (const frame of frames) {
|
|
153
|
-
frame.document = theme =>
|
|
161
|
+
frame.document = theme => frameDocument(frame, theme, css);
|
|
154
162
|
if (write) { const destination = path.join(config.output, path.relative(base,file).replace(/\.tsx$/, ''), `${encodeURIComponent(frame.name)}.html`); mkdirSync(path.dirname(destination),{recursive:true}); writeFileSync(destination,frame.document('light')); }
|
|
155
163
|
}
|
|
156
|
-
|
|
164
|
+
const sourceName = path.relative(base, file).split(path.sep).join('/');
|
|
165
|
+
const parts = Object.keys(mod).filter(name => {
|
|
166
|
+
const owner = typeof mod[name] === 'function' && componentOwner(mod[name]);
|
|
167
|
+
return owner && owner.source === sourceName && owner.export === name;
|
|
168
|
+
}).sort();
|
|
169
|
+
return { frames, parts, dependencies: [...dependencies], imports: [...imports].sort(), css,
|
|
170
|
+
tokenCss: tokenSource, cssWithoutTokens: `${utilities}\n${defaults}`,
|
|
171
|
+
cssBeforeTokens: `${utilities}\n`, cssAfterTokens: `\n${defaults}` };
|
|
157
172
|
}
|
package/src/toolkit/commands.mjs
CHANGED
|
@@ -7,6 +7,9 @@ import { importDirectionViolations } from './asset-rules.mjs';
|
|
|
7
7
|
import { launch, loadFrame, browserTask } from './browser.mjs';
|
|
8
8
|
import { CliError, classifyError } from '../cli-output.mjs';
|
|
9
9
|
import { commandFailure, cleanup, emptySelection } from './results.mjs';
|
|
10
|
+
import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
|
|
11
|
+
import { withImpacted } from './impact-selection.mjs';
|
|
12
|
+
import { mappingFacts } from './source-facts.mjs';
|
|
10
13
|
export function inspectFrame(tokenNames) {
|
|
11
14
|
const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
|
|
12
15
|
const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
|
|
@@ -179,10 +182,12 @@ export function inspectFrame(tokenNames) {
|
|
|
179
182
|
}
|
|
180
183
|
return [...problems.values()];
|
|
181
184
|
}
|
|
182
|
-
export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch } = {}) {
|
|
185
|
+
export async function check(config, args = [], options = {}, log = console.log, error = console.error, { launchBrowser = launch, session } = {}) {
|
|
186
|
+
if (options.impacted && !session) return withImpacted(config, args, options, 'check', selected =>
|
|
187
|
+
check(config, args, options, log, error, { launchBrowser, session: selected }));
|
|
183
188
|
const write = !options['read-only'];
|
|
184
189
|
/** @type {import('./results.mjs').CheckData} */
|
|
185
|
-
const data = { project: config.root, readOnly: !write, complete: false, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
|
|
190
|
+
const data = { project: config.root, readOnly: !write, complete: false, impact: session?.selection ?? null, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [] };
|
|
186
191
|
const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
|
|
187
192
|
let browser, primary;
|
|
188
193
|
const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
|
|
@@ -198,12 +203,14 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
198
203
|
else warnings.push(classifyError(failure).error);
|
|
199
204
|
};
|
|
200
205
|
try {
|
|
201
|
-
const
|
|
206
|
+
const mapping = await loadImplementationMap(config);
|
|
207
|
+
const files = session ? session.sources.map(source => path.join(config.root, source)).filter(existsSync) : selectSources(config, args, { write });
|
|
202
208
|
data.sources = files.map(file => relative(config, file));
|
|
203
209
|
data.summary.sources = files.length;
|
|
204
210
|
const tokens = files.length ? loadTokens(config) : null;
|
|
205
211
|
const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
|
|
206
212
|
let page;
|
|
213
|
+
const builtSources = new Map(), failedSources = new Map();
|
|
207
214
|
for (const file of files) {
|
|
208
215
|
const architecture = file.endsWith('.mmd');
|
|
209
216
|
if (architecture) {
|
|
@@ -218,19 +225,24 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
218
225
|
let built;
|
|
219
226
|
try {
|
|
220
227
|
// Static architecture rejection is a completed rule evaluation and needs no browser.
|
|
221
|
-
|
|
222
|
-
|
|
228
|
+
if (session && !architecture) built = session.views[1].built.get(relative(config, file));
|
|
229
|
+
else if (session && !session.chosen.some(row => row.source === relative(config, file) && session.themes.some(theme => session.scheduled(row, theme)))) continue;
|
|
230
|
+
else { browser ??= await launchBrowser(); built = await buildSource(config, file, { allowLegacy: false, write: session ? false : write, browser }); }
|
|
223
231
|
} catch (cause) {
|
|
224
232
|
const legacy = cause.errors?.find(item => item.detail?.code === 'LEGACY_SOURCE');
|
|
225
233
|
if (legacy) throw legacy.detail;
|
|
226
234
|
if (['PLAYWRIGHT_UNAVAILABLE', 'CHROMIUM_UNAVAILABLE', 'BROWSER_FAILED', 'LEGACY_SOURCE'].includes(cause.code)) throw cause;
|
|
227
235
|
failed(cause);
|
|
236
|
+
failedSources.set(relative(config, file), cause);
|
|
228
237
|
for (const message of cause.message.split('\n')) humanProblems.add(`${relative(config, file)}: ${architecture ? '' : '-: '}${message.replace(/\s+/g, ' ')}`);
|
|
229
238
|
continue;
|
|
230
239
|
}
|
|
231
240
|
data.summary.frames += built.frames.length;
|
|
241
|
+
if (mapping.present && !architecture) builtSources.set(relative(config, file), mappingFacts(built));
|
|
232
242
|
graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
|
|
233
|
-
for (const frame of built.frames) for (const theme of ['light', 'dark']) {
|
|
243
|
+
for (const frame of built.frames) for (const theme of session?.themes ?? ['light', 'dark']) {
|
|
244
|
+
if (session && !session.scheduled({ source: relative(config, file), frame: frame.name }, theme)) continue;
|
|
245
|
+
browser ??= await launchBrowser();
|
|
234
246
|
try {
|
|
235
247
|
page ??= await browserTask(browser, () => browser.newPage());
|
|
236
248
|
await loadFrame(page, frame, theme);
|
|
@@ -243,6 +255,19 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
243
255
|
}
|
|
244
256
|
}
|
|
245
257
|
}
|
|
258
|
+
if (mapping.present) {
|
|
259
|
+
const { listSources } = await import('./project.mjs');
|
|
260
|
+
await validateImplementationMap(config, mapping, {
|
|
261
|
+
sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)),
|
|
262
|
+
selected: args.length ? data.sources : undefined,
|
|
263
|
+
getBuild: source => {
|
|
264
|
+
if (failedSources.has(source)) throw failedSources.get(source);
|
|
265
|
+
if (!builtSources.has(source)) builtSources.set(source, session?.views[1].built.get(source) ?? buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false }));
|
|
266
|
+
return builtSources.get(source);
|
|
267
|
+
},
|
|
268
|
+
onFinding: ({ code, message, line, column, frame }) => add({ code, message, line, column }, mapping.file, frame),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
246
271
|
await cleanup(() => browser?.close(), primary);
|
|
247
272
|
browser = null;
|
|
248
273
|
if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
|
|
@@ -262,10 +287,12 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
262
287
|
} finally { if (browser) await cleanup(() => browser.close(), primary); }
|
|
263
288
|
}
|
|
264
289
|
|
|
265
|
-
export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch } = {}) {
|
|
290
|
+
export async function render(config, args = [], options = {}, log = console.log, { launchBrowser = launch, session } = {}) {
|
|
291
|
+
if (options.impacted && !session) return withImpacted(config, args, options, 'render', selected =>
|
|
292
|
+
render(config, args, options, log, { launchBrowser, session: selected }));
|
|
266
293
|
const output = options['out-dir'] ? path.resolve(config.root, options['out-dir']) : config.output;
|
|
267
294
|
/** @type {import('./results.mjs').RenderData} */
|
|
268
|
-
const data = { project: config.root, outputDirectory: output, complete: false, base: null, captures: [], deleted: [] };
|
|
295
|
+
const data = { project: config.root, outputDirectory: output, complete: false, impact: session?.selection ?? null, base: null, captures: [], deleted: [] };
|
|
269
296
|
const warnings = [], completed = [], failures = [];
|
|
270
297
|
let browser, primary;
|
|
271
298
|
try {
|
|
@@ -276,30 +303,33 @@ export async function render(config, args = [], options = {}, log = console.log,
|
|
|
276
303
|
if (options['out-dir'] === '') throw new CliError('USAGE_INVALID', 'Set --out-dir to a directory.');
|
|
277
304
|
const themes = themeOption === 'both' ? ['light', 'dark'] : [themeOption];
|
|
278
305
|
let base, additional = [];
|
|
279
|
-
if (options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
|
|
306
|
+
if (!session && options.base !== undefined && (!args.length || args.some(arg => arg.endsWith('.mmd')))) {
|
|
280
307
|
const git = await import('./arch-git.mjs');
|
|
281
308
|
base = await git.resolveBase(config, options.base);
|
|
282
309
|
additional = await git.baseArchFiles(config, base);
|
|
283
310
|
data.base = { rev: base.rev, sha: base.sha };
|
|
284
|
-
} else if (options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
|
|
285
|
-
|
|
311
|
+
} else if (!session && options.base !== undefined) warnings.push({ code: 'USAGE_INVALID', message: '--base applies only to architecture sources.', next: [] });
|
|
312
|
+
if (session) data.base = { rev: session.selection.query.base.rev, sha: session.selection.query.base.sha };
|
|
313
|
+
if (session) data.deleted = [...new Set(session.chosen.filter(row => row.status === 'removed').map(row => row.source))];
|
|
314
|
+
const selected = session ? [...new Set(session.chosen.filter(row => row.after && themes.some(theme => session.scheduled(row, theme))).map(row => path.join(config.root, row.source)))] : selectSources(config, args, { additional });
|
|
286
315
|
const currentArchitecture = base ? new Set(archFiles(config.arch)) : null;
|
|
287
316
|
const files = selected.filter(file => {
|
|
288
317
|
if (!existsSync(file) || (base && file.endsWith('.mmd') && !currentArchitecture.has(file))) { data.deleted.push(relative(config, file)); return false; }
|
|
289
318
|
return true;
|
|
290
319
|
});
|
|
291
|
-
if (!selected.length) emptySelection(warnings);
|
|
320
|
+
if (!selected.length && (!session || !session.selection.coverage.expectedRows)) emptySelection(warnings);
|
|
292
321
|
if (files.length) browser = await launchBrowser();
|
|
293
322
|
const captures = [];
|
|
294
323
|
for (const file of files) {
|
|
295
|
-
const built = base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, browser });
|
|
324
|
+
const built = session?.views[1].built.get(relative(config, file)) ?? (base && file.endsWith('.mmd') ? await (await import('./arch-overlay.mjs')).buildOverlay(config, file, { base, browser }) : await buildSource(config, file, { allowLegacy: false, write: !session, browser }));
|
|
296
325
|
for (const frame of built.frames.filter(frame => !options.frame || frame.name === options.frame)) for (const theme of themes) {
|
|
326
|
+
if (session && !session.scheduled({ source: relative(config, file), frame: frame.name }, theme)) continue;
|
|
297
327
|
const outputSource = file.endsWith('.mmd') ? relative(config, file) : path.relative(config.design, file);
|
|
298
328
|
const target = path.join(output, outputSource.replace(/\.(?:tsx|mmd)$/, ''), `${encodeURIComponent(frame.name)}-${theme}.png`);
|
|
299
329
|
captures.push({ source: relative(config, file), frame, theme, target });
|
|
300
330
|
}
|
|
301
331
|
}
|
|
302
|
-
if (options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
|
|
332
|
+
if (!session && options.frame && !captures.length && !data.deleted.length) throw new CliError('FRAME_NOT_FOUND', `Unknown frame ${options.frame}; choose a declared frame`);
|
|
303
333
|
let next = 0;
|
|
304
334
|
await Promise.allSettled(Array.from({ length: Math.min(4, availableParallelism(), captures.length) }, async () => {
|
|
305
335
|
while (next < captures.length) {
|
package/src/toolkit/config.mjs
CHANGED
|
@@ -87,10 +87,11 @@ export function viewport(value) {
|
|
|
87
87
|
if (!match) throw new CliError('CONFIG_INVALID', `Invalid viewport ${value}; use <width>x<height>, for example 1280x800`);
|
|
88
88
|
return { width: Number(match[1]), height: Number(match[2]) };
|
|
89
89
|
}
|
|
90
|
-
|
|
90
|
+
let configEvaluation = 0;
|
|
91
|
+
async function importConfig(file, fresh) {
|
|
91
92
|
if (!file.endsWith('.ts')) {
|
|
92
93
|
const info = statSync(file), url = pathToFileURL(file);
|
|
93
|
-
url.searchParams.set('revision', `${info.mtimeMs}-${info.size}`);
|
|
94
|
+
url.searchParams.set('revision', `${info.mtimeMs}-${info.size}${fresh ? `-${++configEvaluation}` : ''}`);
|
|
94
95
|
return (await import(url.href)).default;
|
|
95
96
|
}
|
|
96
97
|
const require = createRequire(pathToFileURL(file));
|
|
@@ -108,14 +109,14 @@ async function importConfig(file) {
|
|
|
108
109
|
}
|
|
109
110
|
});
|
|
110
111
|
}}] });
|
|
111
|
-
return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`)).default;
|
|
112
|
+
return (await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}${fresh ? `#${++configEvaluation}` : ''}`)).default;
|
|
112
113
|
}
|
|
113
|
-
export async function loadConfig(cwd = process.cwd(), { checkVersion = true, discover = true } = {}) {
|
|
114
|
+
export async function loadConfig(cwd = process.cwd(), { checkVersion = true, discover = true, fresh = false } = {}) {
|
|
114
115
|
const root = discover ? discoverRoot(cwd) : path.resolve(cwd), file = configFile(root);
|
|
115
116
|
if (!discover) requireMigration(root);
|
|
116
117
|
let config = {};
|
|
117
118
|
if (file) {
|
|
118
|
-
try { config = await importConfig(file); }
|
|
119
|
+
try { config = await importConfig(file, fresh); }
|
|
119
120
|
catch (error) { throw new CliError('CONFIG_INVALID', `Cannot load ${file}: ${error.message}; fix ${path.basename(file)}`, { cause: error }); }
|
|
120
121
|
}
|
|
121
122
|
if (!config || typeof config !== 'object' || Array.isArray(config)) throw new CliError('CONFIG_INVALID', 'Export a default object from adg.config.mjs');
|