@gradial/aci 0.1.52-rc.8 → 0.1.52

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 (254) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/README.md +86 -5
  3. package/dist/astro/error-page.js +1 -0
  4. package/dist/astro/index.js +4 -0
  5. package/dist/astro/page.d.ts +5 -2
  6. package/dist/astro/page.js +35 -23
  7. package/dist/astro/preview.js +2 -17
  8. package/dist/audience-data-models.d.ts +308 -197
  9. package/dist/audience-data-models.js +313 -51
  10. package/dist/cli/compile-registry.mjs +6 -34
  11. package/dist/cli/mintlify-render.mjs +8 -0
  12. package/dist/collect/aci.js +1 -1
  13. package/dist/collect/aci.js.sha256 +1 -1
  14. package/dist/collect/api.d.ts +6 -7
  15. package/dist/collect/api.js +21 -8
  16. package/dist/collect/assignments.d.ts +7 -9
  17. package/dist/collect/assignments.js +23 -32
  18. package/dist/collect/batcher.d.ts +9 -7
  19. package/dist/collect/batcher.js +6 -5
  20. package/dist/collect/consent/envelope.d.ts +7 -1
  21. package/dist/collect/consent/envelope.js +3 -1
  22. package/dist/collect/consent/mapping.d.ts +2 -0
  23. package/dist/collect/consent/mapping.js +1 -0
  24. package/dist/collect/consenthold.d.ts +38 -0
  25. package/dist/collect/consenthold.js +82 -0
  26. package/dist/collect/declarative.js +7 -5
  27. package/dist/collect/gapbuffer.d.ts +13 -4
  28. package/dist/collect/gapbuffer.js +21 -10
  29. package/dist/collect/index.js +78 -21
  30. package/dist/collect/pageviews.d.ts +11 -11
  31. package/dist/collect/pageviews.js +27 -22
  32. package/dist/consent-banner/index.d.ts +17 -0
  33. package/dist/consent-banner/index.js +23 -0
  34. package/dist/content/index.d.ts +2 -1
  35. package/dist/content/index.js +4 -1
  36. package/dist/content/provider.d.ts +16 -2
  37. package/dist/content/provider.js +5 -1
  38. package/dist/content/resolve-slots.d.ts +24 -2
  39. package/dist/content/resolve-slots.js +127 -21
  40. package/dist/content/types.d.ts +5 -1
  41. package/dist/edge/expression-capabilities.v1.d.ts +106 -0
  42. package/dist/edge/expression-capabilities.v1.js +165 -0
  43. package/dist/index.d.ts +1 -2
  44. package/dist/index.js +0 -1
  45. package/dist/internal/domain/edge/identity.d.ts +47 -4
  46. package/dist/internal/domain/edge/identity.js +130 -26
  47. package/dist/internal/domain/edge/index.d.ts +1 -1
  48. package/dist/internal/domain/edge/index.js +1 -1
  49. package/dist/internal/domain/edge/mimic_token.d.ts +14 -0
  50. package/dist/internal/domain/edge/mimic_token.js +125 -0
  51. package/dist/internal/domain/edge/personalization-core.d.ts +61 -22
  52. package/dist/internal/domain/edge/personalization-core.js +790 -200
  53. package/dist/internal/domain/edge/personalization_index.d.ts +17 -0
  54. package/dist/internal/domain/edge/personalization_index.js +55 -0
  55. package/dist/internal/domain/edge/resolve.js +76 -39
  56. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.d.ts +10 -0
  57. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.js +253 -0
  58. package/dist/internal/domain/edge/types.d.ts +82 -78
  59. package/dist/internal/domain/edge/types.js +3 -3
  60. package/dist/internal/domain/edge/variant_key.d.ts +4 -0
  61. package/dist/internal/domain/edge/variant_key.js +56 -0
  62. package/dist/internal/platform/collectionstore/errors.d.ts +24 -0
  63. package/dist/internal/platform/collectionstore/errors.js +48 -0
  64. package/dist/mintlify/blocks.d.ts +6 -0
  65. package/dist/mintlify/blocks.js +201 -0
  66. package/dist/mintlify/config.d.ts +3 -0
  67. package/dist/mintlify/config.js +77 -0
  68. package/dist/mintlify/index.d.ts +3 -0
  69. package/dist/mintlify/index.js +2 -0
  70. package/dist/mintlify/json.d.ts +8 -0
  71. package/dist/mintlify/json.js +37 -0
  72. package/dist/mintlify/materialize.d.ts +14 -0
  73. package/dist/mintlify/materialize.js +254 -0
  74. package/dist/mintlify/types.d.ts +74 -0
  75. package/dist/mintlify/types.js +1 -0
  76. package/dist/mintlify/validate.d.ts +7 -0
  77. package/dist/mintlify/validate.js +256 -0
  78. package/dist/next/assignments-navigation.d.ts +4 -0
  79. package/dist/next/assignments-navigation.js +18 -0
  80. package/dist/next/assignments-script.d.ts +3 -2
  81. package/dist/next/assignments-script.js +5 -5
  82. package/dist/next/error-pages.d.ts +4 -0
  83. package/dist/next/error-pages.js +4 -0
  84. package/dist/next/error-seat-payload.d.ts +2 -1
  85. package/dist/next/error-seat-payload.js +14 -24
  86. package/dist/next/error-seat.js +7 -2
  87. package/dist/next/index.d.ts +1 -1
  88. package/dist/next/index.js +3 -1
  89. package/dist/next/page.d.ts +2 -1
  90. package/dist/next/page.js +15 -4
  91. package/dist/next/release-context.d.ts +30 -0
  92. package/dist/next/release-context.js +56 -0
  93. package/dist/next/render.d.ts +1 -1
  94. package/dist/next/render.js +15 -5
  95. package/dist/next/server.d.ts +9 -3
  96. package/dist/next/server.js +17 -32
  97. package/dist/preview/core.d.ts +1 -0
  98. package/dist/preview/core.js +27 -0
  99. package/dist/react/VideoPlayer.d.ts +3 -3
  100. package/dist/react/index.d.ts +3 -3
  101. package/dist/registry.d.ts +4 -2
  102. package/dist/testing/conformance/checks.d.ts +2 -2
  103. package/dist/testing/conformance/checks.js +2 -0
  104. package/dist/testing/conformance/index.d.ts +1 -0
  105. package/dist/testing/conformance/index.js +1 -0
  106. package/dist/testing/conformance/next-stubs.d.ts +6 -0
  107. package/dist/testing/conformance/next-stubs.js +9 -0
  108. package/dist/testing/conformance/preset.d.ts +3 -2
  109. package/dist/testing/conformance/preset.js +15 -8
  110. package/dist/testing/conformance/root-identity.d.ts +31 -0
  111. package/dist/testing/conformance/root-identity.js +361 -0
  112. package/dist/testing/conformance/stubs/next-image.d.ts +7 -0
  113. package/dist/testing/conformance/stubs/next-image.js +5 -0
  114. package/dist/testing/conformance/stubs/next-link.d.ts +7 -0
  115. package/dist/testing/conformance/stubs/next-link.js +4 -0
  116. package/dist/testing/conformance/types.d.ts +5 -2
  117. package/dist/testing/index.d.ts +1 -1
  118. package/dist/testing/index.js +4 -3
  119. package/dist/types/block-ref.js +2 -2
  120. package/dist/types/component.d.ts +9 -0
  121. package/dist/types/config.d.ts +0 -1
  122. package/dist/types/index.d.ts +0 -1
  123. package/dist/types/index.js +0 -1
  124. package/dist/types/page.d.ts +0 -1
  125. package/migrations/conformance-registry.md +22 -0
  126. package/migrations/experiment-goal-ids.md +43 -0
  127. package/package.json +21 -7
  128. package/src/cli/compile-registry.mjs +6 -30
  129. package/src/cli/mintlify-render.mjs +9 -0
  130. package/src/types/block-ref.test.ts +16 -1
  131. package/src/types/block-ref.ts +2 -2
  132. package/src/types/component.ts +10 -0
  133. package/src/types/config.ts +0 -1
  134. package/src/types/index.ts +0 -1
  135. package/src/types/page.ts +0 -1
  136. package/templates/astro/starter-content/src/components/chrome/Footer.astro +5 -3
  137. package/templates/astro/starter-content/src/components/chrome/Header.astro +5 -3
  138. package/templates/astro/starter-content/src/components/elements/Button.astro +5 -2
  139. package/templates/astro/starter-content/src/components/elements/ButtonBlock.astro +5 -3
  140. package/templates/astro/starter-content/src/components/sections/ContainerSection.astro +4 -3
  141. package/templates/astro/starter-content/src/components/sections/FeatureCard.astro +4 -3
  142. package/templates/astro/starter-content/src/components/sections/FeatureGrid.astro +4 -3
  143. package/templates/astro/starter-content/src/components/sections/HomeHero.astro +5 -3
  144. package/templates/astro/starter-content/src/components/sections/PersonalizationChoice.astro +4 -3
  145. package/templates/astro/starter-content/src/components/sections/StatsBar.astro +4 -3
  146. package/templates/astro/starter-content/src/fixtures/sections.ts +1 -1
  147. package/templates/astro/starter-content/src/stories/CompositionStoryFrame.astro +7 -2
  148. package/templates/astro/template/.aci.yaml.tmpl +0 -1
  149. package/templates/astro/template/package.json.tmpl +5 -5
  150. package/templates/astro/template/src/layouts/SiteLayout.astro +2 -2
  151. package/templates/common/.agents/skills/aci/SKILL.md +58 -1
  152. package/templates/common/.agents/skills/authoring/SKILL.md +194 -42
  153. package/templates/common/.agents/skills/authoring/references/block-registry.md +19 -3
  154. package/templates/common/.agents/skills/authoring/references/contracts.md +9 -30
  155. package/templates/common/.agents/skills/authoring/references/repo-structure.md +5 -4
  156. package/templates/common/.agents/skills/authoring/references/sdk-server-functions.md +3 -3
  157. package/templates/common/.agents/skills/dam-delivery/SKILL.md +216 -0
  158. package/templates/common/.agents/skills/dam-delivery/references/permalink-grammar.md +167 -0
  159. package/templates/common/.agents/skills/migration/references/canon-migration.md +18 -67
  160. package/templates/common/.agents/skills/migration/references/selector-map.md +1 -1
  161. package/templates/common/.content/fragments/navbar/_index.json +24 -0
  162. package/templates/common/.content/fragments/site-footer/_index.json +61 -0
  163. package/templates/common/.content/pages/404/_index.json +4 -2
  164. package/templates/common/.content/pages/_index.json +0 -1
  165. package/templates/common/.content/pages/error/_index.json +4 -2
  166. package/templates/common/.content/schemas/site.schema.json +11 -1
  167. package/templates/common/.content/templates/error.json +24 -0
  168. package/templates/common/.content/templates/home.json +28 -0
  169. package/templates/common/.content/templates/site.json +8 -0
  170. package/templates/common/.content/templates/standard.json +24 -0
  171. package/templates/common/.nvmrc +1 -1
  172. package/templates/common/starter-content/.content/config/site.json +1 -1
  173. package/templates/common/starter-content/.content/dam/README.md +74 -0
  174. package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_about_hero → 000000000000000000000000101}/asset.json +1 -1
  175. package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_home_hero → 000000000000000000000000102}/asset.json +1 -1
  176. package/templates/common/starter-content/.content/pages/404/_index.json +1 -2
  177. package/templates/common/starter-content/.content/pages/{home/_index.json → _index.json} +14 -3
  178. package/templates/common/starter-content/.content/pages/about/_index.json +2 -2
  179. package/templates/common/starter-content/.content/pages/error/_index.json +1 -2
  180. package/templates/common/starter-content/.content/patterns/components/button.json +2 -2
  181. package/templates/common/starter-content/.content/patterns/components/container.json +8 -3
  182. package/templates/common/starter-content/.content/patterns/components/feature_card.json +2 -2
  183. package/templates/common/starter-content/.content/patterns/components/feature_grid.json +5 -3
  184. package/templates/common/starter-content/.content/patterns/components/home_hero.json +2 -2
  185. package/templates/common/starter-content/.content/patterns/components/personalization_choice.json +2 -2
  186. package/templates/common/starter-content/.content/patterns/components/site-footer.json +2 -2
  187. package/templates/common/starter-content/.content/patterns/components/site-navigation.json +2 -2
  188. package/templates/common/starter-content/.content/patterns/components/stats_bar.json +2 -2
  189. package/templates/common/starter-content/.content/schemas/site.schema.json +11 -1
  190. package/templates/nextjs/starter-content/src/components/chrome/Footer.tsx +4 -3
  191. package/templates/nextjs/starter-content/src/components/chrome/Header.tsx +4 -3
  192. package/templates/nextjs/starter-content/src/components/elements/Button.tsx +4 -3
  193. package/templates/nextjs/starter-content/src/components/elements/ButtonBlock.tsx +4 -3
  194. package/templates/nextjs/starter-content/src/components/sections/ContainerSection.tsx +4 -2
  195. package/templates/nextjs/starter-content/src/components/sections/FeatureCard.tsx +4 -3
  196. package/templates/nextjs/starter-content/src/components/sections/FeatureGrid.tsx +4 -2
  197. package/templates/nextjs/starter-content/src/components/sections/HomeHero.tsx +4 -3
  198. package/templates/nextjs/starter-content/src/components/sections/PersonalizationChoice.tsx +4 -2
  199. package/templates/nextjs/starter-content/src/components/sections/StatsBar.tsx +4 -3
  200. package/templates/nextjs/template/.aci.yaml +0 -1
  201. package/templates/nextjs/template/.aci.yaml.tmpl +0 -1
  202. package/templates/nextjs/template/package.json.tmpl +4 -3
  203. package/templates/nextjs/template/src/app/_components/c15t-bridge.ts +30 -0
  204. package/templates/nextjs/template/src/app/_components/c15t-consent-ui.tsx +37 -0
  205. package/templates/nextjs/template/src/app/_components/consent-manager.css +63 -0
  206. package/templates/nextjs/template/src/app/_components/consent-manager.tsx +76 -0
  207. package/templates/nextjs/template/src/app/fonts/inter/OFL.txt +93 -0
  208. package/templates/nextjs/template/src/app/fonts/inter/inter-latin.woff2 +0 -0
  209. package/templates/nextjs/template/src/app/fonts/space-grotesk/OFL.txt +93 -0
  210. package/templates/nextjs/template/src/app/fonts/space-grotesk/space-grotesk-latin.woff2 +0 -0
  211. package/templates/nextjs/template/src/app/layout.tsx +12 -7
  212. package/templates/nextjs/template/tests/conformance.test.ts.tmpl +1 -0
  213. package/dist/define-layout.d.ts +0 -6
  214. package/dist/define-layout.js +0 -14
  215. package/dist/edge/personalization-core.d.ts +0 -11
  216. package/dist/edge/personalization-core.js +0 -269
  217. package/dist/internal/domain/edge/compose.d.ts +0 -24
  218. package/dist/internal/domain/edge/compose.js +0 -89
  219. package/dist/internal/domain/edge/record/codec.d.ts +0 -71
  220. package/dist/internal/domain/edge/record/codec.js +0 -401
  221. package/dist/next/collect-route.d.ts +0 -19
  222. package/dist/next/collect-route.js +0 -459
  223. package/dist/next/edge-config.d.ts +0 -1
  224. package/dist/next/edge-config.js +0 -92
  225. package/dist/next/envelope-digest.d.ts +0 -21
  226. package/dist/next/envelope-digest.js +0 -58
  227. package/dist/next/middleware.d.ts +0 -40
  228. package/dist/next/middleware.js +0 -475
  229. package/dist/next/personalization-host.d.ts +0 -134
  230. package/dist/next/personalization-host.js +0 -270
  231. package/dist/next/root-layout.d.ts +0 -4
  232. package/dist/next/root-layout.js +0 -5
  233. package/dist/next/vercel-collect-sdk-route.d.ts +0 -27
  234. package/dist/next/vercel-collect-sdk-route.js +0 -181
  235. package/dist/next/vercel-edge-projection-v1.d.ts +0 -24
  236. package/dist/next/vercel-edge-projection-v1.js +0 -880
  237. package/dist/next/vercel-personalization.d.ts +0 -4
  238. package/dist/next/vercel-personalization.js +0 -4
  239. package/dist/next/vercel-s3-personalization.d.ts +0 -79
  240. package/dist/next/vercel-s3-personalization.js +0 -570
  241. package/dist/types/layout.d.ts +0 -24
  242. package/src/types/layout.ts +0 -29
  243. package/templates/astro/starter-content/src/render/RenderPage.astro +0 -67
  244. package/templates/astro/template/src/cms/contracts/layouts/index.ts +0 -18
  245. package/templates/common/starter-content/.content/patterns/layouts/default.json +0 -14
  246. package/templates/nextjs/starter-content/src/components/elements/AtomicBlock.tsx +0 -13
  247. package/templates/nextjs/template/src/cms/contracts/layouts/index.ts +0 -16
  248. /package/dist/{types/layout.js → cli/mintlify-render.d.mts} +0 -0
  249. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_home_hero → 000000000000000000000000101}/editorial.json +0 -0
  250. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_about_hero → 000000000000000000000000101}/governance.json +0 -0
  251. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_home_hero → 000000000000000000000000101}/versions/v0001.json +0 -0
  252. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_about_hero → 000000000000000000000000102}/editorial.json +0 -0
  253. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_home_hero → 000000000000000000000000102}/governance.json +0 -0
  254. /package/templates/common/starter-content/.content/dam/folders/seed/{ast_site_about_hero → 000000000000000000000000102}/versions/v0001.json +0 -0
