@gradial/aci 0.1.52-rc.16 → 0.1.52-rc.21

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 (48) hide show
  1. package/README.md +4 -4
  2. package/dist/astro/preview.js +2 -17
  3. package/dist/audience-data-models.d.ts +193 -16
  4. package/dist/audience-data-models.js +47 -2
  5. package/dist/collect/batcher.d.ts +6 -5
  6. package/dist/collect/batcher.js +6 -5
  7. package/dist/edge/expression-capabilities.v1.d.ts +106 -0
  8. package/dist/edge/expression-capabilities.v1.js +165 -0
  9. package/dist/internal/domain/edge/identity.js +1 -1
  10. package/dist/internal/domain/edge/mimic_token.js +1 -2
  11. package/dist/internal/domain/edge/personalization-core.d.ts +14 -4
  12. package/dist/internal/domain/edge/personalization-core.js +472 -54
  13. package/dist/internal/domain/edge/record/codec.d.ts +5 -2
  14. package/dist/internal/domain/edge/record/codec.js +83 -10
  15. package/dist/internal/domain/edge/resolve.js +13 -2
  16. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.d.ts +10 -0
  17. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.js +253 -0
  18. package/dist/internal/domain/edge/types.d.ts +36 -9
  19. package/dist/internal/domain/edge/types.js +3 -3
  20. package/dist/mimic/core.d.ts +0 -32
  21. package/dist/mimic/core.js +12 -108
  22. package/dist/next/vercel-edge-projection-v1.d.ts +0 -9
  23. package/dist/next/vercel-edge-projection-v1.js +9 -545
  24. package/dist/preview/core.d.ts +1 -0
  25. package/dist/preview/core.js +27 -0
  26. package/dist/react/VideoPlayer.d.ts +1 -1
  27. package/dist/react/index.d.ts +1 -1
  28. package/package.json +16 -7
  29. package/templates/common/.agents/skills/aci/SKILL.md +6 -0
  30. package/templates/common/.agents/skills/dam-delivery/SKILL.md +228 -0
  31. package/templates/common/.agents/skills/dam-delivery/references/parameter-contract.md +107 -0
  32. package/templates/common/.agents/skills/dam-delivery/references/permalink-grammar.md +131 -0
  33. package/dist/edge/personalization-core.d.ts +0 -35
  34. package/dist/edge/personalization-core.js +0 -483
  35. package/dist/next/collect-route.d.ts +0 -25
  36. package/dist/next/collect-route.js +0 -479
  37. package/dist/next/envelope-digest.d.ts +0 -21
  38. package/dist/next/envelope-digest.js +0 -58
  39. package/dist/next/personalization-host.d.ts +0 -138
  40. package/dist/next/personalization-host.js +0 -280
  41. package/dist/next/root-layout.d.ts +0 -4
  42. package/dist/next/root-layout.js +0 -5
  43. package/dist/next/vercel-collect-sdk-route.d.ts +0 -27
  44. package/dist/next/vercel-collect-sdk-route.js +0 -181
  45. package/dist/next/vercel-personalization.d.ts +0 -4
  46. package/dist/next/vercel-personalization.js +0 -4
  47. package/dist/next/vercel-s3-personalization.d.ts +0 -80
  48. package/dist/next/vercel-s3-personalization.js +0 -571
