@ankhorage/rules-design 0.7.0 → 0.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 8ed1957: Expose canonical website recognition and token inspection through the Ankh CLI provider.
8
+
9
+ ## 0.8.0
10
+
11
+ ### Minor Changes
12
+
13
+ - cd12383: Add the deterministic `recognizeWebsiteDocument` public recognition assembly API.
14
+
3
15
  ## 0.7.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  # @ankhorage/rules-design
5
5
 
6
- ![license: MIT](././paradox/badges/license.svg) ![npm: v0.7.0](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: checked](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
6
+ ![license: MIT](././paradox/badges/license.svg) ![npm: v0.9.0](././paradox/badges/npm.svg) ![runtime: bun](././paradox/badges/runtime.svg) ![typescript: strict](././paradox/badges/typescript.svg) ![eslint: checked](././paradox/badges/eslint.svg) ![prettier: checked](././paradox/badges/prettier.svg) ![build: checked](././paradox/badges/build.svg) ![tests: checked](././paradox/badges/tests.svg) ![paradox: canonical](././paradox/badges/docs.svg)
7
7
 
8
8
  Declarative catalog for reusable design rules.
9
9
 
@@ -0,0 +1,22 @@
1
+ /*** Publish the executable Rules Design capabilities used by Ankh provider discovery. */
2
+ export declare const CAPABILITIES: readonly [{
3
+ readonly id: "rules-design.recognize";
4
+ readonly owner: "@ankhorage/rules-design";
5
+ readonly access: readonly ["invoke"];
6
+ readonly binding: {
7
+ readonly kind: "action";
8
+ readonly bindableAs: readonly ["target"];
9
+ };
10
+ readonly label: "Recognize website design";
11
+ readonly description: "Assemble canonical website recognition from an observation document.";
12
+ }, {
13
+ readonly id: "rules-design.inspect";
14
+ readonly owner: "@ankhorage/rules-design";
15
+ readonly access: readonly ["invoke"];
16
+ readonly binding: {
17
+ readonly kind: "action";
18
+ readonly bindableAs: readonly ["target"];
19
+ };
20
+ readonly label: "Inspect website recognition";
21
+ readonly description: "Read an existing canonical website recognition document.";
22
+ }];
@@ -0,0 +1,19 @@
1
+ /*** Publish the executable Rules Design capabilities used by Ankh provider discovery. */
2
+ export const CAPABILITIES = [
3
+ {
4
+ id: 'rules-design.recognize',
5
+ owner: '@ankhorage/rules-design',
6
+ access: ['invoke'],
7
+ binding: { kind: 'action', bindableAs: ['target'] },
8
+ label: 'Recognize website design',
9
+ description: 'Assemble canonical website recognition from an observation document.',
10
+ },
11
+ {
12
+ id: 'rules-design.inspect',
13
+ owner: '@ankhorage/rules-design',
14
+ access: ['invoke'],
15
+ binding: { kind: 'action', bindableAs: ['target'] },
16
+ label: 'Inspect website recognition',
17
+ description: 'Read an existing canonical website recognition document.',
18
+ },
19
+ ];
@@ -0,0 +1,5 @@
1
+ import type { AnkhCommandContext } from '@ankhorage/ankh';
2
+ /*** Adapt `ankh rules-design inspect` to read canonical recognition data without recomputing it. */
3
+ export declare function inspect(argv: readonly string[], context: AnkhCommandContext): Promise<{
4
+ readonly exitCode: number;
5
+ }>;
@@ -0,0 +1,48 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { validateWebsiteRecognitionDocument } from '../../features/recognition/validateWebsiteRecognitionDocument.js';
4
+ /*** Adapt `ankh rules-design inspect` to read canonical recognition data without recomputing it. */
5
+ export async function inspect(argv, context) {
6
+ try {
7
+ const input = parseInspectInput(argv, context.cwd);
8
+ if ('help' in input) {
9
+ context.writeStdout(`${renderUsage()}\n`);
10
+ return { exitCode: 0 };
11
+ }
12
+ const designTokens = readDesignTokens(await readFile(input.inputPath, 'utf8'));
13
+ context.writeStdout(`${JSON.stringify(designTokens, null, 2)}\n`);
14
+ return { exitCode: 0 };
15
+ }
16
+ catch (error) {
17
+ context.writeStderr(`${errorMessage(error)}\n`);
18
+ return { exitCode: 1 };
19
+ }
20
+ }
21
+ /*** Parse the supported inspect section and reject secondary analysis modes. */
22
+ function parseInspectInput(argv, cwd) {
23
+ if (argv.length === 1 && isHelpToken(argv[0]))
24
+ return { help: true };
25
+ if (argv.length !== 3 || argv[1] !== '--section' || argv[2] !== 'tokens') {
26
+ throw new Error(renderUsage());
27
+ }
28
+ const [input] = argv;
29
+ return { inputPath: resolve(cwd, input) };
30
+ }
31
+ /*** Parse only the existing token collection required by the supported inspection section. */
32
+ function readDesignTokens(value) {
33
+ const document = JSON.parse(value);
34
+ validateWebsiteRecognitionDocument(document);
35
+ return document.designTokens;
36
+ }
37
+ /*** Identify the command help tokens supported by the Ankh delivery surface. */
38
+ function isHelpToken(value) {
39
+ return value === '--help' || value === '-h' || value === 'help';
40
+ }
41
+ /*** Render the canonical inspection invocation shape. */
42
+ function renderUsage() {
43
+ return 'Usage: ankh rules-design inspect <recognition.json> --section tokens';
44
+ }
45
+ /*** Convert an unknown boundary failure to a safe command diagnostic. */
46
+ function errorMessage(error) {
47
+ return error instanceof Error ? error.message : 'Rules Design inspection failed.';
48
+ }
@@ -0,0 +1,5 @@
1
+ import type { AnkhCommandContext } from '@ankhorage/ankh';
2
+ /*** Adapt `ankh rules-design recognize` to the public document-recognition API. */
3
+ export declare function recognize(argv: readonly string[], context: AnkhCommandContext): Promise<{
4
+ readonly exitCode: number;
5
+ }>;
@@ -0,0 +1,66 @@
1
+ import { constants } from 'node:fs';
2
+ import { access, readFile, writeFile } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import { validateWebsiteRecognitionDocument } from '../../features/recognition/validateWebsiteRecognitionDocument.js';
5
+ import { recognizeWebsiteDocument } from '../../index.js';
6
+ /*** Adapt `ankh rules-design recognize` to the public document-recognition API. */
7
+ export async function recognize(argv, context) {
8
+ try {
9
+ const input = parseRecognitionInput(argv, context.cwd);
10
+ if ('help' in input) {
11
+ context.writeStdout(`${renderUsage()}\n`);
12
+ return { exitCode: 0 };
13
+ }
14
+ await assertOutputDoesNotExistAsync(input.outputPath);
15
+ const observed = parseWebsiteObservationDocument(await readFile(input.inputPath, 'utf8'));
16
+ const recognition = recognizeWebsiteDocument(observed);
17
+ validateWebsiteRecognitionDocument(recognition);
18
+ await writeFile(input.outputPath, `${JSON.stringify(recognition, null, 2)}\n`, {
19
+ encoding: 'utf8',
20
+ flag: 'wx',
21
+ });
22
+ context.writeStdout(`Wrote website recognition document to ${input.outputPath}.\n`);
23
+ return { exitCode: 0 };
24
+ }
25
+ catch (error) {
26
+ context.writeStderr(`${errorMessage(error)}\n`);
27
+ return { exitCode: 1 };
28
+ }
29
+ }
30
+ /*** Parse one observation input and its required non-overwriting recognition output. */
31
+ function parseRecognitionInput(argv, cwd) {
32
+ if (argv.length === 1 && isHelpToken(argv[0]))
33
+ return { help: true };
34
+ if (argv.length !== 3 || argv[1] !== '--output') {
35
+ throw new Error(renderUsage());
36
+ }
37
+ const [input, , output] = argv;
38
+ return { inputPath: resolve(cwd, input), outputPath: resolve(cwd, output) };
39
+ }
40
+ /*** Parse JSON at the file boundary and apply the canonical recognition input validation. */
41
+ function parseWebsiteObservationDocument(value) {
42
+ const parsed = JSON.parse(value);
43
+ return parsed;
44
+ }
45
+ /*** Refuse an existing output target before calculating a recognition document. */
46
+ async function assertOutputDoesNotExistAsync(path) {
47
+ try {
48
+ await access(path, constants.F_OK);
49
+ }
50
+ catch {
51
+ return;
52
+ }
53
+ throw new Error(`Refusing to overwrite existing file: ${path}`);
54
+ }
55
+ /*** Identify the command help tokens supported by the Ankh delivery surface. */
56
+ function isHelpToken(value) {
57
+ return value === '--help' || value === '-h' || value === 'help';
58
+ }
59
+ /*** Render the canonical recognition invocation shape. */
60
+ function renderUsage() {
61
+ return 'Usage: ankh rules-design recognize <observation.json> --output <recognition.json>';
62
+ }
63
+ /*** Convert an unknown boundary failure to a safe command diagnostic. */
64
+ function errorMessage(error) {
65
+ return error instanceof Error ? error.message : 'Rules Design recognition failed.';
66
+ }
@@ -0,0 +1,42 @@
1
+ declare const provider: {
2
+ id: string;
3
+ category: string;
4
+ version: string;
5
+ capabilities: readonly [{
6
+ readonly id: "rules-design.recognize";
7
+ readonly owner: "@ankhorage/rules-design";
8
+ readonly access: readonly ["invoke"];
9
+ readonly binding: {
10
+ readonly kind: "action";
11
+ readonly bindableAs: readonly ["target"];
12
+ };
13
+ readonly label: "Recognize website design";
14
+ readonly description: "Assemble canonical website recognition from an observation document.";
15
+ }, {
16
+ readonly id: "rules-design.inspect";
17
+ readonly owner: "@ankhorage/rules-design";
18
+ readonly access: readonly ["invoke"];
19
+ readonly binding: {
20
+ readonly kind: "action";
21
+ readonly bindableAs: readonly ["target"];
22
+ };
23
+ readonly label: "Inspect website recognition";
24
+ readonly description: "Read an existing canonical website recognition document.";
25
+ }];
26
+ commands: ({
27
+ path: string[];
28
+ capability: "rules-design.recognize";
29
+ summary: string;
30
+ } | {
31
+ path: string[];
32
+ capability: "rules-design.inspect";
33
+ summary: string;
34
+ })[];
35
+ handlers: {
36
+ path: string[];
37
+ handler: ({ argv, context }: import("@ankhorage/ankh").AnkhCommandExecutionRequest) => Promise<{
38
+ readonly exitCode: number;
39
+ }>;
40
+ }[];
41
+ };
42
+ export default provider;
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { CAPABILITIES } from '../capabilities/index.js';
3
+ import { inspect } from './commands/inspect.js';
4
+ import { recognize } from './commands/recognize.js';
5
+ const provider = {
6
+ id: '@ankhorage/rules-design',
7
+ category: 'rules-design',
8
+ version: readPackageVersion(),
9
+ capabilities: CAPABILITIES,
10
+ commands: [
11
+ {
12
+ path: ['recognize'],
13
+ capability: 'rules-design.recognize',
14
+ summary: 'Assemble canonical website recognition from an observation document.',
15
+ },
16
+ {
17
+ path: ['inspect'],
18
+ capability: 'rules-design.inspect',
19
+ summary: 'Read design tokens from an existing website recognition document.',
20
+ },
21
+ ],
22
+ handlers: [
23
+ { path: ['recognize'], handler: async ({ argv, context }) => await recognize(argv, context) },
24
+ { path: ['inspect'], handler: async ({ argv, context }) => await inspect(argv, context) },
25
+ ],
26
+ };
27
+ export default provider;
28
+ /*** Read the package version that is published with this provider module. */
29
+ function readPackageVersion() {
30
+ const parsed = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
31
+ if (!isRecord(parsed) || typeof parsed.version !== 'string' || parsed.version.length === 0) {
32
+ throw new Error('package.json must define a non-empty version.');
33
+ }
34
+ return parsed.version;
35
+ }
36
+ /*** Narrow JSON input to a non-null record without accepting arrays. */
37
+ function isRecord(value) {
38
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
39
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteAsset, WebsiteObservationDocument } from '@ankhorage/contracts/website';
2
+ /*** Indexes globally named assets only after rejecting incompatible duplicate identities. */
3
+ export declare function createWebsiteAssetIndex(document: WebsiteObservationDocument): ReadonlyMap<string, WebsiteAsset>;
@@ -0,0 +1,13 @@
1
+ /*** Indexes globally named assets only after rejecting incompatible duplicate identities. */
2
+ export function createWebsiteAssetIndex(document) {
3
+ return new Map([
4
+ ...Map.groupBy(document.pages.flatMap((page) => page.assets), (asset) => asset.id),
5
+ ].map(([id, assets]) => {
6
+ const [asset] = assets;
7
+ if (assets.some((candidate) => candidate.url !== asset.url ||
8
+ candidate.kind !== asset.kind ||
9
+ candidate.contentType !== asset.contentType))
10
+ throw new TypeError(`Conflicting asset identity ${id}.`);
11
+ return [id, asset];
12
+ }));
13
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteRecognizedProp } from '@ankhorage/contracts/website';
2
+ /*** Qualifies nested structural source evidence so equal DOM paths remain page-unique. */
3
+ export declare function qualifyWebsiteRecognitionProps(property: WebsiteRecognizedProp, pageId: string): WebsiteRecognizedProp;
@@ -0,0 +1,28 @@
1
+ /*** Qualifies nested structural source evidence so equal DOM paths remain page-unique. */
2
+ export function qualifyWebsiteRecognitionProps(property, pageId) {
3
+ return {
4
+ ...property,
5
+ originalValues: property.originalValues.map((value) => qualifySourceReferences(value, pageId)),
6
+ value: qualifySourceReferences(property.value, pageId),
7
+ };
8
+ }
9
+ /*** Qualifies the source references in a structural property list without altering observed literals. */
10
+ function qualifySourceReferences(value, pageId) {
11
+ if (!isSerializableArray(value))
12
+ return value;
13
+ return value.map((item) => isSourceReference(item)
14
+ ? { ...item, sourceRef: JSON.stringify([pageId, item.sourceRef]) }
15
+ : item);
16
+ }
17
+ /*** Narrows a serializable value to its immutable list representation. */
18
+ function isSerializableArray(value) {
19
+ return Array.isArray(value);
20
+ }
21
+ /*** Narrows the portable source-linked records used by structural text, link, and media props. */
22
+ function isSourceReference(value) {
23
+ return (value !== null &&
24
+ typeof value === 'object' &&
25
+ !Array.isArray(value) &&
26
+ 'sourceRef' in value &&
27
+ typeof value.sourceRef === 'string');
28
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteObservationDocument, WebsiteRecognitionDocument } from '@ankhorage/contracts/website';
2
+ /*** Assembles the public website recognition contract from structural and factual design recognition. */
3
+ export declare function recognizeWebsiteDocument(document: WebsiteObservationDocument): WebsiteRecognitionDocument;
@@ -0,0 +1,203 @@
1
+ import { recognizeWebsiteStructure } from '../website-recognition/recognizeWebsiteStructure';
2
+ import { createWebsiteAssetIndex } from './createWebsiteAssetIndex';
3
+ import { qualifyWebsiteRecognitionProps } from './qualifyWebsiteRecognitionProps';
4
+ import { recognizeWebsiteDesignProperties } from './recognizeWebsiteDesignProperties';
5
+ import { validateWebsiteObservationDocument } from './validateWebsiteObservationDocument';
6
+ /*** Assembles the public website recognition contract from structural and factual design recognition. */
7
+ export function recognizeWebsiteDocument(document) {
8
+ validateWebsiteObservationDocument(document);
9
+ const design = recognizeWebsiteDesignProperties(document);
10
+ const pages = recognizeWebsiteStructure(document).map((page) => assemblePage(page, observedPageFor(document, page.id), design.nodes));
11
+ return {
12
+ designTokens: design.tokenCandidates.map(assembleDesignToken),
13
+ documentId: `recognition:${document.documentId}`,
14
+ media: assembleMedia(document),
15
+ navigation: document.pages.flatMap((page) => page.navigation.map((item) => ({
16
+ ...item,
17
+ sourceRef: sourceIdentity(page.id, item.sourceRef),
18
+ }))),
19
+ observedDocumentId: document.documentId,
20
+ pages,
21
+ recognizedAt: document.collectedAt,
22
+ schemaVersion: 1,
23
+ site: document.site,
24
+ source: document.source,
25
+ };
26
+ }
27
+ /*** Finds the validated observed page required to join a structural recognition. */
28
+ function observedPageFor(document, pageId) {
29
+ const page = document.pages.find((candidate) => candidate.id === pageId);
30
+ if (page === undefined)
31
+ throw new TypeError(`Missing observed page ${pageId}.`);
32
+ return page;
33
+ }
34
+ /*** Joins factual design observations with the structural page tree by page-local source identity. */
35
+ function assemblePage(page, observedPage, designNodes) {
36
+ const designBySourceRef = new Map(designNodes
37
+ .filter((node) => node.pageId === page.id)
38
+ .map((node) => [node.sourceRef, node]));
39
+ const nodes = page.nodes.map((node) => assembleNode(node, observedPage, designBySourceRef));
40
+ const nodesById = new Map(nodes.map((node) => [node.id, node]));
41
+ return {
42
+ ...page,
43
+ nodes,
44
+ root: assembleUiNode(page.root, page.id, nodesById),
45
+ };
46
+ }
47
+ /*** Adds exact base, responsive, and unresolved design evidence to one structural recognition. */
48
+ function assembleNode(node, page, designBySourceRef) {
49
+ const design = node.sourceRefs.flatMap((sourceRef) => {
50
+ const candidate = designBySourceRef.get(sourceRef);
51
+ return candidate === undefined ? [] : [candidate];
52
+ });
53
+ const ownerDesign = design.filter((candidate) => candidate.sourceRef === node.id);
54
+ const inheritedDesign = design.filter((candidate) => candidate.sourceRef !== node.id);
55
+ const baseViewportId = page.viewports[0]?.id;
56
+ const baseStateId = page.states[0]?.id;
57
+ const designProperties = [...ownerDesign, ...inheritedDesign].flatMap((candidate) => [
58
+ ...candidate.colors,
59
+ ...candidate.typography,
60
+ ...candidate.layout,
61
+ ...candidate.responsive,
62
+ ]);
63
+ return {
64
+ ...node,
65
+ id: sourceIdentity(page.id, node.id),
66
+ props: mergeProperties([
67
+ ...node.props.map((property) => qualifyWebsiteRecognitionProps(property, page.id)),
68
+ ...baseProperties(designProperties, baseViewportId, baseStateId),
69
+ ...unresolvedProperties(design),
70
+ ]),
71
+ responsive: responsiveVariants(designProperties, baseViewportId, baseStateId),
72
+ sourceRefs: node.sourceRefs.map((sourceRef) => sourceIdentity(page.id, sourceRef)),
73
+ unresolved: node.unresolved === null
74
+ ? null
75
+ : {
76
+ ...node.unresolved,
77
+ sourceRefs: node.unresolved.sourceRefs.map((sourceRef) => sourceIdentity(page.id, sourceRef)),
78
+ },
79
+ };
80
+ }
81
+ /*** Selects the first declared viewport and state as the stable non-responsive property baseline. */
82
+ function baseProperties(observations, viewportId, stateId) {
83
+ return observations
84
+ .filter((observation) => observation.viewportId === viewportId && observation.stateId === stateId)
85
+ .map((observation) => propertyFromObservation(observation, stateId));
86
+ }
87
+ /*** Groups every non-baseline measured property by viewport without fabricating breakpoints. */
88
+ function responsiveVariants(observations, baseViewportId, baseStateId) {
89
+ return [
90
+ ...Map.groupBy(observations.filter((observation) => observation.viewportId !== baseViewportId || observation.stateId !== baseStateId), (observation) => observation.viewportId),
91
+ ]
92
+ .map(([viewportId, properties]) => ({
93
+ props: mergeProperties(properties.map((observation) => propertyFromObservation(observation, baseStateId))),
94
+ viewportId,
95
+ }))
96
+ .toSorted((left, right) => left.viewportId.localeCompare(right.viewportId));
97
+ }
98
+ /*** Represents unavailable source evidence explicitly inside the DTO's extensible property channel. */
99
+ function unresolvedProperties(design) {
100
+ return design.flatMap((node) => node.unresolved.map((unresolved) => ({
101
+ name: `unresolved:${unresolved.stateId}:${unresolved.viewportId}:${unresolved.kind}`,
102
+ originalValues: [unresolvedValue(unresolved.missing)],
103
+ value: unresolvedValue(unresolved.missing),
104
+ })));
105
+ }
106
+ /*** Converts the portable missing-value DTO to the serializable map shape required by property values. */
107
+ function unresolvedValue(missing) {
108
+ return { code: missing.code, message: missing.message };
109
+ }
110
+ /*** Converts factual style samples to property names that retain state identity when it is not baseline. */
111
+ function propertyFromObservation(observation, baselineStateId) {
112
+ return {
113
+ name: observation.stateId === baselineStateId
114
+ ? observation.name
115
+ : `state:${observation.stateId}:${observation.name}`,
116
+ originalValues: [observation.value],
117
+ value: observation.value,
118
+ };
119
+ }
120
+ /*** Merges duplicate property samples while retaining every original value in stable JSON order. */
121
+ function mergeProperties(properties) {
122
+ return [...Map.groupBy(properties, (property) => property.name)]
123
+ .map(([name, values]) => ({
124
+ name,
125
+ originalValues: uniqueSerializableValues(values.flatMap((value) => value.originalValues)),
126
+ value: first(values).value,
127
+ }))
128
+ .toSorted((left, right) => left.name.localeCompare(right.name));
129
+ }
130
+ /*** Reads a non-empty collected group after the grouping operation that created it. */
131
+ function first(values) {
132
+ const [value] = values;
133
+ if (value === undefined)
134
+ throw new TypeError('Expected a non-empty collection.');
135
+ return value;
136
+ }
137
+ /*** Deduplicates serializable literals by their exact JSON representation without coercion. */
138
+ function uniqueSerializableValues(values) {
139
+ return [...new Map(values.map((value) => [JSON.stringify(value), value])).values()];
140
+ }
141
+ /*** Rebuilds the canonical tree so node IDs and props agree with the assembled node mapping. */
142
+ function assembleUiNode(node, pageId, nodesById) {
143
+ const recognized = nodesById.get(sourceIdentity(pageId, node.id));
144
+ return {
145
+ ...(node.children === undefined
146
+ ? {}
147
+ : { children: node.children.map((child) => assembleUiNode(child, pageId, nodesById)) }),
148
+ id: sourceIdentity(pageId, node.id),
149
+ ...(recognized === undefined || recognized.props.length === 0
150
+ ? {}
151
+ : {
152
+ props: Object.fromEntries(recognized.props.map((property) => [property.name, property.value])),
153
+ }),
154
+ type: node.type,
155
+ };
156
+ }
157
+ /*** Converts role-free factual token candidates to the published, source-qualified token contract. */
158
+ function assembleDesignToken(candidate) {
159
+ return {
160
+ id: JSON.stringify([candidate.kind, candidate.property, candidate.value]),
161
+ kind: candidate.kind,
162
+ originalValues: candidate.originalValues,
163
+ sourceRefs: candidate.sourceRefs.map((reference) => sourceIdentity(reference.pageId, reference.sourceRef)),
164
+ value: candidate.value,
165
+ };
166
+ }
167
+ /*** Deduplicates media by known asset identity or exact anonymous media identity while retaining sources. */
168
+ function assembleMedia(document) {
169
+ const assetIndex = createWebsiteAssetIndex(document);
170
+ const references = [
171
+ ...document.pages.flatMap((page) => page.nodes.flatMap((node) => node.media.map((media) => ({ media, pageId: page.id })))),
172
+ ...document.pages.flatMap((page) => page.assets.flatMap((asset) => (asset.sourceRefs.length === 0 ? [undefined] : asset.sourceRefs).map((sourceRef) => ({
173
+ media: { assetId: asset.id, kind: asset.kind, sourceRef, url: asset.url },
174
+ pageId: page.id,
175
+ })))),
176
+ ];
177
+ return [
178
+ ...Map.groupBy(references, ({ media }) => media.assetId === null ? `${media.kind}\u0000${media.url}` : `asset\u0000${media.assetId}`),
179
+ ]
180
+ .map(([identity, entries]) => assembleMediaGroup(identity, entries, assetIndex))
181
+ .toSorted((left, right) => left.id.localeCompare(right.id));
182
+ }
183
+ /*** Assembles one deduplicated media record and rejects incompatible observations sharing an asset ID. */
184
+ function assembleMediaGroup(identity, entries, assetsById) {
185
+ const firstEntry = first(entries);
186
+ if (entries.some((entry) => entry.media.url !== firstEntry.media.url))
187
+ throw new TypeError(`Conflicting URLs for media ${identity}.`);
188
+ const asset = firstEntry.media.assetId === null ? undefined : assetsById.get(firstEntry.media.assetId);
189
+ return {
190
+ asset: asset === undefined ? null : { mediaId: asset.id },
191
+ id: identity,
192
+ originalUrl: firstEntry.media.url,
193
+ sourceRefs: [
194
+ ...new Set(entries.flatMap((entry) => entry.media.sourceRef === undefined
195
+ ? []
196
+ : [sourceIdentity(entry.pageId, entry.media.sourceRef)])),
197
+ ],
198
+ };
199
+ }
200
+ /*** Serializes a two-part source identity without delimiters that could collide with source content. */
201
+ function sourceIdentity(pageId, sourceRef) {
202
+ return JSON.stringify([pageId, sourceRef]);
203
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteObservationDocument } from '@ankhorage/contracts/website';
2
+ /*** Validates the identity and reference invariants required for deterministic recognition assembly. */
3
+ export declare function validateWebsiteObservationDocument(document: WebsiteObservationDocument): void;
@@ -0,0 +1,77 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Validates the identity and reference invariants required for deterministic recognition assembly. */
3
+ export function validateWebsiteObservationDocument(document) {
4
+ assertObservationEnvelope(document);
5
+ const schemaVersion = document.schemaVersion;
6
+ if (schemaVersion !== 1)
7
+ throw new TypeError('Unsupported website observation schema.');
8
+ if (document.documentId.length === 0)
9
+ throw new TypeError('Website observation documentId is required.');
10
+ unique(document.pages.map((page) => page.id), 'page id');
11
+ document.pages.forEach(validatePage);
12
+ }
13
+ /*** Validates the complete observation envelope before recognition accesses nested page evidence. */
14
+ function assertObservationEnvelope(document) {
15
+ if (!isRecord(document) || document.schemaVersion !== 1)
16
+ throw new TypeError('Unsupported website observation schema.');
17
+ if (!isNonEmptyString(document.documentId) || !isNonEmptyString(document.collectedAt))
18
+ throw new TypeError('Website observation document identity is required.');
19
+ assertSource(document.source);
20
+ assertSite(document.site);
21
+ assertObservationPages(document.pages);
22
+ }
23
+ /*** Validates the immutable producer metadata required to attribute an observation document. */
24
+ function assertSource(value) {
25
+ if (!isRecord(value) ||
26
+ !isNonEmptyString(value.crawlerId) ||
27
+ !isNonEmptyString(value.crawlerVersion) ||
28
+ !isNonEmptyString(value.crawlId) ||
29
+ (value.revision !== null && typeof value.revision !== 'string')) {
30
+ throw new TypeError('Website observation source metadata is incomplete.');
31
+ }
32
+ }
33
+ /*** Validates the stable site metadata required to scope an observation document. */
34
+ function assertSite(value) {
35
+ if (!isRecord(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.url))
36
+ throw new TypeError('Website observation site metadata is incomplete.');
37
+ }
38
+ /*** Validates page collection boundaries before existing page-reference invariants run. */
39
+ function assertObservationPages(value) {
40
+ if (!Array.isArray(value) || !value.every(isObservationPage))
41
+ throw new TypeError('Website observation pages are incomplete.');
42
+ }
43
+ /*** Validates all page collections read by the recognition algorithm without reimplementing recognition. */
44
+ function isObservationPage(value) {
45
+ return (isRecord(value) &&
46
+ isNonEmptyString(value.id) &&
47
+ isNonEmptyString(value.url) &&
48
+ typeof value.path === 'string' &&
49
+ Array.isArray(value.navigation) &&
50
+ Array.isArray(value.viewports) &&
51
+ Array.isArray(value.states) &&
52
+ Array.isArray(value.nodes) &&
53
+ Array.isArray(value.assets));
54
+ }
55
+ /*** Checks an identity value without accepting empty string placeholders. */
56
+ function isNonEmptyString(value) {
57
+ return typeof value === 'string' && value.length > 0;
58
+ }
59
+ /*** Validates page-local references without rejecting malformed hierarchy evidence that recognition must retain. */
60
+ function validatePage(page) {
61
+ unique(page.nodes.map((node) => node.sourceRef), `source reference on page ${page.id}`);
62
+ unique(page.viewports.map((viewport) => viewport.id), `viewport id on page ${page.id}`);
63
+ unique(page.states.map((state) => state.id), `state id on page ${page.id}`);
64
+ const viewportIds = new Set(page.viewports.map((viewport) => viewport.id));
65
+ const stateIds = new Set(page.states.map((state) => state.id));
66
+ page.nodes.forEach((node) => node.observations.forEach((observation) => {
67
+ if (!viewportIds.has(observation.viewportId))
68
+ throw new TypeError(`Unknown viewport ${observation.viewportId} on page ${page.id}.`);
69
+ if (!stateIds.has(observation.stateId))
70
+ throw new TypeError(`Unknown state ${observation.stateId} on page ${page.id}.`);
71
+ }));
72
+ }
73
+ /*** Rejects ambiguous identities before a Map could silently overwrite an observation. */
74
+ function unique(values, label) {
75
+ if (new Set(values).size !== values.length)
76
+ throw new TypeError(`Duplicate ${label}.`);
77
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteRecognitionDocument } from '@ankhorage/contracts/website';
2
+ /*** Validates the canonical recognition envelope before a delivery adapter reads its derived data. */
3
+ export declare function validateWebsiteRecognitionDocument(document: unknown): asserts document is WebsiteRecognitionDocument;
@@ -0,0 +1,70 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Validates the canonical recognition envelope before a delivery adapter reads its derived data. */
3
+ export function validateWebsiteRecognitionDocument(document) {
4
+ if (!isRecord(document) || document.schemaVersion !== 1)
5
+ throw new TypeError('Unsupported website recognition schema.');
6
+ if (!isNonEmptyString(document.documentId) || !isNonEmptyString(document.observedDocumentId))
7
+ throw new TypeError('Website recognition document identity is required.');
8
+ if (document.documentId !== `recognition:${document.observedDocumentId}`)
9
+ throw new TypeError('Website recognition document identity is not canonical.');
10
+ if (!isNonEmptyString(document.recognizedAt))
11
+ throw new TypeError('Website recognition timestamp is required.');
12
+ assertSource(document.source);
13
+ assertSite(document.site);
14
+ assertRecognitionPages(document.pages);
15
+ assertDesignTokens(document.designTokens);
16
+ assertRecords(document.navigation, 'Website recognition navigation');
17
+ assertRecords(document.media, 'Website recognition media');
18
+ }
19
+ /*** Validates complete source metadata shared by every canonical website document. */
20
+ function assertSource(value) {
21
+ if (!isRecord(value) ||
22
+ !isNonEmptyString(value.crawlerId) ||
23
+ !isNonEmptyString(value.crawlerVersion) ||
24
+ !isNonEmptyString(value.crawlId) ||
25
+ (value.revision !== null && typeof value.revision !== 'string')) {
26
+ throw new TypeError('Website recognition source metadata is incomplete.');
27
+ }
28
+ }
29
+ /*** Validates complete site metadata shared by every canonical website document. */
30
+ function assertSite(value) {
31
+ if (!isRecord(value) || !isNonEmptyString(value.id) || !isNonEmptyString(value.url))
32
+ throw new TypeError('Website recognition site metadata is incomplete.');
33
+ }
34
+ /*** Validates the structural page boundary needed to recognize a document rather than an array of tokens. */
35
+ function assertRecognitionPages(value) {
36
+ assertRecords(value, 'Website recognition pages');
37
+ if (!value.every((page) => isNonEmptyString(page.id) &&
38
+ isNonEmptyString(page.url) &&
39
+ typeof page.path === 'string' &&
40
+ isRecord(page.root) &&
41
+ Array.isArray(page.nodes))) {
42
+ throw new TypeError('Website recognition page structure is incomplete.');
43
+ }
44
+ if (new Set(value.map((page) => page.id)).size !== value.length)
45
+ throw new TypeError('Duplicate recognition page id.');
46
+ }
47
+ /*** Validates each derived token retains its canonical identity, kind, and source evidence. */
48
+ function assertDesignTokens(value) {
49
+ assertRecords(value, 'Website recognition designTokens');
50
+ if (!value.every((token) => isNonEmptyString(token.id) &&
51
+ (token.kind === 'color' ||
52
+ token.kind === 'radius' ||
53
+ token.kind === 'shadow' ||
54
+ token.kind === 'spacing' ||
55
+ token.kind === 'typography') &&
56
+ Array.isArray(token.originalValues) &&
57
+ Array.isArray(token.sourceRefs) &&
58
+ token.sourceRefs.every(isNonEmptyString))) {
59
+ throw new TypeError('Website recognition design token structure is incomplete.');
60
+ }
61
+ }
62
+ /*** Narrows one document collection to records before its members are inspected. */
63
+ function assertRecords(value, label) {
64
+ if (!Array.isArray(value) || !value.every(isRecord))
65
+ throw new TypeError(`${label} must be an array.`);
66
+ }
67
+ /*** Checks an identity value without accepting empty string placeholders. */
68
+ function isNonEmptyString(value) {
69
+ return typeof value === 'string' && value.length > 0;
70
+ }
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCata
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
7
  export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
8
+ export { recognizeWebsiteDocument } from './features/recognition/recognizeWebsiteDocument';
8
9
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
10
  export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
10
11
  export type { DesignAssessmentKind, DesignRuleCatalogEntry, DesignRuleCatalogFilter, DesignRuleEvidence, DesignRulePlanningManifest, DesignRuleProfile, DesignRuleProviderManifest, DesignRuleScope, DesignRuleStatus, } from './types/designRuleCatalog';
package/dist/index.js CHANGED
@@ -5,5 +5,6 @@ export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCata
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
7
  export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
8
+ export { recognizeWebsiteDocument } from './features/recognition/recognizeWebsiteDocument';
8
9
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
10
  export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",
@@ -28,8 +28,52 @@
28
28
  ".": {
29
29
  "types": "./dist/index.d.ts",
30
30
  "import": "./dist/index.js"
31
+ },
32
+ "./cli": {
33
+ "types": "./dist/cli/index.d.ts",
34
+ "import": "./dist/cli/index.js"
35
+ },
36
+ "./capabilities": {
37
+ "types": "./dist/capabilities/index.d.ts",
38
+ "import": "./dist/capabilities/index.js"
31
39
  }
32
40
  },
