@ankhorage/rules-design 0.2.1 → 0.3.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.
Files changed (26) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/features/alignment/createAlignmentRules.d.ts +14 -0
  4. package/dist/features/alignment/createAlignmentRules.js +151 -0
  5. package/dist/features/repetition/createRepetitionRules.d.ts +17 -0
  6. package/dist/features/repetition/createRepetitionRules.js +172 -0
  7. package/dist/features/spacing-proximity/assessSpacingProximityObservation.d.ts +8 -0
  8. package/dist/features/spacing-proximity/assessSpacingProximityObservation.js +294 -0
  9. package/dist/features/spacing-proximity/createSpacingProximityRuleSet.d.ts +4 -0
  10. package/dist/features/spacing-proximity/createSpacingProximityRuleSet.js +86 -0
  11. package/dist/features/spacing-proximity/parseSpacingProximityMeasurements.d.ts +3 -0
  12. package/dist/features/spacing-proximity/parseSpacingProximityMeasurements.js +38 -0
  13. package/dist/features/typography/createTypographyObservationTools.d.ts +18 -0
  14. package/dist/features/typography/createTypographyObservationTools.js +53 -0
  15. package/dist/features/typography/createTypographyRuleSet.d.ts +6 -0
  16. package/dist/features/typography/createTypographyRuleSet.js +114 -0
  17. package/dist/features/typography/parseTypographyObservation.d.ts +3 -0
  18. package/dist/features/typography/parseTypographyObservation.js +62 -0
  19. package/dist/features/typography/validateTypographyRulePolicy.d.ts +3 -0
  20. package/dist/features/typography/validateTypographyRulePolicy.js +68 -0
  21. package/dist/types/designRuleProvider.d.ts +2 -0
  22. package/dist/types/spacingProximity.d.ts +7 -0
  23. package/dist/types/spacingProximity.js +0 -0
  24. package/dist/types/typography.d.ts +35 -0
  25. package/dist/types/typography.js +0 -0
  26. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c1bd0c9: Support normalized versioned facts for Typography and Heading rule evaluation.
8
+
9
+ ## 0.2.2
10
+
11
+ ### Patch Changes
12
+
13
+ - bc8863f: Add the published contracts and utility dependencies required by the alignment rules.
14
+
3
15
  ## 0.2.1
4
16
 
5
17
  ### Patch 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.2.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)
