@whzxc/agent-design-gallery 0.10.0 → 0.13.2
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 +3 -3
- package/package.json +2 -2
- package/public/annotations.js +816 -0
- package/public/app.js +245 -12
- package/public/assets.js +4 -13
- package/public/frame-identity.js +223 -0
- package/public/icons.js +1 -0
- package/public/index.html +3 -0
- package/public/selection.js +1 -1
- package/public/style.css +72 -2
- package/src/annotations.mjs +238 -0
- package/src/cli-output.mjs +25 -2
- package/src/cli.mjs +46 -7
- package/src/http.mjs +2 -1
- package/src/hub/instances.mjs +1 -1
- package/src/hub/registry.mjs +1 -1
- package/src/hub.mjs +2 -2
- package/src/server.mjs +59 -11
- package/src/service.mjs +1 -1
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +1 -1
- package/src/toolkit/build-worker.mjs +1 -1
- package/src/toolkit/build.mjs +27 -11
- package/src/toolkit/commands.mjs +61 -8
- package/src/toolkit/config.mjs +2 -1
- package/src/toolkit/diff.mjs +4 -1
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +1 -1
- package/src/toolkit/frame-facets.mjs +167 -0
- package/src/toolkit/frame-identity.mjs +100 -0
- package/src/toolkit/frame-observation.mjs +147 -0
- package/src/toolkit/frame-primitives.mjs +85 -0
- package/src/toolkit/html.mjs +1 -0
- package/src/toolkit/impact-inputs.mjs +2 -21
- package/src/toolkit/impact.mjs +3 -24
- package/src/toolkit/input-generation.mjs +51 -0
- package/src/toolkit/inspect-encoding.mjs +459 -0
- package/src/toolkit/inspect-observation.mjs +56 -0
- package/src/toolkit/inspect-output.mjs +169 -0
- package/src/toolkit/inspect-styles.mjs +34 -0
- package/src/toolkit/inspect.d.ts +118 -0
- package/src/toolkit/inspect.mjs +125 -0
- package/src/toolkit/owner-observation.mjs +23 -189
- package/src/toolkit/owner-search.mjs +2 -2
- package/src/toolkit/owner.mjs +33 -4
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +22 -5
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
package/src/server.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Adapted from ARC's MIT-licensed tooling/design-server.mjs.
|
|
2
|
+
import { annotations, annotationFile, readAnnotationContext } from './annotations.mjs';
|
|
2
3
|
import { randomUUID, createHash } from 'node:crypto';
|
|
3
4
|
import { directLocal, viewerFile, shell, json } from './http.mjs';
|
|
4
5
|
import { createServer } from "node:http";
|
|
@@ -19,7 +20,7 @@ import { createBuildStore } from './toolkit/build-store.mjs';
|
|
|
19
20
|
import { CliError, asCliError } from './cli-output.mjs';
|
|
20
21
|
import { cleanup } from './toolkit/results.mjs';
|
|
21
22
|
import { createViewerCache } from './viewer-cache.mjs';
|
|
22
|
-
import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories } from './toolkit/project.mjs';
|
|
23
|
+
import { refreshTypes, archFiles, isSourcePath, readGroups, sourceDirectories, isFeatureInternal } from './toolkit/project.mjs';
|
|
23
24
|
import { loadConfig } from './toolkit/config.mjs';
|
|
24
25
|
import { parseTokens } from './toolkit/tokens.mjs';
|
|
25
26
|
import { sourceRelationships } from '../public/relationships.js';
|
|
@@ -30,15 +31,13 @@ function tokenSourcePath(directory, project) {
|
|
|
30
31
|
const base = project.design === directory ? project.root : path.dirname(directory);
|
|
31
32
|
return path.relative(base, path.join(directory, tokenFile)).split(path.sep).join('/');
|
|
32
33
|
}
|
|
33
|
-
const viewerVersion = Promise.all(['assets.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
|
|
34
|
-
const defaultState = path.join(
|
|
35
|
-
process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local/state"),
|
|
36
|
-
"agent-design-gallery",
|
|
37
|
-
);
|
|
34
|
+
const viewerVersion = Promise.all(['assets.js','frame-identity.js','layout.js','selection.js','arrangement.js','arrangement-worker.js'].map(file => readFile(new URL('../public/'+file,import.meta.url)))).then(parts => digest(Buffer.concat(parts)));
|
|
35
|
+
const defaultState = path.join(os.homedir(), ".agent-design-gallery");
|
|
38
36
|
export async function startServer({
|
|
39
37
|
directory,
|
|
40
38
|
port = 0,
|
|
41
39
|
stateDirectory = defaultState,
|
|
40
|
+
annotationStateDirectory = stateDirectory,
|
|
42
41
|
fixtures = null,
|
|
43
42
|
readOnly = false,
|
|
44
43
|
instanceId = randomUUID(),
|
|
@@ -87,6 +86,25 @@ export async function startServer({
|
|
|
87
86
|
for (const client of clients)
|
|
88
87
|
client.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
89
88
|
};
|
|
89
|
+
let annotationStamp = null;
|
|
90
|
+
async function readAnnotationStamp() {
|
|
91
|
+
if (!activeProject) return null;
|
|
92
|
+
try {
|
|
93
|
+
const info = await stat(annotationFile(activeProject.root, annotationStateDirectory));
|
|
94
|
+
return `${info.mtimeMs}-${info.size}`;
|
|
95
|
+
} catch (e) {
|
|
96
|
+
return e.code === 'ENOENT' ? 'missing' : null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const annotationTimer = setInterval(async () => {
|
|
100
|
+
if (closing || !clients.size || !activeProject) return;
|
|
101
|
+
const next = await readAnnotationStamp();
|
|
102
|
+
if (next && next !== annotationStamp) {
|
|
103
|
+
annotationStamp = next;
|
|
104
|
+
emit({ annotations: true });
|
|
105
|
+
}
|
|
106
|
+
}, 800);
|
|
107
|
+
annotationTimer.unref?.();
|
|
90
108
|
const diagnostic = (error, name = null, fallback = 'SOURCE_BUILD_FAILED') => {
|
|
91
109
|
if (error.name === 'AbortError') return;
|
|
92
110
|
const at = error.location ?? error.errors?.[0]?.location ?? error.cause?.errors?.[0]?.location;
|
|
@@ -231,6 +249,7 @@ export async function startServer({
|
|
|
231
249
|
watcher = nextWatcher;
|
|
232
250
|
activeProject=project;watchArch(project,next);
|
|
233
251
|
root = next;
|
|
252
|
+
annotationStamp = await readAnnotationStamp();
|
|
234
253
|
tokenSource = hasTokens ? tokenSourcePath(next, project) : null;
|
|
235
254
|
codePaths=nextCode;
|
|
236
255
|
sources = nextSources;
|
|
@@ -319,10 +338,12 @@ export async function startServer({
|
|
|
319
338
|
}
|
|
320
339
|
const baseManifest = () => ({
|
|
321
340
|
directory: root ?? null,
|
|
341
|
+
projectRoot: activeProject?.root ?? null,
|
|
342
|
+
sourcePrefix: activeProject && root ? path.relative(activeProject.root, root).split(path.sep).join('/') : '',
|
|
322
343
|
label: root
|
|
323
344
|
? path.basename(root) === "design" ? path.basename(path.dirname(root)) : path.basename(root)
|
|
324
345
|
: "Agent Design Gallery",
|
|
325
|
-
assets: [...files.values()].sort((a, b) => a.path.localeCompare(b.path)),
|
|
346
|
+
assets: [...files.values()].filter(asset => !isFeatureInternal(asset.path, sources)).sort((a, b) => a.path.localeCompare(b.path)),
|
|
326
347
|
groups,
|
|
327
348
|
revision,
|
|
328
349
|
recent: state.recent,
|
|
@@ -337,7 +358,7 @@ export async function startServer({
|
|
|
337
358
|
if (Number.isFinite(fixtures.assetModifiedAt)) data.assets = data.assets.map(a => ({...a,modifiedAt:fixtures.assetModifiedAt}));
|
|
338
359
|
const preset = fixtures.states[name];
|
|
339
360
|
if (!preset) throw new Error(`Unknown fixture ${name}; choose a declared ADG fixture.`);
|
|
340
|
-
return { ...data, ...(preset.empty ? { directory: null, assets: [], groups: [] } : {}),
|
|
361
|
+
return { ...data, ...(preset.empty ? { directory: null, projectRoot: null, sourcePrefix: '', assets: [], groups: [] } : {}),
|
|
341
362
|
label: 'agent-remote-control', recent: fixtures.recent, view: null, theme: preset.themeChoice ?? preset.theme,
|
|
342
363
|
sidebar: preset.sidebar, inspector: !!preset.inspector, fixture: { name, ...preset } };
|
|
343
364
|
}
|
|
@@ -427,8 +448,9 @@ export async function startServer({
|
|
|
427
448
|
const built=base&&name.endsWith('.mmd')?await overlayBuild(name,base):await sourceBuild(name);
|
|
428
449
|
const frames = onlyFrame ? built.frames.filter(frame => frame.name === onlyFrame) : built.frames;
|
|
429
450
|
if (!frames.length && onlyFrame) throw new CliError('FRAME_NOT_FOUND', `Frame ${onlyFrame} does not exist in ${name}.`);
|
|
451
|
+
const projectSource = activeProject ? path.relative(activeProject.root, path.join(root, name)).split(path.sep).join('/') : name;
|
|
430
452
|
return {version:built.hash,imports:built.imports,dependencies:built.dependencies,
|
|
431
|
-
body:JSON.stringify({format:'tsx',hash:built.hash,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
|
|
453
|
+
body:JSON.stringify({format:'tsx',hash:built.hash,projectSource,css:built.css,imports:built.imports,component:!onlyFrame && name.endsWith('.tsx') && !name.startsWith('surfaces/'),frames})};
|
|
432
454
|
}
|
|
433
455
|
let content = await readFile(path.join(root, name), "utf8");
|
|
434
456
|
content = content.replace(
|
|
@@ -498,6 +520,30 @@ export async function startServer({
|
|
|
498
520
|
const file = ['GET', 'HEAD'].includes(request.method) && viewerFile(url.pathname);
|
|
499
521
|
if (file) return await shell(request, response, file, request.headers['x-adg-viewer-base']);
|
|
500
522
|
if (!directLocal(request)) return json(response, 401, { error: 'Unauthorized' });
|
|
523
|
+
if (url.pathname === '/api/annotations') {
|
|
524
|
+
if (request.method !== 'GET' && request.method !== 'POST') return json(response,405,{error:'Use GET or POST.'});
|
|
525
|
+
if (request.method === 'POST' && request.headers.origin && ![`http://${host}`,`https://${host}`].includes(request.headers.origin)) return json(response,403,{error:'Cross-origin request refused.'});
|
|
526
|
+
const config = await loadConfig(root);
|
|
527
|
+
if (request.method === 'GET') {
|
|
528
|
+
if (url.searchParams.has('id')) {
|
|
529
|
+
const id = url.searchParams.get('id');
|
|
530
|
+
const result = url.searchParams.get('context') === '1'
|
|
531
|
+
? await readAnnotationContext(config, annotationStateDirectory, id)
|
|
532
|
+
: await annotations(config.root, annotationStateDirectory, 'read', { id });
|
|
533
|
+
return json(response, 200, result);
|
|
534
|
+
}
|
|
535
|
+
const status = url.searchParams.get('status') ?? 'all';
|
|
536
|
+
return json(response, 200, await annotations(config.root, annotationStateDirectory, 'list', { status }));
|
|
537
|
+
}
|
|
538
|
+
const input = await body(request);
|
|
539
|
+
const result = await annotations(config.root, annotationStateDirectory, input.action, {
|
|
540
|
+
...input,
|
|
541
|
+
...(input.action === 'reply' && !input.author ? { author: 'user' } : {}),
|
|
542
|
+
});
|
|
543
|
+
annotationStamp = await readAnnotationStamp();
|
|
544
|
+
emit({ annotations: true });
|
|
545
|
+
return json(response, 200, result);
|
|
546
|
+
}
|
|
501
547
|
if(url.pathname==='/api/cache-stats'&&request.method==='GET')return json(response,200,{process:process.memoryUsage(),builds:buildStore?.stats(),viewer:viewerCache?.stats()});
|
|
502
548
|
if (url.pathname === '/api/health' && request.method === 'GET') return json(response, 200, { id: instanceId, capabilities: { keyAuth: 1 } });
|
|
503
549
|
if (request.method === "POST") {
|
|
@@ -566,6 +612,7 @@ export async function startServer({
|
|
|
566
612
|
return;
|
|
567
613
|
}
|
|
568
614
|
if (url.pathname === "/events") {
|
|
615
|
+
annotationStamp ??= await readAnnotationStamp();
|
|
569
616
|
response.writeHead(200, {
|
|
570
617
|
"Content-Type": "text/event-stream",
|
|
571
618
|
"Cache-Control": "no-store",
|
|
@@ -594,7 +641,7 @@ export async function startServer({
|
|
|
594
641
|
type = "application/json";
|
|
595
642
|
} else if (url.pathname.startsWith("/asset/")) {
|
|
596
643
|
const name = decodeURIComponent(url.pathname.slice(7));
|
|
597
|
-
if (!files.has(name)) {
|
|
644
|
+
if (!files.has(name) || isFeatureInternal(name, sources)) {
|
|
598
645
|
response.writeHead(404);
|
|
599
646
|
response.end("Unknown SVG.");
|
|
600
647
|
return;
|
|
@@ -633,6 +680,7 @@ export async function startServer({
|
|
|
633
680
|
const close = () => closePromise ??= (async () => {
|
|
634
681
|
closing = true;
|
|
635
682
|
clearTimeout(refreshTimer);
|
|
683
|
+
clearInterval(annotationTimer);
|
|
636
684
|
let primary;
|
|
637
685
|
for (const step of [
|
|
638
686
|
async () => { watcher?.close(); },
|
|
@@ -673,7 +721,7 @@ export async function startServer({
|
|
|
673
721
|
return { id: instanceId, directory: root, stateDirectory:path.resolve(stateDirectory), url: `http://127.0.0.1:${server.address().port}/`, port: server.address().port, close,
|
|
674
722
|
cacheStats:()=>({builds:buildStore?.stats(),viewer:viewerCache?.stats()}),
|
|
675
723
|
stats: () => {
|
|
676
|
-
const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name));
|
|
724
|
+
const entries = [...files.keys()].filter(name => /\.(tsx|mmd)$/.test(name) && !isFeatureInternal(name, sources));
|
|
677
725
|
return { sourceCount: entries.length, frameCount: entries.every(name => frameCounts.has(name)) ? entries.reduce((n, name) => n + frameCounts.get(name), 0) : null };
|
|
678
726
|
} };
|
|
679
727
|
}
|
package/src/service.mjs
CHANGED
|
@@ -68,7 +68,7 @@ async function migrateService(values, { home, run, nodePath, cliPath, uid, outpu
|
|
|
68
68
|
const argument = flag => args.includes(flag) ? args[args.indexOf(flag) + 1] : undefined;
|
|
69
69
|
const base = process.env.XDG_STATE_HOME || path.join(home, '.local/state');
|
|
70
70
|
const oldState = path.resolve(argument('--state-dir') ?? path.join(base, 'svg-design-gallery'));
|
|
71
|
-
const newState = path.resolve(values['state-dir'] ?? path.join(
|
|
71
|
+
const newState = path.resolve(values['state-dir'] ?? path.join(home, '.agent-design-gallery'));
|
|
72
72
|
const data = { complete: false, from: {label:oldLabel,stateDirectory:oldState,plist:oldAgent},
|
|
73
73
|
to: {label:SERVICE_LABEL,stateDirectory:newState,plist:newAgent}, changes: [], keyPrefixUpdated:false, references:[], service:null };
|
|
74
74
|
const warnings = [];
|
|
@@ -2,7 +2,7 @@ import { parse } from 'pele';
|
|
|
2
2
|
import { buildArch, inspectArch, vocabulary } from './arch.mjs';
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { readBase } from './arch-git.mjs';
|
|
5
|
-
import { escape } from './
|
|
5
|
+
import { escape } from './html.mjs';
|
|
6
6
|
|
|
7
7
|
export const diffClasses=['added','changed','removed'];
|
|
8
8
|
const words=value=>(Array.isArray(value)?value.join(' '):value??'').split(/[\s,]+/).filter(Boolean);
|
|
@@ -1,14 +1,53 @@
|
|
|
1
|
+
import { isFeatureEntry, sourceFeature } from './project.mjs';
|
|
2
|
+
|
|
1
3
|
// Production sources are ordered from lower to higher layers. Studies are explorations.
|
|
2
|
-
export function importDirectionViolations(graph, sources) {
|
|
3
|
-
const
|
|
4
|
+
export function importDirectionViolations(graph, sources, { strictLayers = false } = {}) {
|
|
5
|
+
const production=sources.filter(name=>name!=='studies'), rank=new Map(production.map((name,index)=>[name,index])), moduleLayer=production.length >= 3 ? production[1] : null, topLayer=production.at(-1);
|
|
4
6
|
const violations=[];
|
|
5
7
|
for (const source of Object.keys(graph).sort()) {
|
|
6
8
|
const from=source.split('/')[0];
|
|
7
9
|
if (!rank.has(from)) continue;
|
|
8
10
|
for (const target of [...new Set(graph[source].uses)].sort()) {
|
|
9
11
|
const to=target.split('/')[0];
|
|
10
|
-
if (rank.has(to)
|
|
12
|
+
if (!rank.has(to)) continue;
|
|
13
|
+
const sameLayer=rank.get(to)===rank.get(from), crossFeature=sameLayer && rank.get(from)===rank.get(moduleLayer) && sourceFeature(source,sources)!==sourceFeature(target,sources);
|
|
14
|
+
const surfaceInternal=from===topLayer && to===moduleLayer && !isFeatureEntry(target,sources);
|
|
15
|
+
const sameLayerViolation=sameLayer && rank.get(from)>0 && (rank.get(from)!==rank.get(moduleLayer) || crossFeature);
|
|
16
|
+
if (rank.get(to)>rank.get(from) || (strictLayers && (sameLayerViolation || surfaceInternal))) {
|
|
17
|
+
violations.push({source,target,from,to,sameLayer,featureBoundary:crossFeature||surfaceInternal});
|
|
18
|
+
}
|
|
11
19
|
}
|
|
12
20
|
}
|
|
13
21
|
return violations;
|
|
14
22
|
}
|
|
23
|
+
|
|
24
|
+
// A component is a library asset only when distinct higher-layer sources reach it.
|
|
25
|
+
// Walk the resolved source graph backwards so component-to-component indirection
|
|
26
|
+
// and feature/surface transitive use are counted without treating its own frames
|
|
27
|
+
// as consumers.
|
|
28
|
+
export function singleConsumerComponents(graph, sources, partsBySource) {
|
|
29
|
+
const production = sources.filter(name => name !== 'studies');
|
|
30
|
+
const rank = new Map(production.map((name, index) => [name, index]));
|
|
31
|
+
const reverse = new Map();
|
|
32
|
+
for (const [source, row] of Object.entries(graph)) for (const target of new Set(row.uses ?? [])) {
|
|
33
|
+
const list = reverse.get(target) ?? []; list.push(source); reverse.set(target, list);
|
|
34
|
+
}
|
|
35
|
+
const warnings = [];
|
|
36
|
+
for (const [source, parts] of Object.entries(partsBySource)) {
|
|
37
|
+
const layer = source.split('/')[0];
|
|
38
|
+
if (layer !== production[0] || !rank.has(layer)) continue;
|
|
39
|
+
for (const part of parts) {
|
|
40
|
+
const consumers = new Set();
|
|
41
|
+
const queue = [source], seen = new Set([source]);
|
|
42
|
+
while (queue.length) for (const importer of reverse.get(queue.shift()) ?? []) {
|
|
43
|
+
if (seen.has(importer)) continue;
|
|
44
|
+
seen.add(importer);
|
|
45
|
+
const importerLayer = importer.split('/')[0];
|
|
46
|
+
if (importerLayer === layer) queue.push(importer);
|
|
47
|
+
else if (rank.has(importerLayer) && rank.get(importerLayer) > rank.get(layer)) consumers.add(sourceFeature(importer, sources));
|
|
48
|
+
}
|
|
49
|
+
if (consumers.size < 2) warnings.push({ code: 'SINGLE_CONSUMER_COMPONENT', source, part, consumers: [...consumers].sort(), message: `${source}#${part} is reached by ${consumers.size} distinct higher-layer source${consumers.size === 1 ? '' : 's'}; move it back to its feature or add another feature consumer` });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return warnings;
|
|
53
|
+
}
|
|
@@ -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', './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)),
|
|
116
|
+
...['../../package.json', './build.mjs', './frame-document.mjs', './html.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)))));
|
|
@@ -25,7 +25,7 @@ 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, parts: built.parts ?? [], css: built.css,
|
|
28
|
+
if (!shuttingDown) parentPort.postMessage({ id, result: { ...(built.observationDynamic?{observationDynamic:true}:{}), frames, parts: built.parts ?? [], css: built.css,
|
|
29
29
|
...(built.tokenCss !== undefined ? { tokenCss: built.tokenCss, cssWithoutTokens: built.cssWithoutTokens,
|
|
30
30
|
cssBeforeTokens: built.cssBeforeTokens, cssAfterTokens: built.cssAfterTokens } : {}),
|
|
31
31
|
...(config.overlay?{baseBlob:built.baseBlob}:{}), imports: built.imports, dependencies, dependencyHashes }, heapBytes: process.memoryUsage().heapUsed });
|
package/src/toolkit/build.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { statSync, readFileSync, realpathSync, mkdirSync, writeFileSync } from '
|
|
|
4
4
|
import { createRequire } from 'node:module';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
-
import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories } from './project.mjs';
|
|
7
|
+
import { loadTokens, refreshTypes, rejectLegacy, relative, isSourcePath, sourceDirectories, isFeatureInternal } from './project.mjs';
|
|
8
8
|
import { themeCss, parseTokens } from './tokens.mjs';
|
|
9
9
|
import { componentOwner } from './runtime.mjs';
|
|
10
10
|
import { CliError, classifyError } from '../cli-output.mjs';
|
|
@@ -67,6 +67,7 @@ export function validateFrame(frame) {
|
|
|
67
67
|
try { if (typeof frame.locale !== 'string' || !frame.locale.trim()) throw Error(); frame.locale = Intl.getCanonicalLocales(frame.locale)[0]; }
|
|
68
68
|
catch { throw Error('Invalid Frame locale; use a BCP 47 language tag.'); }
|
|
69
69
|
}
|
|
70
|
+
if (frame.proposed !== undefined && (typeof frame.proposed !== 'string' || !frame.proposed.trim())) throw Error('Invalid Frame proposed; use a nonempty review scope string');
|
|
70
71
|
const parent = frame.parent;
|
|
71
72
|
if (parent !== undefined) {
|
|
72
73
|
if (!parent || typeof parent !== 'object' || Array.isArray(parent) ||
|
|
@@ -105,6 +106,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
105
106
|
const result = await build({ entryPoints: [file], bundle: true, write: false, format: 'esm', platform: 'node', jsx: 'automatic', jsxImportSource: 'adg', jsxDev: true, metafile: true, logLevel: 'silent', plugins: [{ name: 'adg-sources', setup(api) {
|
|
106
107
|
api.onResolve({ filter: /.*/ }, args => {
|
|
107
108
|
if (args.path === 'adg:self') return {path:args.importer};
|
|
109
|
+
if (args.path.startsWith('adg:art-bytes:')) return {path:args.path.slice('adg:art-bytes:'.length),namespace:'art-bytes'};
|
|
108
110
|
if (['adg','adg/jsx-runtime','adg/jsx-dev-runtime'].includes(args.path)) return { path: pathToFileURL(runtime).href, external: true };
|
|
109
111
|
if (args.kind !== 'entry-point' && !args.path.startsWith('.')) return { errors: [{ text: `Bare import ${args.path} is unavailable; import adg or a relative file inside design/` }] };
|
|
110
112
|
const url = args.path.endsWith('?url');
|
|
@@ -121,7 +123,12 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
121
123
|
if (url && !resolved.startsWith(path.join(base,'art')+path.sep)) return {errors:[{text:'?url imports must be under design/art/'}]};
|
|
122
124
|
return { path: resolved, ...(url ? {namespace:'art-url'} : {}) };
|
|
123
125
|
});
|
|
124
|
-
api.onLoad({filter:/.*/,namespace:'art-
|
|
126
|
+
api.onLoad({filter:/.*/,namespace:'art-bytes'}, args => ({contents:read(args.path),loader:'dataurl'}));
|
|
127
|
+
const artModule = file => {
|
|
128
|
+
const source=path.relative(base,file).split(path.sep).join('/');
|
|
129
|
+
return {contents:`import data from ${JSON.stringify('adg:art-bytes:'+file)};import {registerArtwork} from 'adg';export default registerArtwork(data,${JSON.stringify(source)});`,loader:'js'};
|
|
130
|
+
};
|
|
131
|
+
api.onLoad({filter:/.*/,namespace:'art-url'}, args => artModule(args.path));
|
|
125
132
|
api.onLoad({filter:/\.tsx$/}, async args => {
|
|
126
133
|
const sourcePath = path.relative(base, args.path).split(path.sep).join('/');
|
|
127
134
|
if (!isSourcePath(sourcePath, sources)) return snapshot ? {contents:read(args.path,'utf8'),loader:'tsx'} : undefined;
|
|
@@ -129,12 +136,12 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
129
136
|
return registeredSource(args.path, sourcePath, original);
|
|
130
137
|
});
|
|
131
138
|
if (snapshot) api.onLoad({filter:/\.(?:[cm]?js|jsx|ts|json)$/}, args => ({contents:read(args.path,'utf8'),loader:args.path.endsWith('.ts')?'ts':args.path.endsWith('.jsx')?'jsx':args.path.endsWith('.json')?'json':'js'}));
|
|
132
|
-
api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => (
|
|
139
|
+
api.onLoad({ filter: /\.(png|jpe?g|webp)$/i }, args => artModule(args.path));
|
|
133
140
|
api.onLoad({ filter: /\.svg$/i }, args => {
|
|
134
141
|
const source = read(args.path,'utf8');
|
|
135
142
|
const forbidden = /<(?:style|script)\b|\s(?:on[\w-]+|className)\s*=/i.exec(source);
|
|
136
143
|
if (forbidden) { const before=source.slice(0,forbidden.index); return {errors:[{text:'Forbidden SVG markup; remove styles, scripts and event attributes',location:{file:args.path,line:before.split('\n').length,column:before.length-before.lastIndexOf('\n')-1}}]}; }
|
|
137
|
-
return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props);`, loader:'js' };
|
|
144
|
+
return { contents: `import { artwork } from 'adg'; export default props => artwork(${JSON.stringify(source)}, props, ${JSON.stringify(path.relative(base,args.path).split(path.sep).join('/'))});`, loader:'js' };
|
|
138
145
|
});
|
|
139
146
|
} }] }).catch(error => {
|
|
140
147
|
const typed = error.errors?.find(item => item.detail instanceof CliError)?.detail;
|
|
@@ -142,7 +149,21 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
142
149
|
// Retain esbuild's human diagnostics and details while carrying the owning boundary's code.
|
|
143
150
|
throw Object.assign(new CliError(typed.code, error.message, { cause: error, context: typed.context }), { errors: error.errors });
|
|
144
151
|
});
|
|
145
|
-
const
|
|
152
|
+
const executable=result.outputFiles[0].text;
|
|
153
|
+
// Conservative cache eligibility hint from this entry's bundled helpers; quoted copy is not code.
|
|
154
|
+
const observationDynamic=/\b(?:(?:Date\s*\.\s*now|Math\s*\.\s*random)\s*\(|(?:new\s+)?Date\s*\()/.test(executable.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/g,'""'));
|
|
155
|
+
const mod = await import(`data:text/javascript;base64,${Buffer.from(executable).toString('base64')}#${++evaluation}`);
|
|
156
|
+
const sourceName = path.relative(base, file).split(path.sep).join('/');
|
|
157
|
+
const parts = Object.keys(mod).filter(name => {
|
|
158
|
+
const owner = typeof mod[name] === 'function' && componentOwner(mod[name]);
|
|
159
|
+
return owner && owner.source === sourceName && owner.export === name;
|
|
160
|
+
}).sort();
|
|
161
|
+
const internal = isFeatureInternal(sourceName, sources);
|
|
162
|
+
if (internal) {
|
|
163
|
+
const original = read(file, 'utf8');
|
|
164
|
+
if (/export\s+default[\s\S]*<Frame\b/.test(original)) throw Error(`${relative(config,file)}: feature-internal source must not export Frame defaults; move frames to index.tsx`);
|
|
165
|
+
return { frames: [], parts, dependencies: [...dependencies], imports: [...imports].sort(), css: '', tokenCss: '', cssWithoutTokens: '', cssBeforeTokens: '', cssAfterTokens: '' };
|
|
166
|
+
}
|
|
146
167
|
if (typeof mod.default !== 'function') throw Error(`${relative(config,file)}: export a default function returning Frames`);
|
|
147
168
|
const value = mod.default(), frames = (Array.isArray(value) ? value.flat(Infinity) : [value]).filter(v => v != null && v !== false);
|
|
148
169
|
if (!frames.length) throw Error(`${relative(config,file)}: default export must return at least one Frame`);
|
|
@@ -161,12 +182,7 @@ async function buildDesignSource(config, file, { write = true, allowLegacy = tru
|
|
|
161
182
|
frame.document = theme => frameDocument(frame, theme, css);
|
|
162
183
|
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')); }
|
|
163
184
|
}
|
|
164
|
-
|
|
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,
|
|
185
|
+
return { ...(observationDynamic?{observationDynamic:true}:{}), frames, parts, dependencies: [...dependencies], imports: [...imports].sort(), css,
|
|
170
186
|
tokenCss: tokenSource, cssWithoutTokens: `${utilities}\n${defaults}`,
|
|
171
187
|
cssBeforeTokens: `${utilities}\n`, cssAfterTokens: `\n${defaults}` };
|
|
172
188
|
}
|
package/src/toolkit/commands.mjs
CHANGED
|
@@ -2,14 +2,31 @@ import { mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { availableParallelism } from 'node:os';
|
|
4
4
|
import { buildSource } from './build.mjs';
|
|
5
|
-
import { selectSources, relative, loadTokens, sourceDirectories, archFiles } from './project.mjs';
|
|
6
|
-
import { importDirectionViolations } from './asset-rules.mjs';
|
|
5
|
+
import { selectSources, relative, loadTokens, sourceDirectories, archFiles, featureFolderProblems } from './project.mjs';
|
|
6
|
+
import { importDirectionViolations, singleConsumerComponents } 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
10
|
import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
|
|
11
11
|
import { withImpacted } from './impact-selection.mjs';
|
|
12
|
-
import { mappingFacts } from './source-facts.mjs';
|
|
12
|
+
import { mappingFacts, frameOwners } from './source-facts.mjs';
|
|
13
|
+
|
|
14
|
+
function frameStructure(frame) {
|
|
15
|
+
return frame.html
|
|
16
|
+
.replace(/>[^<]*</g, '><')
|
|
17
|
+
.replace(/\s(?:aria-label|aria-description|title|placeholder|value)="[^"]*"/g, '')
|
|
18
|
+
.replace(/\sdata-adg-keys="[^"]*"/g, '')
|
|
19
|
+
.replace(/\s+/g, ' ')
|
|
20
|
+
.trim();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function frameOwnsPart(frame, source, part) {
|
|
24
|
+
return (frame.owners ?? frameOwners(frame.html)).some(owner => owner.source === source && owner.export === part);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function proposedFrame(source, frame) {
|
|
28
|
+
return frame.proposed ? { source, frame: frame.name, scope: frame.proposed } : null;
|
|
29
|
+
}
|
|
13
30
|
export function inspectFrame(tokenNames) {
|
|
14
31
|
const frame = document.querySelector('[data-adg-frame]'), box = frame.getBoundingClientRect(), problems = new Map();
|
|
15
32
|
const add = (code, message) => problems.set(message, {code, message, line:null, column:null});
|
|
@@ -187,7 +204,7 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
187
204
|
check(config, args, options, log, error, { launchBrowser, session: selected }));
|
|
188
205
|
const write = !options['read-only'];
|
|
189
206
|
/** @type {import('./results.mjs').CheckData} */
|
|
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: [] };
|
|
207
|
+
const data = { project: config.root, readOnly: !write, complete: false, impact: session?.selection ?? null, sources: [], summary: { sources: 0, frames: 0, evaluations: 0, problems: 0 }, findings: [], proposed: [] };
|
|
191
208
|
const warnings = [], humanProblems = new Set(), findingKeys = new Set(), graph = {};
|
|
192
209
|
let browser, primary;
|
|
193
210
|
const add = (problem, file, frame = null, theme = null, source = relative(config, file)) => {
|
|
@@ -207,10 +224,11 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
207
224
|
const files = session ? session.sources.map(source => path.join(config.root, source)).filter(existsSync) : selectSources(config, args, { write });
|
|
208
225
|
data.sources = files.map(file => relative(config, file));
|
|
209
226
|
data.summary.sources = files.length;
|
|
227
|
+
if (config.check?.strictLayers === true) for (const problem of featureFolderProblems(config.design, sourceDirectories(config))) add({ code: problem.code, message: problem.message, line: null, column: null }, problem.file);
|
|
210
228
|
const tokens = files.length ? loadTokens(config) : null;
|
|
211
229
|
const arch = files.some(file => file.endsWith('.mmd')) ? await import('./arch.mjs') : null;
|
|
212
230
|
let page;
|
|
213
|
-
const builtSources = new Map(), failedSources = new Map();
|
|
231
|
+
const builtSources = new Map(), allBuilt = new Map(), failedSources = new Map();
|
|
214
232
|
for (const file of files) {
|
|
215
233
|
const architecture = file.endsWith('.mmd');
|
|
216
234
|
if (architecture) {
|
|
@@ -238,6 +256,8 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
238
256
|
continue;
|
|
239
257
|
}
|
|
240
258
|
data.summary.frames += built.frames.length;
|
|
259
|
+
allBuilt.set(relative(config, file), built);
|
|
260
|
+
for (const frame of built.frames) if (frame.proposed) data.proposed.push(proposedFrame(relative(config, file), frame));
|
|
241
261
|
if (mapping.present && !architecture) builtSources.set(relative(config, file), mappingFacts(built));
|
|
242
262
|
graph[path.relative(config.design, file).split(path.sep).join('/')] = { uses: built.imports };
|
|
243
263
|
for (const frame of built.frames) for (const theme of session?.themes ?? ['light', 'dark']) {
|
|
@@ -255,9 +275,10 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
255
275
|
}
|
|
256
276
|
}
|
|
257
277
|
}
|
|
278
|
+
let validatedMap = null;
|
|
258
279
|
if (mapping.present) {
|
|
259
280
|
const { listSources } = await import('./project.mjs');
|
|
260
|
-
await validateImplementationMap(config, mapping, {
|
|
281
|
+
validatedMap = await validateImplementationMap(config, mapping, {
|
|
261
282
|
sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)),
|
|
262
283
|
selected: args.length ? data.sources : undefined,
|
|
263
284
|
getBuild: source => {
|
|
@@ -270,11 +291,43 @@ export async function check(config, args = [], options = {}, log = console.log,
|
|
|
270
291
|
}
|
|
271
292
|
await cleanup(() => browser?.close(), primary);
|
|
272
293
|
browser = null;
|
|
273
|
-
if (config.check?.importDirection !== false) for (const { source, target, from, to } of importDirectionViolations(graph, sourceDirectories(config))) {
|
|
274
|
-
add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); import from the same or a lower layer in sources`, line: null, column: null }, path.join(config.design, source));
|
|
294
|
+
if (config.check?.importDirection !== false) for (const { source, target, from, to, sameLayer, featureBoundary } of importDirectionViolations(graph, sourceDirectories(config), { strictLayers: config.check?.strictLayers === true })) {
|
|
295
|
+
add({ code: 'IMPORT_DIRECTION', message: `import ${target} violates import direction (${from} -> ${to}); ${featureBoundary ? (sameLayer ? 'module files may import only within their own feature folder' : 'surfaces must import a module feature through its index.tsx') : sameLayer ? 'same-layer imports are allowed only in the lowest layer' : 'import from the same or a lower layer in sources'}`, line: null, column: null }, path.join(config.design, source));
|
|
296
|
+
}
|
|
297
|
+
if (config.check?.lifecycle === true && mapping.present && validatedMap) {
|
|
298
|
+
const production = sourceDirectories(config).filter(name => name !== 'studies');
|
|
299
|
+
const top = production.at(-1);
|
|
300
|
+
const active = validatedMap.bindings.filter(binding => binding.active);
|
|
301
|
+
const hasBinding = (source, part = null) => active.some(binding => binding.design.source === source && (part === null ? binding.design.part === undefined : binding.design.part === part));
|
|
302
|
+
for (const [source, built] of allBuilt) {
|
|
303
|
+
const designSource = path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/');
|
|
304
|
+
const layer = designSource.split('/')[0];
|
|
305
|
+
if (!production.includes(layer)) continue;
|
|
306
|
+
for (const part of built.parts ?? []) {
|
|
307
|
+
const frames = built.frames.filter(frame => frameOwnsPart(frame, designSource, part));
|
|
308
|
+
if (layer !== top && !hasBinding(source, part) && !frames.some(frame => frame.proposed)) add({ code: 'OWNER_PART_UNBOUND', message: `Exported part ${part} has no implementation binding or proposed frame; add a binding or mark a review frame with proposed`, line: null, column: null }, path.join(config.root, source));
|
|
309
|
+
}
|
|
310
|
+
if (layer === top && !hasBinding(source)) add({ code: 'OWNER_SURFACE_UNBOUND', message: `Surface source has no whole-source implementation binding; add a binding without part`, line: null, column: null }, path.join(config.root, source));
|
|
311
|
+
if (layer === top) for (const frame of built.frames) if (!frame.proposed && (!frame.fixture || !frame.capture)) add({ code: 'OWNER_SURFACE_FRAME_UNCAPTURED', message: `Surface frame ${frame.name} needs fixture and capture or a proposed review scope; add both metadata fields or proposed`, line: null, column: null }, path.join(config.root, source), frame.name);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (config.check?.singleConsumer !== false) {
|
|
315
|
+
for (const warning of singleConsumerComponents(graph, sourceDirectories(config), Object.fromEntries([...allBuilt].map(([source, built]) => [path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/'), built.parts ?? []])))) {
|
|
316
|
+
warnings.push({ code: warning.code, message: warning.message, next: [] });
|
|
317
|
+
if (!options.json) log(`WARNING ${warning.message}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (config.check?.redundantFrames !== false) {
|
|
321
|
+
for (const [source, built] of allBuilt) {
|
|
322
|
+
const byStructure = new Map();
|
|
323
|
+
for (const frame of built.frames) { const key = frameStructure(frame); const list = byStructure.get(key) ?? []; list.push(frame.name); byStructure.set(key, list); }
|
|
324
|
+
for (const frames of byStructure.values()) if (frames.length > 1) warnings.push({ code: 'REDUNDANT_FRAME', message: `${source}: frames ${frames.join(', ')} have identical structure apart from text, locale and geometry.`, next: [] });
|
|
325
|
+
}
|
|
275
326
|
}
|
|
276
327
|
for (const problem of humanProblems) error(problem);
|
|
277
328
|
const message = `Design check ${humanProblems.size ? 'failed' : 'passed'} for ${files.length} sources${humanProblems.size ? `: ${humanProblems.size} problems` : ''}.`;
|
|
329
|
+
for (const item of data.proposed) log(`PROPOSED ${item.source}#${item.frame} (${item.scope})`);
|
|
330
|
+
for (const warning of warnings.filter(warning => warning.code === 'REDUNDANT_FRAME')) log(`WARNING ${warning.message}`);
|
|
278
331
|
log(message);
|
|
279
332
|
if (!files.length) emptySelection(warnings);
|
|
280
333
|
if (primary) { primary.humanReported = true; throw primary; }
|
package/src/toolkit/config.mjs
CHANGED
|
@@ -126,6 +126,7 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
|
|
|
126
126
|
for (const key of ['design', 'output', 'arch']) if (config[key] !== undefined && !(key === 'arch' && config[key] === false) && (typeof config[key] !== 'string' || !config[key].trim())) throw new CliError('CONFIG_INVALID', `Set ${key} to a directory path in adg.config.mjs`);
|
|
127
127
|
if (config.check !== undefined && (!config.check || typeof config.check!=='object' || Array.isArray(config.check))) throw new CliError('CONFIG_INVALID', 'Set check to an object in adg.config.mjs');
|
|
128
128
|
if (config.check?.importDirection !== undefined && typeof config.check.importDirection!=='boolean') throw new CliError('CONFIG_INVALID', 'Set check.importDirection to true or false in adg.config.mjs');
|
|
129
|
+
for (const key of ['strictLayers', 'lifecycle', 'singleConsumer']) if (config.check?.[key] !== undefined && typeof config.check[key] !== 'boolean') throw new CliError('CONFIG_INVALID', `Set check.${key} to true or false in adg.config.mjs`);
|
|
129
130
|
const compare = { port: 5188, viewport: '1280x800', ...config.compare };
|
|
130
131
|
viewport(compare.viewport);
|
|
131
132
|
if (!Number.isInteger(compare.port) || compare.port < 1 || compare.port > 65535) throw new CliError('CONFIG_INVALID', 'Set compare.port to an integer from 1 to 65535 in adg.config.mjs');
|
|
@@ -135,5 +136,5 @@ export async function loadConfig(cwd = process.cwd(), { checkVersion = true, dis
|
|
|
135
136
|
if (typeof config.arch === 'string' && (path.isAbsolute(config.arch) || path.relative(root,path.resolve(root,config.arch)).startsWith('..'))) throw new CliError('CONFIG_INVALID', 'Set arch to a project-root-relative directory in adg.config.mjs');
|
|
136
137
|
const arch = config.arch === false ? false : path.resolve(root,config.arch ?? 'arch');
|
|
137
138
|
const design=path.resolve(root,config.design??'design');
|
|
138
|
-
return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
|
|
139
|
+
return { root, name: config.name ?? path.basename(root), requires: config.requires ?? null, compatible, archDirectory: arch, arch: arch && (config.arch !== undefined || archFiles(arch).length) ? arch : false, sources: sourceDirectories({...config,design}), design, output: path.resolve(root, config.output ?? 'output/design'), check:{archMaxEdges:30,importDirection:true,strictLayers:false,lifecycle:false,singleConsumer:true,...config.check}, compare, diff: resolveDiffPolicy(config.diff) };
|
|
139
140
|
}
|
package/src/toolkit/diff.mjs
CHANGED
|
@@ -111,7 +111,10 @@ async function writePair(output, pair, thresholds) {
|
|
|
111
111
|
relation: pair.parent ? 'parent_crop' : 'revision', before: pair.parent?.ref ?? (pair.before ? ref : null), after: pair.after ? ref : null,
|
|
112
112
|
beforeSize, afterSize, parent: pair.parent ?? null, snapshots: pair.snapshots ?? null, pixels: pair.pixels,
|
|
113
113
|
verdict: reasons.length ? 'changed' : pair.parent ? 'structural' : 'identical', reasons,
|
|
114
|
-
note: { before: row.before?.note ?? null, after: row.after?.note ?? null },
|
|
114
|
+
note: { before: row.before?.note ?? null, after: row.after?.note ?? null },
|
|
115
|
+
proposed: row.after?.proposed ?? row.before?.proposed ?? null,
|
|
116
|
+
metadata: { before: row.before ? { locale: row.before.locale ?? null, proposed: row.before.proposed ?? null, fixture: row.before.fixture ?? null, capture: row.before.capture ?? null } : null,
|
|
117
|
+
after: row.after ? { locale: row.after.locale ?? null, proposed: row.after.proposed ?? null, fixture: row.after.fixture ?? null, capture: row.after.capture ?? null } : null }, paths,
|
|
115
118
|
};
|
|
116
119
|
await Promise.all([
|
|
117
120
|
pair.before && writeFile(paths.before, pair.before.png),
|
package/src/toolkit/document.mjs
CHANGED
|
@@ -20,10 +20,10 @@ export function implementationTexts(root, clip) {
|
|
|
20
20
|
}
|
|
21
21
|
return box.left >= left - 0.5 && box.right <= right + 0.5 && (box.top + box.bottom) / 2 >= top && (box.top + box.bottom) / 2 <= bottom;
|
|
22
22
|
};
|
|
23
|
-
const push = (text, box, owner, style = getComputedStyle(owner)) => {
|
|
23
|
+
const push = (text, box, owner, style = getComputedStyle(owner), leadingSpace = false) => {
|
|
24
24
|
if (!inside(box, owner)) return;
|
|
25
25
|
texts.push({ text, x: box.left - origin.left, y: box.top - origin.top, width: box.right - box.left, height: box.bottom - box.top,
|
|
26
|
-
space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
|
|
26
|
+
space: (measure.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, measure.measureText(' ').width), leadingSpace, anchor: style.textAlign === 'center' ? 'middle' : style.textAlign === 'right' ? 'end' : 'start', fill: style.color, size: style.fontSize, weight: style.fontWeight, family: style.fontFamily });
|
|
27
27
|
};
|
|
28
28
|
const linesFor = node => {
|
|
29
29
|
const result=[];
|
|
@@ -34,7 +34,7 @@ export function implementationTexts(root, clip) {
|
|
|
34
34
|
if (!rect) continue;
|
|
35
35
|
let line = lines.at(-1);
|
|
36
36
|
if (!line || Math.abs(line.top - rect.top) >= rect.height / 2) {
|
|
37
|
-
line = { text: '', top: rect.top, bottom: rect.bottom, chars: [] }; lines.push(line);
|
|
37
|
+
line = { text: '', top: rect.top, bottom: rect.bottom, chars: [], leadingSpace: /^\s/.test(node.data) }; lines.push(line);
|
|
38
38
|
}
|
|
39
39
|
line.text += node.data[index]; line.chars.push({ index, rect }); line.bottom = Math.max(line.bottom, rect.bottom);
|
|
40
40
|
}
|
|
@@ -43,7 +43,7 @@ export function implementationTexts(root, clip) {
|
|
|
43
43
|
if (!content) continue;
|
|
44
44
|
const chars = line.chars.filter(({ index }) => !/\s/.test(node.data[index]));
|
|
45
45
|
const box = { left: Math.min(...chars.map(c => c.rect.left)), right: Math.max(...chars.map(c => c.rect.right)), top: line.top, bottom: line.bottom };
|
|
46
|
-
result.push({content,box});
|
|
46
|
+
result.push({content,box,leadingSpace:line.leadingSpace});
|
|
47
47
|
}
|
|
48
48
|
return result;
|
|
49
49
|
};
|
|
@@ -51,7 +51,7 @@ export function implementationTexts(root, clip) {
|
|
|
51
51
|
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
52
52
|
const owner=node.parentElement;
|
|
53
53
|
if (!node.textContent.trim() || !owner || owner.closest('input,textarea') || !visible(owner)) continue;
|
|
54
|
-
for (const {content,box} of linesFor(node)) push(content,box,owner);
|
|
54
|
+
for (const {content,box,leadingSpace} of linesFor(node)) push(content,box,owner,undefined,leadingSpace);
|
|
55
55
|
}
|
|
56
56
|
const canvas = document.createElement('canvas').getContext('2d');
|
|
57
57
|
const fields='input:not([type]), input[type=text], input[type=search], input[type=email], input[type=url], input[type=tel], input[type=number], textarea';
|
|
@@ -77,7 +77,7 @@ export function implementationTexts(root, clip) {
|
|
|
77
77
|
}
|
|
78
78
|
const merged = [];
|
|
79
79
|
for (const item of texts.sort((a,b) => a.y - b.y || a.x - b.x)) {
|
|
80
|
-
const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width
|
|
80
|
+
const previous = merged.findLast(p => Math.abs(p.y + p.height/2 - item.y - item.height/2) < 1 && item.x >= p.x + p.width - .5 && item.x - p.x - p.width <= Math.max(p.space, item.space, item.leadingSpace ? 6 : 0) + .1);
|
|
81
81
|
if (previous) { const gap = item.x - previous.x - previous.width; previous.text += (gap > .5 ? ' ' : '') + item.text; previous.width = item.x + item.width - previous.x; }
|
|
82
82
|
else merged.push({...item});
|
|
83
83
|
}
|