@@ -1,76 +1,181 @@
1
1
  // Runtime-neutral personalization selection. The backend owns this logic
2
- // and pushes compiled artifacts to each host (CloudFront Function, Vercel
2
+ // and pushes compiled artifacts to each host (Lambda@Edge, Vercel
3
3
  // middleware, Cloudflare Worker). Keep this file free of platform APIs.
4
4
  //
5
5
  // This is the pure decision algorithm — no I/O, no cookies, no identity
6
6
  // minting. The caller resolves identity and claims, then calls this.
7
- import { variantValuesFromKey } from './record/codec.js';
8
- // Build-time constant. The CloudFront Functions bundle replaces this with
9
- // true and uses the runtime's built-in crypto module; other host bundles
10
- // replace it with false and retain the portable implementation.
11
- export function selectPersonalizationVariant(request, route, claims, experiments, identity) {
12
- return resolvePersonalizationDecision(request, route, claims, experiments, identity).variant;
13
- }
14
- export function resolvePersonalizationDecision(request, route, claims, experiments, identity) {
7
+ import { canonicalVariantKey, variantValuesFromKey } from './variant_key.js';
8
+ import { personalizationSelection } from './personalization_index.js';
9
+ export { preparePersonalizationRoute } from './personalization_index.js';
10
+ export class PersonalizationResolutionError extends Error {
11
+ variantKey;
12
+ code = 'personalization.tuple_missing';
13
+ constructor(variantKey) {
14
+ super(`materialized personalization tuple ${variantKey} is absent from the route projection`);
15
+ this.variantKey = variantKey;
16
+ this.name = 'PersonalizationResolutionError';
17
+ }
18
+ }
19
+ export function resolvePersonalizationDecision(request, route, claims, experiments, identity, forcedArms) {
15
20
  if (!route)
16
- return { variant: null, experiment: null };
17
- let variant = selectRuleVariant(request, route, claims, experiments);
18
- let experiment = null;
19
- if (identity && identity.usable && route.variants && experiments) {
20
- const candidates = Object.values(experiments)
21
- .filter((item) => (item.kind === 'ab' || item.kind === 'abn') && item.status === 'running')
22
- .filter((item) => routeHasExperiment(route, item.id))
23
- .sort((left, right) => (right.priority || 0) - (left.priority || 0)
24
- || String(left.id || '').localeCompare(String(right.id || '')));
25
- for (let index = 0; index < candidates.length; index++) {
26
- const item = candidates[index];
27
- const assignment = assignExperiment(item, identity);
28
- const candidate = assignment ? route.variants[assignment.variantKey] : undefined;
29
- if (!candidate)
21
+ return { variant: null, experiments: [] };
22
+ const selection = personalizationSelection(route, experiments);
23
+ const legacyExperimentExclusions = selection.legacyExperimentExclusions;
24
+ const authored = selectRuleVariant(request, selection, claims);
25
+ const values = { ...(authored ? authored.variantValues || variantValuesFromKey(authored.variantKey) : {}) };
26
+ // The leg selectRuleVariant chose is the selected-mode predicate's only
27
+ // input (ADR 0050, edge-functions I-16): "" when no leg won — an organic
28
+ // visit admits no selected-mode experiment.
29
+ const selectedLegAudienceId = String(values.audience || '');
30
+ const assignments = [];
31
+ const rejected = [];
32
+ const attempted = { ...values };
33
+ // Experiment-arm forcing (audience-mimic design/09, edge-functions I-17):
34
+ // an arms-bearing mimic token runs the experiment tier with the token's
35
+ // assertion replacing the dice for each experiment the request selects
36
+ // through the ordinary gate. Selection, eligibility, and arm-rule
37
+ // evaluation are the ordinary path — only allocation is replaced. No
38
+ // identity exists under mimic, so experiments the token does not name are
39
+ // skipped, and unselected experiments' forces are inert.
40
+ const forcing = !!forcedArms && Object.keys(forcedArms).length > 0;
41
+ if ((identity?.usable || forcing) && experiments) {
42
+ // The immutable route projection is the authority for scope. Missing
43
+ // qualified entries are corruption, never evidence to omit an experiment.
44
+ for (const item of selection.experiments) {
45
+ const id = item.id;
46
+ if (!experimentEligible(item, claims, selectedLegAudienceId))
47
+ continue;
48
+ const assignment = forcing
49
+ ? forceExperimentArm(item, forcedArms)
50
+ : assignExperiment(item, identity);
51
+ if (!assignment)
30
52
  continue;
31
- if (assignment && !candidate.variantKey)
32
- candidate.variantKey = assignment.variantKey;
33
- if (!variant || betterVariant(candidate.priority || 0, candidate.variantKey, variant.priority || 0, variant.variantKey)) {
34
- variant = candidate;
35
- experiment = assignment;
53
+ attempted[`experiment.${id}`] = assignment.armId;
54
+ if (item.eligibilityMode !== 'selected') {
55
+ const candidate = selection.arms[id]?.[assignment.armId];
56
+ // Under forcing an absent single-factor entry is publish/mint skew,
57
+ // not corruption (D-12 forbids the error page on the live origin):
58
+ // the factor degrades to absent and the plain mimic view renders.
59
+ if (!candidate) {
60
+ if (!forcing)
61
+ throw new PersonalizationResolutionError(assignment.variantKey);
62
+ continue;
63
+ }
64
+ const factorEvents = [];
65
+ const factorRequest = { ...request, onRuleRejected: (event) => factorEvents.push(event) };
66
+ if (candidate.rule && !evaluateRule(factorRequest, candidate.rule, claims, assignment.variantKey)) {
67
+ if (!factorEvents.length)
68
+ factorEvents.push({ variantKey: assignment.variantKey, diagnosticCode: 'expression.not_matched', diagnosticPath: 'expression', diagnosticCount: 1 });
69
+ for (const event of factorEvents)
70
+ rejected.push({ ...event, experimentId: id, armId: assignment.armId });
71
+ continue;
72
+ }
73
+ }
74
+ // A selected-mode experiment carries no arm rules (experiment I-18) and
75
+ // its arms materialize only composed with the selected leg, so there is
76
+ // no single-factor arm entry to look up; the composed-tuple resolution
77
+ // below stays the fail-closed corruption guard.
78
+ assignments.push(assignment);
79
+ values[`experiment.${id}`] = assignment.armId;
80
+ }
81
+ }
82
+ const attemptedKey = canonicalVariantKey(attempted);
83
+ for (const event of rejected)
84
+ request.onRuleRejected?.({ ...event, variantKey: attemptedKey });
85
+ let variant = authored;
86
+ if (assignments.length) {
87
+ const key = canonicalVariantKey(values);
88
+ const selected = selection.tuples[key];
89
+ // Under forcing a forced tuple absent from the projection (publish/mint
90
+ // skew) degrades every forced factor to absent — the plain mimic view.
91
+ // The fail-closed named error applies only to non-mimic traffic (I-17).
92
+ if (!selected && !forcing)
93
+ throw new PersonalizationResolutionError(key);
94
+ if (selected) {
95
+ variant = { ...selected, variantKey: key };
96
+ }
97
+ else {
98
+ assignments.length = 0;
99
+ for (const name of Object.keys(values)) {
100
+ if (name.startsWith('experiment.'))
101
+ delete values[name];
36
102
  }
37
- break;
38
103
  }
39
104
  }
40
- return { variant: variant || null, experiment };
105
+ return { variant, experiments: assignments, ...(legacyExperimentExclusions ? { legacyExperimentExclusions } : {}) };
41
106
  }
42
- function selectRuleVariant(request, route, claims, experiments) {
43
- if (!route.variants)
107
+ // forceExperimentArm resolves the token's named arm for one selected
108
+ // experiment instead of bucketing (design/09). Null when the token does not
109
+ // name this experiment (unforced experiments never run under mimic — no
110
+ // identity exists) or names an arm the active projection does not carry
111
+ // (skew degrades to the plain mimic view, never an error).
112
+ function forceExperimentArm(experiment, forcedArms) {
113
+ const armId = forcedArms[experiment.id];
114
+ if (armId === undefined)
44
115
  return null;
45
- const matches = [];
46
- for (const key in route.variants) {
47
- const variant = route.variants[key];
48
- if (!variant.variantKey)
49
- variant.variantKey = key;
50
- const values = variant.variantValues || variantValuesFromKey(key);
51
- const experimentID = String(values.experiment || '').trim();
52
- if (experimentID && (!experiments || !experiments[experimentID]
53
- || experiments[experimentID].status !== 'running'))
116
+ const arm = (experiment.arms || []).find((candidate) => candidate.id === armId);
117
+ if (!arm)
118
+ return null;
119
+ return {
120
+ experimentId: experiment.id,
121
+ armId,
122
+ allocationVersion: String(experiment.allocationVersion || ''),
123
+ variantKey: `experiment.${experiment.id}=${armId}`,
124
+ // The dice never rolled; -1 marks the forced origin in the decision
125
+ // record where a bucket would otherwise sit.
126
+ bucket: -1,
127
+ forced: true,
128
+ };
129
+ }
130
+ function selectRuleVariant(request, selection, claims) {
131
+ let best = null;
132
+ for (const candidate of selection.authored) {
133
+ const { variant, values, key } = candidate;
134
+ if (candidate.experiments.some((item) => !experimentEligible(item, claims, String(values.audience || ''))))
54
135
  continue;
55
136
  if (!requestDimensionsMatch(request, values))
56
137
  continue;
57
138
  const membershipMatch = (values.audience && claims && (claims.aud || []).includes(values.audience))
58
139
  || (values.segment && claims && (claims.seg || []).includes(values.segment));
59
- const ruleMatch = variant.rule ? evaluateRule(request, variant.rule) : false;
60
- if (membershipMatch || ruleMatch)
61
- matches.push(variant);
140
+ const ruleMatch = variant.rule ? evaluateRule(request, variant.rule, claims, key) : false;
141
+ if (!best && (membershipMatch || ruleMatch))
142
+ best = { ...variant, variantKey: key, variantValues: values };
62
143
  }
63
- matches.sort((left, right) => (right.priority || 0) - (left.priority || 0)
64
- || String(left.variantKey || '').localeCompare(String(right.variantKey || '')));
65
- return matches[0] || null;
144
+ return best;
66
145
  }
67
- function routeHasExperiment(route, experimentID) {
68
- for (const key in route.variants || {}) {
69
- const values = route.variants[key].variantValues || variantValuesFromKey(key);
70
- if (values.experiment === experimentID)
71
- return true;
72
- }
73
- return false;
146
+ // The eligibility gate (audience-scoped-experiments ASE-F4/F5): an
147
+ // experiment declaring eligibilityAudienceId is skipped entirely — before
148
+ // bucketing or arm candidacy — unless the verified claims carry the ID.
149
+ // Ungated experiments return true, preserving byte-identical behavior.
150
+ //
151
+ // ADR 0050 (edge-functions I-16): an experiment whose projection carries
152
+ // eligibilityMode "selected" is gated by the selected-leg predicate INSTEAD
153
+ // of the claims gate — it is a factor only when the leg the request selected
154
+ // carries audience=<eligibilityAudienceId>. Claims are never consulted for
155
+ // it: a rule-backed audience cannot enter claims, so the claims gate would
156
+ // hold the experiment dormant, and the selected leg is the fact the
157
+ // planner's sum built this route's tuples for. Out of selection there is no
158
+ // bucket, assignment, exposure, or rule-rejection record.
159
+ function experimentEligible(item, claims, selectedLegAudienceId) {
160
+ if (item.eligibilityMode === 'selected')
161
+ return selectedModeFactorOf(item, selectedLegAudienceId);
162
+ const audienceID = String(item.eligibilityAudienceId || '').trim();
163
+ if (!audienceID)
164
+ return true;
165
+ return !!claims && (claims.aud || []).includes(audienceID);
166
+ }
167
+ // selectedModeFactorOf is the decision core's spelling of the planner's
168
+ // leg-membership predicate (ADR 0050) — one name, one rule, two runtimes:
169
+ // experiment.SelectedModeFactorOf in Go, applied by Assign and by the
170
+ // contentbuild planner's leg factors, candidates, and Lookup. A
171
+ // selected-mode experiment with an unresolved eligibility audience is a
172
+ // factor of no leg, base included. Both inputs are canonical by variant-key
173
+ // construction (the variant-key reader and the strict document decode
174
+ // pre-trim them), so this comparison needs no normalization — the Go twin's TrimSpace
175
+ // is defensive only and never changes the outcome.
176
+ function selectedModeFactorOf(item, legAudienceId) {
177
+ const audienceID = String(item.eligibilityAudienceId || '').trim();
178
+ return audienceID !== '' && audienceID === legAudienceId;
74
179
  }
75
180
  function assignExperiment(experiment, identity) {
76
181
  const version = String(experiment.allocationVersion || '').trim();
@@ -93,25 +198,20 @@ function assignExperiment(experiment, identity) {
93
198
  experimentId: experiment.id,
94
199
  armId: arm.id,
95
200
  allocationVersion: version,
96
- variantKey: arm.variantKey,
201
+ variantKey: `experiment.${experiment.id}=${arm.id}`,
97
202
  bucket,
98
203
  };
99
204
  }
100
205
  }
101
206
  return null;
102
207
  }
103
- function betterVariant(candidatePriority, candidateKey, bestPriority, bestKey) {
104
- if (candidatePriority !== bestPriority)
105
- return candidatePriority > bestPriority;
106
- return String(candidateKey || '').localeCompare(String(bestKey || '')) < 0;
107
- }
108
208
  function requestDimensionsMatch(request, values) {
109
209
  for (const rawKey in values) {
110
210
  const rawWant = values[rawKey];
111
211
  const key = String(rawKey).trim();
112
212
  const normalized = key.toLowerCase();
113
213
  const want = String(rawWant).trim();
114
- if (!key || !want || ['audience', 'segment', 'experiment', 'experimentarm'].includes(normalized))
214
+ if (!key || !want || ['audience', 'segment'].includes(normalized) || normalized.startsWith('experiment.'))
115
215
  continue;
116
216
  const candidates = (request.query[key] || []).concat(request.query['aci_' + key] || [], request.headers['x-aci-' + normalized] || '', request.headers['x-gradial-' + normalized] || '', request.cookies[key] || '', request.cookies['aci_' + key] || '');
117
217
  if (normalized === 'locale') {
@@ -127,52 +227,565 @@ function requestDimensionsMatch(request, values) {
127
227
  }
128
228
  return true;
129
229
  }
130
- function evaluateRule(request, rule) {
131
- const all = (rule.all || []);
132
- const any = (rule.any || []);
230
+ const MAX_EXPRESSION_CONDITIONS = 64;
231
+ // Authored nesting depth (ADR 0040). The top-level envelope is depth 1 and a
232
+ // group node is one deeper than the list containing it. Pinned to the
233
+ // capability artifact by the drift test, like the grammars above.
234
+ const MAX_EXPRESSION_DEPTH = 5;
235
+ // A member carrying `all` or `any` is an envelope, not a condition. Presence
236
+ // decides — never the value's type — so all three runtimes classify the same
237
+ // member the same way.
238
+ function isExpressionGroup(member) {
239
+ // Null-guarded because this runs on a viewer request path: a malformed
240
+ // member must fail closed to the base experience, never throw. A non-object
241
+ // member is classified as a leaf and rejected by ordinary validation.
242
+ return !!member && typeof member === 'object'
243
+ && (Object.prototype.hasOwnProperty.call(member, 'all')
244
+ || Object.prototype.hasOwnProperty.call(member, 'any'));
245
+ }
246
+ // expressionMembers returns a group node's member list: [] when the key is
247
+ // absent, null when it is present but not an array. Go rejects that document
248
+ // at decode; here it fails closed as a diagnostic rather than letting the
249
+ // member reclassify as a leaf.
250
+ function expressionMembers(member, group) {
251
+ if (!Object.prototype.hasOwnProperty.call(member, group))
252
+ return [];
253
+ const value = member[group];
254
+ if (!Array.isArray(value))
255
+ return null;
256
+ return value;
257
+ }
258
+ // countExpressionLeaves counts leaves across the tree, applying the same depth
259
+ // cutoff the validating walk does so the two bounds cannot disagree about one
260
+ // expression.
261
+ function countExpressionLeaves(members, depth) {
262
+ let total = 0;
263
+ for (const member of members) {
264
+ if (!isExpressionGroup(member)) {
265
+ total++;
266
+ continue;
267
+ }
268
+ if (depth + 1 > MAX_EXPRESSION_DEPTH)
269
+ continue;
270
+ total += countExpressionLeaves(expressionMembers(member, 'all') || [], depth + 1)
271
+ + countExpressionLeaves(expressionMembers(member, 'any') || [], depth + 1);
272
+ }
273
+ return total;
274
+ }
275
+ /** Evaluate one request expression and produce the same redacted trace used for qualification. */
276
+ export function evaluateRequestExpression(rule, resolve) {
277
+ const all = (Array.isArray(rule.all) ? rule.all : []);
278
+ const any = (Array.isArray(rule.any) ? rule.any : []);
279
+ const empty = all.length + any.length === 0;
280
+ const diagnostics = validateRequestExpression(rule, all, any);
281
+ const trace = { scope: 'request', empty, groups: [], leaves: [] };
282
+ if (diagnostics.length > 0)
283
+ return { qualified: false, diagnostics, trace };
284
+ const qualified = qualifyRequestExpression(all, any, resolve, trace);
285
+ return { qualified, diagnostics, trace };
286
+ }
287
+ function evaluateRule(request, rule, claims, variantKey) {
288
+ const all = (Array.isArray(rule.all) ? rule.all : []);
289
+ const any = (Array.isArray(rule.any) ? rule.any : []);
290
+ const diagnostics = validateRequestExpression(rule, all, any);
291
+ if (diagnostics.length > 0) {
292
+ // Records pass the write-time gate before they ship, so a rule rejected
293
+ // HERE — at serve time — is always version skew or a projection bug, never
294
+ // ordinary authoring error. That makes it a precise signal, and discarding
295
+ // it silently is what made the predicted incident (author previews a rule
296
+ // successfully while a stale lane serves base) undebuggable (ADR 0040).
297
+ // Codes and paths only; never a fact, operand, or request value.
298
+ if (request.onRuleRejected) {
299
+ request.onRuleRejected({
300
+ variantKey: variantKey || '',
301
+ diagnosticCode: diagnostics[0].code,
302
+ diagnosticPath: diagnostics[0].path,
303
+ diagnosticCount: diagnostics.length,
304
+ });
305
+ }
306
+ return false;
307
+ }
308
+ // audience.memberships resolves from the verified (or mimic) claims object
309
+ // the decision entry points already hold, never from the request bag — an
310
+ // unverified cookie can never impersonate membership (ADR 0039).
311
+ return qualifyRequestExpression(all, any, (field) => field === 'audience.memberships'
312
+ ? membershipsFact(claims)
313
+ : signalFact(request, field));
314
+ }
315
+ // No claims → unavailable: an unconsented visitor is not a known non-member,
316
+ // so every operator fails closed, exists:false included. Verified claims with
317
+ // no memberships → absent, so exists:false selects exactly the consented
318
+ // visitor who belongs to nothing (ADR 0039).
319
+ function membershipsFact(claims) {
320
+ if (!claims)
321
+ return { status: 'unavailable' };
322
+ // Array.isArray, not || []: a malformed truthy aud (a scalar from a buggy
323
+ // claims writer) must degrade to absent, never reach the matcher's
324
+ // .some() and throw on a viewer-request path.
325
+ const memberships = Array.isArray(claims.aud) ? claims.aud : [];
326
+ return memberships.length > 0 ? { status: 'present', values: memberships } : { status: 'absent' };
327
+ }
328
+ function validateRequestExpression(rule, all, any) {
329
+ const diagnostics = [];
133
330
  if (all.length + any.length === 0)
331
+ diagnostics.push({ code: 'expression.empty', path: 'expression', scope: 'request', message: 'expression must include at least one all or any condition' });
332
+ if (countExpressionLeaves(all, 1) + countExpressionLeaves(any, 1) > MAX_EXPRESSION_CONDITIONS)
333
+ diagnostics.push({ code: 'expression.conditions.too_many', path: 'expression', scope: 'request', message: `expression must contain at most ${MAX_EXPRESSION_CONDITIONS} conditions` });
334
+ Object.keys(rule).filter((group) => group !== 'all' && group !== 'any').sort().forEach((group) => {
335
+ diagnostics.push({ code: 'expression.group.unsupported', path: `expression.${group}`, scope: 'request', message: `expression.${group} is not a supported expression group` });
336
+ });
337
+ for (const [group, members] of [['all', all], ['any', any]]) {
338
+ validateExpressionMembers('expression', group, members, 1, diagnostics);
339
+ }
340
+ return diagnostics;
341
+ }
342
+ // validateExpressionMembers validates one envelope's member list. depth is the
343
+ // depth of the envelope owning these members; the top-level envelope is 1.
344
+ function validateExpressionMembers(path, group, members, depth, diagnostics) {
345
+ members.forEach((member, index) => {
346
+ const memberPath = `${path}.${group}[${index}]`;
347
+ if (!member || typeof member !== 'object' || !isExpressionGroup(member)) {
348
+ validateRequestCondition(member || {}, memberPath, diagnostics);
349
+ return;
350
+ }
351
+ // One diagnostic per broken node, and no descent past it: a too-deep
352
+ // branch reports its depth once rather than once per buried condition.
353
+ if (depth + 1 > MAX_EXPRESSION_DEPTH) {
354
+ diagnostics.push({ code: 'expression.depth.exceeded', path: memberPath, scope: 'request', message: `${memberPath} must not nest more than ${MAX_EXPRESSION_DEPTH} levels deep` });
355
+ return;
356
+ }
357
+ const nestedAll = expressionMembers(member, 'all');
358
+ const nestedAny = expressionMembers(member, 'any');
359
+ if (nestedAll === null || nestedAny === null) {
360
+ const malformed = nestedAll === null ? 'all' : 'any';
361
+ diagnostics.push({ code: 'expression.group.unsupported', path: `${memberPath}.${malformed}`, scope: 'request', message: `${memberPath}.${malformed} must be an array of conditions or groups` });
362
+ return;
363
+ }
364
+ if (nestedAll.length + nestedAny.length === 0) {
365
+ diagnostics.push({ code: 'expression.empty', path: memberPath, scope: 'request', message: `${memberPath} must include at least one all or any condition` });
366
+ return;
367
+ }
368
+ Object.keys(member).filter((key) => key !== 'all' && key !== 'any').sort().forEach((key) => {
369
+ // Name the mistake, not its symptom: telling an author that `field` "is
370
+ // not a supported group" describes the classification, not the error.
371
+ const message = key === 'field' || key === 'operator' || key === 'value'
372
+ ? `${memberPath}.${key} is not supported: a member carrying all or any is a group, not a condition, so it cannot also carry ${key}`
373
+ : `${memberPath}.${key} is not a supported expression group`;
374
+ diagnostics.push({ code: 'expression.group.unsupported', path: `${memberPath}.${key}`, scope: 'request', message });
375
+ });
376
+ validateExpressionMembers(memberPath, 'all', nestedAll, depth + 1, diagnostics);
377
+ validateExpressionMembers(memberPath, 'any', nestedAny, depth + 1, diagnostics);
378
+ });
379
+ }
380
+ // qualifyRequestExpression applies the envelope truth table to one node's
381
+ // member lists, recursing through group nodes (ADR 0040). Evaluation stays
382
+ // exhaustive so the trace holds every leaf outcome.
383
+ //
384
+ // topLevel carries nesting's one asymmetry: the top envelope always records
385
+ // both group rows because they express the scope's empty-envelope policy,
386
+ // while a nested node records only for a list it carries members in — which
387
+ // also keeps the trace stable across a serialization that drops empty lists.
388
+ function qualifyRequestExpression(all, any, resolve, trace, path = 'expression', topLevel = true) {
389
+ let qualified = true;
390
+ for (const [group, members] of [['all', all], ['any', any]]) {
391
+ if (!topLevel && members.length === 0)
392
+ continue;
393
+ let matched = 0;
394
+ members.forEach((member, index) => {
395
+ const memberPath = `${path}.${group}[${index}]`;
396
+ let passed = false;
397
+ if (isExpressionGroup(member)) {
398
+ passed = qualifyRequestExpression(expressionMembers(member, 'all') || [], expressionMembers(member, 'any') || [], resolve, trace, memberPath, false);
399
+ }
400
+ else {
401
+ const fact = normalizeFact(resolve(String(member.field || '')));
402
+ const outcome = matchRequestCondition(member, fact);
403
+ passed = outcome.matched;
404
+ if (trace)
405
+ trace.leaves.push({
406
+ path: memberPath, group, index,
407
+ field: String(member.field || ''), operator: String(member.operator || ''),
408
+ status: fact.status, matched: outcome.matched, reason: outcome.reason,
409
+ });
410
+ }
411
+ if (passed)
412
+ matched++;
413
+ });
414
+ const passed = group === 'all' ? matched === members.length : members.length === 0 || matched > 0;
415
+ if (trace)
416
+ trace.groups.push({ path: `${path}.${group}`, group, total: members.length, matched, passed });
417
+ qualified = qualified && passed;
418
+ }
419
+ return qualified;
420
+ }
421
+ function validateRequestCondition(condition, path, diagnostics) {
422
+ Object.keys(condition).filter((property) => !['field', 'operator', 'value'].includes(property)).sort().forEach((property) => {
423
+ diagnostics.push({ code: 'expression.property.unsupported', path: `${path}.${property}`, scope: 'request', message: `${path}.${property} is not a supported condition property` });
424
+ });
425
+ const field = String(condition.field || '');
426
+ if (field !== 'referrer' && field !== 'device.class' && field !== 'time.now' && field !== 'audience.memberships' && !['query.', 'header.', 'cookie.', 'geo.', 'utm.'].some((prefix) => field.startsWith(prefix) && field.length > prefix.length)) {
427
+ diagnostics.push({ code: 'expression.field.unsupported', path: `${path}.field`, scope: 'request', message: `${path}.field ${JSON.stringify(field)} is not supported` });
428
+ }
429
+ const operator = String(condition.operator || '');
430
+ if (!EXPRESSION_OPERATORS.includes(operator)) {
431
+ diagnostics.push({ code: 'expression.operator.unsupported', path: `${path}.operator`, scope: 'request', message: `${path}.operator ${JSON.stringify(operator)} is not supported` });
432
+ return;
433
+ }
434
+ // device.class compares against a closed four-value set, so substring
435
+ // operators express nothing the set cannot — and admitting them would
436
+ // re-create the user-agent-substring habit inside the safe field (ADR 0037).
437
+ if (field === 'device.class' && !['equals', 'in', 'exists'].includes(operator)) {
438
+ diagnostics.push({ code: 'expression.operator.unsupported', path: `${path}.operator`, scope: 'request', message: `${path}.operator ${JSON.stringify(operator)} is not supported for field ${JSON.stringify(field)}, which compares against a closed value set` });
439
+ return;
440
+ }
441
+ // time.now is a sub-second-churning clock: string operators are silently
442
+ // inert on it and the numeric family can never match an RFC 3339 string
443
+ // (ADR 0038).
444
+ if (field === 'time.now' && !['before', 'after', 'between', 'exists'].includes(operator)) {
445
+ diagnostics.push({ code: 'expression.operator.unsupported', path: `${path}.operator`, scope: 'request', message: `${path}.operator ${JSON.stringify(operator)} is not supported for field ${JSON.stringify(field)}, which supports only before, after, between, exists` });
446
+ return;
447
+ }
448
+ // audience.memberships is an opaque-ID list: equals is already
449
+ // any-member-equals under the multi-valued match loop, so the substring
450
+ // family would only add silent overmatching of prefixed IDs, and the
451
+ // numeric/instant families can never match an ID (ADR 0039).
452
+ if (field === 'audience.memberships' && !['equals', 'in', 'exists'].includes(operator)) {
453
+ diagnostics.push({ code: 'expression.operator.unsupported', path: `${path}.operator`, scope: 'request', message: `${path}.operator ${JSON.stringify(operator)} is not supported for field ${JSON.stringify(field)}, which supports only equals, in, exists` });
454
+ return;
455
+ }
456
+ const value = condition.value;
457
+ if (operator === 'exists') {
458
+ if (value !== undefined && value !== null && typeof value !== 'boolean') {
459
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be a boolean for operator exists` });
460
+ }
461
+ return;
462
+ }
463
+ if (value === undefined || value === null) {
464
+ diagnostics.push({ code: 'expression.value.required', path: `${path}.value`, scope: 'request', message: `${path}.value is required for operator ${operator}` });
465
+ return;
466
+ }
467
+ if (['equals', 'contains', 'startsWith'].includes(operator)) {
468
+ if (!['string', 'number', 'boolean'].includes(typeof value)
469
+ || (typeof value === 'number' && !expressionNumberInDomain(value))) {
470
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be a string, boolean, or finite number using only safe integers` });
471
+ }
472
+ else if (field === 'device.class' && DEVICE_CLASSES.indexOf(canonicalScalar(value)) < 0) {
473
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be one of ${DEVICE_CLASSES.join(', ')} for field ${JSON.stringify(field)}` });
474
+ }
475
+ return;
476
+ }
477
+ if (['greaterThan', 'greaterThanOrEqual', 'lessThan', 'lessThanOrEqual'].includes(operator)) {
478
+ if (typeof value !== 'number' || !expressionNumberInDomain(value)) {
479
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be a finite JSON number using only safe integers for operator ${operator}` });
480
+ }
481
+ return;
482
+ }
483
+ if (operator === 'before' || operator === 'after') {
484
+ if (typeof value !== 'string' || parseExpressionTimestamp(value) === null) {
485
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be an RFC 3339 timestamp with an explicit UTC offset for operator ${operator}` });
486
+ }
487
+ return;
488
+ }
489
+ if (operator === 'between') {
490
+ if (!validExpressionRange(value)) {
491
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be a min/max object whose bounds are both numbers or both timestamps with min not above max` });
492
+ }
493
+ else if (field === 'time.now' && typeof value.min === 'number') {
494
+ // An instant field's observed values are instants: a numeric range on
495
+ // it would validate and then sit silently inert at execution.
496
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value bounds must be timestamps for field ${JSON.stringify(field)}` });
497
+ }
498
+ return;
499
+ }
500
+ // in: bounded, non-empty, every member one canonicalizable scalar, all
501
+ // members one JSON type — a mixed list is almost always an authoring bug.
502
+ const members = homogeneousExpressionMembers(value);
503
+ if (members === null) {
504
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be an array of 1 to ${MAX_IN_VALUES} scalars sharing one type` });
505
+ return;
506
+ }
507
+ if (field === 'device.class') {
508
+ for (const member of members) {
509
+ if (DEVICE_CLASSES.indexOf(member) < 0) {
510
+ diagnostics.push({ code: 'expression.value.invalid', path: `${path}.value`, scope: 'request', message: `${path}.value must be one of ${DEVICE_CLASSES.join(', ')} for field ${JSON.stringify(field)}` });
511
+ return;
512
+ }
513
+ }
514
+ }
515
+ }
516
+ function matchRequestCondition(condition, fact) {
517
+ if (fact.status === 'unavailable')
518
+ return { matched: false, reason: 'unavailable' };
519
+ if (condition.operator === 'exists') {
520
+ const expected = typeof condition.value === 'boolean' ? condition.value : true;
521
+ const matched = (fact.status === 'present') === expected;
522
+ return { matched, reason: matched ? 'matched' : fact.status === 'absent' ? 'absent' : 'not_matched' };
523
+ }
524
+ if (fact.status === 'absent')
525
+ return { matched: false, reason: 'absent' };
526
+ const matcher = expressionConditionMatcher(condition);
527
+ if (!matcher)
528
+ return { matched: false, reason: 'not_matched' };
529
+ const matched = (fact.values || []).some(matcher);
530
+ return { matched, reason: matched ? 'matched' : 'not_matched' };
531
+ }
532
+ export const EXPRESSION_OPERATORS = [
533
+ 'equals', 'contains', 'startsWith', 'exists',
534
+ 'greaterThan', 'greaterThanOrEqual', 'lessThan', 'lessThanOrEqual',
535
+ 'before', 'after', 'between', 'in',
536
+ ];
537
+ const MAX_IN_VALUES = 32;
538
+ // Observed values are gated on the published grammars before any host parser
539
+ // runs (ADR 0038): Number() and Date.parse accept supersets (hex, empty
540
+ // string, vendor date formats) that would let the same fact match here and
541
+ // not in Go. Keep these literals identical to the capability artifact — the
542
+ // drift test compares them byte-for-byte.
543
+ export const EXPRESSION_NUMBER_GRAMMAR = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
544
+ export const EXPRESSION_TIMESTAMP_GRAMMAR = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
545
+ function expressionNumberInDomain(value) {
546
+ if (!Number.isFinite(value))
547
+ return false;
548
+ if (Number.isInteger(value) && !Number.isSafeInteger(value))
549
+ return false;
550
+ return true;
551
+ }
552
+ function parseObservedExpressionNumber(value) {
553
+ if (!EXPRESSION_NUMBER_GRAMMAR.test(value))
554
+ return null;
555
+ const parsed = Number(value);
556
+ return expressionNumberInDomain(parsed) ? parsed : null;
557
+ }
558
+ // Explicit calendar validation runs before Date arithmetic because Date.UTC
559
+ // (like Go's time.Date) silently normalizes impossible dates. Instants
560
+ // compare as epoch milliseconds; fractional seconds truncate to milliseconds.
561
+ function parseExpressionTimestamp(value) {
562
+ const match = EXPRESSION_TIMESTAMP_GRAMMAR.exec(value);
563
+ if (!match)
564
+ return null;
565
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
566
+ const hour = Number(match[4]), minute = Number(match[5]), second = Number(match[6]);
567
+ if (month < 1 || month > 12 || day < 1 || day > expressionDaysInMonth(year, month))
568
+ return null;
569
+ if (hour > 23 || minute > 59 || second > 59)
570
+ return null;
571
+ let offsetMinutes = 0;
572
+ if (match[8] !== 'Z') {
573
+ const offsetHour = Number(match[8].slice(1, 3)), offsetMinute = Number(match[8].slice(4, 6));
574
+ if (offsetHour > 23 || offsetMinute > 59)
575
+ return null;
576
+ offsetMinutes = offsetHour * 60 + offsetMinute;
577
+ if (match[8][0] === '-')
578
+ offsetMinutes = -offsetMinutes;
579
+ }
580
+ const fractionMillis = match[7] ? Number((match[7].slice(1) + '00').slice(0, 3)) : 0;
581
+ // setUTCFullYear, not Date.UTC: Date.UTC maps two-digit years to 1900+.
582
+ const date = new Date(0);
583
+ date.setUTCFullYear(year, month - 1, day);
584
+ date.setUTCHours(hour, minute, second, 0);
585
+ return date.getTime() - offsetMinutes * 60000 + fractionMillis;
586
+ }
587
+ function expressionDaysInMonth(year, month) {
588
+ if (month === 4 || month === 6 || month === 9 || month === 11)
589
+ return 30;
590
+ if (month === 2)
591
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
592
+ return 31;
593
+ }
594
+ function scalarExpressionOperand(value) {
595
+ if (value === undefined || value === null)
596
+ return null;
597
+ const kind = typeof value;
598
+ if (kind !== 'string' && kind !== 'number' && kind !== 'boolean')
599
+ return null;
600
+ if (kind === 'number' && !expressionNumberInDomain(value))
601
+ return null;
602
+ return canonicalScalar(value);
603
+ }
604
+ function validExpressionRange(value) {
605
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
134
606
  return false;
135
- return all.every((condition) => evaluateCondition(request, condition))
136
- && (any.length === 0 || any.some((condition) => evaluateCondition(request, condition)));
137
- }
138
- function evaluateCondition(request, condition) {
139
- const values = signalValues(request, String(condition.field || ''));
140
- if (condition.operator === 'exists')
141
- return values.length > 0;
142
- if (values.length === 0 || typeof condition.value !== 'string' && typeof condition.value !== 'number' && typeof condition.value !== 'boolean')
607
+ const record = value;
608
+ if (Object.keys(record).some((key) => key !== 'min' && key !== 'max'))
143
609
  return false;
144
- const e = String(condition.value);
145
- if (condition.operator === 'equals')
146
- return values.some(v => v === e);
147
- if (condition.operator === 'contains')
148
- return values.some(v => v.includes(e));
149
- if (condition.operator === 'startsWith')
150
- return values.some(v => v.startsWith(e));
151
- return false;
152
- }
153
- function signalValues(request, field) {
610
+ const min = record.min, max = record.max;
611
+ if (min === undefined || min === null || max === undefined || max === null)
612
+ return false;
613
+ if (typeof min === 'number' && expressionNumberInDomain(min)) {
614
+ return typeof max === 'number' && expressionNumberInDomain(max) && min <= max;
615
+ }
616
+ const minMillis = typeof min === 'string' ? parseExpressionTimestamp(min) : null;
617
+ if (minMillis === null)
618
+ return false;
619
+ const maxMillis = typeof max === 'string' ? parseExpressionTimestamp(max) : null;
620
+ return maxMillis !== null && minMillis <= maxMillis;
621
+ }
622
+ function homogeneousExpressionMembers(value) {
623
+ if (!Array.isArray(value) || value.length === 0 || value.length > MAX_IN_VALUES)
624
+ return null;
625
+ let memberKind = '';
626
+ const members = [];
627
+ for (const member of value) {
628
+ const kind = typeof member;
629
+ if (kind !== 'string' && kind !== 'number' && kind !== 'boolean')
630
+ return null;
631
+ if (kind === 'number' && !expressionNumberInDomain(member))
632
+ return null;
633
+ if (!memberKind)
634
+ memberKind = kind;
635
+ else if (memberKind !== kind)
636
+ return null;
637
+ members.push(canonicalScalar(member));
638
+ }
639
+ return members;
640
+ }
641
+ // expressionConditionMatcher builds the per-observed-value predicate for one
642
+ // condition. Null means the authored side cannot be interpreted — validation
643
+ // rejects those expressions first, so this only fails closed for direct use.
644
+ function expressionConditionMatcher(condition) {
645
+ const operator = String(condition.operator || '');
646
+ const operand = condition.value;
647
+ switch (operator) {
648
+ case 'equals':
649
+ case 'contains':
650
+ case 'startsWith': {
651
+ const expected = scalarExpressionOperand(operand);
652
+ if (expected === null)
653
+ return null;
654
+ return (value) => operator === 'equals' ? value === expected
655
+ : operator === 'contains' ? value.includes(expected) : value.startsWith(expected);
656
+ }
657
+ case 'greaterThan':
658
+ case 'greaterThanOrEqual':
659
+ case 'lessThan':
660
+ case 'lessThanOrEqual': {
661
+ if (typeof operand !== 'number' || !expressionNumberInDomain(operand))
662
+ return null;
663
+ return (value) => {
664
+ const observed = parseObservedExpressionNumber(value);
665
+ if (observed === null)
666
+ return false;
667
+ return operator === 'greaterThan' ? observed > operand
668
+ : operator === 'greaterThanOrEqual' ? observed >= operand
669
+ : operator === 'lessThan' ? observed < operand : observed <= operand;
670
+ };
671
+ }
672
+ case 'before':
673
+ case 'after': {
674
+ const operandMillis = typeof operand === 'string' ? parseExpressionTimestamp(operand) : null;
675
+ if (operandMillis === null)
676
+ return null;
677
+ return (value) => {
678
+ const observed = parseExpressionTimestamp(value);
679
+ if (observed === null)
680
+ return false;
681
+ return operator === 'after' ? observed > operandMillis : observed < operandMillis;
682
+ };
683
+ }
684
+ case 'between': {
685
+ if (!validExpressionRange(operand))
686
+ return null;
687
+ const record = operand;
688
+ if (typeof record.min === 'number') {
689
+ const min = record.min, max = record.max;
690
+ return (value) => {
691
+ const observed = parseObservedExpressionNumber(value);
692
+ return observed !== null && observed >= min && observed <= max;
693
+ };
694
+ }
695
+ const min = parseExpressionTimestamp(record.min);
696
+ const max = parseExpressionTimestamp(record.max);
697
+ return (value) => {
698
+ const observed = parseExpressionTimestamp(value);
699
+ return observed !== null && observed >= min && observed <= max;
700
+ };
701
+ }
702
+ case 'in': {
703
+ if (!Array.isArray(operand) || operand.length === 0 || operand.length > MAX_IN_VALUES)
704
+ return null;
705
+ const members = [];
706
+ for (const member of operand) {
707
+ const canonical = scalarExpressionOperand(member);
708
+ if (canonical === null)
709
+ return null;
710
+ members.push(canonical);
711
+ }
712
+ return (value) => members.includes(value);
713
+ }
714
+ default:
715
+ return null;
716
+ }
717
+ }
718
+ function canonicalScalar(value) {
719
+ if (typeof value === 'number')
720
+ return Object.is(value, -0) ? '0' : JSON.stringify(value);
721
+ return String(value);
722
+ }
723
+ function normalizeFact(fact) {
724
+ if (!fact || !['present', 'absent', 'unavailable'].includes(fact.status))
725
+ return { status: 'unavailable' };
726
+ return fact;
727
+ }
728
+ function signalFact(request, field) {
729
+ const own = (record, key) => !!record && Object.prototype.hasOwnProperty.call(record, key);
154
730
  const d = field.indexOf('.');
155
- if (d < 0)
156
- return field === 'referrer' ? [request.headers.referer || request.headers.referrer].filter(Boolean) : [];
731
+ if (d < 0) {
732
+ if (field !== 'referrer')
733
+ return { status: 'absent' };
734
+ const key = own(request.headers, 'referer') ? 'referer' : 'referrer';
735
+ return own(request.headers, key) ? { status: 'present', values: [request.headers[key]] } : { status: 'absent' };
736
+ }
157
737
  const p = field.slice(0, d), k = field.slice(d + 1);
158
738
  if (p === 'query')
159
- return request.query[k] || [];
160
- if (p === 'utm')
161
- return request.query['utm_' + k] || [];
739
+ return own(request.query, k) ? { status: 'present', values: request.query[k] } : { status: 'absent' };
740
+ if (p === 'utm') {
741
+ const key = 'utm_' + k;
742
+ return own(request.query, key) ? { status: 'present', values: request.query[key] } : { status: 'absent' };
743
+ }
162
744
  if (p === 'header') {
163
- const v = request.headers[k.toLowerCase()];
164
- return v ? [v] : [];
745
+ const key = k.toLowerCase();
746
+ return own(request.headers, key) ? { status: 'present', values: [request.headers[key]] } : { status: 'absent' };
165
747
  }
166
- if (p === 'cookie') {
167
- const v = request.cookies[k];
168
- return v ? [v] : [];
748
+ if (p === 'cookie')
749
+ return own(request.cookies, k) ? { status: 'present', values: [request.cookies[k]] } : { status: 'absent' };
750
+ if (p === 'device') {
751
+ // Derived, not injected: no signals plumbing, so preview, edge, and SDK
752
+ // agree by construction. A request with no user-agent header is absent.
753
+ if (k !== 'class')
754
+ return { status: 'absent' };
755
+ const deviceClass = cachedDeviceClass(request);
756
+ return deviceClass ? { status: 'present', values: [deviceClass] } : { status: 'absent' };
169
757
  }
170
758
  if (p === 'geo') {
171
- const g = request.signals && request.signals.geo;
172
- const v = g && g[k.toLowerCase()];
173
- return v ? [v] : [];
759
+ const record = request.signals?.geo;
760
+ if (!record)
761
+ return { status: 'unavailable' };
762
+ return own(record, k) ? { status: 'present', values: [record[k]] } : { status: 'absent' };
174
763
  }
175
- return [];
764
+ if (p === 'time') {
765
+ // The one clock fact (ADR 0038): resolved from the runtime's own clock,
766
+ // one RFC 3339 UTC value, so the kernel stays clock-free. Hosts set
767
+ // request.now (epoch ms) once per request for determinism.
768
+ if (k !== 'now')
769
+ return { status: 'absent' };
770
+ return { status: 'present', values: [cachedTimeNow(request)] };
771
+ }
772
+ return { status: 'absent' };
773
+ }
774
+ const TIME_NOW_CACHE = new WeakMap();
775
+ // cachedTimeNow resolves the clock ONCE per request context, like
776
+ // cachedDeviceClass: every time.now leaf in one evaluation reads the same
777
+ // instant. A host-supplied request.now outside Date's representable range
778
+ // falls back to the runtime clock rather than throwing from a viewer-request
779
+ // path — this module fails closed, never open.
780
+ function cachedTimeNow(request) {
781
+ const hit = TIME_NOW_CACHE.get(request);
782
+ if (hit !== undefined)
783
+ return hit;
784
+ const pinned = typeof request.now === 'number' && Number.isFinite(request.now)
785
+ && Math.abs(request.now) <= 8640000000000000 ? request.now : Date.now();
786
+ const value = new Date(pinned).toISOString();
787
+ TIME_NOW_CACHE.set(request, value);
788
+ return value;
176
789
  }
177
790
  // SHA-256 mirrors experiment/assignment.go: the first eight digest bytes are
178
791
  // interpreted big-endian and reduced modulo 10,000 basis points. Keep the
@@ -257,114 +870,91 @@ function utf8(value) {
257
870
  }
258
871
  return new Uint8Array(out);
259
872
  }
260
- // ── Normalized two-phase model: classify → decide ─────────────────────
873
+ // ── Derived request device class (ADR 0037) ──────────────────────────
261
874
  //
262
- // Phase 1 (classify): evaluate all audience/segment rules page-agnostically
263
- // and assign experiment arms. Returns a Classification that is used by
264
- // Phase 2 for cheap set-membership lookups per route.
875
+ // device.class is the one request fact that is neither transcribed from the
876
+ // request nor injected as a signal: it is classified here from headers the
877
+ // request already carries, so this module, the released SDK copy, and the Go
878
+ // preview evaluator agree without three separate plumbing points.
265
879
  //
266
- // Phase 2 (decide): for a given route record, check which variants match
267
- // the classification (set membership + priority). No rule evaluation —
268
- // just "is this audience in matchedAudiences?" and "is this experiment arm
269
- // the one we assigned?"
270
- //
271
- // The per-route record stays small: just variant keys (e.g.
272
- // "audience=trade") + priorities. Rules live in the classification data,
273
- // evaluated once per request.
880
+ // The ORDER below is the contract, not an implementation detail. It is fixed
881
+ // by internal/domain/audience/testdata/device-class.v1.json, which Go and both
882
+ // TypeScript copies execute. Change the order only by changing that fixture.
274
883
  //
884
+ // The result is approximate and derived from client-controlled input: a
885
+ // personalization convenience, never an authorization or entitlement input.
886
+ export const DEVICE_CLASSES = ['desktop', 'mobile', 'tablet', 'unknown'];
887
+ // Mirrors MaxDeviceHeaderBytes in internal/domain/audience/device.go.
888
+ const MAX_DEVICE_HEADER_BYTES = 512;
889
+ // Tablet runs first because Android tablet agents contain "android" (mobile)
890
+ // and every Android agent contains "linux" (desktop); iPad agents contain
891
+ // neither. Sec-CH-UA-Mobile is a tiebreaker rather than the primary source
892
+ // because UA-CH cannot express tablet at all.
893
+ const DEVICE_TABLET_SIGNATURES = ['ipad', 'tablet', 'playbook', 'kindle', 'silk'];
894
+ // 'iemobile' is deliberately absent: it contains 'mobi' and could never
895
+ // match. Every signature must be reachable given the ones before it.
896
+ const DEVICE_MOBILE_SIGNATURES = ['iphone', 'ipod', 'mobi', 'windows phone', 'blackberry', 'opera mini'];
897
+ const DEVICE_DESKTOP_SIGNATURES = ['windows nt', 'macintosh', 'mac os x', 'x11', 'cros', 'linux'];
275
898
  /**
276
- * Phase 1: Classify the visitor against all release-level rules.
277
- *
278
- * @param ctx The request context (cookies, headers, geo, query)
279
- * @param data Release-level classification data (audiences, segments, experiments)
280
- * @param identity Visitor identity (for experiment bucketing). Pass undefined
281
- * if no identity or privacy denied.
282
- * @returns Classification — matched audiences, segments, and experiment arm assignments
899
+ * Classifies the request's device class from its own headers. Returns '' when
900
+ * the request carried neither User-Agent nor Sec-CH-UA-Mobile, which the fact
901
+ * resolver reports as ABSENT — the same status the missing header itself
902
+ * resolves to, and deliberately distinct from the 'unknown' class, which means
903
+ * classified and unrecognized.
283
904
  */
284
- export function classify(ctx, data, identity) {
285
- // Evaluate audience rules
286
- const matchedAudiences = [];
287
- for (const key in data.audiences) {
288
- const def = data.audiences[key];
289
- if (def.rule && evaluateRule(ctx, def.rule)) {
290
- matchedAudiences.push(key);
291
- }
292
- }
293
- // Evaluate segment rules
294
- const matchedSegments = [];
295
- for (const key in data.segments) {
296
- const def = data.segments[key];
297
- if (def.rule && evaluateRule(ctx, def.rule)) {
298
- matchedSegments.push(key);
299
- }
300
- }
301
- // Assign experiment arms (only for identified visitors)
302
- const experimentArms = {};
303
- if (identity && identity.usable) {
304
- for (const expId in data.experiments) {
305
- const exp = data.experiments[expId];
306
- if (exp.status !== 'running')
307
- continue;
308
- if (exp.kind !== 'ab' && exp.kind !== 'abn')
309
- continue;
310
- const assignment = assignExperiment(exp, identity);
311
- if (assignment) {
312
- experimentArms[expId] = assignment;
313
- }
314
- }
315
- }
316
- return { matchedAudiences, matchedSegments, experimentArms };
905
+ export function deviceClassFromHeaders(headers) {
906
+ const userAgent = deviceHeader(headers, 'user-agent');
907
+ const uaMobile = deviceHeader(headers, 'sec-ch-ua-mobile');
908
+ if (!userAgent && !uaMobile)
909
+ return '';
910
+ const lower = userAgent.toLowerCase();
911
+ if (DEVICE_TABLET_SIGNATURES.some((token) => lower.indexOf(token) >= 0))
912
+ return 'tablet';
913
+ // An Android agent without a "mobi" token is a tablet: Chrome on Android
914
+ // phones appends "Mobile", Android tablets do not. The explicit !"mobi"
915
+ // guard is required, not redundant — the mobile pass runs AFTER this one.
916
+ if (lower.indexOf('android') >= 0 && lower.indexOf('mobi') < 0)
917
+ return 'tablet';
918
+ if (DEVICE_MOBILE_SIGNATURES.some((token) => lower.indexOf(token) >= 0))
919
+ return 'mobile';
920
+ if (uaMobile === '?1')
921
+ return 'mobile';
922
+ if (DEVICE_DESKTOP_SIGNATURES.some((token) => lower.indexOf(token) >= 0))
923
+ return 'desktop';
924
+ if (uaMobile === '?0')
925
+ return 'desktop';
926
+ return 'unknown';
317
927
  }
318
- /**
319
- * Phase 2: Decide the winning variant for a specific route.
320
- *
321
- * Uses the classification from Phase 1 for cheap set-membership lookups.
322
- * No rule evaluation — just set membership and priority comparison.
323
- *
324
- * @param record The route entry (path, dispatch, variants)
325
- * @param classification The visitor's classification from Phase 1
326
- * @returns The decision — winning variant + experiment assignment, or nulls
327
- */
328
- export function decide(record, classification, ctx) {
329
- if (!record.variants)
330
- return { variant: null, experiment: null };
331
- let bestVariant = null;
332
- let bestExperiment = null;
333
- for (const key in record.variants) {
334
- const variant = record.variants[key];
335
- if (!variant.variantKey)
336
- variant.variantKey = key;
337
- const values = variant.variantValues || variantValuesFromKey(key);
338
- // Check if this variant references a paused experiment — skip if so
339
- const experimentID = String(values.experiment || '').trim();
340
- if (experimentID && !classification.experimentArms[experimentID])
341
- continue;
342
- let matched = false;
343
- // Audience membership
344
- if (values.audience && classification.matchedAudiences.includes(values.audience)) {
345
- matched = true;
346
- }
347
- // Segment membership
348
- if (!matched && values.segment && classification.matchedSegments.includes(values.segment)) {
349
- matched = true;
350
- }
351
- // Experiment arm assignment
352
- if (!matched && experimentID) {
353
- const arm = classification.experimentArms[experimentID];
354
- if (arm && arm.variantKey === variant.variantKey) {
355
- matched = true;
356
- bestExperiment = arm;
357
- }
358
- }
359
- if (matched) {
360
- if (!bestVariant || betterVariant(variant.priority || 0, variant.variantKey, bestVariant.priority || 0, bestVariant.variantKey)) {
361
- bestVariant = variant;
362
- // Only set experiment if this variant's experiment arm won
363
- if (!experimentID || !classification.experimentArms[experimentID]) {
364
- bestExperiment = null;
365
- }
366
- }
367
- }
368
- }
369
- return { variant: bestVariant, experiment: bestExperiment };
928
+ // deviceHeader reads one header so that Go's audience.ClassifyDeviceClass
929
+ // cannot disagree with this function about the same request.
930
+ //
931
+ // Keys are lowercase here: every context builder flattens through the Fetch
932
+ // API, which lowercases. There is deliberately NO case-insensitive fallback —
933
+ // the header.* branch above has none either, and adding one for this field
934
+ // only would mean a device rule resolves where an equivalent header rule
935
+ // silently does not.
936
+ //
937
+ // Trimming is ASCII-only on purpose. String.prototype.trim strips U+FEFF but
938
+ // not U+0085; Go's strings.TrimSpace does the reverse. Neither is "right";
939
+ // they only have to match, so both sides trim the same ASCII set. The length
940
+ // bound matches MaxDeviceHeaderBytes in device.go — no signature lives past
941
+ // it, and the header is attacker-sized on an unauthenticated path.
942
+ function deviceHeader(headers, key) {
943
+ const raw = (headers && headers[key]) || '';
944
+ if (typeof raw !== 'string')
945
+ return '';
946
+ return raw.slice(0, MAX_DEVICE_HEADER_BYTES).replace(/^[ \t\r\n\f\v]+|[ \t\r\n\f\v]+$/g, '');
947
+ }
948
+ // The class describes the REQUEST, so it is identical for every leaf. An
949
+ // envelope may carry up to 64 conditions and a route many candidate variants,
950
+ // each building its own resolver — without this, one page view could lowercase
951
+ // and scan the user agent hundreds of times. Keyed on the context object, so
952
+ const DEVICE_CLASS_CACHE = new WeakMap();
953
+ function cachedDeviceClass(request) {
954
+ const hit = DEVICE_CLASS_CACHE.get(request);
955
+ if (hit !== undefined)
956
+ return hit;
957
+ const deviceClass = deviceClassFromHeaders(request.headers);
958
+ DEVICE_CLASS_CACHE.set(request, deviceClass);
959
+ return deviceClass;
370
960
  }