6
+ ![license: MIT](././paradox/badges/license.svg) ![npm: v0.3.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,14 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { Rule } from '@ankhorage/rules';
3
+ /*** Supplies portable layout facts to the Alignment and Layout rule family. */
4
+ export interface AlignmentRuleContext {
5
+ readonly facts: readonly FactEnvelope[];
6
+ }
7
+ type AlignmentRuleId = 'design.alignment.shared-edges' | 'design.alignment.grid-tracks' | 'design.alignment.baselines' | 'design.alignment.text' | 'design.alignment.flex-items' | 'design.alignment.component-axes' | 'design.layout.container-width' | 'design.layout.grid-gap' | 'design.layout.horizontal-overflow' | 'design.layout.vertical-clipping' | 'design.layout.unintended-overlap' | 'design.layout.unnecessary-wrapper' | 'design.layout.visual-balance';
8
+ /*** Configures trusted, group-local acceptance tolerances by frozen Alignment and Layout rule ID. */
9
+ export interface AlignmentRuleOptions {
10
+ readonly tolerances?: Partial<Record<AlignmentRuleId, number>>;
11
+ }
12
+ /*** Creates the independently registrable Alignment and Layout rules without mutating a provider registry. */
13
+ export declare function createAlignmentRules(options?: AlignmentRuleOptions): readonly Rule<AlignmentRuleContext>[];
14
+ export {};
@@ -0,0 +1,151 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ const definitions = [
3
+ metricRule('design.alignment.shared-edges', 'edge-offset', 'Shared visual edges align.'),
4
+ metricRule('design.alignment.grid-tracks', 'grid-track-offset', 'Elements follow grid tracks.'),
5
+ metricRule('design.alignment.baselines', 'baseline-offset', 'Typical baselines align.'),
6
+ metricRule('design.alignment.text', 'text-alignment-offset', 'Text alignment is intentional and consistent.'),
7
+ metricRule('design.alignment.flex-items', 'flex-alignment-offset', 'Flex alignment follows its defined pattern.'),
8
+ metricRule('design.alignment.component-axes', 'component-axis-offset', 'Equivalent components share axes.'),
9
+ metricRule('design.layout.container-width', 'container-width-deviation', 'Container widths obey configured bounds.'),
10
+ metricRule('design.layout.grid-gap', 'grid-gap-deviation', 'Grid gaps follow the system.'),
11
+ {
12
+ ...metricRule('design.layout.horizontal-overflow', 'horizontal-overflow', 'Unexpected horizontal overflow is absent.'),
13
+ capability: 'viewport.layout',
14
+ criterion: 'horizontal overflow',
15
+ },
16
+ {
17
+ ...metricRule('design.layout.vertical-clipping', 'vertical-clipping', 'Unexpected vertical clipping is absent.'),
18
+ criterion: 'vertical clipping',
19
+ },
20
+ {
21
+ ...metricRule('design.layout.unintended-overlap', 'overlap-area', 'Unexpected overlap is absent.'),
22
+ criterion: 'unintended overlap area',
23
+ },
24
+ {
25
+ ...metricRule('design.layout.unnecessary-wrapper', 'avoidable-wrapper-count', 'Avoidable structural wrappers are identified.'),
26
+ assessment: 'heuristic',
27
+ criterion: 'avoidable wrapper count',
28
+ },
29
+ {
30
+ ...metricRule('design.layout.visual-balance', 'visual-weight-imbalance', 'Visual weight is balanced.'),
31
+ assessment: 'heuristic',
32
+ capability: 'rendered.area-analysis',
33
+ criterion: 'visual weight imbalance',
34
+ tolerance: 0.1,
35
+ },
36
+ ];
37
+ /*** Creates the independently registrable Alignment and Layout rules without mutating a provider registry. */
38
+ export function createAlignmentRules(options = {}) {
39
+ return definitions.map((definition) => createAlignmentRule({ ...definition, tolerance: resolveTolerance(definition, options) }));
40
+ }
41
+ /*** Creates one pure rule from its frozen catalog definition. */
42
+ function createAlignmentRule(definition) {
43
+ return {
44
+ defaultSeverity: definition.assessment === 'objective' ? 'warning' : 'info',
45
+ dependencies: [],
46
+ evaluate: (input) => evaluateAlignmentMetric(definition, input),
47
+ facets: [
48
+ { id: 'assessment', value: definition.assessment },
49
+ { id: 'group', value: 'alignment-layout' },
50
+ { id: 'measurement', value: definition.measurement },
51
+ ],
52
+ identity: { id: definition.id, version: '1.0.0' },
53
+ requiredCapabilities: [definition.capability],
54
+ summary: definition.summary,
55
+ };
56
+ }
57
+ /*** Evaluates the normalized metric for one fact at the exact rule scope. */
58
+ function evaluateAlignmentMetric(definition, input) {
59
+ const metric = findAlignmentMetric(input.context.facts, definition, input.scope);
60
+ if (!metric)
61
+ return incompleteOutcome(definition, input);
62
+ if (metric.observed <= definition.tolerance)
63
+ return { findings: [], status: 'PASS' };
64
+ return { findings: [finding(definition, input, metric)], status: 'FAIL' };
65
+ }
66
+ /*** Finds one unambiguous, valid metric fact at the exact active Rules scope. */
67
+ function findAlignmentMetric(facts, definition, scope) {
68
+ const matchingFacts = facts.filter((fact) => fact.kind === definition.id && scopeMatches(fact.scope, scope));
69
+ const metrics = matchingFacts.map((fact) => fact.status === 'available' ? parseMetric(fact.value, definition.measurement) : undefined);
70
+ const [metric, ...otherMetrics] = metrics;
71
+ if (!metric || otherMetrics.some((otherMetric) => !sameMetric(metric, otherMetric))) {
72
+ return undefined;
73
+ }
74
+ return metric;
75
+ }
76
+ /*** Compares the full Rules scope rather than accepting another scope with the same identifier. */
77
+ function scopeMatches(factScope, scope) {
78
+ return factScope.id === scope.id && factScope.kind === scope.kind;
79
+ }
80
+ /*** Validates the group-local observed geometry payload without trusting adapter acceptance criteria. */
81
+ function parseMetric(value, measurement) {
82
+ if (!isRecord(value))
83
+ return undefined;
84
+ const { measurement: candidateMeasurement, observed, subjectIds } = value;
85
+ if (candidateMeasurement !== measurement ||
86
+ typeof observed !== 'number' ||
87
+ !Number.isFinite(observed) ||
88
+ observed < 0 ||
89
+ !Array.isArray(subjectIds) ||
90
+ subjectIds.length === 0 ||
91
+ !subjectIds.every((id) => typeof id === 'string' && id.trim().length > 0) ||
92
+ new Set(subjectIds).size !== subjectIds.length) {
93
+ return undefined;
94
+ }
95
+ return { measurement, observed, subjectIds };
96
+ }
97
+ /*** Requires duplicate facts to state the same complete normalized observation. */
98
+ function sameMetric(metric, otherMetric) {
99
+ return (otherMetric?.measurement === metric.measurement &&
100
+ metric.observed === otherMetric.observed &&
101
+ metric.subjectIds.length === otherMetric.subjectIds.length &&
102
+ metric.subjectIds.every((subjectId, index) => subjectId === otherMetric.subjectIds.at(index)));
103
+ }
104
+ /*** Produces an explicit incomplete result when an adapter supplied no usable metric. */
105
+ function incompleteOutcome(definition, input) {
106
+ return {
107
+ findings: [
108
+ {
109
+ evidence: { scopeId: input.scope.id },
110
+ message: `${definition.summary} No available normalized metric was supplied for this scope.`,
111
+ ruleId: definition.id,
112
+ severity: 'info',
113
+ subjects: [{ id: input.scope.id, kind: input.scope.kind }],
114
+ },
115
+ ],
116
+ status: 'INCOMPLETE',
117
+ };
118
+ }
119
+ /*** Describes an observation that exceeds this rule's trusted acceptance tolerance. */
120
+ function finding(definition, input, metric) {
121
+ return {
122
+ evidence: {
123
+ observed: metric.observed,
124
+ tolerance: definition.tolerance,
125
+ },
126
+ message: `${definition.summary} Observed ${definition.criterion} ${metric.observed} exceeds tolerance ${definition.tolerance}.`,
127
+ ruleId: definition.id,
128
+ severity: definition.assessment === 'objective' ? 'warning' : 'info',
129
+ subjects: metric.subjectIds.map((id) => ({ id, kind: input.scope.kind })),
130
+ };
131
+ }
132
+ /*** Resolves a trusted policy override and rejects invalid acceptance thresholds at the factory boundary. */
133
+ function resolveTolerance(definition, options) {
134
+ const tolerance = options.tolerances?.[definition.id] ?? definition.tolerance;
135
+ if (!Number.isFinite(tolerance) || tolerance < 0) {
136
+ throw new TypeError(`Tolerance for "${definition.id}" must be a finite non-negative number.`);
137
+ }
138
+ return tolerance;
139
+ }
140
+ /*** Builds one objective layout metric rule definition with a zero-deviation semantic default. */
141
+ function metricRule(id, measurement, summary) {
142
+ return {
143
+ assessment: 'objective',
144
+ capability: 'dom.layout',
145
+ criterion: 'layout deviation',
146
+ id,
147
+ measurement,
148
+ summary,
149
+ tolerance: 0,
150
+ };
151
+ }
@@ -0,0 +1,17 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { Rule } from '@ankhorage/rules';
3
+ declare const repetitionRuleDefinitions: readonly [readonly ["design.repetition.button-variants", "Button variants are consistent."], readonly ["design.repetition.card-variants", "Card variants and templates are consistent."], readonly ["design.repetition.heading-variants", "Heading roles are consistent."], readonly ["design.repetition.form-control-style", "Form controls are consistently styled."], readonly ["design.repetition.link-treatment", "Link treatment is consistent."], readonly ["design.repetition.navigation-treatment", "Navigation treatment is consistent."], readonly ["design.repetition.icons", "Icon size and style are consistent."], readonly ["design.repetition.border-radius", "Border radii follow tokens and variants."], readonly ["design.repetition.border-weight", "Border weights are consistent."], readonly ["design.repetition.elevation", "Shadows and elevation are consistent."], readonly ["design.repetition.motion", "Motion patterns are consistent."], readonly ["design.repetition.local-overrides", "Unwanted local overrides are identified."], readonly ["design.repetition.template-drift", "Instances do not drift from their template."]];
4
+ type RepetitionRuleId = (typeof repetitionRuleDefinitions)[number][0];
5
+ type RepetitionRule = Rule<RepetitionRuleContext> & {
6
+ readonly identity: {
7
+ readonly id: RepetitionRuleId;
8
+ readonly version: '1.0.0';
9
+ };
10
+ };
11
+ /*** Creates the atomic Repetition and Components Rules from normalized inspected facts. */
12
+ export declare function createRepetitionRules(): readonly RepetitionRule[];
13
+ /*** Supplies immutable FactEnvelope observations without coupling Rules to a browser host. */
14
+ export interface RepetitionRuleContext {
15
+ readonly facts: readonly FactEnvelope[];
16
+ }
17
+ export {};
@@ -0,0 +1,172 @@
1
+ import { isSerializableValue } from '@ankhorage/contracts';
2
+ const repetitionRuleDefinitions = [
3
+ ['design.repetition.button-variants', 'Button variants are consistent.'],
4
+ ['design.repetition.card-variants', 'Card variants and templates are consistent.'],
5
+ ['design.repetition.heading-variants', 'Heading roles are consistent.'],
6
+ ['design.repetition.form-control-style', 'Form controls are consistently styled.'],
7
+ ['design.repetition.link-treatment', 'Link treatment is consistent.'],
8
+ ['design.repetition.navigation-treatment', 'Navigation treatment is consistent.'],
9
+ ['design.repetition.icons', 'Icon size and style are consistent.'],
10
+ ['design.repetition.border-radius', 'Border radii follow tokens and variants.'],
11
+ ['design.repetition.border-weight', 'Border weights are consistent.'],
12
+ ['design.repetition.elevation', 'Shadows and elevation are consistent.'],
13
+ ['design.repetition.motion', 'Motion patterns are consistent.'],
14
+ ['design.repetition.local-overrides', 'Unwanted local overrides are identified.'],
15
+ ['design.repetition.template-drift', 'Instances do not drift from their template.'],
16
+ ];
17
+ /*** Creates the atomic Repetition and Components Rules from normalized inspected facts. */
18
+ export function createRepetitionRules() {
19
+ return repetitionRuleDefinitions.map(([id, summary]) => createRepetitionRule(id, summary));
20
+ }
21
+ /*** Constructs one fact-driven Repetition rule with the catalog's component-tree capability. */
22
+ function createRepetitionRule(id, summary) {
23
+ return {
24
+ defaultSeverity: 'warning',
25
+ dependencies: [],
26
+ evaluate: ({ context, scope }) => evaluateRepetitionFacts(id, context.facts, scope),
27
+ facets: [{ id: 'principle', value: 'repetition' }],
28
+ identity: { id, version: '1.0.0' },
29
+ requiredCapabilities: ['ui.component-tree'],
30
+ summary,
31
+ };
32
+ }
33
+ /*** Evaluates inspected facts for one rule without treating absent scope evidence as a pass. */
34
+ function evaluateRepetitionFacts(ruleId, facts, scope) {
35
+ const scopedFacts = facts.filter((fact) => isRepetitionFactForScope(fact, ruleId, scope));
36
+ const normalizedFacts = scopedFacts
37
+ .filter((fact) => fact.status === 'available')
38
+ .map((fact) => ({ fact, observation: normalizeRepetitionObservation(fact) }));
39
+ const observations = normalizedFacts.flatMap(({ fact, observation }) => observation !== null && observation.ruleId === ruleId ? [{ fact, observation }] : []);
40
+ if (scopedFacts.length === 0 || observations.length !== scopedFacts.length) {
41
+ return {
42
+ findings: [
43
+ {
44
+ evidence: { factCount: 0, scopeId: scope.id },
45
+ message: `Rule "${ruleId}" requires an available normalized component observation for scope "${scope.id}".`,
46
+ ruleId,
47
+ severity: 'warning',
48
+ subjects: [{ id: scope.id, kind: scope.kind }],
49
+ },
50
+ ],
51
+ status: 'INCOMPLETE',
52
+ };
53
+ }
54
+ const findings = observations
55
+ .filter(({ observation }) => !isSameJsonValue(observation.actual, observation.expected))
56
+ .map(({ fact, observation }) => ({
57
+ evidence: { actual: observation.actual, expected: observation.expected, factId: fact.id },
58
+ message: `Observed value for "${observation.subject.id}" does not match the expected repeated value.`,
59
+ ruleId,
60
+ severity: 'warning',
61
+ subjects: [observation.subject],
62
+ }));
63
+ return { findings, status: findings.length === 0 ? 'PASS' : 'FAIL' };
64
+ }
65
+ /*** Accepts only the provider's component-observation envelopes for the exact evaluation scope. */
66
+ function isRepetitionFactForScope(fact, ruleId, scope) {
67
+ return (fact.kind === 'design.repetition.observation' &&
68
+ fact.id.startsWith(`${ruleId}:`) &&
69
+ fact.scope.id === scope.id &&
70
+ fact.scope.kind === scope.kind);
71
+ }
72
+ /*** Validates the normalized portable observation payload before repetition policy consumes it. */
73
+ function normalizeRepetitionObservation(fact) {
74
+ if (!isValidFactEnvelope(fact) || fact.status !== 'available' || !isRecord(fact.value)) {
75
+ return null;
76
+ }
77
+ const { actual, expected, ruleId, subject } = fact.value;
78
+ return isRepetitionRuleId(ruleId) &&
79
+ isRuleSubject(subject) &&
80
+ isSerializableValue(actual) &&
81
+ isSerializableValue(expected)
82
+ ? { actual, expected, ruleId, subject }
83
+ : null;
84
+ }
85
+ /*** Verifies that required FactEnvelope identity, scope, provenance, availability, and hash fields are usable. */
86
+ function isValidFactEnvelope(fact) {
87
+ return (hasValidFactIdentity(fact) &&
88
+ hasValidFactScope(fact) &&
89
+ hasValidFactProvenance(fact) &&
90
+ hasValidFactAvailability(fact));
91
+ }
92
+ /*** Verifies stable identity fields and content integrity metadata on one portable fact. */
93
+ function hasValidFactIdentity(fact) {
94
+ return hasText(fact.id) && hasText(fact.kind) && hasText(fact.contentHash);
95
+ }
96
+ /*** Verifies the complete target partition attached to one portable fact scope. */
97
+ function hasValidFactScope(fact) {
98
+ return (hasText(fact.scope.id) &&
99
+ hasText(fact.scope.kind) &&
100
+ hasText(fact.scope.target.tenantId) &&
101
+ hasText(fact.scope.target.projectId) &&
102
+ hasText(fact.scope.target.targetId) &&
103
+ hasText(fact.scope.target.kind));
104
+ }
105
+ /*** Verifies that a portable fact retains a traceable producer and inspected source. */
106
+ function hasValidFactProvenance(fact) {
107
+ return (hasText(fact.provenance.collectedAt) &&
108
+ hasText(fact.provenance.producer.id) &&
109
+ hasText(fact.provenance.producer.version) &&
110
+ hasText(fact.provenance.source.id) &&
111
+ (fact.provenance.source.revision === null || hasText(fact.provenance.source.revision)));
112
+ }
113
+ /*** Verifies that available values and unavailable reasons remain explicitly represented. */
114
+ function hasValidFactAvailability(fact) {
115
+ return fact.status === 'available'
116
+ ? isSerializableValue(fact.value)
117
+ : hasText(fact.missing.code) && hasText(fact.missing.message);
118
+ }
119
+ /*** Narrows a non-empty serializable text field without accepting whitespace-only identities. */
120
+ function hasText(value) {
121
+ return value.trim().length > 0;
122
+ }
123
+ /*** Narrows one observation rule identifier to the frozen Repetition catalog. */
124
+ function isRepetitionRuleId(value) {
125
+ return typeof value === 'string' && repetitionRuleDefinitions.some(([id]) => id === value);
126
+ }
127
+ /*** Narrows an observation subject without admitting anonymous or host-specific values. */
128
+ function isRuleSubject(value) {
129
+ return (isRecord(value) &&
130
+ typeof value.id === 'string' &&
131
+ typeof value.kind === 'string' &&
132
+ hasText(value.id) &&
133
+ hasText(value.kind));
134
+ }
135
+ /*** Narrows an unknown JSON value to a non-array record before reading named fields. */
136
+ function isRecord(value) {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
138
+ }
139
+ /*** Compares normalized JSON facts structurally so host-specific object identity cannot affect results. */
140
+ function isSameJsonValue(left, right) {
141
+ if (left === right)
142
+ return true;
143
+ if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
144
+ return false;
145
+ }
146
+ if (isJsonArray(left)) {
147
+ return isJsonArray(right) && isSameJsonArray(left, right);
148
+ }
149
+ if (isJsonArray(right))
150
+ return false;
151
+ const leftEntries = Object.entries(left).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));
152
+ const rightEntries = Object.entries(right).sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey));
153
+ return (leftEntries.length === rightEntries.length &&
154
+ leftEntries.every(([leftKey, leftValue], index) => {
155
+ const rightEntry = rightEntries.at(index);
156
+ if (rightEntry === undefined)
157
+ return false;
158
+ return leftKey === rightEntry[0] && isSameJsonValue(leftValue, rightEntry[1]);
159
+ }));
160
+ }
161
+ /*** Narrows one serializable JSON value to an ordered JSON array. */
162
+ function isJsonArray(value) {
163
+ return Array.isArray(value);
164
+ }
165
+ /*** Compares JSON arrays in order without relying on host object identity. */
166
+ function isSameJsonArray(left, right) {
167
+ return (left.length === right.length &&
168
+ left.every((value, index) => {
169
+ const rightValue = right.at(index);
170
+ return rightValue !== undefined && isSameJsonValue(value, rightValue);
171
+ }));
172
+ }
@@ -0,0 +1,8 @@
1
+ import type { SpacingProximityObservation } from '../../types/spacingProximity';
2
+ interface Failure {
3
+ readonly message: string;
4
+ readonly values: readonly number[];
5
+ }
6
+ /*** Applies the frozen rule-specific policy to complete normalized adapter evidence. */
7
+ export declare function assessSpacingProximityObservation(observation: SpacingProximityObservation): Failure | null | undefined;
8
+ export {};
@@ -0,0 +1,294 @@
1
+ /*** Applies the frozen rule-specific policy to complete normalized adapter evidence. */
2
+ export function assessSpacingProximityObservation(observation) {
3
+ const { value } = observation;
4
+ switch (observation.kind) {
5
+ case 'design.spacing.token-allowed':
6
+ return tokens(value);
7
+ case 'design.spacing.vertical-rhythm':
8
+ return rhythm(value);
9
+ case 'design.spacing.section-gap':
10
+ return allowed(value, 'Section gaps include a value outside the permitted spacing values.');
11
+ case 'design.spacing.container-padding':
12
+ return padding(value);
13
+ case 'design.proximity.related-grouping':
14
+ return related(value);
15
+ case 'design.proximity.unrelated-separation':
16
+ return unrelated(value);
17
+ case 'design.proximity.label-control':
18
+ return pairs(value, 'Labels are farther from their controls than unrelated content.');
19
+ case 'design.proximity.heading-content':
20
+ return pairs(value, 'Headings are farther from their content than unrelated content.');
21
+ case 'design.proximity.card-internals':
22
+ return card(value);
23
+ case 'design.spacing.double-application':
24
+ return doubled(value);
25
+ case 'design.spacing.unexpected-collapse':
26
+ return collapsed(value);
27
+ }
28
+ }
29
+ /*** Confirms each used token name and value exists in the permitted token inventory. */
30
+ function tokens(value) {
31
+ const source = record(value);
32
+ const permitted = source === undefined ? undefined : tokenList(source.permittedTokens);
33
+ const usages = source === undefined ? undefined : tokenList(source.tokenUsages);
34
+ if (permitted === undefined || usages === undefined)
35
+ return undefined;
36
+ const invalid = usages.find((usage) => !permitted.some((token) => token.name === usage.name && token.value === usage.value));
37
+ return invalid === undefined
38
+ ? null
39
+ : {
40
+ message: `Spacing token "${invalid.name}" is not permitted at its measured value.`,
41
+ values: [invalid.value],
42
+ };
43
+ }
44
+ /*** Confirms measured vertical gaps are whole units of the supplied rhythm. */
45
+ function rhythm(value) {
46
+ const source = record(value);
47
+ const gaps = source === undefined ? undefined : numbers(source.gaps);
48
+ const unit = source?.rhythmUnit;
49
+ if (gaps === undefined || !positive(unit))
50
+ return undefined;
51
+ const invalid = gaps.find((gap) => gap % unit !== 0);
52
+ return invalid === undefined
53
+ ? null
54
+ : {
55
+ message: 'A measured vertical gap is not a whole multiple of the rhythm unit.',
56
+ values: [invalid, unit],
57
+ };
58
+ }
59
+ /*** Confirms each measured gap is a permitted spacing value. */
60
+ function allowed(value, message) {
61
+ const source = record(value);
62
+ const gaps = source === undefined ? undefined : numbers(source.gaps);
63
+ const permitted = source === undefined ? undefined : numbers(source.permittedValues);
64
+ if (gaps === undefined || permitted === undefined)
65
+ return undefined;
66
+ const invalid = gaps.find((gap) => !permitted.includes(gap));
67
+ return invalid === undefined ? null : { message, values: [invalid] };
68
+ }
69
+ /*** Confirms all four measured container edges use permitted padding values. */
70
+ function padding(value) {
71
+ const source = record(value);
72
+ const permitted = source === undefined ? undefined : numbers(source.permittedValues);
73
+ const containers = source?.containers;
74
+ if (permitted === undefined || !Array.isArray(containers) || containers.length === 0)
75
+ return undefined;
76
+ const values = containers.flatMap(edges);
77
+ if (values.length !== containers.length * 4)
78
+ return undefined;
79
+ const invalid = values.find((item) => !permitted.includes(item));
80
+ return invalid === undefined
81
+ ? null
82
+ : {
83
+ message: 'Container padding includes a value outside the permitted spacing values.',
84
+ values: [invalid],
85
+ };
86
+ }
87
+ /*** Confirms related members are no farther apart than their nearest unrelated group. */
88
+ function related(value) {
89
+ const groups = relatedGroups(value);
90
+ if (groups === undefined)
91
+ return undefined;
92
+ const invalid = groups.find((group) => group.distances.some((distance) => distance > group.reference));
93
+ return invalid === undefined
94
+ ? null
95
+ : {
96
+ message: 'A related group has a larger internal distance than its nearest unrelated group.',
97
+ values: [...invalid.distances, invalid.reference],
98
+ };
99
+ }
100
+ /*** Confirms unrelated groups exceed every internal grouping distance. */
101
+ function unrelated(value) {
102
+ const groups = unrelatedGroups(value);
103
+ if (groups === undefined)
104
+ return undefined;
105
+ const invalid = groups.find((group) => group.distances.some((distance) => distance >= group.reference));
106
+ return invalid === undefined
107
+ ? null
108
+ : {
109
+ message: 'An unrelated group is not separated beyond its internal grouping distances.',
110
+ values: [...invalid.distances, invalid.reference],
111
+ };
112
+ }
113
+ /*** Confirms each label-control or heading-content pair beats its unrelated distance. */
114
+ function pairs(value, message) {
115
+ const groups = relatedGroups(value);
116
+ if (groups === undefined || groups.some((group) => group.distances.length !== 1))
117
+ return undefined;
118
+ const invalid = groups.find((group) => (group.distances[0] ?? 0) > group.reference);
119
+ return invalid === undefined
120
+ ? null
121
+ : { message, values: [invalid.distances[0] ?? 0, invalid.reference] };
122
+ }
123
+ /*** Confirms card internals remain closer than outside content. */
124
+ function card(value) {
125
+ const cards = cardGroups(value);
126
+ if (cards === undefined)
127
+ return undefined;
128
+ const invalid = cards.find((item) => item.distances.some((distance) => distance > item.reference));
129
+ return invalid === undefined
130
+ ? null
131
+ : {
132
+ message: 'A card internal distance exceeds the measured distance to outside content.',
133
+ values: [...invalid.distances, invalid.reference],
134
+ };
135
+ }
136
+ /*** Detects cumulative parent and child spacing in a rendered distance. */
137
+ function doubled(value) {
138
+ const triples = spacingTriples(value);
139
+ if (triples === undefined)
140
+ return undefined;
141
+ const invalid = triples.find((item) => item.third > Math.max(item.first, item.second));
142
+ return invalid === undefined
143
+ ? null
144
+ : {
145
+ message: 'Parent and child spacing accumulate into a larger rendered distance.',
146
+ values: [invalid.first, invalid.second, invalid.third],
147
+ };
148
+ }
149
+ /*** Detects a collapsed gap where structure proves margins should remain separated. */
150
+ function collapsed(value) {
151
+ const source = record(value);
152
+ const pairs = source?.pairs;
153
+ if (!Array.isArray(pairs) || pairs.length === 0)
154
+ return undefined;
155
+ const margins = pairs.map(collapse);
156
+ if (margins.some((margin) => margin === undefined))
157
+ return undefined;
158
+ const invalid = margins.find((margin) => margin?.separates && margin.rendered < margin.preceding + margin.following);
159
+ return invalid === undefined
160
+ ? null
161
+ : {
162
+ message: 'A structurally separated margin pair has a collapsed rendered distance.',
163
+ values: [invalid.preceding, invalid.following, invalid.rendered],
164
+ };
165
+ }
166
+ /*** Parses a finite non-negative measurement list. */
167
+ function numbers(value) {
168
+ return Array.isArray(value) && value.length > 0 && value.every(measurement) ? value : undefined;
169
+ }
170
+ /*** Parses named spacing tokens. */
171
+ function tokenList(value) {
172
+ return Array.isArray(value) && value.length > 0 && value.every(token) ? value : undefined;
173
+ }
174
+ /*** Parses a four-edge padding measurement. */
175
+ function edges(value) {
176
+ return isRecord(value) &&
177
+ measurement(value.top) &&
178
+ measurement(value.right) &&
179
+ measurement(value.bottom) &&
180
+ measurement(value.left)
181
+ ? [value.top, value.right, value.bottom, value.left]
182
+ : [];
183
+ }
184
+ /*** Parses groups of related distances and their nearest unrelated distance. */
185
+ function relatedGroups(value) {
186
+ const source = record(value);
187
+ const collection = source?.groups;
188
+ if (!Array.isArray(collection) || collection.length === 0)
189
+ return undefined;
190
+ const groups = collection.map((item) => {
191
+ const itemRecord = record(item);
192
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.relatedDistances);
193
+ const reference = itemRecord?.nearestUnrelatedDistance;
194
+ return distances === undefined || !measurement(reference)
195
+ ? undefined
196
+ : { distances, reference };
197
+ });
198
+ return groups.every(group) ? groups : undefined;
199
+ }
200
+ /*** Parses groups of internal distances and their unrelated-group distance. */
201
+ function unrelatedGroups(value) {
202
+ const source = record(value);
203
+ const collection = source?.groups;
204
+ if (!Array.isArray(collection) || collection.length === 0)
205
+ return undefined;
206
+ const groups = collection.map((item) => {
207
+ const itemRecord = record(item);
208
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.internalDistances);
209
+ const reference = itemRecord?.unrelatedDistance;
210
+ return distances === undefined || !measurement(reference)
211
+ ? undefined
212
+ : { distances, reference };
213
+ });
214
+ return groups.every(group) ? groups : undefined;
215
+ }
216
+ /*** Parses card-internal distances and their nearest outside-content distance. */
217
+ function cardGroups(value) {
218
+ const source = record(value);
219
+ const collection = source?.cards;
220
+ if (!Array.isArray(collection) || collection.length === 0)
221
+ return undefined;
222
+ const groups = collection.map((item) => {
223
+ const itemRecord = record(item);
224
+ const distances = itemRecord === undefined ? undefined : numbers(itemRecord.internalDistances);
225
+ const reference = itemRecord?.nearestOutsideDistance;
226
+ return distances === undefined || !measurement(reference)
227
+ ? undefined
228
+ : { distances, reference };
229
+ });
230
+ return groups.every(group) ? groups : undefined;
231
+ }
232
+ /*** Parses raw parent, child, and rendered spacing measurements. */
233
+ function spacingTriples(value) {
234
+ const source = record(value);
235
+ const pairs = source?.pairs;
236
+ if (!Array.isArray(pairs) || pairs.length === 0)
237
+ return undefined;
238
+ const triples = pairs.map((item) => {
239
+ const itemRecord = record(item);
240
+ const first = itemRecord?.parentSpacing;
241
+ const second = itemRecord?.childSpacing;
242
+ const third = itemRecord?.renderedDistance;
243
+ return measurement(first) && measurement(second) && measurement(third)
244
+ ? { first, second, third }
245
+ : undefined;
246
+ });
247
+ return triples.every(isTriple) ? triples : undefined;
248
+ }
249
+ /*** Parses one margin pair and its structural relationship. */
250
+ function collapse(value) {
251
+ return isRecord(value) &&
252
+ measurement(value.precedingMargin) &&
253
+ measurement(value.followingMargin) &&
254
+ measurement(value.renderedDistance) &&
255
+ typeof value.separatesMargins === 'boolean'
256
+ ? {
257
+ following: value.followingMargin,
258
+ preceding: value.precedingMargin,
259
+ rendered: value.renderedDistance,
260
+ separates: value.separatesMargins,
261
+ }
262
+ : undefined;
263
+ }
264
+ /*** Narrows a record-shaped serializable value. */
265
+ function record(value) {
266
+ return isRecord(value) ? value : undefined;
267
+ }
268
+ /*** Narrows a token record. */
269
+ function token(value) {
270
+ return (isRecord(value) &&
271
+ typeof value.name === 'string' &&
272
+ value.name.length > 0 &&
273
+ measurement(value.value));
274
+ }
275
+ /*** Narrows a complete parsed group. */
276
+ function group(value) {
277
+ return value !== undefined;
278
+ }
279
+ /*** Narrows a complete parsed spacing triple. */
280
+ function isTriple(value) {
281
+ return value !== undefined;
282
+ }
283
+ /*** Narrows a serializable record. */
284
+ function isRecord(value) {
285
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
286
+ }
287
+ /*** Narrows a finite non-negative layout measurement. */
288
+ function measurement(value) {
289
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
290
+ }
291
+ /*** Narrows a finite positive layout measurement. */
292
+ function positive(value) {
293
+ return measurement(value) && value > 0;
294
+ }
@@ -0,0 +1,4 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
2
+ import type { RuleSet } from '@ankhorage/rules';
3
+ /*** Creates the independently owned Spacing and Proximity Rules contribution. */
4
+ export declare function createSpacingProximityRuleSet(): RuleSet<readonly FactEnvelope[]>;
@@ -0,0 +1,86 @@
1
+ import { assessSpacingProximityObservation } from './assessSpacingProximityObservation';
2
+ import { parseSpacingProximityMeasurements } from './parseSpacingProximityMeasurements';
3
+ /*** Creates the independently owned Spacing and Proximity Rules contribution. */
4
+ export function createSpacingProximityRuleSet() {
5
+ return { id: 'ankhorage.rules-design.spacing-proximity', rules: definitions.map(createRule) };
6
+ }
7
+ const factKind = 'design.spacing-proximity.measurements';
8
+ const definitions = [
9
+ ['design.spacing.token-allowed', 'source.style-tokens', 'project', 'error', 'spacing'],
10
+ ['design.spacing.vertical-rhythm', 'dom.layout', 'component', 'error', 'spacing'],
11
+ ['design.spacing.section-gap', 'dom.layout', 'component', 'error', 'spacing'],
12
+ ['design.spacing.container-padding', 'dom.layout', 'component', 'error', 'spacing'],
13
+ ['design.proximity.related-grouping', 'dom.layout', 'component', 'warning', 'proximity'],
14
+ ['design.proximity.unrelated-separation', 'dom.layout', 'component', 'warning', 'proximity'],
15
+ ['design.proximity.label-control', 'dom.layout', 'component', 'error', 'proximity'],
16
+ ['design.proximity.heading-content', 'dom.layout', 'component', 'error', 'proximity'],
17
+ ['design.proximity.card-internals', 'dom.layout', 'component', 'error', 'proximity'],
18
+ ['design.spacing.double-application', 'dom.layout', 'component', 'error', 'spacing'],
19
+ ['design.spacing.unexpected-collapse', 'dom.layout', 'component', 'error', 'spacing'],
20
+ ].map(([id, capability, scopeKind, severity, topic]) => ({
21
+ capability,
22
+ id,
23
+ scopeKind,
24
+ severity,
25
+ topic,
26
+ }));
27
+ /*** Creates one deterministic rule from its frozen catalog definition. */
28
+ function createRule(definition) {
29
+ return {
30
+ defaultSeverity: definition.severity,
31
+ dependencies: [],
32
+ evaluate: ({ context, scope }) => evaluate(context, definition, scope),
33
+ facets: facets(definition),
34
+ identity: { id: definition.id, version: '1.0.0' },
35
+ requiredCapabilities: [definition.capability],
36
+ summary: `Evaluate ${definition.id} from supplied normalized measurements.`,
37
+ };
38
+ }
39
+ /*** Evaluates one rule from normalized evidence, never from an adapter-supplied verdict. */
40
+ function evaluate(facts, definition, scope) {
41
+ const fact = matchingFact(facts, scope);
42
+ if (fact === null || fact.status === 'missing')
43
+ return incomplete();
44
+ const observations = parseSpacingProximityMeasurements(fact.value)?.filter((candidate) => candidate.kind === definition.id);
45
+ if (observations === undefined || observations.length === 0)
46
+ return incomplete();
47
+ const assessments = observations.map(assessSpacingProximityObservation);
48
+ if (assessments.some((assessment) => assessment === undefined))
49
+ return incomplete();
50
+ const failures = assessments.filter((assessment) => assessment !== null);
51
+ if (failures.length === 0)
52
+ return { findings: [], status: 'PASS' };
53
+ return failures.length === assessments.length
54
+ ? failed(definition, fact, scope, failures)
55
+ : incomplete();
56
+ }
57
+ /*** Selects exactly one scope-local fact to prevent ambiguous evidence from passing. */
58
+ function matchingFact(facts, scope) {
59
+ const matches = facts.filter((fact) => fact.kind === factKind && fact.scope.id === scope.id && fact.scope.kind === scope.kind);
60
+ return matches.length === 1 ? (matches[0] ?? null) : null;
61
+ }
62
+ /*** Produces an evidence-backed failure without accepting an adapter-provided pass or fail state. */
63
+ function failed(definition, fact, scope, failures) {
64
+ return {
65
+ findings: failures.map((failure) => ({
66
+ evidence: { factId: fact.id, scopeId: scope.id, values: failure.values },
67
+ message: failure.message,
68
+ ruleId: definition.id,
69
+ severity: definition.severity,
70
+ subjects: [{ id: scope.id, kind: scope.kind }],
71
+ })),
72
+ status: 'FAIL',
73
+ };
74
+ }
75
+ /*** Produces an incomplete result whenever factual measurements cannot be established. */
76
+ function incomplete() {
77
+ return { findings: [], status: 'INCOMPLETE' };
78
+ }
79
+ /*** Creates controlled rule facets for capability consumers and catalog queries. */
80
+ function facets(definition) {
81
+ return [
82
+ { id: 'principle', value: 'proximity' },
83
+ { id: 'scope', value: definition.scopeKind },
84
+ { id: 'topic', value: definition.topic },
85
+ ];
86
+ }
@@ -0,0 +1,3 @@
1
+ import type { SpacingProximityObservation } from '../../types/spacingProximity';
2
+ /*** Parses a complete versioned sequence of raw spacing and proximity observations. */
3
+ export declare function parseSpacingProximityMeasurements(value: unknown): readonly SpacingProximityObservation[] | undefined;
@@ -0,0 +1,38 @@
1
+ /*** Parses a complete versioned sequence of raw spacing and proximity observations. */
2
+ export function parseSpacingProximityMeasurements(value) {
3
+ if (!isRecord(value) || value.schemaVersion !== 2 || !Array.isArray(value.observations))
4
+ return undefined;
5
+ const observations = value.observations.map(parseObservation);
6
+ return observations.every(isObservation) ? observations : undefined;
7
+ }
8
+ /*** Parses one adapter observation containing a frozen rule ID and raw serializable evidence. */
9
+ function parseObservation(value) {
10
+ if (!isRecord(value) || !isRuleId(value.kind) || value.value === undefined)
11
+ return undefined;
12
+ return { kind: value.kind, value: value.value };
13
+ }
14
+ /*** Narrows a parsed value to a complete spacing or proximity observation. */
15
+ function isObservation(value) {
16
+ return value !== undefined;
17
+ }
18
+ /*** Narrows a serializable unknown value to a record without assuming a prototype. */
19
+ function isRecord(value) {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
21
+ }
22
+ /*** Narrows the only frozen rule IDs permitted in this group-local evidence schema. */
23
+ function isRuleId(value) {
24
+ return (typeof value === 'string' &&
25
+ [
26
+ 'design.spacing.token-allowed',
27
+ 'design.spacing.vertical-rhythm',
28
+ 'design.spacing.section-gap',
29
+ 'design.spacing.container-padding',
30
+ 'design.proximity.related-grouping',
31
+ 'design.proximity.unrelated-separation',
32
+ 'design.proximity.label-control',
33
+ 'design.proximity.heading-content',
34
+ 'design.proximity.card-internals',
35
+ 'design.spacing.double-application',
36
+ 'design.spacing.unexpected-collapse',
37
+ ].includes(value));
38
+ }
@@ -0,0 +1,18 @@
1
+ import type { TypographyObservation } from '../../types/typography';
2
+ /*** Creates the shared completeness and viewport grouping operations for Typography evidence. */
3
+ export declare function createTypographyObservationTools(): {
4
+ measurementsComplete: typeof measurementsComplete;
5
+ orderedHeadings: typeof orderedHeadings;
6
+ viewports: typeof viewports;
7
+ };
8
+ type TypographyMeasurement = keyof TypographyObservation;
9
+ /*** Checks required measurements and document-order uniqueness when a rule needs it. */
10
+ declare function measurementsComplete(observations: readonly TypographyObservation[], measurements: readonly TypographyMeasurement[]): boolean;
11
+ /*** Groups observations by responsive viewport so rendered variants remain independent. */
12
+ declare function viewports(observations: readonly TypographyObservation[]): readonly (readonly TypographyObservation[])[];
13
+ /*** Sorts complete heading observations by explicit document order. */
14
+ declare function orderedHeadings(observations: readonly TypographyObservation[]): readonly (TypographyObservation & {
15
+ readonly documentOrder: number;
16
+ readonly headingLevel: number;
17
+ })[];
18
+ export {};
@@ -0,0 +1,53 @@
1
+ /*** Creates the shared completeness and viewport grouping operations for Typography evidence. */
2
+ export function createTypographyObservationTools() {
3
+ return { measurementsComplete, orderedHeadings, viewports };
4
+ }
5
+ /*** Checks required measurements and document-order uniqueness when a rule needs it. */
6
+ function measurementsComplete(observations, measurements) {
7
+ return (observations.every((observation) => measurements.every((measurement) => measurementAvailable(observation, measurement))) &&
8
+ (!measurements.includes('documentOrder') ||
9
+ viewports(observations).every((viewport) => uniqueDocumentOrder(viewport))));
10
+ }
11
+ /*** Checks one named observation measurement without indexing dynamic external property names. */
12
+ function measurementAvailable(observation, measurement) {
13
+ switch (measurement) {
14
+ case 'documentOrder':
15
+ return observation.documentOrder !== null;
16
+ case 'headingLevel':
17
+ return observation.headingLevel !== null;
18
+ case 'marginAfter':
19
+ return observation.marginAfter !== null;
20
+ case 'marginBefore':
21
+ return observation.marginBefore !== null;
22
+ case 'paragraphMeasure':
23
+ return observation.paragraphMeasure !== null;
24
+ case 'responsiveRole':
25
+ return observation.responsiveRole !== null;
26
+ case 'semanticStyle':
27
+ return observation.semanticStyle !== null;
28
+ case 'textClipped':
29
+ return observation.textClipped !== null;
30
+ default:
31
+ return true;
32
+ }
33
+ }
34
+ /*** Groups observations by responsive viewport so rendered variants remain independent. */
35
+ function viewports(observations) {
36
+ return Object.values(Object.groupBy(observations, (observation) => observation.viewport)).flatMap((viewport) => (viewport === undefined ? [] : [viewport]));
37
+ }
38
+ /*** Confirms that every heading in one viewport has a distinct document position. */
39
+ function uniqueDocumentOrder(observations) {
40
+ const documentOrders = observations.map((observation) => observation.documentOrder);
41
+ return (documentOrders.every((order) => order !== null) &&
42
+ new Set(documentOrders).size === documentOrders.length);
43
+ }
44
+ /*** Sorts complete heading observations by explicit document order. */
45
+ function orderedHeadings(observations) {
46
+ return observations
47
+ .filter(hasDocumentOrderAndHeadingLevel)
48
+ .toSorted((left, right) => left.documentOrder - right.documentOrder);
49
+ }
50
+ /*** Confirms that an observation can participate in a document heading hierarchy. */
51
+ function hasDocumentOrderAndHeadingLevel(observation) {
52
+ return observation.documentOrder !== null && observation.headingLevel !== null;
53
+ }
@@ -0,0 +1,6 @@
1
+ import type { RuleSet } from '@ankhorage/rules';
2
+ import type { DesignContext } from '../../types/designRuleProvider';
3
+ import type { TypographyRulePolicy } from '../../types/typography';
4
+ export type { TypographyRulePolicy } from '../../types/typography';
5
+ /*** Creates the independent Typography and Heading RuleSet from explicit serialized-fact policy. */
6
+ export declare function createTypographyRuleSet(policy: TypographyRulePolicy): RuleSet<DesignContext>;
@@ -0,0 +1,114 @@
1
+ import { createTypographyObservationTools } from './createTypographyObservationTools';
2
+ import { parseTypographyObservation } from './parseTypographyObservation';
3
+ import { validateTypographyRulePolicy } from './validateTypographyRulePolicy';
4
+ const typographyObservationTools = createTypographyObservationTools();
5
+ /*** Creates the independent Typography and Heading RuleSet from explicit serialized-fact policy. */
6
+ export function createTypographyRuleSet(policy) {
7
+ validateTypographyRulePolicy(policy);
8
+ return {
9
+ id: 'ankhorage.rules-design.typography',
10
+ rules: ruleDefinitions.map((definition) => createRule(definition, policy)),
11
+ };
12
+ }
13
+ const ruleDefinitions = [
14
+ definition('design.typography.font-family', 'Typography uses configured font families.', (facts, policy) => facts.filter((fact) => !policy.allowedFontFamilies.includes(fact.fontFamily)), requiredMeasurements('fontFamily')),
15
+ definition('design.typography.scale', 'Typography sizes use the configured scale.', (facts, policy) => facts.filter((fact) => !policy.allowedFontSizes.includes(fact.fontSize)), requiredMeasurements('fontSize')),
16
+ definition('design.typography.weight', 'Typography uses configured font weights.', (facts, policy) => facts.filter((fact) => !policy.allowedFontWeights.includes(fact.fontWeight)), requiredMeasurements('fontWeight')),
17
+ definition('design.typography.line-height', 'Typography uses configured line heights.', (facts, policy) => facts.filter((fact) => !policy.allowedLineHeights.includes(fact.lineHeight)), requiredMeasurements('lineHeight')),
18
+ definition('design.typography.letter-spacing', 'Typography uses configured letter spacing.', (facts, policy) => facts.filter((fact) => !policy.allowedLetterSpacings.includes(fact.letterSpacing)), requiredMeasurements('letterSpacing')),
19
+ definition('design.typography.paragraph-measure', 'Paragraphs stay within the configured readable measure.', (facts, policy) => facts.filter((fact) => fact.paragraphMeasure !== null &&
20
+ (fact.paragraphMeasure < policy.minimumParagraphMeasure ||
21
+ fact.paragraphMeasure > policy.maximumParagraphMeasure)), requiredMeasurements('paragraphMeasure'), 'warning'),
22
+ definition('design.typography.body-minimum', 'Body text meets the configured minimum font size.', (facts, policy) => facts.filter((fact) => fact.headingLevel === null && fact.fontSize < policy.minimumBodyFontSize), () => true),
23
+ definition('design.typography.responsive-scale', 'Responsive text sizes follow the configured scale for their role.', (facts, policy) => facts.filter((fact) => fact.responsiveRole !== null &&
24
+ !configuredValues(policy.responsiveFontSizes, fact.responsiveRole).includes(fact.fontSize)), requiredMeasurements('responsiveRole', 'fontSize')),
25
+ definition('design.heading.h1-presence', 'A page contains the configured minimum number of H1 headings.', (facts, policy) => typographyObservationTools
26
+ .viewports(facts)
27
+ .flatMap((factsForViewport) => factsForViewport.filter((fact) => fact.headingLevel === 1).length < policy.minimumH1Count
28
+ ? factsForViewport.slice(0, 1)
29
+ : []), requiredMeasurements('headingLevel', 'viewport'), 'error', 'design.heading-facts'),
30
+ definition('design.heading.h1-count', 'A page does not exceed the configured number of H1 headings.', (facts, policy) => typographyObservationTools.viewports(facts).flatMap((factsForViewport) => {
31
+ const h1Headings = typographyObservationTools
32
+ .orderedHeadings(factsForViewport)
33
+ .filter((fact) => fact.headingLevel === 1);
34
+ return h1Headings.slice(policy.maximumH1Count);
35
+ }), requiredMeasurements('documentOrder', 'headingLevel', 'viewport'), 'error', 'design.heading-facts'),
36
+ definition('design.heading.level-order', 'Heading levels do not skip hierarchy levels.', (facts) => typographyObservationTools
37
+ .viewports(facts)
38
+ .flatMap((factsForViewport) => typographyObservationTools
39
+ .orderedHeadings(factsForViewport)
40
+ .filter((fact, index, ordered) => index > 0 && fact.headingLevel > (ordered[index - 1]?.headingLevel ?? 0) + 1)), requiredMeasurements('documentOrder', 'headingLevel'), 'error', 'design.heading-facts'),
41
+ definition('design.heading.semantic-style', 'Heading semantics use a configured visual style.', (facts, policy) => facts.filter((fact) => fact.semanticStyle !== null &&
42
+ !configuredValues(policy.allowedSemanticStyles, `h${fact.headingLevel}`).includes(fact.semanticStyle)), requiredMeasurements('headingLevel', 'semanticStyle'), 'error', 'design.heading-facts'),
43
+ definition('design.heading.spacing-before', 'Headings use configured preceding spacing.', (facts, policy) => facts.filter((fact) => fact.marginBefore !== null && !policy.allowedSpacingBefore.includes(fact.marginBefore)), requiredMeasurements('headingLevel', 'marginBefore'), 'error', 'design.heading-facts'),
44
+ definition('design.heading.spacing-after', 'Headings use configured following spacing.', (facts, policy) => facts.filter((fact) => fact.marginAfter !== null && !policy.allowedSpacingAfter.includes(fact.marginAfter)), requiredMeasurements('headingLevel', 'marginAfter'), 'error', 'design.heading-facts'),
45
+ definition('design.heading.text-clipping', 'Heading text is not clipped in the rendered layout.', (facts) => facts.filter((fact) => fact.textClipped === true), requiredMeasurements('headingLevel', 'textClipped'), 'error', 'design.heading-facts'),
46
+ ];
47
+ /*** Builds one pure generic Rules rule from a Typography fact predicate. */
48
+ function createRule(definition, policy) {
49
+ return {
50
+ defaultSeverity: definition.severity,
51
+ dependencies: [],
52
+ evaluate: ({ context, scope }) => {
53
+ const [complete, observations] = typographyEvidence(context, definition.capability, scope);
54
+ if (!complete || observations.length === 0 || !definition.measurementsComplete(observations))
55
+ return incomplete(definition.id);
56
+ const violations = definition.evaluate(observations, policy);
57
+ return violations.length === 0
58
+ ? { findings: [], status: 'PASS' }
59
+ : {
60
+ findings: violations.map((fact) => violationFinding(definition.id, fact)),
61
+ status: 'FAIL',
62
+ };
63
+ },
64
+ identity: { id: definition.id, version: '1.0.0' },
65
+ requiredCapabilities: [definition.capability],
66
+ summary: definition.summary,
67
+ };
68
+ }
69
+ /*** Creates a Typography rule definition with its capability inferred from its stable ID. */
70
+ function definition(id, summary, evaluate, measurementsComplete, severity = 'error', capability = 'design.typography-facts') {
71
+ return { capability, evaluate, id, measurementsComplete, severity, summary };
72
+ }
73
+ /*** Reads scoped Typography facts without discarding malformed or unavailable evidence. */
74
+ function typographyEvidence(context, capability, scope) {
75
+ const factObservations = (context.facts ?? [])
76
+ .filter((fact) => fact.kind === capability && fact.scope.id === scope.id && fact.scope.kind === scope.kind)
77
+ .map((fact) => fact.status === 'available' ? parseTypographyObservation(fact.value, fact.id) : []);
78
+ return [
79
+ factObservations.every((observations) => observations.length > 0),
80
+ factObservations.flat(),
81
+ ];
82
+ }
83
+ /*** Returns an explicit incomplete outcome when required measurements cannot support a verdict. */
84
+ function incomplete(ruleId) {
85
+ return { findings: [missingEvidenceFinding(ruleId)], status: 'INCOMPLETE' };
86
+ }
87
+ /*** Produces a serializable incomplete finding when a rule has no valid measured observation. */
88
+ function missingEvidenceFinding(ruleId) {
89
+ return {
90
+ evidence: { reason: 'No valid normalized Typography observation was supplied.' },
91
+ message: `Rule "${ruleId}" is incomplete because Typography evidence is missing.`,
92
+ ruleId,
93
+ severity: 'info',
94
+ subjects: [{ id: 'design-context', kind: 'design-context' }],
95
+ };
96
+ }
97
+ /*** Produces a serializable finding for one measured Typography policy violation. */
98
+ function violationFinding(ruleId, fact) {
99
+ return {
100
+ evidence: { observationId: fact.id, viewport: fact.viewport },
101
+ message: `Rule "${ruleId}" is violated by Typography observation "${fact.id}".`,
102
+ ruleId,
103
+ severity: 'error',
104
+ subjects: [{ id: fact.id, kind: 'typography-observation' }],
105
+ };
106
+ }
107
+ /*** Reads a configured allow-list without treating an unknown role as allowed. */
108
+ function configuredValues(values, key) {
109
+ return Object.entries(values).find(([candidate]) => candidate === key)?.[1] ?? [];
110
+ }
111
+ /*** Builds a completeness predicate from one frozen rule's required measurements. */
112
+ function requiredMeasurements(...keys) {
113
+ return (observations) => typographyObservationTools.measurementsComplete(observations, keys);
114
+ }
@@ -0,0 +1,3 @@
1
+ import type { TypographyObservation } from '../../types/typography';
2
+ /*** Parses one available serialized fact into a normalized Typography observation. */
3
+ export declare function parseTypographyObservation(value: unknown, id: string): readonly TypographyObservation[];
@@ -0,0 +1,62 @@
1
+ import { isRecord } from '@ankhorage/utility/object';
2
+ /*** Parses one available serialized fact into a normalized Typography observation. */
3
+ export function parseTypographyObservation(value, id) {
4
+ if (!isRecord(value) ||
5
+ !isString(value.fontFamily) ||
6
+ !isNumber(value.fontSize) ||
7
+ !isString(value.fontWeight) ||
8
+ !isNumber(value.letterSpacing) ||
9
+ !isNumber(value.lineHeight) ||
10
+ !isString(value.viewport))
11
+ return [];
12
+ const headingLevel = nullableHeadingLevel(value.headingLevel);
13
+ if (headingLevel === undefined)
14
+ return [];
15
+ return [
16
+ {
17
+ fontFamily: value.fontFamily,
18
+ fontSize: value.fontSize,
19
+ fontWeight: value.fontWeight,
20
+ documentOrder: nullableNumber(value.documentOrder),
21
+ headingLevel: headingLevel ?? null,
22
+ id,
23
+ letterSpacing: value.letterSpacing,
24
+ lineHeight: value.lineHeight,
25
+ marginAfter: nullableNumber(value.marginAfter),
26
+ marginBefore: nullableNumber(value.marginBefore),
27
+ paragraphMeasure: nullableNumber(value.paragraphMeasure),
28
+ responsiveRole: nullableString(value.responsiveRole),
29
+ semanticStyle: nullableString(value.semanticStyle),
30
+ textClipped: nullableBoolean(value.textClipped),
31
+ viewport: value.viewport,
32
+ },
33
+ ];
34
+ }
35
+ /*** Narrows an unknown serialized value to a finite number. */
36
+ function isNumber(value) {
37
+ return typeof value === 'number' && Number.isFinite(value);
38
+ }
39
+ /*** Narrows an optional serialized value to a nullable boolean. */
40
+ function nullableBoolean(value) {
41
+ return value === undefined || value === null ? null : typeof value === 'boolean' ? value : null;
42
+ }
43
+ /*** Narrows an optional serialized value to a valid nullable heading level. */
44
+ function nullableHeadingLevel(value) {
45
+ return value === undefined || value === null
46
+ ? null
47
+ : isNumber(value) && Number.isInteger(value) && value >= 1 && value <= 6
48
+ ? value
49
+ : undefined;
50
+ }
51
+ /*** Narrows an optional serialized value to a nullable finite number. */
52
+ function nullableNumber(value) {
53
+ return value === undefined || value === null ? null : isNumber(value) ? value : null;
54
+ }
55
+ /*** Narrows an optional serialized value to a nullable string. */
56
+ function nullableString(value) {
57
+ return value === undefined || value === null ? null : isString(value) ? value : null;
58
+ }
59
+ /*** Narrows an unknown serialized value to a string. */
60
+ function isString(value) {
61
+ return typeof value === 'string';
62
+ }
@@ -0,0 +1,3 @@
1
+ import type { TypographyRulePolicy } from '../../types/typography';
2
+ /*** Rejects malformed policy before rule construction can produce ambiguous verdicts. */
3
+ export declare function validateTypographyRulePolicy(policy: TypographyRulePolicy): void;
@@ -0,0 +1,68 @@
1
+ /*** Rejects malformed policy before rule construction can produce ambiguous verdicts. */
2
+ export function validateTypographyRulePolicy(policy) {
3
+ if (invalidTypographyRulePolicy(policy)) {
4
+ throw new Error('Typography rule policy must contain complete, internally consistent measurements.');
5
+ }
6
+ }
7
+ /*** Checks every policy invariant required by the Typography rule family. */
8
+ function invalidTypographyRulePolicy(policy) {
9
+ return (!hasNonEmptyStrings(policy.allowedFontFamilies) ||
10
+ !hasPositiveNumbers(policy.allowedFontSizes) ||
11
+ !hasNonEmptyStrings(policy.allowedFontWeights) ||
12
+ !hasFiniteNumbers(policy.allowedLetterSpacings) ||
13
+ !hasPositiveNumbers(policy.allowedLineHeights) ||
14
+ !hasNonNegativeNumbers(policy.allowedSpacingAfter) ||
15
+ !hasNonNegativeNumbers(policy.allowedSpacingBefore) ||
16
+ !hasConfiguredValues(policy.allowedSemanticStyles, hasNonEmptyStrings) ||
17
+ !hasConfiguredValues(policy.responsiveFontSizes, hasPositiveNumbers) ||
18
+ !hasValidH1Counts(policy) ||
19
+ !hasValidTypographyThresholds(policy));
20
+ }
21
+ /*** Checks that H1 count bounds are non-negative integers in ascending order. */
22
+ function hasValidH1Counts(policy) {
23
+ return (Number.isInteger(policy.minimumH1Count) &&
24
+ Number.isInteger(policy.maximumH1Count) &&
25
+ policy.minimumH1Count >= 0 &&
26
+ policy.maximumH1Count >= policy.minimumH1Count);
27
+ }
28
+ /*** Checks positive Typography thresholds and paragraph-measure bounds. */
29
+ function hasValidTypographyThresholds(policy) {
30
+ return (isPositiveFiniteNumber(policy.minimumBodyFontSize) &&
31
+ isPositiveFiniteNumber(policy.minimumParagraphMeasure) &&
32
+ isPositiveFiniteNumber(policy.maximumParagraphMeasure) &&
33
+ policy.maximumParagraphMeasure >= policy.minimumParagraphMeasure);
34
+ }
35
+ /*** Checks a non-empty serializable string allow-list. */
36
+ function hasNonEmptyStrings(values) {
37
+ return (Array.isArray(values) &&
38
+ values.length > 0 &&
39
+ values.every((value) => typeof value === 'string' && value.length > 0));
40
+ }
41
+ /*** Checks a non-empty serializable positive numeric allow-list. */
42
+ function hasPositiveNumbers(values) {
43
+ return Array.isArray(values) && values.length > 0 && values.every(isPositiveFiniteNumber);
44
+ }
45
+ /*** Checks a non-empty serializable finite numeric allow-list. */
46
+ function hasFiniteNumbers(values) {
47
+ return (Array.isArray(values) &&
48
+ values.length > 0 &&
49
+ values.every((value) => typeof value === 'number' && Number.isFinite(value)));
50
+ }
51
+ /*** Checks a non-empty serializable non-negative numeric allow-list. */
52
+ function hasNonNegativeNumbers(values) {
53
+ return (Array.isArray(values) &&
54
+ values.length > 0 &&
55
+ values.every((value) => typeof value === 'number' && Number.isFinite(value) && value >= 0));
56
+ }
57
+ /*** Checks a finite positive measurement. */
58
+ function isPositiveFiniteNumber(value) {
59
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
60
+ }
61
+ /*** Checks every named policy role supplies a non-empty valid allow-list. */
62
+ function hasConfiguredValues(values, validate) {
63
+ return (typeof values === 'object' &&
64
+ values !== null &&
65
+ !Array.isArray(values) &&
66
+ Object.keys(values).length > 0 &&
67
+ Object.entries(values).every(([key, value]) => key.length > 0 && validate(value)));
68
+ }
@@ -1,3 +1,4 @@
1
+ import type { FactEnvelope } from '@ankhorage/contracts/rules';
1
2
  import type { RuleSet } from '@ankhorage/rules';
