@ankhorage/rules-design 0.8.0 → 0.9.1

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.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 3346adc: Recognize semantic HTML landmarks and content alongside evidence-backed layout, card, and transparent-wrapper structures without losing child provenance.
8
+
9
+ ## 0.9.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 8ed1957: Expose canonical website recognition and token inspection through the Ankh CLI provider.
14
+
3
15
  ## 0.8.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.8.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.1](././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
 
@@ -38,5 +38,4 @@ import { createRuleRegistry, evaluateRules } from '@ankhorage/rules';
38
38
  - [Module relationships](././paradox/diagrams/module-relationships.mmd)
39
39
  - [Export graph](././paradox/diagrams/export-graph.mmd)
40
40
  - [recognizeWebsiteDesignProperties sequence](././paradox/diagrams/sequences/recognize-website-design-properties.mmd)
41
- - [recognizeWebsiteDocument sequence](././paradox/diagrams/sequences/recognize-website-document.mmd)
42
41
  - [selectDesignRuleProfile sequence](././paradox/diagrams/sequences/select-design-rule-profile.mmd)
@@ -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
+ }
@@ -1,5 +1,7 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
1
2
  /*** Validates the identity and reference invariants required for deterministic recognition assembly. */
2
3
  export function validateWebsiteObservationDocument(document) {
4
+ assertObservationEnvelope(document);
3
5
  const schemaVersion = document.schemaVersion;
4
6
  if (schemaVersion !== 1)
5
7
  throw new TypeError('Unsupported website observation schema.');
@@ -8,6 +10,52 @@ export function validateWebsiteObservationDocument(document) {
8
10
  unique(document.pages.map((page) => page.id), 'page id');
9
11
  document.pages.forEach(validatePage);
10
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
+ }
11
59
  /*** Validates page-local references without rejecting malformed hierarchy evidence that recognition must retain. */
12
60
  function validatePage(page) {
13
61
  unique(page.nodes.map((node) => node.sourceRef), `source reference on page ${page.id}`);
@@ -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
+ }
@@ -1,4 +1,5 @@
1
1
  import { recognizeWebsiteStructureProps } from './recognizeWebsiteStructureProps';
2
+ import { websiteStructureEvidence } from './websiteStructureEvidence';
2
3
  import { recognizeWebsiteStructureSemanticComponentType } from './websiteStructureSemantics';
3
4
  import { createWebsiteStructureTreeNode } from './websiteStructureTreeNodes';
4
5
  /*** Recognizes source-linked canonical component trees from validated website observations. */
@@ -52,7 +53,8 @@ function recognizeTreeNode(node, nodesBySourceRef, childNodesByParent, effective
52
53
  return [];
53
54
  }
54
55
  const children = childNodesByParent.get(node.sourceRef) ?? [];
55
- if (!isCyclicSourceRef(node, nodesBySourceRef) && isTransparentWrapper(node, children)) {
56
+ if (!isCyclicSourceRef(node, nodesBySourceRef) &&
57
+ websiteStructureEvidence(node, children).isTransparentWrapper) {
56
58
  return children.flatMap((child) => recognizeTreeNode(child, nodesBySourceRef, childNodesByParent, effectiveParentSourceRef, [...inheritedSourceRefs, node.sourceRef], [...ancestorSourceRefs, node.sourceRef]));
57
59
  }
58
60
  const childRecognitions = children.flatMap((child) => recognizeTreeNode(child, nodesBySourceRef, childNodesByParent, node.sourceRef, [], [...ancestorSourceRefs, node.sourceRef]));
@@ -69,7 +71,7 @@ function createRecognizedTreeNode(node, parent, childNodesByParent, nodesBySourc
69
71
  const props = recognizeWebsiteStructureProps(node);
70
72
  return createWebsiteStructureTreeNode(node, componentType, [...inheritedSourceRefs, node.sourceRef], props, children, cyclic
71
73
  ? 'Source hierarchy contains a cycle.'
72
- : availableObservation(node) === null
74
+ : websiteStructureEvidence(node).availableObservation === null
73
75
  ? 'No available rendered observation exists for this source node.'
74
76
  : 'Visible source node has no canonical component mapping.');
75
77
  }
@@ -89,44 +91,31 @@ function isCyclicSourceRef(node, nodesBySourceRef) {
89
91
  function containsSourceRef(recognitions, sourceRef) {
90
92
  return recognitions.some((recognition) => recognition.nodes.some((node) => node.sourceRefs.includes(sourceRef)));
91
93
  }
92
- /*** Identifies wrappers with no independently meaningful semantic, textual, media, or visual role. */
93
- function isTransparentWrapper(node, children) {
94
- const observation = availableObservation(node);
95
- const tagName = node.dom.tagName.toLowerCase();
96
- return (children.length > 0 &&
97
- node.links.length === 0 &&
98
- node.media.length === 0 &&
99
- node.textRuns.length === 0 &&
100
- (tagName === 'div' || tagName === 'span') &&
101
- observation !== null &&
102
- !hasLayoutRole(observation) &&
103
- !hasSurfaceRole(observation));
104
- }
105
94
  /*** Maps observed DOM semantics and measured layout traits to already representable UI components. */
106
95
  function recognizeComponentType(node, parent, childNodesByParent) {
107
- const observation = availableObservation(node);
96
+ const observation = websiteStructureEvidence(node).availableObservation;
108
97
  if (observation === null)
109
98
  return 'Unknown';
110
99
  const tagName = node.dom.tagName.toLowerCase();
111
100
  const semanticType = recognizeWebsiteStructureSemanticComponentType(tagName);
112
101
  if (semanticType !== null)
113
102
  return semanticType;
114
- if (node.media.length > 0)
115
- return node.media.every((media) => media.kind === 'image') ? 'Image' : 'Media';
116
- if (node.links.length > 0)
117
- return 'Link';
118
- if (node.textRuns.length > 0)
119
- return 'RichText';
120
- if (isGroupedCard(node, parent, childNodesByParent))
121
- return 'Card';
122
103
  const { css } = observation;
123
104
  if (css === null)
124
105
  return 'Unknown';
106
+ if (isGroupedCard(node, parent, childNodesByParent))
107
+ return 'Card';
125
108
  if (css.display.includes('grid'))
126
109
  return 'Grid';
127
110
  if (css.display.includes('flex'))
128
111
  return 'Flex';
129
- return hasLayoutRole(observation) || hasSurfaceRole(observation) ? 'Container' : 'Unknown';
112
+ if (node.media.length > 0)
113
+ return node.media.every((media) => media.kind === 'image') ? 'Image' : 'Media';
114
+ if (node.links.length > 0)
115
+ return 'Link';
116
+ if (node.textRuns.length > 0)
117
+ return 'RichText';
118
+ return websiteStructureEvidence(node).hasVisualRole ? 'Container' : 'Unknown';
130
119
  }
131
120
  /*** Recognizes a card only when a measured sibling group shares explicit surface traits. */
132
121
  function isGroupedCard(node, parent, childNodesByParent) {
@@ -140,70 +129,17 @@ function meaningfulChildren(parentSourceRef, childNodesByParent) {
140
129
  const children = childNodesByParent.get(parentSourceRef) ?? [];
141
130
  return children.flatMap((child) => {
142
131
  const nestedChildren = childNodesByParent.get(child.sourceRef) ?? [];
143
- return isTransparentWrapper(child, nestedChildren)
132
+ return websiteStructureEvidence(child, nestedChildren).isTransparentWrapper
144
133
  ? meaningfulChildren(child.sourceRef, childNodesByParent)
145
134
  : [child];
146
135
  });
147
136
  }
148
137
  /*** Tests whether a parent has measured Grid or Flex grouping semantics. */
149
138
  function isLayoutGroup(node) {
150
- const css = availableObservation(node)?.css;
139
+ const css = websiteStructureEvidence(node).availableObservation?.css;
151
140
  return css === null || css === undefined ? false : /grid|flex/.test(css.display);
152
141
  }
153
142
  /*** Requires padding plus radius, border, or shadow so colored columns are not invented as cards. */
154
143
  function isCardSurface(node) {
155
- const observation = availableObservation(node);
156
- const css = observation?.css;
157
- return (css !== null &&
158
- css !== undefined &&
159
- hasNonZeroEdge(css.padding) &&
160
- (hasNonZeroCssValue(css.borderRadius) ||
161
- hasNonZeroCssValue(css.borderWidth) ||
162
- css.boxShadow !== 'none'));
163
- }
164
- /*** Selects a visible available observation deterministically without inventing a missing style. */
165
- function availableObservation(node) {
166
- return ([...node.observations]
167
- .sort((left, right) => left.viewportId.localeCompare(right.viewportId) ||
168
- left.stateId.localeCompare(right.stateId))
169
- .find((observation) => observation.availability.status === 'available' &&
170
- observation.css !== null &&
171
- observation.rect !== null &&
172
- observation.rect.width > 0 &&
173
- observation.rect.height > 0 &&
174
- observation.css.display !== 'none' &&
175
- observation.css.visibility !== 'hidden' &&
176
- observation.css.visibility !== 'collapse' &&
177
- observation.css.opacity !== '0') ?? null);
178
- }
179
- /*** Identifies layout evidence that gives an otherwise generic container a real component role. */
180
- function hasLayoutRole(observation) {
181
- const { css } = observation;
182
- return (css !== null &&
183
- (css.display.includes('grid') ||
184
- css.display.includes('flex') ||
185
- hasNonZeroEdge(css.padding) ||
186
- hasNonZeroEdge(css.margin) ||
187
- hasNonZeroCssValue(css.gap)));
188
- }
189
- /*** Identifies measured border, radius, background, or shadow evidence for a visual container. */
190
- function hasSurfaceRole(observation) {
191
- const { css } = observation;
192
- return (css !== null &&
193
- (hasNonZeroCssValue(css.borderRadius) ||
194
- hasNonZeroCssValue(css.borderWidth) ||
195
- css.boxShadow !== 'none' ||
196
- !isTransparentColor(css.backgroundColor)));
197
- }
198
- /*** Tests CSS box edges without parsing or normalizing their original literals. */
199
- function hasNonZeroEdge(edges) {
200
- return [edges.top, edges.right, edges.bottom, edges.left].some(hasNonZeroCssValue);
201
- }
202
- /*** Detects non-zero CSS literals while preserving their exact source value elsewhere. */
203
- function hasNonZeroCssValue(value) {
204
- return value !== '0' && value !== '0px' && value !== 'normal' && value !== 'auto';
205
- }
206
- /*** Recognizes the transparent computed color forms without assigning a color token. */
207
- function isTransparentColor(value) {
208
- return value === 'transparent' || value === 'rgba(0, 0, 0, 0)';
144
+ return websiteStructureEvidence(node).hasCardSurface;
209
145
  }
@@ -0,0 +1,10 @@
1
+ import type { WebsiteNodeObservation, WebsiteObservedNode } from '@ankhorage/contracts/website';
2
+ /*** Collects complete evidence needed to classify an observed website structure node. */
3
+ export declare function websiteStructureEvidence(node: WebsiteObservedNode, children?: readonly WebsiteObservedNode[]): WebsiteStructureEvidence;
4
+ interface WebsiteStructureEvidence {
5
+ readonly availableObservation: WebsiteNodeObservation | null;
6
+ readonly hasCardSurface: boolean;
7
+ readonly hasVisualRole: boolean;
8
+ readonly isTransparentWrapper: boolean;
9
+ }
10
+ export {};
@@ -0,0 +1,88 @@
1
+ /*** Collects complete evidence needed to classify an observed website structure node. */
2
+ export function websiteStructureEvidence(node, children = []) {
3
+ return {
4
+ availableObservation: availableObservation(node),
5
+ hasCardSurface: hasCardSurface(node),
6
+ hasVisualRole: hasVisualRole(node),
7
+ isTransparentWrapper: isTransparentWrapper(node, children),
8
+ };
9
+ }
10
+ /*** Selects a visible available observation deterministically without inventing a missing style. */
11
+ function availableObservation(node) {
12
+ return ([...node.observations]
13
+ .sort((left, right) => left.viewportId.localeCompare(right.viewportId) ||
14
+ left.stateId.localeCompare(right.stateId))
15
+ .find((observation) => observation.availability.status === 'available' &&
16
+ observation.css !== null &&
17
+ observation.rect !== null &&
18
+ observation.rect.width > 0 &&
19
+ observation.rect.height > 0 &&
20
+ observation.css.display !== 'none' &&
21
+ observation.css.visibility !== 'hidden' &&
22
+ observation.css.visibility !== 'collapse' &&
23
+ observation.css.opacity !== '0') ?? null);
24
+ }
25
+ /*** Requires padding plus radius, border, or shadow so colored columns are not invented as cards. */
26
+ function hasCardSurface(node) {
27
+ const css = availableObservation(node)?.css;
28
+ return (css !== null &&
29
+ css !== undefined &&
30
+ hasNonZeroEdge(css.padding) &&
31
+ (hasNonZeroCssValue(css.borderRadius) ||
32
+ hasNonZeroCssValue(css.borderWidth) ||
33
+ css.boxShadow !== 'none'));
34
+ }
35
+ /*** Tests whether a visible observation gives a generic node a layout or surface role. */
36
+ function hasVisualRole(node) {
37
+ const observation = availableObservation(node);
38
+ return observation !== null && (hasLayoutRole(observation) || hasSurfaceRole(observation));
39
+ }
40
+ /*** Identifies wrappers only when complete observations prove no independent role. */
41
+ function isTransparentWrapper(node, children) {
42
+ const tagName = node.dom.tagName.toLowerCase();
43
+ return (children.length > 0 &&
44
+ node.links.length === 0 &&
45
+ node.media.length === 0 &&
46
+ node.textRuns.length === 0 &&
47
+ (tagName === 'div' || tagName === 'span') &&
48
+ node.observations.length > 0 &&
49
+ node.observations.every(isTransparentObservation));
50
+ }
51
+ /*** Requires usable CSS evidence and excludes every measured layout or surface role. */
52
+ function isTransparentObservation(observation) {
53
+ return (observation.availability.status === 'available' &&
54
+ observation.css !== null &&
55
+ !hasLayoutRole(observation) &&
56
+ !hasSurfaceRole(observation));
57
+ }
58
+ /*** Identifies layout evidence that gives an otherwise generic container a real component role. */
59
+ function hasLayoutRole(observation) {
60
+ const { css } = observation;
61
+ return (css !== null &&
62
+ (css.display.includes('grid') ||
63
+ css.display.includes('flex') ||
64
+ hasNonZeroEdge(css.padding) ||
65
+ hasNonZeroEdge(css.margin) ||
66
+ hasNonZeroCssValue(css.gap)));
67
+ }
68
+ /*** Identifies measured border, radius, background, or shadow evidence for a visual container. */
69
+ function hasSurfaceRole(observation) {
70
+ const { css } = observation;
71
+ return (css !== null &&
72
+ (hasNonZeroCssValue(css.borderRadius) ||
73
+ hasNonZeroCssValue(css.borderWidth) ||
74
+ css.boxShadow !== 'none' ||
75
+ !isTransparentColor(css.backgroundColor)));
76
+ }
77
+ /*** Tests CSS box edges without parsing or normalizing their original literals. */
78
+ function hasNonZeroEdge(edges) {
79
+ return [edges.top, edges.right, edges.bottom, edges.left].some(hasNonZeroCssValue);
80
+ }
81
+ /*** Detects non-zero CSS literals while preserving their exact source value elsewhere. */
82
+ function hasNonZeroCssValue(value) {
83
+ return value !== '0' && value !== '0px' && value !== 'normal' && value !== 'auto';
84
+ }
85
+ /*** Recognizes transparent computed-color forms without assigning a color token. */
86
+ function isTransparentColor(value) {
87
+ return value === 'transparent' || value === 'rgba(0, 0, 0, 0)';
88
+ }
@@ -6,22 +6,36 @@ export function recognizeWebsiteStructureSemanticComponentType(tagName) {
6
6
  }
7
7
  const semanticComponentTypes = [
8
8
  ['a', 'Link'],
9
+ ['address', 'RichText'],
10
+ ['aside', 'Container'],
9
11
  ['article', 'Container'],
10
12
  ['audio', 'Media'],
11
13
  ['body', 'Container'],
12
14
  ['blockquote', 'RichText'],
13
15
  ['button', 'Button'],
16
+ ['dd', 'ListItem'],
17
+ ['details', 'Container'],
18
+ ['dl', 'List'],
19
+ ['dt', 'ListItem'],
20
+ ['em', 'RichText'],
14
21
  ['footer', 'Footer'],
15
22
  ['form', 'Form'],
23
+ ['figure', 'Container'],
24
+ ['figcaption', 'RichText'],
16
25
  ['header', 'Header'],
17
26
  ['iframe', 'Media'],
18
27
  ['img', 'Image'],
19
28
  ['label', 'RichText'],
20
29
  ['li', 'ListItem'],
21
30
  ['main', 'Container'],
31
+ ['menu', 'List'],
32
+ ['nav', 'Container'],
22
33
  ['ol', 'List'],
23
34
  ['p', 'RichText'],
24
35
  ['section', 'Section'],
36
+ ['small', 'RichText'],
37
+ ['strong', 'RichText'],
38
+ ['summary', 'RichText'],
25
39
  ['ul', 'List'],
26
40
  ['video', 'Media'],
27
41
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
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"
@@ -60,6 +104,8 @@
60
104
  "@ankhorage/paradox": "^0.3.6"
61
105
  },
62
106
  "dependencies": {
107
+ "@ankhorage/ankh": "^0.13.4",
108
+ "@ankhorage/capability": "^0.2.2",
63
109
  "@ankhorage/contracts": "^26.6.0",
64
110
  "@ankhorage/rules": "^0.4.0",
65
111
  "@ankhorage/utility": "^1.10.0"