@ankhorage/rules-design 0.5.0 → 0.7.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.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e6da8f0: Add a pure website structure recognizer that maps observed pages to source-linked canonical UI trees.
8
+
9
+ ## 0.6.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 34695ae: Add factual website design-property recognition with retained provenance and unresolved evidence.
14
+
3
15
  ## 0.5.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.5.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.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)
7
7
 
8
8
  Declarative catalog for reusable design rules.
9
9
 
@@ -37,4 +37,5 @@ import { createRuleRegistry, evaluateRules } from '@ankhorage/rules';
37
37
  - [Architecture overview](././paradox/diagrams/architecture-overview.mmd)
38
38
  - [Module relationships](././paradox/diagrams/module-relationships.mmd)
39
39
  - [Export graph](././paradox/diagrams/export-graph.mmd)
40
+ - [recognizeWebsiteDesignProperties sequence](././paradox/diagrams/sequences/recognize-website-design-properties.mmd)
40
41
  - [selectDesignRuleProfile sequence](././paradox/diagrams/sequences/select-design-rule-profile.mmd)
@@ -0,0 +1,4 @@
1
+ import type { WebsiteObservationDocument } from '@ankhorage/contracts/website';
2
+ import type { WebsiteDesignRecognition } from '../../types/websiteDesignRecognition';
3
+ /*** Recognizes exact design properties from validated website observations without evaluating them. */
4
+ export declare function recognizeWebsiteDesignProperties(document: WebsiteObservationDocument): WebsiteDesignRecognition;
@@ -0,0 +1,191 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ import { tokenCandidates } from './tokenCandidates';
3
+ /*** Recognizes exact design properties from validated website observations without evaluating them. */
4
+ export function recognizeWebsiteDesignProperties(document) {
5
+ const nodes = document.pages.flatMap((page) => page.nodes.map((node) => recognizeNode(page.id, node)));
6
+ return { nodes, tokenCandidates: tokenCandidates(nodes) };
7
+ }
8
+ const colorProperties = ['color', 'backgroundColor', 'borderColor', 'opacity'];
9
+ const typographyProperties = [
10
+ 'fontFamily',
11
+ 'fontSize',
12
+ 'fontStyle',
13
+ 'fontWeight',
14
+ 'letterSpacing',
15
+ 'lineHeight',
16
+ 'textAlign',
17
+ 'textDecoration',
18
+ ];
19
+ const layoutProperties = [
20
+ 'display',
21
+ 'position',
22
+ 'visibility',
23
+ 'borderRadius',
24
+ 'borderWidth',
25
+ 'boxShadow',
26
+ 'margin',
27
+ 'padding',
28
+ 'alignContent',
29
+ 'alignItems',
30
+ 'alignSelf',
31
+ 'gap',
32
+ 'flexDirection',
33
+ 'flexBasis',
34
+ 'flexGrow',
35
+ 'flexShrink',
36
+ 'flexWrap',
37
+ 'justifyContent',
38
+ 'justifyItems',
39
+ 'justifySelf',
40
+ 'order',
41
+ 'placeContent',
42
+ 'placeItems',
43
+ 'placeSelf',
44
+ 'gridAutoColumns',
45
+ 'gridAutoFlow',
46
+ 'gridAutoRows',
47
+ 'gridColumn',
48
+ 'gridColumnEnd',
49
+ 'gridColumnStart',
50
+ 'gridRow',
51
+ 'gridRowEnd',
52
+ 'gridRowStart',
53
+ 'gridTemplateColumns',
54
+ 'gridTemplateRows',
55
+ 'overflow',
56
+ 'overflowX',
57
+ 'overflowY',
58
+ 'backgroundImage',
59
+ 'backgroundPosition',
60
+ 'backgroundRepeat',
61
+ 'backgroundSize',
62
+ ];
63
+ /*** Retains every available node style and safe semantic observation at its source identity. */
64
+ function recognizeNode(pageId, node) {
65
+ return {
66
+ sourceRef: node.sourceRef,
67
+ pageId,
68
+ colors: cssObservations(pageId, node, colorProperties),
69
+ typography: cssObservations(pageId, node, typographyProperties),
70
+ layout: cssObservations(pageId, node, layoutProperties),
71
+ responsive: responsiveObservations(pageId, node),
72
+ accessibility: accessibilityObservations(pageId, node),
73
+ media: node.media,
74
+ unresolved: unresolvedObservations(pageId, node),
75
+ };
76
+ }
77
+ /*** Projects exact available computed CSS values while retaining viewport, state, and provenance. */
78
+ function cssObservations(pageId, node, properties) {
79
+ return node.observations.flatMap((observation) => {
80
+ const { css } = observation;
81
+ return observation.availability.status === 'available' && css !== null
82
+ ? properties.map((name) => cssObservation(pageId, node.sourceRef, observation, css, name))
83
+ : [];
84
+ });
85
+ }
86
+ /*** Creates one source-linked computed CSS observation without normalizing its original literal. */
87
+ function cssObservation(pageId, sourceRef, observation, css, name) {
88
+ return {
89
+ name,
90
+ value: cssValue(cssPropertyValue(css, name)),
91
+ viewportId: observation.viewportId,
92
+ stateId: observation.stateId,
93
+ sourceRef,
94
+ pageId,
95
+ provenance: observation.provenance,
96
+ };
97
+ }
98
+ /*** Reads a named computed CSS field without indexing an untrusted external object. */
99
+ function cssPropertyValue(css, name) {
100
+ const value = Object.entries(isRecord(css) ? css : {}).find(([property]) => property === name)?.[1];
101
+ if (value === undefined)
102
+ throw new TypeError(`Unknown computed CSS property: ${name}`);
103
+ return value;
104
+ }
105
+ /*** Converts the one structured CSS box value into a portable serializable value. */
106
+ function cssValue(value) {
107
+ if (typeof value === 'string')
108
+ return value;
109
+ if (isRecord(value) &&
110
+ typeof value.bottom === 'string' &&
111
+ typeof value.left === 'string' &&
112
+ typeof value.right === 'string' &&
113
+ typeof value.top === 'string')
114
+ return { bottom: value.bottom, left: value.left, right: value.right, top: value.top };
115
+ throw new TypeError('Computed CSS values must be strings or complete box edges.');
116
+ }
117
+ /*** Retains responsive geometry and CSS state samples without inventing source-authored breakpoints. */
118
+ function responsiveObservations(pageId, node) {
119
+ return node.observations.map((observation) => ({
120
+ name: 'observation',
121
+ value: {
122
+ availability: observation.availability.status,
123
+ rect: observation.rect === null
124
+ ? null
125
+ : {
126
+ height: observation.rect.height,
127
+ width: observation.rect.width,
128
+ x: observation.rect.x,
129
+ y: observation.rect.y,
130
+ },
131
+ },
132
+ viewportId: observation.viewportId,
133
+ stateId: observation.stateId,
134
+ sourceRef: node.sourceRef,
135
+ pageId,
136
+ provenance: observation.provenance,
137
+ }));
138
+ }
139
+ /*** Retains semantic and accessible-name evidence without producing accessibility conclusions. */
140
+ function accessibilityObservations(pageId, node) {
141
+ const { sourceRef } = node;
142
+ const semantic = {
143
+ attributes: node.dom.attributes,
144
+ links: node.links.map((link) => ({
145
+ label: link.label,
146
+ sourceRef: link.sourceRef,
147
+ url: link.url,
148
+ })),
149
+ tagName: node.dom.tagName,
150
+ textRuns: node.textRuns.map((textRun) => ({
151
+ end: textRun.end,
152
+ sourceRef: textRun.sourceRef,
153
+ start: textRun.start,
154
+ text: textRun.text,
155
+ })),
156
+ };
157
+ return node.observations.map((observation) => ({
158
+ name: 'semantics',
159
+ value: semantic,
160
+ viewportId: observation.viewportId,
161
+ stateId: observation.stateId,
162
+ sourceRef,
163
+ pageId,
164
+ provenance: observation.provenance,
165
+ }));
166
+ }
167
+ /*** Records unavailable CSS or geometry samples with their producer-supplied missing reason. */
168
+ function unresolvedObservations(pageId, node) {
169
+ return node.observations.flatMap((observation) => {
170
+ const { availability } = observation;
171
+ if (availability.status !== 'missing' || availability.missing === null)
172
+ return [];
173
+ const { missing } = availability;
174
+ return unresolvedObservationKinds(observation).map((kind) => ({
175
+ kind,
176
+ missing,
177
+ provenance: observation.provenance,
178
+ sourceRef: node.sourceRef,
179
+ pageId,
180
+ stateId: observation.stateId,
181
+ viewportId: observation.viewportId,
182
+ }));
183
+ });
184
+ }
185
+ /*** Distinguishes each unavailable evidence channel without pretending it was observed. */
186
+ function unresolvedObservationKinds(observation) {
187
+ return [
188
+ ...(observation.css === null ? ['computed-css'] : []),
189
+ ...(observation.rect === null ? ['geometry'] : []),
190
+ ];
191
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteDesignNodeRecognition, WebsiteDesignTokenCandidate } from '../../types/websiteDesignRecognition';
2
+ /*** Finds repeated exact design literals and records them as role-free reusable token candidates. */
3
+ export declare function tokenCandidates(nodes: readonly WebsiteDesignNodeRecognition[]): readonly WebsiteDesignTokenCandidate[];
@@ -0,0 +1,77 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ const tokenKinds = ['color', 'radius', 'shadow', 'spacing', 'typography'];
3
+ /*** Finds repeated exact design literals and records them as role-free reusable token candidates. */
4
+ export function tokenCandidates(nodes) {
5
+ return tokenKinds.flatMap((kind) => candidatesForKind(nodes, kind));
6
+ }
7
+ /*** Extracts deterministic repeated candidates for one design-token family. */
8
+ function candidatesForKind(nodes, kind) {
9
+ const observations = nodes.flatMap((node) => tokenObservationsForKind(node, kind));
10
+ return [
11
+ ...Map.groupBy(observations, (observation) => `${observation.property}\u0000${observation.value}`).entries(),
12
+ ]
13
+ .filter(([, values]) => sourceReferences(values).length > 1)
14
+ .map(([, values]) => ({
15
+ kind,
16
+ property: values[0].property,
17
+ value: values[0].value,
18
+ originalValues: [...new Set(values.map((item) => item.value))],
19
+ sourceRefs: sourceReferences(values),
20
+ confidence: sourceReferences(values).length / sourceReferences(observations).length,
21
+ inferredRole: null,
22
+ }))
23
+ .toSorted((left, right) => left.property.localeCompare(right.property) || left.value.localeCompare(right.value));
24
+ }
25
+ /*** Extracts deterministic page-qualified source identities so viewport samples do not fabricate repetition. */
26
+ function sourceReferences(observations) {
27
+ return [
28
+ ...new Map(observations.map((observation) => [
29
+ sourceReferenceKey(observation),
30
+ { pageId: observation.pageId, sourceRef: observation.sourceRef },
31
+ ])).values(),
32
+ ].toSorted((left, right) => sourceReferenceKey(left).localeCompare(sourceReferenceKey(right)));
33
+ }
34
+ /*** Serializes the two-part observed-node identity only for deterministic deduplication and ordering. */
35
+ function sourceReferenceKey(reference) {
36
+ return `${reference.pageId}\u0000${reference.sourceRef}`;
37
+ }
38
+ /*** Selects only the observations that belong to one factual token family. */
39
+ function tokenObservationsForKind(node, kind) {
40
+ return observationsForKind(node, kind).flatMap((observation) => tokenObservations(observation, kind));
41
+ }
42
+ /*** Retains each exact scalar or spacing-edge literal with its CSS-property ownership. */
43
+ function tokenObservations(observation, kind) {
44
+ if (typeof observation.value === 'string') {
45
+ return [
46
+ { ...sourceReference(observation), property: observation.name, value: observation.value },
47
+ ];
48
+ }
49
+ return kind === 'spacing' ? spacingEdgeTokenObservations(observation) : [];
50
+ }
51
+ /*** Expands a structured margin or padding value into its exact physical-edge token evidence. */
52
+ function spacingEdgeTokenObservations(observation) {
53
+ return isRecord(observation.value)
54
+ ? Object.entries(observation.value).flatMap(([edge, value]) => typeof value === 'string' && ['top', 'right', 'bottom', 'left'].includes(edge)
55
+ ? [{ ...sourceReference(observation), property: `${observation.name}.${edge}`, value }]
56
+ : [])
57
+ : [];
58
+ }
59
+ /*** Extracts the reusable page-qualified source identity from one design property observation. */
60
+ function sourceReference(observation) {
61
+ return { pageId: observation.pageId, sourceRef: observation.sourceRef };
62
+ }
63
+ /*** Selects only the property observations that belong to one factual token family. */
64
+ function observationsForKind(node, kind) {
65
+ switch (kind) {
66
+ case 'color':
67
+ return node.colors.filter((observation) => observation.name !== 'opacity');
68
+ case 'radius':
69
+ return node.layout.filter((observation) => observation.name === 'borderRadius');
70
+ case 'shadow':
71
+ return node.layout.filter((observation) => observation.name === 'boxShadow');
72
+ case 'spacing':
73
+ return node.layout.filter((observation) => ['gap', 'margin', 'padding'].includes(observation.name));
74
+ case 'typography':
75
+ return node.typography;
76
+ }
77
+ }
@@ -0,0 +1,9 @@
1
+ import type { UiNode } from '@ankhorage/contracts';
2
+ import type { WebsiteObservationDocument, WebsitePageRecognition, WebsiteRecognizedNode } from '@ankhorage/contracts/website';
3
+ /*** Recognizes source-linked canonical component trees from validated website observations. */
4
+ export declare function recognizeWebsiteStructure(document: WebsiteObservationDocument): readonly WebsitePageRecognition[];
5
+ export interface RecognizedTreeNode {
6
+ readonly node: WebsiteRecognizedNode;
7
+ readonly nodes: readonly WebsiteRecognizedNode[];
8
+ readonly uiNode: UiNode;
9
+ }
@@ -0,0 +1,209 @@
1
+ import { recognizeWebsiteStructureProps } from './recognizeWebsiteStructureProps';
2
+ import { recognizeWebsiteStructureSemanticComponentType } from './websiteStructureSemantics';
3
+ import { createWebsiteStructureTreeNode } from './websiteStructureTreeNodes';
4
+ /*** Recognizes source-linked canonical component trees from validated website observations. */
5
+ export function recognizeWebsiteStructure(document) {
6
+ return document.pages.map(recognizePage);
7
+ }
8
+ /*** Recognizes one page while retaining every source node in the canonical tree or node mapping. */
9
+ function recognizePage(page) {
10
+ const nodesBySourceRef = new Map(page.nodes.map((node) => [node.sourceRef, node]));
11
+ const childNodesByParent = createChildNodesByParent(page.nodes);
12
+ const rootNodes = page.nodes.filter((node) => node.parentSourceRef === null || !nodesBySourceRef.has(node.parentSourceRef));
13
+ const recognizedNodes = rootNodes.flatMap((node) => recognizeTreeNode(node, nodesBySourceRef, childNodesByParent, node.parentSourceRef, [], []));
14
+ const allRecognitions = page.nodes.reduce((recognitions, node) => containsSourceRef(recognitions, node.sourceRef)
15
+ ? recognitions
16
+ : [
17
+ ...recognitions,
18
+ ...recognizeTreeNode(node, nodesBySourceRef, childNodesByParent, null, [], []),
19
+ ], recognizedNodes);
20
+ return {
21
+ id: page.id,
22
+ nodes: allRecognitions.flatMap((recognition) => recognition.nodes),
23
+ path: page.path,
24
+ root: {
25
+ children: allRecognitions.map((recognition) => recognition.uiNode),
26
+ id: `${page.id}:root`,
27
+ type: 'Container',
28
+ },
29
+ url: page.url,
30
+ };
31
+ }
32
+ /*** Indexes observed children in DOM order for deterministic parent traversal. */
33
+ function createChildNodesByParent(nodes) {
34
+ const entries = nodes.reduce((childrenByParent, node) => {
35
+ if (node.parentSourceRef === null)
36
+ return childrenByParent;
37
+ const siblings = childrenByParent.get(node.parentSourceRef) ?? [];
38
+ return new Map(childrenByParent).set(node.parentSourceRef, [...siblings, node]);
39
+ }, new Map());
40
+ return new Map([...entries].map(([parentSourceRef, children]) => [
41
+ parentSourceRef,
42
+ [...children].sort(compareDomOrder),
43
+ ]));
44
+ }
45
+ /*** Orders source nodes by their observed sibling position and stable source reference. */
46
+ function compareDomOrder(left, right) {
47
+ return (left.dom.childIndex - right.dom.childIndex || left.sourceRef.localeCompare(right.sourceRef));
48
+ }
49
+ /*** Recognizes one node and folds transparent wrappers into their meaningful descendants. */
50
+ function recognizeTreeNode(node, nodesBySourceRef, childNodesByParent, effectiveParentSourceRef, inheritedSourceRefs, ancestorSourceRefs) {
51
+ if (ancestorSourceRefs.includes(node.sourceRef)) {
52
+ return [];
53
+ }
54
+ const children = childNodesByParent.get(node.sourceRef) ?? [];
55
+ if (!isCyclicSourceRef(node, nodesBySourceRef) && isTransparentWrapper(node, children)) {
56
+ return children.flatMap((child) => recognizeTreeNode(child, nodesBySourceRef, childNodesByParent, effectiveParentSourceRef, [...inheritedSourceRefs, node.sourceRef], [...ancestorSourceRefs, node.sourceRef]));
57
+ }
58
+ const childRecognitions = children.flatMap((child) => recognizeTreeNode(child, nodesBySourceRef, childNodesByParent, node.sourceRef, [], [...ancestorSourceRefs, node.sourceRef]));
59
+ return [
60
+ createRecognizedTreeNode(node, nodesBySourceRef.get(effectiveParentSourceRef ?? '') ?? null, childNodesByParent, nodesBySourceRef, inheritedSourceRefs, childRecognitions),
61
+ ];
62
+ }
63
+ /*** Combines component classification, source lineage, and child mappings into one canonical node. */
64
+ function createRecognizedTreeNode(node, parent, childNodesByParent, nodesBySourceRef, inheritedSourceRefs, children) {
65
+ const cyclic = isCyclicSourceRef(node, nodesBySourceRef);
66
+ const componentType = cyclic
67
+ ? 'Unknown'
68
+ : recognizeComponentType(node, parent, childNodesByParent);
69
+ const props = recognizeWebsiteStructureProps(node);
70
+ return createWebsiteStructureTreeNode(node, componentType, [...inheritedSourceRefs, node.sourceRef], props, children, cyclic
71
+ ? 'Source hierarchy contains a cycle.'
72
+ : availableObservation(node) === null
73
+ ? 'No available rendered observation exists for this source node.'
74
+ : 'Visible source node has no canonical component mapping.');
75
+ }
76
+ /*** Tests whether a source reference participates in a parent-reference cycle. */
77
+ function isCyclicSourceRef(node, nodesBySourceRef) {
78
+ const visitedSourceRefs = new Set();
79
+ let currentSourceRef = node.sourceRef;
80
+ while (currentSourceRef !== null) {
81
+ if (visitedSourceRefs.has(currentSourceRef))
82
+ return currentSourceRef === node.sourceRef;
83
+ visitedSourceRefs.add(currentSourceRef);
84
+ currentSourceRef = nodesBySourceRef.get(currentSourceRef)?.parentSourceRef ?? null;
85
+ }
86
+ return false;
87
+ }
88
+ /*** Tests whether already emitted recognitions retain a source reference. */
89
+ function containsSourceRef(recognitions, sourceRef) {
90
+ return recognitions.some((recognition) => recognition.nodes.some((node) => node.sourceRefs.includes(sourceRef)));
91
+ }
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
+ /*** Maps observed DOM semantics and measured layout traits to already representable UI components. */
106
+ function recognizeComponentType(node, parent, childNodesByParent) {
107
+ const observation = availableObservation(node);
108
+ if (observation === null)
109
+ return 'Unknown';
110
+ const tagName = node.dom.tagName.toLowerCase();
111
+ const semanticType = recognizeWebsiteStructureSemanticComponentType(tagName);
112
+ if (semanticType !== null)
113
+ 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
+ const { css } = observation;
123
+ if (css === null)
124
+ return 'Unknown';
125
+ if (css.display.includes('grid'))
126
+ return 'Grid';
127
+ if (css.display.includes('flex'))
128
+ return 'Flex';
129
+ return hasLayoutRole(observation) || hasSurfaceRole(observation) ? 'Container' : 'Unknown';
130
+ }
131
+ /*** Recognizes a card only when a measured sibling group shares explicit surface traits. */
132
+ function isGroupedCard(node, parent, childNodesByParent) {
133
+ if (parent === null || !isLayoutGroup(parent))
134
+ return false;
135
+ const siblings = meaningfulChildren(parent.sourceRef, childNodesByParent);
136
+ return siblings.length >= 2 && siblings.every(isCardSurface) && isCardSurface(node);
137
+ }
138
+ /*** Flattens transparent DOM wrappers before measuring the source siblings in a layout group. */
139
+ function meaningfulChildren(parentSourceRef, childNodesByParent) {
140
+ const children = childNodesByParent.get(parentSourceRef) ?? [];
141
+ return children.flatMap((child) => {
142
+ const nestedChildren = childNodesByParent.get(child.sourceRef) ?? [];
143
+ return isTransparentWrapper(child, nestedChildren)
144
+ ? meaningfulChildren(child.sourceRef, childNodesByParent)
145
+ : [child];
146
+ });
147
+ }
148
+ /*** Tests whether a parent has measured Grid or Flex grouping semantics. */
149
+ function isLayoutGroup(node) {
150
+ const css = availableObservation(node)?.css;
151
+ return css === null || css === undefined ? false : /grid|flex/.test(css.display);
152
+ }
153
+ /*** Requires padding plus radius, border, or shadow so colored columns are not invented as cards. */
154
+ 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)';
209
+ }
@@ -0,0 +1,3 @@
1
+ import type { WebsiteObservedNode, WebsiteRecognizedProp } from '@ankhorage/contracts/website';
2
+ /*** Retains text runs, links, media references, and heading level as source-linked structural props. */
3
+ export declare function recognizeWebsiteStructureProps(node: WebsiteObservedNode): readonly WebsiteRecognizedProp[];
@@ -0,0 +1,36 @@
1
+ /*** Retains text runs, links, media references, and heading level as source-linked structural props. */
2
+ export function recognizeWebsiteStructureProps(node) {
3
+ const textRuns = node.textRuns.map((textRun) => ({
4
+ end: textRun.end,
5
+ sourceRef: textRun.sourceRef,
6
+ start: textRun.start,
7
+ text: textRun.text,
8
+ }));
9
+ const links = node.links.map((link) => ({
10
+ label: link.label,
11
+ sourceRef: link.sourceRef,
12
+ url: link.url,
13
+ }));
14
+ const media = node.media.map((item) => ({
15
+ alt: item.alt,
16
+ assetId: item.assetId,
17
+ kind: item.kind,
18
+ sourceRef: item.sourceRef,
19
+ url: item.url,
20
+ }));
21
+ const headingLevel = headingLevelFor(node.dom.tagName);
22
+ return [
23
+ ...(textRuns.length === 0 ? [] : [recognizedProp('textRuns', textRuns)]),
24
+ ...(links.length === 0 ? [] : [recognizedProp('links', links)]),
25
+ ...(media.length === 0 ? [] : [recognizedProp('media', media)]),
26
+ ...(headingLevel === null ? [] : [recognizedProp('level', headingLevel)]),
27
+ ];
28
+ }
29
+ /*** Creates one serializable recognition prop while retaining the exact source value. */
30
+ function recognizedProp(name, value) {
31
+ return { name, originalValues: [value], value };
32
+ }
33
+ /*** Extracts an explicit heading level only from an observed heading tag. */
34
+ function headingLevelFor(tagName) {
35
+ return /^h[1-6]$/i.test(tagName) ? Number(tagName[1]) : null;
36
+ }
@@ -0,0 +1,2 @@
1
+ /*** Maps explicit HTML semantics without relying on framework or page-builder selectors. */
2
+ export declare function recognizeWebsiteStructureSemanticComponentType(tagName: string): string | null;
@@ -0,0 +1,27 @@
1
+ /*** Maps explicit HTML semantics without relying on framework or page-builder selectors. */
2
+ export function recognizeWebsiteStructureSemanticComponentType(tagName) {
3
+ if (/^h[1-6]$/.test(tagName))
4
+ return 'Heading';
5
+ return semanticComponentTypes.find(([name]) => name === tagName)?.[1] ?? null;
6
+ }
7
+ const semanticComponentTypes = [
8
+ ['a', 'Link'],
9
+ ['article', 'Container'],
10
+ ['audio', 'Media'],
11
+ ['body', 'Container'],
12
+ ['blockquote', 'RichText'],
13
+ ['button', 'Button'],
14
+ ['footer', 'Footer'],
15
+ ['form', 'Form'],
16
+ ['header', 'Header'],
17
+ ['iframe', 'Media'],
18
+ ['img', 'Image'],
19
+ ['label', 'RichText'],
20
+ ['li', 'ListItem'],
21
+ ['main', 'Container'],
22
+ ['ol', 'List'],
23
+ ['p', 'RichText'],
24
+ ['section', 'Section'],
25
+ ['ul', 'List'],
26
+ ['video', 'Media'],
27
+ ];
@@ -0,0 +1,4 @@
1
+ import type { WebsiteObservedNode, WebsiteRecognizedProp } from '@ankhorage/contracts/website';
2
+ import type { RecognizedTreeNode } from './recognizeWebsiteStructure';
3
+ /*** Creates a recognized tree node and retains all descendant source mappings. */
4
+ export declare function createWebsiteStructureTreeNode(node: WebsiteObservedNode, componentType: string, sourceRefs: readonly string[], props: readonly WebsiteRecognizedProp[], children: readonly RecognizedTreeNode[], unresolvedReason: string): RecognizedTreeNode;
@@ -0,0 +1,39 @@
1
+ /*** Creates a recognized tree node and retains all descendant source mappings. */
2
+ export function createWebsiteStructureTreeNode(node, componentType, sourceRefs, props, children, unresolvedReason) {
3
+ const unresolved = componentType === 'Unknown';
4
+ const recognizedNode = {
5
+ componentType,
6
+ confidence: unresolved ? 0 : confidenceFor(componentType),
7
+ id: node.sourceRef,
8
+ props,
9
+ responsive: [],
10
+ sourceRefs,
11
+ status: unresolved ? 'unresolved' : 'recognized',
12
+ unresolved: unresolved ? { reason: unresolvedReason, sourceRefs } : null,
13
+ };
14
+ return {
15
+ node: recognizedNode,
16
+ nodes: [recognizedNode, ...children.flatMap((child) => child.nodes)],
17
+ uiNode: createWebsiteStructureUiNode(node.sourceRef, componentType, props, children),
18
+ };
19
+ }
20
+ /*** Creates a stable source-derived UI node with ordered recognized children. */
21
+ function createWebsiteStructureUiNode(id, componentType, props, children) {
22
+ const uiProps = Object.fromEntries(props.map((prop) => [prop.name, prop.value]));
23
+ return {
24
+ ...(children.length === 0 ? {} : { children: children.map((child) => child.uiNode) }),
25
+ id,
26
+ ...(props.length === 0 ? {} : { props: uiProps }),
27
+ type: componentType,
28
+ };
29
+ }
30
+ /*** Assigns bounded confidence from the evidence class rather than an aesthetic assessment. */
31
+ function confidenceFor(componentType) {
32
+ if (componentType === 'Grid' || componentType === 'Flex')
33
+ return 0.98;
34
+ if (componentType === 'Card')
35
+ return 0.9;
36
+ if (componentType === 'Container')
37
+ return 0.8;
38
+ return 1;
39
+ }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,10 @@ export { designRuleProviderManifest } from './features/catalog/designRuleProvide
4
4
  export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCatalog';
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
+ export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
7
8
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
+ export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
8
10
  export type { DesignAssessmentKind, DesignRuleCatalogEntry, DesignRuleCatalogFilter, DesignRuleEvidence, DesignRulePlanningManifest, DesignRuleProfile, DesignRuleProviderManifest, DesignRuleScope, DesignRuleStatus, } from './types/designRuleCatalog';