@@ -1,138 +0,0 @@
1
- import { type PersonalizationExperiment } from '../edge/personalization-core.js';
2
- import { type PortableConsentSnapshot } from '../consent/portable-envelope.js';
3
- export declare const CONTENT_PATH_HEADER = "x-aci-content-path";
4
- export declare const CONTENT_PATH_CACHE_PARAM = "__aci_content_path";
5
- export declare const ROUTED_PATH_HEADER = "x-aci-routed-path";
6
- export declare const VARIANT_KEY_HEADER = "x-aci-variant-key";
7
- export interface EdgeDispatch {
8
- kind: 'static-direct' | 'compose-origin' | 'framework-origin' | string;
9
- artifactPath?: string;
10
- contentPath?: string;
11
- }
12
- export interface EdgeRuleCondition {
13
- field: string;
14
- operator: 'exists' | 'equals' | 'contains' | 'startsWith' | string;
15
- value?: unknown;
16
- }
17
- export interface EdgeRuleExpression {
18
- all?: EdgeRuleCondition[];
19
- any?: EdgeRuleCondition[];
20
- }
21
- export interface EdgeRouteVariant {
22
- variantKey: string;
23
- variantValues?: Record<string, string>;
24
- priority?: number;
25
- rule?: EdgeRuleExpression;
26
- dispatch: EdgeDispatch;
27
- }
28
- export interface EdgeRouteEntry {
29
- pattern: string;
30
- priority: number;
31
- dispatch: EdgeDispatch;
32
- variants?: Record<string, EdgeRouteVariant>;
33
- }
34
- export interface CollectSDKEntry {
35
- hash: string;
36
- path: string;
37
- }
38
- export interface EdgeRouteManifest {
39
- manifestVersion: string;
40
- releaseId: string;
41
- siteId: string;
42
- routes: Record<string, EdgeRouteEntry>;
43
- experiments?: Record<string, PersonalizationExperiment>;
44
- collectSdk?: CollectSDKEntry;
45
- notFoundPage?: string;
46
- errorPage?: string;
47
- }
48
- export interface PersonalizationEnvelopeWrite {
49
- key: string;
50
- envelopeId: string;
51
- siteId: string;
52
- identityNamespace: string;
53
- identityHash: string;
54
- records: readonly unknown[];
55
- digest: string;
56
- }
57
- export declare class IdentityErasureFencedError extends Error {
58
- readonly name = "IdentityErasureFencedError";
59
- constructor();
60
- }
61
- /** Immutable release routing state read by an EdgeRouter. */
62
- export interface PersonalizationRouteStore {
63
- readEdgeManifest(releaseId: string): Promise<EdgeRouteManifest | null>;
64
- }
65
- /** Customer-owned collection state. This is deliberately not an EdgeRouter dependency. */
66
- export interface PersonalizationCollectionStore {
67
- readClaims(siteId: string, namespace: string, identityHash: string): Promise<string | null>;
68
- appendEnvelope(write: PersonalizationEnvelopeWrite): Promise<void>;
69
- putSuppression(key: string, record: unknown): Promise<void>;
70
- }
71
- /** @deprecated Use the narrower router or collection store at each boundary. */
72
- export interface PersonalizationBlobStore extends PersonalizationRouteStore, PersonalizationCollectionStore {
73
- }
74
- export interface SigningKey {
75
- kid: string;
76
- secret: string;
77
- }
78
- export interface IdentitySigningKeys {
79
- current: SigningKey;
80
- previous?: SigningKey;
81
- }
82
- export interface PersonalizationHostConfig {
83
- siteId: string;
84
- store: PersonalizationRouteStore;
85
- identityKeys: IdentitySigningKeys;
86
- claimsKeys?: Record<string, string>;
87
- identityCookieTTLSeconds?: number;
88
- secureCookies?: boolean;
89
- now?: () => Date;
90
- randomBytes?: (length: number) => Uint8Array;
91
- mimicClaims?: {
92
- aud?: string[];
93
- seg?: string[];
94
- };
95
- }
96
- export interface CookieMutation {
97
- name: string;
98
- value: string;
99
- options: {
100
- path: '/';
101
- httpOnly?: boolean;
102
- secure?: boolean;
103
- sameSite: 'lax';
104
- maxAge: number;
105
- expires?: Date;
106
- };
107
- }
108
- export interface PersonalizationResolution {
109
- requestHeaders: Headers;
110
- contentPath: string;
111
- variantKey: string;
112
- experiment?: {
113
- id: string;
114
- arm: string;
115
- allocationVersion: string;
116
- };
117
- cookies: CookieMutation[];
118
- }
119
- export type ConsentSnapshot = PortableConsentSnapshot;
120
- interface ClaimsPayload {
121
- aud?: string[];
122
- seg?: string[];
123
- iat: number;
124
- exp: number;
125
- }
126
- export declare function resolvePersonalizationRequest(request: Request, releaseId: string, config: PersonalizationHostConfig): Promise<PersonalizationResolution>;
127
- export declare function consentSignals(request: Request, cookies: Map<string, string>): {
128
- hasConsent: boolean;
129
- snapshot: ConsentSnapshot | null;
130
- allowsIdentityTier: boolean;
131
- privacyDenied: boolean;
132
- };
133
- export declare function parseCookieHeader(value: string | null): Map<string, string>;
134
- export declare function verifyIdentityCookie(value: string, keys: IdentitySigningKeys): Promise<string | null>;
135
- export declare function sha256Hex(value: string): Promise<string>;
136
- export declare function identityHashHex(namespace: string, value: string): Promise<string>;
137
- export declare function verifyClaims(value: string, keys: Record<string, string>, now: Date): Promise<ClaimsPayload | null>;
138
- export {};
@@ -1,280 +0,0 @@
1
- import { resolvePersonalizationDecision, } from '../edge/personalization-core.js';
2
- import { parsePortableConsentEnvelope, portableConsentAllowsPersonalization, trimPortableConsentWhitespace, } from '../consent/portable-envelope.js';
3
- const DEFAULT_IDENTITY_TTL_SECONDS = 90 * 24 * 60 * 60;
4
- const DEFAULT_CLAIMS_TTL_SECONDS = 24 * 60 * 60;
5
- const textEncoder = new TextEncoder();
6
- export const CONTENT_PATH_HEADER = 'x-aci-content-path';
7
- export const CONTENT_PATH_CACHE_PARAM = '__aci_content_path';
8
- // Names the public route the edge decision was made FOR. The server render
9
- // applies the content-path selector only to lookups of this route; content
10
- // reads for any other route fall back to that route's base payload instead of
11
- // inheriting a selector that names a different route's content.
12
- export const ROUTED_PATH_HEADER = 'x-aci-routed-path';
13
- // Names the variant the edge decision selected. Like the content path and
14
- // routed path, it is a reserved dispatch signal: only the middleware may set
15
- // it, and a viewer-supplied value must never reach the SSR render (a bare
16
- // variant key without a matching ref is an integrity error there).
17
- export const VARIANT_KEY_HEADER = 'x-aci-variant-key';
18
- export class IdentityErasureFencedError extends Error {
19
- name = 'IdentityErasureFencedError';
20
- constructor() {
21
- super('identity collection is fenced by erasure');
22
- }
23
- }
24
- export async function resolvePersonalizationRequest(request, releaseId, config) {
25
- const requestHeaders = new Headers(request.headers);
26
- // The mimic banner header is middleware-emitted only; a viewer-presented
27
- // copy never reaches the render.
28
- requestHeaders.delete('x-aci-mimic-banner');
29
- const cookies = parseCookieHeader(request.headers.get('cookie'));
30
- const consent = consentSignals(request, cookies);
31
- const mutations = [];
32
- const now = (config.now ?? (() => new Date()))();
33
- const secure = config.secureCookies ?? new URL(request.url).protocol === 'https:';
34
- // Universal minting (spec anonymous-experiments REQ-1 / ADR 0016):
35
- // identity existence is privacy-signal gated, never consent gated.
36
- // GPC/DNT deny FULLY — no mint, no resolve, even with a valid cookie or a
37
- // stored granting envelope (D-2). An unverifiable cookie self-heals by
38
- // re-minting (REQ-4). aci_m is issue-only (D-11): a resolve-path refresh
39
- // would put a Set-Cookie on every returning visitor's response, defeating
40
- // the any-Set-Cookie => private, no-store cache rule.
41
- //
42
- // Mimic (audience-mimic): a validated mimicClaims input skips identity
43
- // entirely — no read, no mint, no claims-cookie touch (REQ-5).
44
- const mimic = config.mimicClaims;
45
- let rawIdentity = mimic || consent.privacyDenied
46
- ? null
47
- : await verifyIdentityCookie(cookies.get('aci_id') || '', config.identityKeys);
48
- if (!mimic && !consent.privacyDenied && !rawIdentity) {
49
- rawIdentity = randomIdentity(config.randomBytes);
50
- const signed = await signIdentity(rawIdentity, config.identityKeys.current);
51
- const maxAge = config.identityCookieTTLSeconds ?? DEFAULT_IDENTITY_TTL_SECONDS;
52
- mutations.push(cookieMutation('aci_id', signed, maxAge, now, secure, true));
53
- mutations.push(cookieMutation('aci_m', '1', maxAge, now, secure, false));
54
- }
55
- // The identity hash feeds experiment bucketing for EVERY identified
56
- // visitor. Claims are a signed cookie written by /collect; the EdgeRouter
57
- // never reads the customer object store to refresh or revoke them.
58
- let signedClaims = mimic ? '' : cookies.get('aci_claims') || '';
59
- let identityHash = '';
60
- if (rawIdentity) {
61
- identityHash = await identityHashHex('aci_id', rawIdentity);
62
- }
63
- if (rawIdentity && consent.allowsIdentityTier && signedClaims) {
64
- if (!await verifyClaims(signedClaims, config.claimsKeys || {}, now)) {
65
- signedClaims = '';
66
- }
67
- }
68
- // Under mimic the visitor's real aci_claims is never touched (REQ-5) — the
69
- // exit path returns them to exactly their pre-mimic state.
70
- if (!mimic && (!consent.allowsIdentityTier || !rawIdentity || !signedClaims) && cookies.has('aci_claims')) {
71
- mutations.push(expireCookie('aci_claims', secure));
72
- }
73
- const manifest = await config.store.readEdgeManifest(releaseId);
74
- const route = manifest ? matchRoute(new URL(request.url).pathname, manifest) : null;
75
- let contentPath = route?.dispatch.contentPath || '';
76
- let variantKey = '';
77
- if (route) {
78
- const claims = mimic
79
- ? { aud: mimic.aud, seg: mimic.seg, iat: 0, exp: 0 }
80
- : consent.allowsIdentityTier
81
- ? await verifyClaims(signedClaims, config.claimsKeys || {}, now)
82
- : null;
83
- const decision = resolvePersonalizationDecision(toPersonalizationRequestContext(request), route, claims, manifest?.experiments, identityHash
84
- ? { usable: true, siteId: config.siteId, namespace: 'aci_id', identityHash }
85
- : undefined);
86
- if (decision.variant) {
87
- variantKey = decision.variant.variantKey;
88
- contentPath = decision.variant.dispatch.contentPath || contentPath;
89
- }
90
- if (decision.experiment) {
91
- requestHeaders.set('X-ACI-Experiment-ID', decision.experiment.experimentId);
92
- requestHeaders.set('X-ACI-Experiment-Arm', decision.experiment.armId);
93
- requestHeaders.set('X-ACI-Experiment-Allocation-Version', decision.experiment.allocationVersion);
94
- }
95
- const experiment = decision.experiment
96
- ? { id: decision.experiment.experimentId, arm: decision.experiment.armId, allocationVersion: decision.experiment.allocationVersion }
97
- : undefined;
98
- if (contentPath) {
99
- requestHeaders.set(CONTENT_PATH_HEADER, contentPath);
100
- requestHeaders.set(ROUTED_PATH_HEADER, normalizePath(new URL(request.url).pathname));
101
- }
102
- if (variantKey)
103
- requestHeaders.set(VARIANT_KEY_HEADER, variantKey);
104
- return { requestHeaders, contentPath, variantKey, experiment, cookies: mutations };
105
- }
106
- if (contentPath) {
107
- requestHeaders.set(CONTENT_PATH_HEADER, contentPath);
108
- requestHeaders.set(ROUTED_PATH_HEADER, normalizePath(new URL(request.url).pathname));
109
- }
110
- if (variantKey) {
111
- requestHeaders.set(VARIANT_KEY_HEADER, variantKey);
112
- }
113
- return { requestHeaders, contentPath, variantKey, cookies: mutations };
114
- }
115
- export function consentSignals(request, cookies) {
116
- const privacyDenied = request.headers.get('sec-gpc')?.trim() === '1'
117
- || request.headers.get('dnt')?.trim() === '1'
118
- || ['deny', 'opt-out', 'off'].includes((request.headers.get('x-gradial-privacy-override') || '').trim().toLowerCase());
119
- const headerConsent = request.headers.get('x-aci-consent');
120
- const hasHeaderConsent = trimPortableConsentWhitespace(headerConsent || '') !== '';
121
- const raw = hasHeaderConsent
122
- ? headerConsent
123
- : cookies.get('aci_consent') || '';
124
- const snapshot = parsePortableConsentEnvelope(raw, !hasHeaderConsent);
125
- const allows = portableConsentAllowsPersonalization(snapshot);
126
- return {
127
- hasConsent: snapshot !== null,
128
- snapshot,
129
- allowsIdentityTier: !privacyDenied && allows,
130
- privacyDenied,
131
- };
132
- }
133
- export function parseCookieHeader(value) {
134
- const cookies = new Map();
135
- for (const part of (value || '').split(';')) {
136
- const separator = part.indexOf('=');
137
- if (separator < 0)
138
- continue;
139
- const name = part.slice(0, separator).trim();
140
- if (name)
141
- cookies.set(name, part.slice(separator + 1).trim());
142
- }
143
- return cookies;
144
- }
145
- export async function verifyIdentityCookie(value, keys) {
146
- const parts = value.trim().split('.');
147
- if (parts.length !== 3 || parts.some((part) => part === ''))
148
- return null;
149
- const [rawID, kid, signature] = parts;
150
- const key = [keys.current, keys.previous].find((candidate) => candidate?.kid === kid);
151
- if (!key)
152
- return null;
153
- return await verifyHMAC(`${rawID}.${kid}`, signature, key.secret) ? rawID : null;
154
- }
155
- export async function sha256Hex(value) {
156
- const digest = await crypto.subtle.digest('SHA-256', textEncoder.encode(value));
157
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
158
- }
159
- export async function identityHashHex(namespace, value) {
160
- return sha256Hex(`${namespace.trim().toLowerCase()}\x00${value.trim()}`);
161
- }
162
- function matchRoute(pathname, manifest) {
163
- const normalized = normalizePath(pathname);
164
- if (manifest.routes[normalized])
165
- return manifest.routes[normalized];
166
- const candidates = Object.values(manifest.routes)
167
- .filter((route) => routePatternMatches(route.pattern, normalized))
168
- .sort((left, right) => right.priority - left.priority || left.pattern.localeCompare(right.pattern));
169
- return candidates[0] || null;
170
- }
171
- function normalizePath(value) {
172
- let path = value.trim() || '/';
173
- if (!path.startsWith('/'))
174
- path = `/${path}`;
175
- if (path.length > 1)
176
- path = path.replace(/\/+$/, '');
177
- return path;
178
- }
179
- function routePatternMatches(pattern, pathname) {
180
- pattern = normalizePath(pattern);
181
- if (pattern === pathname)
182
- return true;
183
- const expression = pattern
184
- .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
185
- .replace(/\\\[\\\[\\\.\\\.\\\.[^\]]+\\\]\\\]/g, '.*')
186
- .replace(/\\\[\\\.\\\.\\\.[^\]]+\\\]/g, '.+')
187
- .replace(/\\\[[^\]]+\\\]/g, '[^/]+')
188
- .replace(/:[^/]+/g, '[^/]+')
189
- .replace(/\\\*/g, '.*');
190
- try {
191
- return new RegExp(`^${expression}$`).test(pathname);
192
- }
193
- catch {
194
- return false;
195
- }
196
- }
197
- function toPersonalizationRequestContext(request) {
198
- const url = new URL(request.url);
199
- const cookies = parseCookieHeader(request.headers.get('cookie'));
200
- const query = {};
201
- url.searchParams.forEach((value, key) => {
202
- (query[key] ||= []).push(value);
203
- });
204
- const headers = Object.fromEntries(request.headers.entries());
205
- const geo = Object.fromEntries(Object.entries({
206
- country: headers['x-vercel-ip-country'] || '',
207
- region: headers['x-vercel-ip-country-region'] || '',
208
- city: headers['x-vercel-ip-city'] || '',
209
- }).filter(([, value]) => value !== ''));
210
- return {
211
- path: url.pathname,
212
- query,
213
- headers,
214
- cookies: Object.fromEntries(cookies.entries()),
215
- ...(Object.keys(geo).length > 0 ? { signals: { geo } } : {}),
216
- };
217
- }
218
- export async function verifyClaims(value, keys, now) {
219
- const parts = value.trim().split('.');
220
- if (parts.length !== 4 || parts[0] !== 'v1')
221
- return null;
222
- const [, kid, body, signature] = parts;
223
- const secret = keys[kid];
224
- if (!secret || !await verifyHMAC(`v1.${kid}.${body}`, signature, secret))
225
- return null;
226
- try {
227
- const payload = JSON.parse(new TextDecoder().decode(base64URLDecode(body)));
228
- if (!Number.isFinite(payload.exp) || payload.exp <= Math.floor(now.getTime() / 1000))
229
- return null;
230
- return payload;
231
- }
232
- catch {
233
- return null;
234
- }
235
- }
236
- async function signIdentity(rawID, key) {
237
- const signature = await hmac(`${rawID}.${key.kid}`, key.secret);
238
- return `${rawID}.${key.kid}.${signature}`;
239
- }
240
- function randomIdentity(random) {
241
- const bytes = random ? random(16) : crypto.getRandomValues(new Uint8Array(16));
242
- return base64URLEncode(bytes);
243
- }
244
- async function verifyHMAC(value, signature, secret) {
245
- try {
246
- const key = await crypto.subtle.importKey('raw', textEncoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
247
- return await crypto.subtle.verify('HMAC', key, base64URLDecode(signature), textEncoder.encode(value));
248
- }
249
- catch {
250
- return false;
251
- }
252
- }
253
- async function hmac(value, secret) {
254
- const key = await crypto.subtle.importKey('raw', textEncoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
255
- return base64URLEncode(new Uint8Array(await crypto.subtle.sign('HMAC', key, textEncoder.encode(value))));
256
- }
257
- function base64URLEncode(bytes) {
258
- let binary = '';
259
- for (const byte of bytes)
260
- binary += String.fromCharCode(byte);
261
- return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
262
- }
263
- function base64URLDecode(value) {
264
- const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4);
265
- const binary = atob(padded);
266
- const bytes = new Uint8Array(binary.length);
267
- for (let index = 0; index < binary.length; index += 1)
268
- bytes[index] = binary.charCodeAt(index);
269
- return bytes;
270
- }
271
- function cookieMutation(name, value, maxAge, now, secure, httpOnly) {
272
- return {
273
- name,
274
- value,
275
- options: { path: '/', httpOnly, secure, sameSite: 'lax', maxAge, expires: new Date(now.getTime() + maxAge * 1000) },
276
- };
277
- }
278
- function expireCookie(name, secure) {
279
- return { name, value: '', options: { path: '/', httpOnly: true, secure, sameSite: 'lax', maxAge: 0, expires: new Date(0) } };
280
- }
@@ -1,4 +0,0 @@
1
- import type { ReactNode } from 'react';
2
- export declare function RootLayout({ children }: {
3
- children: ReactNode;
4
- }): import("react").JSX.Element;
@@ -1,5 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { DevRefresh } from './dev-refresh.js';
3
- export function RootLayout({ children }) {
4
- return (_jsx("html", { lang: "en", children: _jsxs("body", { children: [children, _jsx(DevRefresh, {})] }) }));
5
- }
@@ -1,27 +0,0 @@
1
- export interface VercelCollectSDKRouteConfig {
2
- siteId: string;
3
- edgeConfig: string;
4
- region: string;
5
- roleArn: string;
6
- hostingBucket: string;
7
- hostingKeyPrefix?: string;
8
- }
9
- export interface VercelCollectSDKRouteDependencies {
10
- s3Client?: VercelCollectSDKS3Client;
11
- readEdgeConfig?: (connection: string, key: string) => Promise<unknown>;
12
- onError?: (error: unknown) => void;
13
- }
14
- export interface VercelCollectSDKS3Client {
15
- send(command: {
16
- input: unknown;
17
- }): Promise<unknown>;
18
- }
19
- export type VercelCollectSDKRoute = (request: Request) => Promise<Response>;
20
- /**
21
- * Creates the Node-only stable collect-SDK route used by ACI's injected
22
- * Vercel Function. The provider pointer selects the immutable release on every
23
- * uncached invocation, so an old code deployment remains correct while a
24
- * canonical activation converges through Edge Config and deployment promotion.
25
- */
26
- export declare function createVercelCollectSDKRoute(input: VercelCollectSDKRouteConfig, dependencies?: VercelCollectSDKRouteDependencies): VercelCollectSDKRoute;
27
- export declare function createVercelCollectSDKRouteFromEnv(env?: Record<string, string | undefined>, dependencies?: VercelCollectSDKRouteDependencies): VercelCollectSDKRoute;
@@ -1,181 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
3
- import { awsCredentialsProvider } from '@vercel/oidc-aws-credentials-provider';
4
- import { getUncachedEdgeConfigValue } from './edge-config.js';
5
- import { activeReleaseV1Key, decodeActiveReleaseV1, decodeEdgeRouteProjectionV1, edgeRoutesV1Key, } from './vercel-edge-projection-v1.js';
6
- const SHA256_HEX = /^[0-9a-f]{64}$/;
7
- /**
8
- * Creates the Node-only stable collect-SDK route used by ACI's injected
9
- * Vercel Function. The provider pointer selects the immutable release on every
10
- * uncached invocation, so an old code deployment remains correct while a
11
- * canonical activation converges through Edge Config and deployment promotion.
12
- */
13
- export function createVercelCollectSDKRoute(input, dependencies = {}) {
14
- const config = validateConfig(input);
15
- const readEdgeConfig = dependencies.readEdgeConfig || getUncachedEdgeConfigValue;
16
- const client = dependencies.s3Client || new S3Client({
17
- region: config.region,
18
- credentials: awsCredentialsProvider({
19
- roleArn: config.roleArn,
20
- clientConfig: { region: config.region },
21
- }),
22
- });
23
- const onError = dependencies.onError || ((error) => {
24
- console.error('[ACI collect SDK] route failed', error);
25
- });
26
- return async (request) => {
27
- const method = request.method.toUpperCase();
28
- if (method !== 'GET' && method !== 'HEAD') {
29
- return new Response('method not allowed', {
30
- status: 405,
31
- headers: {
32
- Allow: 'GET, HEAD',
33
- 'Cache-Control': 'private, no-store',
34
- },
35
- });
36
- }
37
- try {
38
- const active = decodeActiveReleaseV1(await readEdgeConfig(config.edgeConfig, activeReleaseV1Key(config.siteId)));
39
- const projection = decodeEdgeRouteProjectionV1(await readEdgeConfig(config.edgeConfig, edgeRoutesV1Key(config.siteId, active.releaseId)), {
40
- siteId: config.siteId,
41
- releaseId: active.releaseId,
42
- });
43
- if (!Object.prototype.hasOwnProperty.call(projection, 'collectSdk')) {
44
- return new Response(method === 'HEAD' ? null : 'collect SDK is not enabled for this release', {
45
- status: 404,
46
- headers: { 'Cache-Control': 'no-store' },
47
- });
48
- }
49
- const entry = validateCollectSDKEntry(projection.collectSdk);
50
- const body = await readSDKObject(client, config.hostingBucket, joinKey(config.hostingKeyPrefix, 'releases', active.releaseId, entry.path));
51
- const actualHash = createHash('sha256').update(body).digest('hex');
52
- if (actualHash !== entry.hash) {
53
- throw new Error(`collect SDK digest mismatch: got ${actualHash}, want ${entry.hash}`);
54
- }
55
- const etag = `"${entry.hash}"`;
56
- const headers = new Headers({
57
- 'Content-Type': 'text/javascript; charset=utf-8',
58
- 'Cache-Control': 'public, max-age=300, must-revalidate',
59
- ETag: etag,
60
- });
61
- if (ifNoneMatchSatisfied(request.headers.get('if-none-match'), etag)) {
62
- return new Response(null, { status: 304, headers });
63
- }
64
- headers.set('Content-Length', String(body.byteLength));
65
- const responseBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
66
- return new Response(method === 'HEAD' ? null : responseBody, { status: 200, headers });
67
- }
68
- catch (error) {
69
- onError(error);
70
- return new Response(method === 'HEAD' ? null : 'collect SDK is temporarily unavailable', {
71
- status: 503,
72
- headers: { 'Cache-Control': 'private, no-store' },
73
- });
74
- }
75
- };
76
- }
77
- export function createVercelCollectSDKRouteFromEnv(env = process.env, dependencies = {}) {
78
- try {
79
- return createVercelCollectSDKRoute({
80
- siteId: requiredEnv(env, 'ACI_SITE_ID'),
81
- edgeConfig: requiredEnv(env, 'EDGE_CONFIG'),
82
- region: env.AWS_REGION || env.AWS_DEFAULT_REGION || '',
83
- roleArn: requiredEnv(env, 'AWS_ROLE_ARN'),
84
- hostingBucket: requiredEnv(env, 'HOSTING_BUCKET'),
85
- hostingKeyPrefix: env.HOSTING_KEY_PREFIX || env.GRADIAL_S3_KEY_PREFIX,
86
- }, dependencies);
87
- }
88
- catch (error) {
89
- (dependencies.onError || ((value) => {
90
- console.error('[ACI collect SDK] configuration failed', value);
91
- }))(error);
92
- return async (request) => new Response(request.method.toUpperCase() === 'HEAD' ? null : 'collect SDK is temporarily unavailable', { status: 503, headers: { 'Cache-Control': 'private, no-store' } });
93
- }
94
- }
95
- function validateConfig(input) {
96
- const siteId = requiredPathSegment(input.siteId, 'ACI site ID');
97
- const edgeConfig = input.edgeConfig.trim();
98
- const region = input.region.trim();
99
- const roleArn = input.roleArn.trim();
100
- const hostingBucket = input.hostingBucket.trim();
101
- if (!edgeConfig)
102
- throw new Error('Edge Config connection is required');
103
- if (!region)
104
- throw new Error('AWS region is required');
105
- if (!roleArn)
106
- throw new Error('AWS role ARN is required');
107
- if (!hostingBucket)
108
- throw new Error('hosting bucket is required');
109
- return {
110
- siteId,
111
- edgeConfig,
112
- region,
113
- roleArn,
114
- hostingBucket,
115
- hostingKeyPrefix: cleanKey(input.hostingKeyPrefix || ''),
116
- };
117
- }
118
- function parseRecord(value, label) {
119
- const parsed = typeof value === 'string' ? JSON.parse(value) : value;
120
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
121
- throw new Error(`${label} is unavailable or malformed`);
122
- }
123
- return parsed;
124
- }
125
- function validateCollectSDKEntry(value) {
126
- const entry = parseRecord(value, 'collect SDK metadata');
127
- if (typeof entry.hash !== 'string' || typeof entry.path !== 'string') {
128
- throw new Error('collect SDK metadata must contain string hash and path fields');
129
- }
130
- const hash = entry.hash.trim().toLowerCase();
131
- const path = cleanKey(entry.path);
132
- if (!SHA256_HEX.test(hash))
133
- throw new Error('collect SDK hash must be lowercase SHA-256');
134
- const expectedPath = `_aci/aci.${hash}.js`;
135
- if (path !== expectedPath || path !== entry.path) {
136
- throw new Error(`collect SDK path ${JSON.stringify(entry.path)} must equal ${JSON.stringify(expectedPath)}`);
137
- }
138
- return { hash, path };
139
- }
140
- async function readSDKObject(client, bucket, key) {
141
- const output = await client.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
142
- if (output.Body?.transformToByteArray)
143
- return await output.Body.transformToByteArray();
144
- if (output.Body?.transformToString) {
145
- return new TextEncoder().encode(await output.Body.transformToString());
146
- }
147
- throw new Error(`collect SDK object ${key} returned an unsupported body`);
148
- }
149
- function ifNoneMatchSatisfied(value, etag) {
150
- const header = (value || '').trim();
151
- if (!header)
152
- return false;
153
- if (header === '*')
154
- return true;
155
- return header.split(',').some((candidate) => {
156
- const normalized = candidate.trim().replace(/^W\//, '');
157
- return normalized === etag;
158
- });
159
- }
160
- function requiredPathSegment(value, label) {
161
- const clean = value.trim();
162
- if (!clean || clean === '.' || clean === '..' || clean.includes('/') || clean.includes('\\')) {
163
- throw new Error(`${label} is required and must be one path segment`);
164
- }
165
- return clean;
166
- }
167
- function cleanKey(value) {
168
- const segments = value.replaceAll('\\', '/').split('/').filter((segment) => segment && segment !== '.');
169
- if (segments.some((segment) => segment === '..'))
170
- throw new Error('S3 key traversal is not allowed');
171
- return segments.join('/');
172
- }
173
- function joinKey(...parts) {
174
- return parts.map((part) => cleanKey(part || '')).filter(Boolean).join('/');
175
- }
176
- function requiredEnv(env, key) {
177
- const value = env[key]?.trim() || '';
178
- if (!value)
179
- throw new Error(`${key} is required for the Vercel collect SDK route`);
180
- return value;
181
- }
@@ -1,4 +0,0 @@
1
- export { createPersonalizationCollectRoute, type PersonalizationCollectRouteConfig, } from './collect-route.js';
2
- export { computeEnvelopeDigest, type EnvelopeDigestInput, } from './envelope-digest.js';
3
- export { CONTENT_PATH_CACHE_PARAM, CONTENT_PATH_HEADER, IdentityErasureFencedError, resolvePersonalizationRequest, type EdgeRouteManifest, type PersonalizationBlobStore, type PersonalizationCollectionStore, type PersonalizationEnvelopeWrite, type PersonalizationHostConfig, type PersonalizationRouteStore, type PersonalizationResolution, } from './personalization-host.js';
4
- export { createVercelPersonalizationFromEnv, createVercelCollectionFromEnv, VercelEdgeConfigRouteStore, createVercelS3PersonalizationStore, EnvelopeIDCollisionError, VercelS3PersonalizationStore, type VercelS3PersonalizationConfig, } from './vercel-s3-personalization.js';
@@ -1,4 +0,0 @@
1
- export { createPersonalizationCollectRoute, } from './collect-route.js';
2
- export { computeEnvelopeDigest, } from './envelope-digest.js';
3
- export { CONTENT_PATH_CACHE_PARAM, CONTENT_PATH_HEADER, IdentityErasureFencedError, resolvePersonalizationRequest, } from './personalization-host.js';
4
- export { createVercelPersonalizationFromEnv, createVercelCollectionFromEnv, VercelEdgeConfigRouteStore, createVercelS3PersonalizationStore, EnvelopeIDCollisionError, VercelS3PersonalizationStore, } from './vercel-s3-personalization.js';