41
+ "ankh": {
42
+ "category": "rules-design",
43
+ "provider": "./dist/cli/index.js",
44
+ "capabilities": [
45
+ {
46
+ "id": "rules-design.recognize",
47
+ "owner": "@ankhorage/rules-design",
48
+ "access": [
49
+ "invoke"
50
+ ],
51
+ "binding": {
52
+ "kind": "action",
53
+ "bindableAs": [
54
+ "target"
55
+ ]
56
+ },
57
+ "label": "Recognize website design",
58
+ "description": "Assemble canonical website recognition from an observation document."
59
+ },
60
+ {
61
+ "id": "rules-design.inspect",
62
+ "owner": "@ankhorage/rules-design",
63
+ "access": [
64
+ "invoke"
65
+ ],
66
+ "binding": {
67
+ "kind": "action",
68
+ "bindableAs": [
69
+ "target"
70
+ ]
71
+ },
72
+ "label": "Inspect website recognition",
73
+ "description": "Read an existing canonical website recognition document."
74
+ }
75
+ ]
76
+ },
33
77
  "repository": {
34
78
  "type": "git",
35
79
  "url": "git+https://github.com/ankhorage/rules-design.git"
@@ -42,6 +86,8 @@
42
86
  "test": "bun test",
43
87
  "lint": "ankhorage-eslint . --max-warnings=0",
44
88
  "knip:check": "ankhorage-knip",
89
+ "test:packed-consumer": "bun test/packed-consumer.ts",
90
+ "test:php-consumer": "bun test/php-consumer.ts",
45
91
  "format": "ankhorage-prettier --write .",
46
92
  "format:check": "ankhorage-prettier --check .",
47
93
  "lint:fix": "ankhorage-eslint . --fix --max-warnings=0",
@@ -58,6 +104,8 @@
58
104
  "@ankhorage/paradox": "^0.3.6"
59
105
  },
60
106
  "dependencies": {
107
+ "@ankhorage/ankh": "^0.13.4",
108
+ "@ankhorage/capability": "^0.2.2",
61
109
  "@ankhorage/contracts": "^26.6.0",
62
110
  "@ankhorage/rules": "^0.4.0",
63
111
  "@ankhorage/utility": "^1.10.0"