9
11
  export type { DesignContext, DesignRuleProfileSelection, DesignRuleProvider, DesignRuleProviderOptions, } from './types/designRuleProvider';
10
12
  export type { WebsiteAssessmentRuleOptions } from './types/websiteAssessment';
13
+ export type { WebsiteDesignNodeRecognition, WebsiteDesignPropertyObservation, WebsiteDesignRecognition, WebsiteDesignSourceReference, WebsiteDesignTokenCandidate, WebsiteDesignUnresolvedObservation, } from './types/websiteDesignRecognition';
package/dist/index.js CHANGED
@@ -4,4 +4,6 @@ export { designRuleProviderManifest } from './features/catalog/designRuleProvide
4
4
  export { filterDesignRuleCatalog } from './features/catalog/filterDesignRuleCatalog';
5
5
  export { createDesignRuleProvider } from './features/provider/designRuleProvider';
6
6
  export { selectDesignRuleProfile } from './features/provider/selectDesignRuleProfile';
7
+ export { recognizeWebsiteDesignProperties } from './features/recognition/recognizeWebsiteDesignProperties';
7
8
  export { createWebsiteAssessmentRuleSet } from './features/website-assessment/createWebsiteAssessmentRuleSet';
9
+ export { recognizeWebsiteStructure } from './features/website-recognition/recognizeWebsiteStructure';
@@ -0,0 +1,54 @@
1
+ import type { SerializableValue } from '@ankhorage/contracts';
2
+ import type { WebsiteMediaReference, WebsiteMissingValue, WebsiteObservationProvenance } from '@ankhorage/contracts/website';
3
+ /*** Identifies one observed DOM node within the page that owns its local source reference. */
4
+ export interface WebsiteDesignSourceReference {
5
+ readonly pageId: string;
6
+ readonly sourceRef: string;
7
+ }
8
+ /*** Describes one exact observed design value without assigning a quality verdict. */
9
+ export interface WebsiteDesignPropertyObservation {
10
+ readonly name: string;
11
+ readonly value: SerializableValue;
12
+ readonly viewportId: string;
13
+ readonly stateId: string;
14
+ readonly sourceRef: string;
15
+ readonly pageId: string;
16
+ readonly provenance: WebsiteObservationProvenance;
17
+ }
18
+ /*** Retains an unavailable observation instead of substituting or silently omitting design evidence. */
19
+ export interface WebsiteDesignUnresolvedObservation {
20
+ readonly kind: 'computed-css' | 'geometry';
21
+ readonly viewportId: string;
22
+ readonly stateId: string;
23
+ readonly sourceRef: string;
24
+ readonly pageId: string;
25
+ readonly provenance: WebsiteObservationProvenance;
26
+ readonly missing: WebsiteMissingValue;
27
+ }
28
+ /*** Groups all factual design observations for one stable observed DOM node. */
29
+ export interface WebsiteDesignNodeRecognition {
30
+ readonly sourceRef: string;
31
+ readonly pageId: string;
32
+ readonly colors: readonly WebsiteDesignPropertyObservation[];
33
+ readonly typography: readonly WebsiteDesignPropertyObservation[];
34
+ readonly layout: readonly WebsiteDesignPropertyObservation[];
35
+ readonly responsive: readonly WebsiteDesignPropertyObservation[];
36
+ readonly accessibility: readonly WebsiteDesignPropertyObservation[];
37
+ readonly media: readonly WebsiteMediaReference[];
38
+ readonly unresolved: readonly WebsiteDesignUnresolvedObservation[];
39
+ }
40
+ /*** Records a repeated observed value as a reusable token candidate without inventing a role. */
41
+ export interface WebsiteDesignTokenCandidate {
42
+ readonly kind: 'color' | 'radius' | 'shadow' | 'spacing' | 'typography';
43
+ readonly property: string;
44
+ readonly value: string;
45
+ readonly originalValues: readonly string[];
46
+ readonly sourceRefs: readonly WebsiteDesignSourceReference[];
47
+ readonly confidence: number;
48
+ readonly inferredRole: null;
49
+ }
50
+ /*** Provides the factual design-property contribution for later website recognition assembly. */
51
+ export interface WebsiteDesignRecognition {
52
+ readonly nodes: readonly WebsiteDesignNodeRecognition[];
53
+ readonly tokenCandidates: readonly WebsiteDesignTokenCandidate[];
54
+ }
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",
@@ -58,7 +58,7 @@
58
58
  "@ankhorage/paradox": "^0.3.6"
59
59
  },
60
60
  "dependencies": {
61
- "@ankhorage/contracts": "^26.4.0",
61
+ "@ankhorage/contracts": "^26.6.0",
62
62
  "@ankhorage/rules": "^0.4.0",
63
63
  "@ankhorage/utility": "^1.10.0"
64
64
  }