2
3
  /*** One provider-neutral design observation supplied by a Design context. */
3
4
  export interface DesignEvidence {
@@ -7,6 +8,7 @@ export interface DesignEvidence {
7
8
  /*** The minimal context shared by Design rules without prescribing its source. */
8
9
  export interface DesignContext {
9
10
  readonly evidence: readonly DesignEvidence[];
11
+ readonly facts?: readonly FactEnvelope[];
10
12
  }
11
13
  /*** The public identity and generic Rules contribution for the Design provider. */
12
14
  export interface DesignRuleProvider {
@@ -0,0 +1,7 @@
1
+ /*** The frozen rule IDs owned by the Spacing and Proximity rule group. */
2
+ export type SpacingProximityRuleId = 'design.proximity.card-internals' | 'design.proximity.heading-content' | 'design.proximity.label-control' | 'design.proximity.related-grouping' | 'design.proximity.unrelated-separation' | 'design.spacing.container-padding' | 'design.spacing.double-application' | 'design.spacing.section-gap' | 'design.spacing.token-allowed' | 'design.spacing.unexpected-collapse' | 'design.spacing.vertical-rhythm';
3
+ /*** One normalized raw observation supplied by a layout or token adapter. */
4
+ export interface SpacingProximityObservation {
5
+ readonly kind: SpacingProximityRuleId;
6
+ readonly value: unknown;
7
+ }
File without changes
@@ -0,0 +1,35 @@
1
+ /** One normalized, provider-neutral rendered Typography observation. */
2
+ export interface TypographyObservation {
3
+ readonly documentOrder: number | null;
4
+ readonly fontFamily: string;
5
+ readonly fontSize: number;
6
+ readonly fontWeight: string;
7
+ readonly headingLevel: number | null;
8
+ readonly id: string;
9
+ readonly letterSpacing: number;
10
+ readonly lineHeight: number;
11
+ readonly marginAfter: number | null;
12
+ readonly marginBefore: number | null;
13
+ readonly paragraphMeasure: number | null;
14
+ readonly responsiveRole: string | null;
15
+ readonly semanticStyle: string | null;
16
+ readonly textClipped: boolean | null;
17
+ readonly viewport: string;
18
+ }
19
+ /** Explicit allow-lists and thresholds used to evaluate Typography observations. */
20
+ export interface TypographyRulePolicy {
21
+ readonly allowedFontFamilies: readonly string[];
22
+ readonly allowedFontSizes: readonly number[];
23
+ readonly allowedFontWeights: readonly string[];
24
+ readonly allowedLetterSpacings: readonly number[];
25
+ readonly allowedLineHeights: readonly number[];
26
+ readonly allowedSemanticStyles: Readonly<Record<string, readonly string[]>>;
27
+ readonly allowedSpacingAfter: readonly number[];
28
+ readonly allowedSpacingBefore: readonly number[];
29
+ readonly maximumH1Count: number;
30
+ readonly maximumParagraphMeasure: number;
31
+ readonly minimumBodyFontSize: number;
32
+ readonly minimumH1Count: number;
33
+ readonly minimumParagraphMeasure: number;
34
+ readonly responsiveFontSizes: Readonly<Record<string, readonly number[]>>;
35
+ }
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ankhorage/rules-design",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Declarative catalog for reusable design rules.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://github.com/ankhorage/rules-design#readme",
@@ -59,6 +59,7 @@
59
59
  },
60
60
  "dependencies": {
61
61
  "@ankhorage/contracts": "^26.4.0",
62
- "@ankhorage/rules": "^0.4.0"
62
+ "@ankhorage/rules": "^0.4.0",
63
+ "@ankhorage/utility": "^1.10.0"
63
64
  }
64
65
  }