@appfunnel-dev/sdk 2.0.0-canary.7 → 2.0.0-canary.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{capabilities-7_hy5f5G.d.cts → capabilities-CsnkVwna.d.cts} +34 -1
- package/dist/{capabilities-7_hy5f5G.d.ts → capabilities-CsnkVwna.d.ts} +34 -1
- package/dist/{checkout-D1NUPv4p.d.ts → checkout-3PkKwPd7.d.ts} +1 -1
- package/dist/{checkout-CMEdxpgo.d.cts → checkout-Cg20l53c.d.cts} +1 -1
- package/dist/{chunk-VAOR77NW.cjs → chunk-FY3TMSRU.cjs} +7 -7
- package/dist/{chunk-VAOR77NW.cjs.map → chunk-FY3TMSRU.cjs.map} +1 -1
- package/dist/{chunk-CFFMZYPE.js → chunk-PWXMQGO6.js} +3 -3
- package/dist/{chunk-CFFMZYPE.js.map → chunk-PWXMQGO6.js.map} +1 -1
- package/dist/{chunk-TNLRQPVY.js → chunk-RVJLR4RS.js} +36 -8
- package/dist/chunk-RVJLR4RS.js.map +1 -0
- package/dist/{chunk-QMAZGLGV.cjs → chunk-RY3LOSVZ.cjs} +37 -7
- package/dist/chunk-RY3LOSVZ.cjs.map +1 -0
- package/dist/{chunk-7YQLPPPG.js → chunk-VW2HVPR4.js} +7 -2
- package/dist/chunk-VW2HVPR4.js.map +1 -0
- package/dist/{chunk-BPOAWI4G.cjs → chunk-Y4YNJ2EX.cjs} +7 -2
- package/dist/chunk-Y4YNJ2EX.cjs.map +1 -0
- package/dist/driver-paddle.cjs +22 -22
- package/dist/driver-paddle.d.cts +2 -2
- package/dist/driver-paddle.d.ts +2 -2
- package/dist/driver-paddle.js +2 -2
- package/dist/driver-stripe.cjs +24 -24
- package/dist/driver-stripe.d.cts +2 -2
- package/dist/driver-stripe.d.ts +2 -2
- package/dist/driver-stripe.js +2 -2
- package/dist/index.cjs +60 -60
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/{manifest-CMe8yVkr.d.cts → manifest-B3Tdab0M.d.cts} +64 -1
- package/dist/{manifest-CMe8yVkr.d.ts → manifest-B3Tdab0M.d.ts} +64 -1
- package/dist/manifest-entry.cjs +100 -31
- package/dist/manifest-entry.cjs.map +1 -1
- package/dist/manifest-entry.d.cts +9 -26
- package/dist/manifest-entry.d.ts +9 -26
- package/dist/manifest-entry.js +64 -3
- package/dist/manifest-entry.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-7YQLPPPG.js.map +0 -1
- package/dist/chunk-BPOAWI4G.cjs.map +0 -1
- package/dist/chunk-QMAZGLGV.cjs.map +0 -1
- package/dist/chunk-TNLRQPVY.js.map +0 -1
package/dist/manifest-entry.d.ts
CHANGED
|
@@ -1,29 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { af as CheckoutUsageScan } from './manifest-B3Tdab0M.js';
|
|
2
|
+
export { h as CompileInput, i as Condition, j as ConditionOp, E as EdgeCondition, l as ExperimentArm, n as FlowPage, c as FunnelDefinition, o as FunnelLocales, p as FunnelManifest, ag as FunnelPage, b as FunnelSnapshot, G as Gate, q as Interval, M as ManifestEdge, r as ManifestPage, s as ManifestValidation, t as Money, O as Offering, e as OfferingInput, ah as OfferingRefScan, ai as OfferingSlot, P as PageMeta, v as PageType, w as Predicate, x as ResolvedOffering, y as Route, R as RuntimeExperiment, H as assignVariant, J as bucketingSeed, N as buildCatalog, Q as compileManifest, T as currencyExponent, W as defineFunnel, Y as entryGuard, Z as evaluateCondition, a1 as formatMoney, a2 as formatOffering, aj as funnelCatalogKeys, a4 as isRtl, a5 as isVariantKey, ak as normalizeOfferings, a8 as pageMeta, a9 as parseSlotKey, ac as resolveLocale, ad as resolveOffering, al as scanOfferingRefs, am as weightsOf } from './manifest-B3Tdab0M.js';
|
|
3
|
+
import { C as CheckoutError, b as CheckoutIntent, U as UpsellKind, d as CheckoutSurface } from './capabilities-CsnkVwna.js';
|
|
4
|
+
export { a as CheckoutErrorCategory, c as CheckoutProvider, I as INLINE_SURFACES, O as OffSessionReliability, P as PROVIDER_PROFILES, e as ProviderProfile, S as SurfaceCapability, T as TrialShape, V as ValidationResult, f as checkoutError, i as isInlineSurface, g as isMerchantOfRecord, h as isOrchestrator, s as surfacesFor, t as trialShapesFor, v as validateCheckout, k as validateTrial, j as validateUpsell } from './capabilities-CsnkVwna.js';
|
|
4
5
|
import 'react';
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
-
* Pure, React-free page scan: find which offering SLOTS a funnel's pages reference — the first
|
|
8
|
-
* string-literal arg of `useOffering(...)` and the `offering` prop of `<Checkout>` / `<Upsell>`.
|
|
9
|
-
* Ships via `@appfunnel-dev/sdk/manifest` so the BUILD, the EDITOR, and the AI all run the SAME
|
|
10
|
-
* check. The result feeds `compileManifest({ offeringRefs })`, which flags references to slots the
|
|
11
|
-
* funnel doesn't declare (unknown) or hasn't assigned a catalog charge key to (unassigned).
|
|
12
|
-
*
|
|
13
|
-
* Non-literal args (`useOffering(selectedId)`, `offering={expr}`) and the `useOfferings()` wildcard are
|
|
14
|
-
* DYNAMIC — they can't be statically enumerated, so they're reported via `dynamic` and never turned
|
|
15
|
-
* into a hard error (validation relaxes when a funnel is dynamic). Mirrors the mask-then-read
|
|
16
|
-
* discipline the funnel.ts code-mods use, so a `useOffering('x')` inside a comment or string literal
|
|
17
|
-
* can't false-positive.
|
|
18
|
-
*/
|
|
19
|
-
interface OfferingRefScan {
|
|
20
|
-
/** Concrete slot names referenced by LITERAL args, deduped, in first-seen order. */
|
|
21
|
-
slots: string[];
|
|
22
|
-
/** True if any ref is a non-literal arg or a `useOfferings()` wildcard (not statically enumerable). */
|
|
23
|
-
dynamic: boolean;
|
|
24
|
-
}
|
|
25
|
-
declare function scanOfferingRefs(files: Record<string, string>): OfferingRefScan;
|
|
26
|
-
|
|
27
7
|
/**
|
|
28
8
|
* Source generators for the funnel build "machinery" authors no longer write. `funnel.ts` (the
|
|
29
9
|
* spine: id, responses, offerings, checkout, and the page list + declarative routing) plus the
|
|
@@ -36,6 +16,7 @@ declare function scanOfferingRefs(files: Record<string, string>): OfferingRefSca
|
|
|
36
16
|
* All string templates, zero runtime deps — this module lives in the pure `@appfunnel-dev/sdk/
|
|
37
17
|
* manifest` entry so tooling imports it without the funnel runtime.
|
|
38
18
|
*/
|
|
19
|
+
|
|
39
20
|
interface ScaffoldOptions {
|
|
40
21
|
/** Page component keys = `pages/<key>.tsx` filenames (base flow pages AND `@variant` pages). */
|
|
41
22
|
pageKeys: string[];
|
|
@@ -51,13 +32,15 @@ interface ScaffoldOptions {
|
|
|
51
32
|
messageLocales?: string[];
|
|
52
33
|
/** Slot names the pages reference (from `scanOfferingRefs`), baked into the manifest for validation. */
|
|
53
34
|
offeringRefs?: string[];
|
|
35
|
+
/** Checkout-surface usage the pages express (from `scanOfferingRefs(...).checkout`), baked into the manifest for the publish capability gate. */
|
|
36
|
+
checkoutRefs?: CheckoutUsageScan;
|
|
54
37
|
}
|
|
55
38
|
/** `mount.tsx` — the code-split loaders + tree, derived from `config.pages` and the `pages/` files. */
|
|
56
39
|
declare function generateMount(opts: ScaffoldOptions): string;
|
|
57
40
|
/** `entry.client.tsx` — hydrate the SSR'd markup from the injected `#__af_data`. */
|
|
58
41
|
declare function generateEntryClient(opts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'>): string;
|
|
59
42
|
/** `entry.server.tsx` — `ssr(opts)` HTML + the compiled `manifest` (read by the build). */
|
|
60
|
-
declare function generateEntryServer(opts: Pick<ScaffoldOptions, 'importPrefix' | 'offeringRefs'>): string;
|
|
43
|
+
declare function generateEntryServer(opts: Pick<ScaffoldOptions, 'importPrefix' | 'offeringRefs' | 'checkoutRefs'>): string;
|
|
61
44
|
/** Client-only dev entry (createRoot, no SSR) — for the CLI `dev` server. */
|
|
62
45
|
declare function generateDevEntry(opts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'> & {
|
|
63
46
|
data: unknown;
|
|
@@ -206,4 +189,4 @@ interface CheckoutCompleteRequest {
|
|
|
206
189
|
}
|
|
207
190
|
type CheckoutCompleteResponse = StepSettled | StepPending | StepFailed;
|
|
208
191
|
|
|
209
|
-
export { type CheckoutCompleteRequest, type CheckoutCompleteResponse, CheckoutError, CheckoutIntent, type CheckoutSessionRequest, type CheckoutSessionResponse, type CheckoutSettlement, CheckoutSurface,
|
|
192
|
+
export { type CheckoutCompleteRequest, type CheckoutCompleteResponse, CheckoutError, CheckoutIntent, type CheckoutSessionRequest, type CheckoutSessionResponse, type CheckoutSettlement, CheckoutSurface, CheckoutUsageScan, type ScaffoldOptions, type StepClientConfirm, type StepEmbedded, type StepFailed, type StepPending, type StepProviderCheckout, type StepRedirect, type StepSettled, UpsellKind, generateDevEntry, generateEntryClient, generateEntryServer, generateMount };
|
package/dist/manifest-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { assignVariant, bucketingSeed, buildCatalog, compileManifest, currencyExponent, defineFunnel, entryGuard, evaluateCondition, formatMoney, formatOffering, funnelCatalogKeys, isRtl, isVariantKey, normalizeOfferings, pageMeta, parseSlotKey, resolveLocale, resolveOffering, weightsOf } from './chunk-
|
|
2
|
-
export { INLINE_SURFACES, PROVIDER_PROFILES, checkoutError, isInlineSurface, isMerchantOfRecord, isOrchestrator, surfacesFor, validateCheckout, validateUpsell } from './chunk-
|
|
1
|
+
export { assignVariant, bucketingSeed, buildCatalog, compileManifest, currencyExponent, defineFunnel, entryGuard, evaluateCondition, formatMoney, formatOffering, funnelCatalogKeys, isRtl, isVariantKey, normalizeOfferings, pageMeta, parseSlotKey, resolveLocale, resolveOffering, weightsOf } from './chunk-VW2HVPR4.js';
|
|
2
|
+
export { INLINE_SURFACES, PROVIDER_PROFILES, checkoutError, isInlineSurface, isMerchantOfRecord, isOrchestrator, surfacesFor, trialShapesFor, validateCheckout, validateTrial, validateUpsell } from './chunk-RVJLR4RS.js';
|
|
3
3
|
import './chunk-G3PMV62Z.js';
|
|
4
4
|
|
|
5
5
|
// src/manifest/offering-refs.ts
|
|
@@ -58,6 +58,27 @@ function skipWs(masked, i) {
|
|
|
58
58
|
while (i < masked.length && (masked[i] === " " || masked[i] === " " || masked[i] === "\n" || masked[i] === "\r")) i++;
|
|
59
59
|
return i;
|
|
60
60
|
}
|
|
61
|
+
function tagAttrEnd(masked, from) {
|
|
62
|
+
let depth = 0;
|
|
63
|
+
for (let i = from; i < masked.length; i++) {
|
|
64
|
+
const c = masked[i];
|
|
65
|
+
if (c === "{") depth++;
|
|
66
|
+
else if (c === "}") {
|
|
67
|
+
if (depth > 0) depth--;
|
|
68
|
+
} else if (c === ">" && depth === 0) return i;
|
|
69
|
+
}
|
|
70
|
+
return masked.length;
|
|
71
|
+
}
|
|
72
|
+
function readAttr(src, masked, start, end, name) {
|
|
73
|
+
const re = new RegExp(`\\b${name}\\s*=\\s*`, "g");
|
|
74
|
+
re.lastIndex = start;
|
|
75
|
+
const m = re.exec(masked);
|
|
76
|
+
if (!m || m.index >= end) return null;
|
|
77
|
+
const at = m.index + m[0].length;
|
|
78
|
+
if (masked[at] === "{") return { dynamic: true };
|
|
79
|
+
const lit = literalAt(src, masked, at);
|
|
80
|
+
return lit !== null ? { value: lit } : { dynamic: true };
|
|
81
|
+
}
|
|
61
82
|
function scanOfferingRefs(files) {
|
|
62
83
|
const seen = /* @__PURE__ */ new Set();
|
|
63
84
|
const order = [];
|
|
@@ -68,6 +89,23 @@ function scanOfferingRefs(files) {
|
|
|
68
89
|
order.push(v);
|
|
69
90
|
}
|
|
70
91
|
};
|
|
92
|
+
const surfaceSeen = /* @__PURE__ */ new Set();
|
|
93
|
+
const surfaces = [];
|
|
94
|
+
const kindSeen = /* @__PURE__ */ new Set();
|
|
95
|
+
const upsellKinds = [];
|
|
96
|
+
let checkoutDynamic = false;
|
|
97
|
+
const addSurface = (v) => {
|
|
98
|
+
if (v && !surfaceSeen.has(v)) {
|
|
99
|
+
surfaceSeen.add(v);
|
|
100
|
+
surfaces.push(v);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
const addKind = (v) => {
|
|
104
|
+
if (v && !kindSeen.has(v)) {
|
|
105
|
+
kindSeen.add(v);
|
|
106
|
+
upsellKinds.push(v);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
71
109
|
for (const [path, source] of Object.entries(files)) {
|
|
72
110
|
if (!/\.(tsx|jsx|ts|js)$/.test(path)) continue;
|
|
73
111
|
const masked = mask(source);
|
|
@@ -88,8 +126,30 @@ function scanOfferingRefs(files) {
|
|
|
88
126
|
if (lit !== null) add(lit);
|
|
89
127
|
else if (masked[j] === "{") dynamic = true;
|
|
90
128
|
}
|
|
129
|
+
for (const m of masked.matchAll(/<(Checkout|Upsell)\b/g)) {
|
|
130
|
+
const comp = m[1];
|
|
131
|
+
const tagStart = m.index + m[0].length;
|
|
132
|
+
const tagEnd = tagAttrEnd(masked, tagStart);
|
|
133
|
+
const attr = (name) => readAttr(source, masked, tagStart, tagEnd, name);
|
|
134
|
+
const fallback = attr("fallback");
|
|
135
|
+
if (fallback?.value) addSurface(fallback.value);
|
|
136
|
+
else if (fallback?.dynamic) checkoutDynamic = true;
|
|
137
|
+
const recovery = attr("recoverySurface");
|
|
138
|
+
if (recovery?.value) addSurface(recovery.value);
|
|
139
|
+
else if (recovery?.dynamic) checkoutDynamic = true;
|
|
140
|
+
if (comp === "Checkout") {
|
|
141
|
+
const surface = attr("surface");
|
|
142
|
+
if (surface?.value) addSurface(surface.value);
|
|
143
|
+
else if (surface?.dynamic) checkoutDynamic = true;
|
|
144
|
+
} else {
|
|
145
|
+
const kind = attr("kind");
|
|
146
|
+
if (kind?.value) addKind(kind.value);
|
|
147
|
+
else if (kind?.dynamic) checkoutDynamic = true;
|
|
148
|
+
else addKind("subscription");
|
|
149
|
+
}
|
|
150
|
+
}
|
|
91
151
|
}
|
|
92
|
-
return { slots: order, dynamic };
|
|
152
|
+
return { slots: order, dynamic, checkout: { surfaces, upsellKinds, dynamic: checkoutDynamic } };
|
|
93
153
|
}
|
|
94
154
|
|
|
95
155
|
// src/flow/scaffold.ts
|
|
@@ -183,6 +243,7 @@ export const manifest = compileManifest({
|
|
|
183
243
|
funnel: config,
|
|
184
244
|
pages: pages.map((pg) => ({ key: pg.key, meta: pg.meta })),
|
|
185
245
|
offeringRefs: ${JSON.stringify(opts.offeringRefs ?? [])},
|
|
246
|
+
checkoutRefs: ${JSON.stringify(opts.checkoutRefs ?? { surfaces: [], upsellKinds: [], dynamic: false })},
|
|
186
247
|
})
|
|
187
248
|
|
|
188
249
|
export async function ssr(opts: MountOpts): Promise<string> {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/manifest/offering-refs.ts","../src/flow/scaffold.ts"],"names":[],"mappings":";;;;;AAsBA,SAAS,KAAK,GAAA,EAAqB;AACjC,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA;AACxB,EAAA,MAAM,IAAI,GAAA,CAAI,MAAA;AACd,EAAA,IAAI,CAAA,GAAI,CAAA;AACR,EAAA,OAAO,IAAI,CAAA,EAAG;AACZ,IAAA,MAAM,CAAA,GAAI,IAAI,CAAC,CAAA;AACf,IAAA,MAAM,CAAA,GAAI,GAAA,CAAI,CAAA,GAAI,CAAC,CAAA;AACnB,IAAA,IAAI,CAAA,KAAM,GAAA,IAAO,CAAA,KAAM,GAAA,EAAK;AAC1B,MAAA,OAAO,CAAA,GAAI,CAAA,IAAK,GAAA,CAAI,CAAC,MAAM,IAAA,EAAM;AAAE,QAAA,GAAA,CAAI,CAAC,CAAA,GAAI,GAAA;AAAK,QAAA,CAAA,EAAA;AAAA,MAAI;AAAA,IACvD,CAAA,MAAA,IAAW,CAAA,KAAM,GAAA,IAAO,CAAA,KAAM,GAAA,EAAK;AACjC,MAAA,GAAA,CAAI,CAAC,CAAA,GAAI,GAAA;AAAK,MAAA,GAAA,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;AAGO,SAAS,oBACf,IAAA,EACS;AACT,EAAA,MAAM,CAAA,GAAI,KAAK,YAAA,IAAgB,IAAA;AAC/B,EAAA,OAAO,GAAG,MAAM,CAAA;AAAA;AAAA,wBAAA,EAES,CAAC,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA,eAAA,EAMV,KAAK,SAAA,CAAU,IAAA,CAAK,YAAA,IAAgB,EAAE,CAAC,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AASxD;AAGO,SAAS,iBACf,IAAA,EAGS;AACT,EAAA,MAAM,CAAA,GAAI,KAAK,YAAA,IAAgB,IAAA;AAC/B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,GAAY,CAAA,QAAA,EAAW,CAAC,CAAA;AAAA,CAAA,GAAkB,EAAA;AAC9D,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,EAAG,MAAM,CAAA;AAAA;;AAAA;AAAA,mCAAA,EAIW,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,CAAA;AAE9D","file":"manifest-entry.js","sourcesContent":["/**\n * Pure, React-free page scan: find which offering SLOTS a funnel's pages reference — the first\n * string-literal arg of `useOffering(...)` and the `offering` prop of `<Checkout>` / `<Upsell>`.\n * Ships via `@appfunnel-dev/sdk/manifest` so the BUILD, the EDITOR, and the AI all run the SAME\n * check. The result feeds `compileManifest({ offeringRefs })`, which flags references to slots the\n * funnel doesn't declare (unknown) or hasn't assigned a catalog charge key to (unassigned).\n *\n * Non-literal args (`useOffering(selectedId)`, `offering={expr}`) and the `useOfferings()` wildcard are\n * DYNAMIC — they can't be statically enumerated, so they're reported via `dynamic` and never turned\n * into a hard error (validation relaxes when a funnel is dynamic). Mirrors the mask-then-read\n * discipline the funnel.ts code-mods use, so a `useOffering('x')` inside a comment or string literal\n * can't false-positive.\n */\n\nexport interface OfferingRefScan {\n /** Concrete slot names referenced by LITERAL args, deduped, in first-seen order. */\n slots: string[]\n /** True if any ref is a non-literal arg or a `useOfferings()` wildcard (not statically enumerable). */\n dynamic: boolean\n}\n\n/** Blank comment + string/template CONTENTS (keep quote delimiters + length) so scans don't fire inside them. */\nfunction mask(src: string): string {\n const out = src.split('')\n const n = src.length\n let i = 0\n while (i < n) {\n const c = src[i]\n const d = src[i + 1]\n if (c === '/' && d === '/') {\n while (i < n && src[i] !== '\\n') { out[i] = ' '; i++ }\n } else if (c === '/' && d === '*') {\n out[i] = ' '; out[i + 1] = ' '; i += 2\n while (i < n) {\n if (src[i] === '*' && src[i + 1] === '/') { out[i] = ' '; out[i + 1] = ' '; i += 2; break }\n if (src[i] !== '\\n') out[i] = ' '\n i++\n }\n } else if (c === \"'\" || c === '\"' || c === '`') {\n i++\n while (i < n && src[i] !== c) {\n if (src[i] === '\\\\') { out[i] = ' '; i++; if (i < n && src[i] !== '\\n') out[i] = ' '; i++; continue }\n if (src[i] !== '\\n') out[i] = ' '\n i++\n }\n i++ // closing delimiter (kept)\n } else i++\n }\n return out.join('')\n}\n\n/** A quoted string literal starting at `open` (a quote char in the MASK). Value read from the ORIGINAL. */\nfunction literalAt(src: string, masked: string, open: number): string | null {\n const q = masked[open]\n if (q !== \"'\" && q !== '\"' && q !== '`') return null\n const close = masked.indexOf(q, open + 1)\n if (close === -1) return null\n return src.slice(open + 1, close)\n}\n\n/** Advance past whitespace in `masked` from `i`. */\nfunction skipWs(masked: string, i: number): number {\n while (i < masked.length && (masked[i] === ' ' || masked[i] === '\\t' || masked[i] === '\\n' || masked[i] === '\\r')) i++\n return i\n}\n\nexport function scanOfferingRefs(files: Record<string, string>): OfferingRefScan {\n const seen = new Set<string>()\n const order: string[] = []\n let dynamic = false\n const add = (v: string) => { if (v && !seen.has(v)) { seen.add(v); order.push(v) } }\n\n for (const [path, source] of Object.entries(files)) {\n if (!/\\.(tsx|jsx|ts|js)$/.test(path)) continue\n const masked = mask(source)\n\n // useOffering( … ) / useOfferings( … ) — positions on the MASK (a call inside a string won't match).\n for (const m of masked.matchAll(/\\buseOfferings?\\s*\\(/g)) {\n const plural = source.slice(m.index!, m.index! + 12) === 'useOfferings'\n const j = skipWs(masked, m.index! + m[0].length)\n if (masked[j] === ')') { if (plural) dynamic = true; continue } // useOfferings() = whole-catalog wildcard\n const lit = literalAt(source, masked, j)\n if (lit !== null) add(lit)\n else dynamic = true // useOffering(variable) — can't resolve statically\n }\n\n // <Checkout offering=\"…\"> / <Upsell offering=\"…\"> — the `offering` attribute value.\n for (const m of masked.matchAll(/<(?:Checkout|Upsell)\\b[^>]*?\\boffering\\s*=\\s*/g)) {\n const j = m.index! + m[0].length\n const lit = literalAt(source, masked, j)\n if (lit !== null) add(lit)\n else if (masked[j] === '{') dynamic = true // offering={expr}\n }\n }\n return { slots: order, dynamic }\n}\n","/**\n * Source generators for the funnel build \"machinery\" authors no longer write. `funnel.ts` (the\n * spine: id, responses, offerings, checkout, and the page list + declarative routing) plus the\n * `pages/` folder are the ONLY authored source. The build (renderer/builder) and the CLI dev server\n * call these to synthesize:\n * - `mount.tsx` — code-split page loaders + `createFunnelTree`\n * - `entry.client.tsx` — hydrate the SSR'd markup from injected data\n * - `entry.server.tsx` — `ssr()` + the compiled `manifest`\n *\n * All string templates, zero runtime deps — this module lives in the pure `@appfunnel-dev/sdk/\n * manifest` entry so tooling imports it without the funnel runtime.\n */\n\nexport interface ScaffoldOptions {\n\t/** Page component keys = `pages/<key>.tsx` filenames (base flow pages AND `@variant` pages). */\n\tpageKeys: string[]\n\t/** Import prefix to reach the funnel root: `'./'` at the root (build), `'../../'` in a subdir (CLI dev). */\n\timportPrefix?: string\n\t/** Whether a `layout.tsx` exists to wrap the pages. */\n\thasLayout?: boolean\n\t/** Whether a `styles.css` exists (client entry imports it). */\n\thasStyles?: boolean\n\t/** Checkout provider from `config.checkout` — wires the driver; omit for none. */\n\tcheckout?: 'stripe' | 'paddle' | null\n\t/** Locales with a `messages/<locale>.json` catalog to bake into the mount (so `t()` resolves at render). */\n\tmessageLocales?: string[]\n\t/** Slot names the pages reference (from `scanOfferingRefs`), baked into the manifest for validation. */\n\tofferingRefs?: string[]\n}\n\n/** A safe JS identifier for a message-catalog import (`en` → `msg_en`, `pt-BR` → `msg_pt_BR`). */\nfunction msgId(locale: string): string {\n\treturn 'msg_' + locale.replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nconst DRIVERS = {\n\tstripe: { name: 'stripeCheckoutDriver', sub: 'driver-stripe' },\n\tpaddle: { name: 'paddleCheckoutDriver', sub: 'driver-paddle' },\n} as const\n\nconst HEADER =\n\t'// GENERATED by Appfunnel — do not edit. Built from funnel.ts + the pages/ folder.\\n'\n\n/** `mount.tsx` — the code-split loaders + tree, derived from `config.pages` and the `pages/` files. */\nexport function generateMount(opts: ScaffoldOptions): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst driver = opts.checkout ? DRIVERS[opts.checkout] : null\n\n\tconst locales = opts.messageLocales ?? []\n\tconst imports = [\n\t\t`import { createFunnelTree, type MountOpts, type RuntimePage } from '@appfunnel-dev/sdk'`,\n\t\tdriver &&\n\t\t\t`import { ${driver.name} } from '@appfunnel-dev/sdk/${driver.sub}'`,\n\t\t`import { config } from '${p}funnel'`,\n\t\topts.hasLayout && `import Layout from '${p}layout'`,\n\t\t...locales.map(\n\t\t\t(loc) => `import ${msgId(loc)} from '${p}messages/${loc}.json'`\n\t\t),\n\t]\n\t\t.filter(Boolean)\n\t\t.join('\\n')\n\n\t// A static import() per page file so Vite emits one code-split chunk each.\n\tconst loaders = opts.pageKeys\n\t\t.map(\n\t\t\t(k) =>\n\t\t\t\t`\\t${JSON.stringify(k)}: () => import(${JSON.stringify(`${p}pages/${k}`)}),`\n\t\t)\n\t\t.join('\\n')\n\n\tconst treeArgs = [\n\t\t'config',\n\t\t'pages',\n\t\topts.hasLayout && 'layout: Layout',\n\t\tdriver && `checkoutDriver: ${driver.name}`,\n\t\tlocales.length > 0 && 'messages',\n\t]\n\t\t.filter(Boolean)\n\t\t.join(', ')\n\n\t// The baked message catalog: locale → messages/<locale>.json (so `t()` resolves at render).\n\tconst messagesConst =\n\t\tlocales.length > 0\n\t\t\t? `\\nconst messages = { ${locales.map((loc) => `${JSON.stringify(loc)}: ${msgId(loc)}`).join(', ')} }\\n`\n\t\t\t: ''\n\n\treturn `${HEADER}${imports}\n\nconst loaders: Record<string, () => Promise<unknown>> = {\n${loaders}\n}\n\n// Flow pages come from funnel.ts (order + meta + routing). A \\`@variant\\` page MAY also be declared\n// there (with its \\`@\\` key) to carry its OWN optional routing (\\`next\\`) — it still collapses out of\n// the linear flow by the \\`@\\` marker, but its meta rides along here. Any page file NOT declared is an\n// off-flow \\`@variant\\` with no own routing, appended with empty meta so it's still loadable.\nconst decls = config.pages ?? []\nconst flowKeys = new Set(decls.map((d) => d.key))\nexport const pages: RuntimePage[] = [\n\t...decls.map((d) => ({ key: d.key, meta: d, load: loaders[d.key] })),\n\t...Object.keys(loaders)\n\t\t.filter((k) => !flowKeys.has(k))\n\t\t.map((k) => ({ key: k, meta: {}, load: loaders[k] })),\n] as RuntimePage[]\n${messagesConst}\nexport const tree = createFunnelTree({ ${treeArgs} })\n\nexport type { MountOpts }\n`\n}\n\n/** `entry.client.tsx` — hydrate the SSR'd markup from the injected `#__af_data`. */\nexport function generateEntryClient(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'>\n): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst styles = opts.hasStyles ? `import '${p}styles.css'\\n` : ''\n\treturn `${HEADER}${styles}import { hydrateRoot } from 'react-dom/client'\nimport { tree, type MountOpts } from './mount'\n\nconst dataEl = document.getElementById('__af_data')\nconst data = (dataEl?.textContent ? JSON.parse(dataEl.textContent) : {}) as MountOpts & {\n\tinitialKey?: string | null\n}\nconst root = document.getElementById('root')\n// FLASH-FREE HYDRATION (SSR-isolation Option B): always DEFER sessionValues on the client. The\n// markup we hydrate against is DEFAULT-state (build-time prerendered, or an SSR render with empty\n// sessionValues), so seeding the store with defaults for the first render is a byte-clean match —\n// no hydration mismatch. The visitor's saved answers (data.sessionValues, present on the \"tail\"\n// path) are then applied post-hydration, popping into already-visible controls with no empty\n// flash. On the cold path sessionValues is absent, so deferring is a no-op (identical output).\nif (root) hydrateRoot(root, tree({ ...data, initialKey: data.initialKey ?? undefined, deferSessionValues: true }))\n`\n}\n\n/** `entry.server.tsx` — `ssr(opts)` HTML + the compiled `manifest` (read by the build). */\nexport function generateEntryServer(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'offeringRefs'>\n): string {\n\tconst p = opts.importPrefix ?? './'\n\treturn `${HEADER}import { renderToReadableStream } from 'react-dom/server.browser'\nimport { compileManifest } from '@appfunnel-dev/sdk'\nimport { config } from '${p}funnel'\nimport { tree, pages, type MountOpts } from './mount'\n\nexport const manifest = compileManifest({\n\tfunnel: config,\n\tpages: pages.map((pg) => ({ key: pg.key, meta: pg.meta })),\n\tofferingRefs: ${JSON.stringify(opts.offeringRefs ?? [])},\n})\n\nexport async function ssr(opts: MountOpts): Promise<string> {\n\tconst stream = await renderToReadableStream(tree(opts))\n\tawait stream.allReady\n\treturn await new Response(stream).text()\n}\n`\n}\n\n/** Client-only dev entry (createRoot, no SSR) — for the CLI `dev` server. */\nexport function generateDevEntry(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'> & {\n\t\tdata: unknown\n\t}\n): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst styles = opts.hasStyles ? `import '${p}styles.css'\\n` : ''\n\treturn `${HEADER}${styles}import { createRoot } from 'react-dom/client'\nimport { tree } from './mount'\n\nconst el = document.getElementById('root')\nif (el) createRoot(el).render(tree(${JSON.stringify(opts.data)}))\n`\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/manifest/offering-refs.ts","../src/flow/scaffold.ts"],"names":[],"mappings":";;;;;AAmDA,SAAS,KAAK,GAAA,EAAqB;AACjC,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA;AACxB,EAAA,MA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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAgB1B;AAGO,SAAS,oBACf,IAAA,EACS;AACT,EAAA,MAAM,CAAA,GAAI,KAAK,YAAA,IAAgB,IAAA;AAC/B,EAAA,OAAO,GAAG,MAAM,CAAA;AAAA;AAAA,wBAAA,EAES,CAAC,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA,eAAA,EAMV,KAAK,SAAA,CAAU,IAAA,CAAK,YAAA,IAAgB,EAAE,CAAC,CAAA;AAAA,eAAA,EACvC,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,YAAA,IAAgB,EAAE,QAAA,EAAU,EAAC,EAAG,WAAA,EAAa,EAAC,EAAG,OAAA,EAAS,KAAA,EAAO,CAAC,CAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AASvG;AAGO,SAAS,iBACf,IAAA,EAGS;AACT,EAAA,MAAM,CAAA,GAAI,KAAK,YAAA,IAAgB,IAAA;AAC/B,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,SAAA,GAAY,CAAA,QAAA,EAAW,CAAC,CAAA;AAAA,CAAA,GAAkB,EAAA;AAC9D,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,EAAG,MAAM,CAAA;AAAA;;AAAA;AAAA,mCAAA,EAIW,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,CAAA;AAE9D","file":"manifest-entry.js","sourcesContent":["/**\n * Pure, React-free page scan: find which offering SLOTS a funnel's pages reference — the first\n * string-literal arg of `useOffering(...)` and the `offering` prop of `<Checkout>` / `<Upsell>`.\n * Ships via `@appfunnel-dev/sdk/manifest` so the BUILD, the EDITOR, and the AI all run the SAME\n * check. The result feeds `compileManifest({ offeringRefs })`, which flags references to slots the\n * funnel doesn't declare (unknown) or hasn't assigned a catalog charge key to (unassigned).\n *\n * Non-literal args (`useOffering(selectedId)`, `offering={expr}`) and the `useOfferings()` wildcard are\n * DYNAMIC — they can't be statically enumerated, so they're reported via `dynamic` and never turned\n * into a hard error (validation relaxes when a funnel is dynamic). Mirrors the mask-then-read\n * discipline the funnel.ts code-mods use, so a `useOffering('x')` inside a comment or string literal\n * can't false-positive.\n */\n\nexport interface OfferingRefScan {\n /** Concrete slot names referenced by LITERAL args, deduped, in first-seen order. */\n slots: string[]\n /** True if any ref is a non-literal arg or a `useOfferings()` wildcard (not statically enumerable). */\n dynamic: boolean\n /**\n * Checkout-SURFACE usage the pages express — feeds the publish (provider × surface) capability\n * gate. Absent-field back-compat: a manifest compiled before this existed simply omits it, and\n * the gate skips (no false blocks). See {@link CheckoutUsageScan}.\n */\n checkout: CheckoutUsageScan\n}\n\n/**\n * What the pages ask the checkout to DO, statically — the surfaces they mount and the off-session\n * upsell kinds they charge. Literal values only; a computed value (`surface={expr}`) sets\n * {@link dynamic} so the publish gate WARNS instead of hard-failing (it can't enumerate it).\n */\nexport interface CheckoutUsageScan {\n /**\n * Purchase SURFACES the pages request, deduped in first-seen order. Captures every literal\n * `<Checkout surface=\"…\">` plus the on-session re-collect surfaces `<Checkout|Upsell fallback=\"…\">`\n * and `recoverySurface=\"…\"` (a fallback re-collects a card → it IS a purchase surface the provider\n * must support). Validated with `validateCheckout(provider, surface)`.\n */\n surfaces: string[]\n /**\n * Off-session upsell KINDS from `<Upsell kind=\"…\">`, deduped. A `<Upsell>` with no `kind` attr\n * defaults to `'subscription'` (mirrors the runtime default), so an unadorned `<Upsell>` records\n * `'subscription'`. Validated with `validateUpsell(provider, paywallSurface, kind)`.\n */\n upsellKinds: string[]\n /** True if any surface/kind was a non-literal (computed) value → the gate WARNS, never blocks, on it. */\n dynamic: boolean\n}\n\n/** Blank comment + string/template CONTENTS (keep quote delimiters + length) so scans don't fire inside them. */\nfunction mask(src: string): string {\n const out = src.split('')\n const n = src.length\n let i = 0\n while (i < n) {\n const c = src[i]\n const d = src[i + 1]\n if (c === '/' && d === '/') {\n while (i < n && src[i] !== '\\n') { out[i] = ' '; i++ }\n } else if (c === '/' && d === '*') {\n out[i] = ' '; out[i + 1] = ' '; i += 2\n while (i < n) {\n if (src[i] === '*' && src[i + 1] === '/') { out[i] = ' '; out[i + 1] = ' '; i += 2; break }\n if (src[i] !== '\\n') out[i] = ' '\n i++\n }\n } else if (c === \"'\" || c === '\"' || c === '`') {\n i++\n while (i < n && src[i] !== c) {\n if (src[i] === '\\\\') { out[i] = ' '; i++; if (i < n && src[i] !== '\\n') out[i] = ' '; i++; continue }\n if (src[i] !== '\\n') out[i] = ' '\n i++\n }\n i++ // closing delimiter (kept)\n } else i++\n }\n return out.join('')\n}\n\n/** A quoted string literal starting at `open` (a quote char in the MASK). Value read from the ORIGINAL. */\nfunction literalAt(src: string, masked: string, open: number): string | null {\n const q = masked[open]\n if (q !== \"'\" && q !== '\"' && q !== '`') return null\n const close = masked.indexOf(q, open + 1)\n if (close === -1) return null\n return src.slice(open + 1, close)\n}\n\n/** Advance past whitespace in `masked` from `i`. */\nfunction skipWs(masked: string, i: number): number {\n while (i < masked.length && (masked[i] === ' ' || masked[i] === '\\t' || masked[i] === '\\n' || masked[i] === '\\r')) i++\n return i\n}\n\n/**\n * Index of the `>` that closes the opening tag begun at `from` (the char after `<Checkout`). Tracks\n * brace depth so a `surface={a > b}` attribute expression doesn't end the tag early; `>` at depth 0\n * closes it (covers `/>` too — the `/` is at depth 0 and we stop at `>`). Returns end-of-string if\n * the tag never closes (masked never fires a value scan past it).\n */\nfunction tagAttrEnd(masked: string, from: number): number {\n let depth = 0\n for (let i = from; i < masked.length; i++) {\n const c = masked[i]\n if (c === '{') depth++\n else if (c === '}') { if (depth > 0) depth-- }\n else if (c === '>' && depth === 0) return i\n }\n return masked.length\n}\n\n/**\n * Read a JSX attribute `name` inside the opening-tag span `[start, end)`: returns its literal value,\n * `{ dynamic: true }` for a `{expr}` value, or null when the attribute is absent. Positions are on\n * the MASK; the value is read from the ORIGINAL (so a string-literal value survives masking).\n */\nfunction readAttr(\n src: string,\n masked: string,\n start: number,\n end: number,\n name: string,\n): { value?: string; dynamic?: boolean } | null {\n const re = new RegExp(`\\\\b${name}\\\\s*=\\\\s*`, 'g')\n re.lastIndex = start\n const m = re.exec(masked)\n if (!m || m.index >= end) return null\n const at = m.index + m[0].length\n if (masked[at] === '{') return { dynamic: true }\n const lit = literalAt(src, masked, at)\n return lit !== null ? { value: lit } : { dynamic: true }\n}\n\nexport function scanOfferingRefs(files: Record<string, string>): OfferingRefScan {\n const seen = new Set<string>()\n const order: string[] = []\n let dynamic = false\n const add = (v: string) => { if (v && !seen.has(v)) { seen.add(v); order.push(v) } }\n\n // Checkout-surface usage (separate dynamic flag: a computed SURFACE relaxes the capability gate,\n // independent of whether an OFFERING ref is computed).\n const surfaceSeen = new Set<string>()\n const surfaces: string[] = []\n const kindSeen = new Set<string>()\n const upsellKinds: string[] = []\n let checkoutDynamic = false\n const addSurface = (v: string) => { if (v && !surfaceSeen.has(v)) { surfaceSeen.add(v); surfaces.push(v) } }\n const addKind = (v: string) => { if (v && !kindSeen.has(v)) { kindSeen.add(v); upsellKinds.push(v) } }\n\n for (const [path, source] of Object.entries(files)) {\n if (!/\\.(tsx|jsx|ts|js)$/.test(path)) continue\n const masked = mask(source)\n\n // useOffering( … ) / useOfferings( … ) — positions on the MASK (a call inside a string won't match).\n for (const m of masked.matchAll(/\\buseOfferings?\\s*\\(/g)) {\n const plural = source.slice(m.index!, m.index! + 12) === 'useOfferings'\n const j = skipWs(masked, m.index! + m[0].length)\n if (masked[j] === ')') { if (plural) dynamic = true; continue } // useOfferings() = whole-catalog wildcard\n const lit = literalAt(source, masked, j)\n if (lit !== null) add(lit)\n else dynamic = true // useOffering(variable) — can't resolve statically\n }\n\n // <Checkout offering=\"…\"> / <Upsell offering=\"…\"> — the `offering` attribute value.\n for (const m of masked.matchAll(/<(?:Checkout|Upsell)\\b[^>]*?\\boffering\\s*=\\s*/g)) {\n const j = m.index! + m[0].length\n const lit = literalAt(source, masked, j)\n if (lit !== null) add(lit)\n else if (masked[j] === '{') dynamic = true // offering={expr}\n }\n\n // <Checkout …> / <Upsell …> checkout-SURFACE usage. Parse each opening tag's attribute span so\n // attribute order doesn't matter and a `>` inside a `{expr}` value can't truncate it.\n for (const m of masked.matchAll(/<(Checkout|Upsell)\\b/g)) {\n const comp = m[1]\n const tagStart = m.index! + m[0].length\n const tagEnd = tagAttrEnd(masked, tagStart)\n const attr = (name: string) => readAttr(source, masked, tagStart, tagEnd, name)\n // A fallback / recoverySurface re-collects a card ON-SESSION → it's a purchase surface too.\n const fallback = attr('fallback')\n if (fallback?.value) addSurface(fallback.value)\n else if (fallback?.dynamic) checkoutDynamic = true\n const recovery = attr('recoverySurface')\n if (recovery?.value) addSurface(recovery.value)\n else if (recovery?.dynamic) checkoutDynamic = true\n\n if (comp === 'Checkout') {\n const surface = attr('surface')\n if (surface?.value) addSurface(surface.value)\n else if (surface?.dynamic) checkoutDynamic = true\n } else {\n // <Upsell>: off-session; `kind` defaults to 'subscription' when the attr is absent.\n const kind = attr('kind')\n if (kind?.value) addKind(kind.value)\n else if (kind?.dynamic) checkoutDynamic = true\n else addKind('subscription')\n }\n }\n }\n return { slots: order, dynamic, checkout: { surfaces, upsellKinds, dynamic: checkoutDynamic } }\n}\n","/**\n * Source generators for the funnel build \"machinery\" authors no longer write. `funnel.ts` (the\n * spine: id, responses, offerings, checkout, and the page list + declarative routing) plus the\n * `pages/` folder are the ONLY authored source. The build (renderer/builder) and the CLI dev server\n * call these to synthesize:\n * - `mount.tsx` — code-split page loaders + `createFunnelTree`\n * - `entry.client.tsx` — hydrate the SSR'd markup from injected data\n * - `entry.server.tsx` — `ssr()` + the compiled `manifest`\n *\n * All string templates, zero runtime deps — this module lives in the pure `@appfunnel-dev/sdk/\n * manifest` entry so tooling imports it without the funnel runtime.\n */\n\nimport type { CheckoutUsageScan } from '../manifest/offering-refs'\n\nexport interface ScaffoldOptions {\n\t/** Page component keys = `pages/<key>.tsx` filenames (base flow pages AND `@variant` pages). */\n\tpageKeys: string[]\n\t/** Import prefix to reach the funnel root: `'./'` at the root (build), `'../../'` in a subdir (CLI dev). */\n\timportPrefix?: string\n\t/** Whether a `layout.tsx` exists to wrap the pages. */\n\thasLayout?: boolean\n\t/** Whether a `styles.css` exists (client entry imports it). */\n\thasStyles?: boolean\n\t/** Checkout provider from `config.checkout` — wires the driver; omit for none. */\n\tcheckout?: 'stripe' | 'paddle' | null\n\t/** Locales with a `messages/<locale>.json` catalog to bake into the mount (so `t()` resolves at render). */\n\tmessageLocales?: string[]\n\t/** Slot names the pages reference (from `scanOfferingRefs`), baked into the manifest for validation. */\n\tofferingRefs?: string[]\n\t/** Checkout-surface usage the pages express (from `scanOfferingRefs(...).checkout`), baked into the manifest for the publish capability gate. */\n\tcheckoutRefs?: CheckoutUsageScan\n}\n\n/** A safe JS identifier for a message-catalog import (`en` → `msg_en`, `pt-BR` → `msg_pt_BR`). */\nfunction msgId(locale: string): string {\n\treturn 'msg_' + locale.replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nconst DRIVERS = {\n\tstripe: { name: 'stripeCheckoutDriver', sub: 'driver-stripe' },\n\tpaddle: { name: 'paddleCheckoutDriver', sub: 'driver-paddle' },\n} as const\n\nconst HEADER =\n\t'// GENERATED by Appfunnel — do not edit. Built from funnel.ts + the pages/ folder.\\n'\n\n/** `mount.tsx` — the code-split loaders + tree, derived from `config.pages` and the `pages/` files. */\nexport function generateMount(opts: ScaffoldOptions): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst driver = opts.checkout ? DRIVERS[opts.checkout] : null\n\n\tconst locales = opts.messageLocales ?? []\n\tconst imports = [\n\t\t`import { createFunnelTree, type MountOpts, type RuntimePage } from '@appfunnel-dev/sdk'`,\n\t\tdriver &&\n\t\t\t`import { ${driver.name} } from '@appfunnel-dev/sdk/${driver.sub}'`,\n\t\t`import { config } from '${p}funnel'`,\n\t\topts.hasLayout && `import Layout from '${p}layout'`,\n\t\t...locales.map(\n\t\t\t(loc) => `import ${msgId(loc)} from '${p}messages/${loc}.json'`\n\t\t),\n\t]\n\t\t.filter(Boolean)\n\t\t.join('\\n')\n\n\t// A static import() per page file so Vite emits one code-split chunk each.\n\tconst loaders = opts.pageKeys\n\t\t.map(\n\t\t\t(k) =>\n\t\t\t\t`\\t${JSON.stringify(k)}: () => import(${JSON.stringify(`${p}pages/${k}`)}),`\n\t\t)\n\t\t.join('\\n')\n\n\tconst treeArgs = [\n\t\t'config',\n\t\t'pages',\n\t\topts.hasLayout && 'layout: Layout',\n\t\tdriver && `checkoutDriver: ${driver.name}`,\n\t\tlocales.length > 0 && 'messages',\n\t]\n\t\t.filter(Boolean)\n\t\t.join(', ')\n\n\t// The baked message catalog: locale → messages/<locale>.json (so `t()` resolves at render).\n\tconst messagesConst =\n\t\tlocales.length > 0\n\t\t\t? `\\nconst messages = { ${locales.map((loc) => `${JSON.stringify(loc)}: ${msgId(loc)}`).join(', ')} }\\n`\n\t\t\t: ''\n\n\treturn `${HEADER}${imports}\n\nconst loaders: Record<string, () => Promise<unknown>> = {\n${loaders}\n}\n\n// Flow pages come from funnel.ts (order + meta + routing). A \\`@variant\\` page MAY also be declared\n// there (with its \\`@\\` key) to carry its OWN optional routing (\\`next\\`) — it still collapses out of\n// the linear flow by the \\`@\\` marker, but its meta rides along here. Any page file NOT declared is an\n// off-flow \\`@variant\\` with no own routing, appended with empty meta so it's still loadable.\nconst decls = config.pages ?? []\nconst flowKeys = new Set(decls.map((d) => d.key))\nexport const pages: RuntimePage[] = [\n\t...decls.map((d) => ({ key: d.key, meta: d, load: loaders[d.key] })),\n\t...Object.keys(loaders)\n\t\t.filter((k) => !flowKeys.has(k))\n\t\t.map((k) => ({ key: k, meta: {}, load: loaders[k] })),\n] as RuntimePage[]\n${messagesConst}\nexport const tree = createFunnelTree({ ${treeArgs} })\n\nexport type { MountOpts }\n`\n}\n\n/** `entry.client.tsx` — hydrate the SSR'd markup from the injected `#__af_data`. */\nexport function generateEntryClient(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'>\n): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst styles = opts.hasStyles ? `import '${p}styles.css'\\n` : ''\n\treturn `${HEADER}${styles}import { hydrateRoot } from 'react-dom/client'\nimport { tree, type MountOpts } from './mount'\n\nconst dataEl = document.getElementById('__af_data')\nconst data = (dataEl?.textContent ? JSON.parse(dataEl.textContent) : {}) as MountOpts & {\n\tinitialKey?: string | null\n}\nconst root = document.getElementById('root')\n// FLASH-FREE HYDRATION (SSR-isolation Option B): always DEFER sessionValues on the client. The\n// markup we hydrate against is DEFAULT-state (build-time prerendered, or an SSR render with empty\n// sessionValues), so seeding the store with defaults for the first render is a byte-clean match —\n// no hydration mismatch. The visitor's saved answers (data.sessionValues, present on the \"tail\"\n// path) are then applied post-hydration, popping into already-visible controls with no empty\n// flash. On the cold path sessionValues is absent, so deferring is a no-op (identical output).\nif (root) hydrateRoot(root, tree({ ...data, initialKey: data.initialKey ?? undefined, deferSessionValues: true }))\n`\n}\n\n/** `entry.server.tsx` — `ssr(opts)` HTML + the compiled `manifest` (read by the build). */\nexport function generateEntryServer(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'offeringRefs' | 'checkoutRefs'>\n): string {\n\tconst p = opts.importPrefix ?? './'\n\treturn `${HEADER}import { renderToReadableStream } from 'react-dom/server.browser'\nimport { compileManifest } from '@appfunnel-dev/sdk'\nimport { config } from '${p}funnel'\nimport { tree, pages, type MountOpts } from './mount'\n\nexport const manifest = compileManifest({\n\tfunnel: config,\n\tpages: pages.map((pg) => ({ key: pg.key, meta: pg.meta })),\n\tofferingRefs: ${JSON.stringify(opts.offeringRefs ?? [])},\n\tcheckoutRefs: ${JSON.stringify(opts.checkoutRefs ?? { surfaces: [], upsellKinds: [], dynamic: false })},\n})\n\nexport async function ssr(opts: MountOpts): Promise<string> {\n\tconst stream = await renderToReadableStream(tree(opts))\n\tawait stream.allReady\n\treturn await new Response(stream).text()\n}\n`\n}\n\n/** Client-only dev entry (createRoot, no SSR) — for the CLI `dev` server. */\nexport function generateDevEntry(\n\topts: Pick<ScaffoldOptions, 'importPrefix' | 'hasStyles'> & {\n\t\tdata: unknown\n\t}\n): string {\n\tconst p = opts.importPrefix ?? './'\n\tconst styles = opts.hasStyles ? `import '${p}styles.css'\\n` : ''\n\treturn `${HEADER}${styles}import { createRoot } from 'react-dom/client'\nimport { tree } from './mount'\n\nconst el = document.getElementById('root')\nif (el) createRoot(el).render(tree(${JSON.stringify(opts.data)}))\n`\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/i18n/locale.ts","../src/commerce/money.ts","../src/flow/spine.ts","../src/flow/experiments.ts","../src/manifest/manifest.ts"],"names":[],"mappings":";AAUA,IAAM,SAAA,mBAAY,IAAI,GAAA,CAAI,CAAC,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,IAAI,CAAC,CAAA;AAGnE,SAAS,MAAM,MAAA,EAAyB;AAC7C,EAAA,OAAO,UAAU,GAAA,CAAI,MAAA,CAAO,MAAM,GAAG,CAAA,CAAE,CAAC,CAAC,CAAA;AAC3C;AAEA,IAAM,OAAO,CAAC,CAAA,KAA8C,GAAG,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA;AAQpE,SAAS,aAAA,CACd,MAAA,EACA,QAAA,EACA,QAAA,EACQ;AACR,EAAA,MAAM,SAAA,GAAY,MAAA,EAAQ,SAAA,KAAc,MAAA,EAAQ,OAAA,GAAU,CAAC,MAAA,CAAO,OAAO,CAAA,GAAI,CAAC,IAAI,CAAA,CAAA;AAClF,EAAA,MAAM,GAAA,GAAM,MAAA,EAAQ,OAAA,IAAW,SAAA,CAAU,CAAC,CAAA,IAAK,IAAA;AAC/C,EAAA,MAAM,IAAA,GAAO,CAAC,CAAA,KAAmC;AAC/C,IAAA,IAAI,CAAC,GAAG,OAAO,MAAA;AACf,IAAA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AS,MAAA,KAAW,CAAA,IACpB,WAAA,CAAY,WAAW,CAAA,IACvB,UAAA,CAAW,MAAA,KAAW,CAAA,IACtB,CAAC,mBAAA,IACD,cAAc,MAAA,KAAW,CAAA,IACzB,cAAA,CAAe,MAAA,KAAW,CAAA,IAC1B,CAAC,qBACD,mBAAA,CAAoB,MAAA,KAAW,CAAA,IAC/B,eAAA,CAAgB,MAAA,KAAW,CAAA;AAAA,IAC7B,QAAA;AAAA,IACA,WAAA;AAAA,IACA,UAAA;AAAA,IACA,mBAAA;AAAA,IACA,aAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,iBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-7YQLPPPG.js","sourcesContent":["/**\n * Pure locale resolution — no React. Split out of {@link ./translation} so the\n * server/tooling entry (`@appfunnel-dev/sdk/manifest`) can resolve a visitor's\n * locale without pulling component code. {@link ./translation} re-exports it.\n */\n\nimport type { FunnelLocales } from '../flow/spine'\n\nexport type Direction = 'ltr' | 'rtl'\n\nconst RTL_LANGS = new Set(['ar', 'he', 'fa', 'ur', 'ps', 'sd', 'dv', 'yi'])\n\n/** Whether a locale is right-to-left (by language subtag). */\nexport function isRtl(locale: string): boolean {\n return RTL_LANGS.has(locale.split('-')[0])\n}\n\nconst base = (l: string | undefined): string | undefined => l?.split('-')[0]\n\n/**\n * Resolve the active locale: `override` (URL/param) → `detected` (device) →\n * funnel default, each only if supported (matched by exact tag or language\n * subtag). Mirrors doc 05's resolution chain (the geo/header steps happen\n * server-side and arrive via `override`/`detected`).\n */\nexport function resolveLocale(\n config: FunnelLocales | undefined,\n detected: string,\n override?: string,\n): string {\n const supported = config?.supported ?? (config?.default ? [config.default] : ['en'])\n const def = config?.default ?? supported[0] ?? 'en'\n const pick = (l?: string): string | undefined => {\n if (!l) return undefined\n if (supported.includes(l)) return l\n return supported.find((s) => base(s) === base(l))\n }\n return pick(override) ?? pick(detected) ?? def\n}\n","/**\n * Pure catalog math — no React, no I/O. Split out of {@link ./catalog} so the\n * server/tooling entry (`@appfunnel-dev/sdk/manifest`) can compile/resolve\n * offerings without pulling react-dom or any component code into its graph.\n * {@link ./catalog} re-exports everything here and adds the React wiring.\n */\n\n// ── Shape ────────────────────────────────────────────────\n\nexport type Interval = 'day' | 'week' | 'month' | 'year' | 'one_time'\n\n/** What the platform hands the funnel per offering (a single provider-resolved price). */\nexport interface OfferingInput {\n id: string\n /** The catalog charge KEY this input charges (the slot's assignment). Defaults to `id` (legacy/identity slots). */\n catalogKey?: string\n name?: string\n displayName?: string\n /** Provider-resolved price in **minor units** (the provider chose the currency). */\n amount: number\n /** Currency of `amount`, as the provider resolved it (e.g. `DKK`). */\n currency: string\n interval?: Interval\n intervalCount?: number\n trialDays?: number\n /** Trial price in minor units (omit/0 = free trial). */\n trialAmount?: number\n /** Settlement provider — opaque to the author, used by the checkout driver. */\n provider?: string\n}\n\n/** A money value with a locale-formatted string. */\nexport interface Money {\n /** Major units, e.g. `79`. */\n amount: number\n /** Minor units, e.g. `7900`. */\n minor: number\n currency: string\n /** Locale-formatted, e.g. `kr 79,00` / `€9,99` / `$9.99`. */\n formatted: string\n}\n\n/**\n * The offering with its amounts resolved (currency + period math), **before**\n * locale formatting — what the catalog stores. `useOffering` formats it.\n */\nexport interface ResolvedOffering {\n id: string\n /** The catalog charge KEY charged (the CHARGE identity; `id` is the SLOT/display identity). */\n catalogKey: string\n name: string\n displayName: string\n provider: string\n currency: string\n priceMinor: number\n perDayMinor: number\n perWeekMinor: number\n perMonthMinor: number\n perYearMinor: number\n period: string\n periodly: string\n hasTrial: boolean\n trialDays: number\n trialMinor: number\n}\n\n/** Display-ready offering the author reads (every amount locale-formatted). */\nexport interface Offering {\n id: string\n /** The catalog charge KEY charged (the CHARGE identity; `id` is the SLOT/display identity). */\n catalogKey: string\n name: string\n displayName: string\n provider: string\n price: Money\n /** e.g. `month`, `quarter`, `one-time`. */\n period: string\n /** e.g. `monthly`, `quarterly`, `one-time`. */\n periodly: string\n /** Period-normalized prices (for \"just $0.27/day\" style copy). */\n perDay: Money\n perWeek: Money\n perMonth: Money\n perYear: Money\n hasTrial: boolean\n trialDays: number\n trialPrice: Money | null\n}\n\n// ── Resolve (currency-agnostic) ──────────────────────────\n\n/**\n * The period model: the **day is the canonical unit** and every interval is a\n * consistent number of days — `year = 365`, `month = 365/12` (~30.42),\n * `week = 7`. Consistent means the derived periods are exact multiples of each\n * other: a monthly offering's `perMonthMinor` is its price, its `perYearMinor`\n * is exactly `12×` the price, and a yearly offering's `perMonthMinor` is exactly\n * `price / 12` — no 360-vs-365 drift (the old `month = 30` model made a yearly\n * plan's \"per month\" ~1.4% off).\n */\nconst PERIOD_DAYS: Record<Interval, number> = {\n day: 1, week: 7, month: 365 / 12, year: 365, one_time: 0,\n}\n\nfunction periodDays(interval: Interval, count: number): number {\n return PERIOD_DAYS[interval] * count\n}\n\nfunction intervalLabel(interval: Interval, count: number): { period: string; periodly: string } {\n if (interval === 'one_time') return { period: 'one-time', periodly: 'one-time' }\n if (interval === 'month' && count === 3) return { period: 'quarter', periodly: 'quarterly' }\n if (interval === 'month' && count === 6) return { period: '6 months', periodly: 'semiannually' }\n if (interval === 'week' && count === 2) return { period: '2 weeks', periodly: 'biweekly' }\n if (count === 1) {\n const periodly = { day: 'daily', week: 'weekly', month: 'monthly', year: 'yearly' }[interval]\n return { period: interval, periodly }\n }\n return { period: `${count} ${interval}s`, periodly: `every ${count} ${interval}s` }\n}\n\n/**\n * Resolve an {@link OfferingInput} into amounts + period math (no formatting yet).\n * Per-period amounts are **integer minor units** (each derived from the exact\n * daily rate, then rounded — never round-then-multiply, so error doesn't compound).\n */\nexport function resolveOffering(input: OfferingInput): ResolvedOffering {\n const interval = input.interval ?? 'one_time'\n const count = input.intervalCount ?? 1\n const days = periodDays(interval, count)\n // Derive each period from the exact price/days ratio, rounding each result\n // independently to whole minor units.\n const per = (targetDays: number): number =>\n days > 0 ? Math.round((input.amount * targetDays) / days) : input.amount\n const label = intervalLabel(interval, count)\n // A paid trial can be \"N days for X\" OR an intro price with no day count —\n // a set trialAmount alone still makes it a trial (trialDays: 0 must not\n // swallow the trial price).\n const trialDays = input.trialDays ?? 0\n const trialMinor = input.trialAmount ?? 0\n\n return {\n id: input.id,\n catalogKey: input.catalogKey ?? input.id,\n name: input.name ?? input.id,\n displayName: input.displayName ?? input.name ?? input.id,\n provider: input.provider ?? 'stripe',\n currency: input.currency,\n priceMinor: input.amount,\n perDayMinor: per(1),\n perWeekMinor: per(7),\n perMonthMinor: per(365 / 12),\n perYearMinor: per(365),\n period: label.period,\n periodly: label.periodly,\n hasTrial: trialDays > 0 || trialMinor > 0,\n trialDays,\n trialMinor,\n }\n}\n\n/** Build the id → {@link ResolvedOffering} catalog. Formatting happens at read time. */\nexport function buildCatalog(inputs: OfferingInput[]): Map<string, ResolvedOffering> {\n return new Map(inputs.map((i) => [i.id, resolveOffering(i)]))\n}\n\n// ── Format (locale-dependent) ────────────────────────────\n\n/** currency code → minor-unit exponent, resolved once via Intl (JPY→0, KWD→3, …). */\nconst EXPONENT_CACHE = new Map<string, number>()\n\n/**\n * The minor-unit exponent for a currency (`USD`→2, `JPY`→0, `KWD`/`BHD`→3),\n * derived from `Intl.NumberFormat(...).resolvedOptions().maximumFractionDigits`\n * with a fallback of 2 for unknown/invalid codes.\n */\nexport function currencyExponent(currency: string): number {\n const code = currency.toUpperCase()\n const hit = EXPONENT_CACHE.get(code)\n if (hit !== undefined) return hit\n let exp = 2\n try {\n exp = new Intl.NumberFormat('en', { style: 'currency', currency: code })\n .resolvedOptions().maximumFractionDigits ?? 2\n } catch {\n exp = 2\n }\n EXPONENT_CACHE.set(code, exp)\n return exp\n}\n\n/** Format minor units of `currency` in `locale` (exponent-aware: 7900 JPY = ¥7,900). */\nexport function formatMoney(minor: number, currency: string, locale: string): Money {\n const code = currency.toUpperCase()\n const exp = currencyExponent(code)\n const amount = minor / 10 ** exp\n let formatted: string\n try {\n formatted = new Intl.NumberFormat(locale, { style: 'currency', currency: code }).format(amount)\n } catch {\n formatted = `${code} ${amount.toFixed(exp)}`\n }\n return { amount, minor, currency: code, formatted }\n}\n\n/** Format a {@link ResolvedOffering} into a display {@link Offering} in `locale`. */\nexport function formatOffering(r: ResolvedOffering, locale: string): Offering {\n const m = (minor: number): Money => formatMoney(minor, r.currency, locale)\n return {\n id: r.id,\n catalogKey: r.catalogKey,\n name: r.name,\n displayName: r.displayName,\n provider: r.provider,\n price: m(r.priceMinor),\n period: r.period,\n periodly: r.periodly,\n perDay: m(r.perDayMinor),\n perWeek: m(r.perWeekMinor),\n perMonth: m(r.perMonthMinor),\n perYear: m(r.perYearMinor),\n hasTrial: r.hasTrial,\n trialDays: r.trialDays,\n trialPrice: r.hasTrial ? m(r.trialMinor) : null,\n }\n}\n","import type { ComponentType } from 'react'\nimport type { VariableConfig, VariableValue } from '../types'\nimport type { FunnelContext } from '../state/context'\n\n/**\n * The funnel **spine** — the constrained, declarative configuration authored as\n * code (`defineFunnel` / `pageMeta` / `definePage`) yet **dashboard-editable**\n * (static AST parse → pretty UI → codegen) and compiled to the manifest IR.\n *\n * Principle: **presentation = code** (the page components), **configuration =\n * data** (this spine). See docs/platform-v2/06-funnel-project-model.md.\n *\n * Routing is **declarative nodes + code predicates** (decided — doc 06): a\n * page's `next` is an ordered list of {@link Route}s, each with a **static `to`\n * page key** (so the dashboard can draw every possible edge without executing\n * anything) and an optional `when` **gate** that returns true/false. The gate is\n * either a declarative {@link Condition} (one field — UI-editable data) or a code\n * {@link Predicate} (`s => boolean` — the escape hatch, opaque body but the edge\n * is still visible). First matching route wins; a route with no `when` is the\n * fallback. Multiple conditions = multiple routes (or boolean logic in one\n * predicate). Omit `next` entirely for the default linear flow.\n */\n\n// ── Snapshot (what a predicate sees) ─────────────────────\n\n/**\n * Read-only view of every namespace a routing/condition predicate can branch\n * on. `user`/`responses`/`data` are the writable namespaces; `context` is the\n * read-only computed one ({@link FunnelContext}).\n */\nexport interface FunnelSnapshot {\n\tuser: Record<string, VariableValue>\n\tresponses: Record<string, VariableValue>\n\tdata: Record<string, VariableValue>\n\tcontext: FunnelContext\n}\n\n/** A code-predicate gate — `s => s.responses.goal === 'gain'`. */\nexport type Predicate = (s: FunnelSnapshot) => boolean\n\nexport type ConditionOp =\n\t| 'eq'\n\t| 'neq'\n\t| 'in'\n\t| 'gt'\n\t| 'gte'\n\t| 'lt'\n\t| 'lte'\n\t| 'exists'\n\t| 'empty'\n\t| 'contains'\n\n/**\n * A declarative gate over **one** namespaced field — UI-editable data the\n * dashboard renders as a condition row (`field` `op` `value`). `field` is a\n * dotted path into the snapshot: `responses.goal`, `user.country`,\n * `context.device.isMobile`.\n */\nexport interface Condition {\n\tfield: string\n\top: ConditionOp\n\tvalue?: VariableValue | VariableValue[]\n}\n\n/** An edge gate: either declarative data ({@link Condition}) or a {@link Predicate}. */\nexport type Gate = Condition | Predicate\n\n/**\n * One routing edge out of a page. `to` is a **static** target key (the dashboard\n * reads these to draw the flow graph); `when` gates the edge (omit = fallback).\n */\nexport interface Route {\n\tto: string\n\twhen?: Gate\n}\n\n/** Read a dotted path out of the snapshot (flat namespaces + nested `context`). */\nfunction readField(s: FunnelSnapshot, field: string): VariableValue {\n\tlet cur: unknown = s\n\tfor (const part of field.split('.')) {\n\t\tif (cur == null) return undefined\n\t\tcur = (cur as Record<string, unknown>)[part]\n\t}\n\treturn cur as VariableValue\n}\n\n/** Evaluate a declarative {@link Condition} against a snapshot. */\nexport function evaluateCondition(cond: Condition, s: FunnelSnapshot): boolean {\n\tconst val = readField(s, cond.field)\n\tconst { op, value } = cond\n\tswitch (op) {\n\t\tcase 'eq':\n\t\t\treturn val === value\n\t\tcase 'neq':\n\t\t\treturn val !== value\n\t\tcase 'in':\n\t\t\treturn (\n\t\t\t\tArray.isArray(value) &&\n\t\t\t\t(value as VariableValue[]).includes(val as VariableValue)\n\t\t\t)\n\t\tcase 'gt':\n\t\t\treturn (\n\t\t\t\ttypeof val === 'number' &&\n\t\t\t\ttypeof value === 'number' &&\n\t\t\t\tval > value\n\t\t\t)\n\t\tcase 'gte':\n\t\t\treturn (\n\t\t\t\ttypeof val === 'number' &&\n\t\t\t\ttypeof value === 'number' &&\n\t\t\t\tval >= value\n\t\t\t)\n\t\tcase 'lt':\n\t\t\treturn (\n\t\t\t\ttypeof val === 'number' &&\n\t\t\t\ttypeof value === 'number' &&\n\t\t\t\tval < value\n\t\t\t)\n\t\tcase 'lte':\n\t\t\treturn (\n\t\t\t\ttypeof val === 'number' &&\n\t\t\t\ttypeof value === 'number' &&\n\t\t\t\tval <= value\n\t\t\t)\n\t\tcase 'contains':\n\t\t\tif (typeof val === 'string') return val.includes(String(value))\n\t\t\tif (Array.isArray(val))\n\t\t\t\treturn (val as VariableValue[]).includes(value as VariableValue)\n\t\t\treturn false\n\t\tcase 'exists':\n\t\t\treturn val !== undefined && val !== null && val !== ''\n\t\tcase 'empty':\n\t\t\treturn (\n\t\t\t\tval === undefined ||\n\t\t\t\tval === null ||\n\t\t\t\tval === '' ||\n\t\t\t\t(Array.isArray(val) && val.length === 0)\n\t\t\t)\n\t\tdefault:\n\t\t\treturn false\n\t}\n}\n\n/** Evaluate either gate kind to a boolean. */\nexport function evaluateGate(gate: Gate, s: FunnelSnapshot): boolean {\n\treturn typeof gate === 'function' ? gate(s) : evaluateCondition(gate, s)\n}\n\n/**\n * Resolve an ordered list of routes to a target page key, or `undefined` to fall\n * through to the linear next. First route whose gate passes (or has no `when`)\n * wins.\n */\nexport function resolveRoute(\n\troutes: Route[] | undefined,\n\ts: FunnelSnapshot\n): string | undefined {\n\tif (!routes) return undefined\n\tfor (const route of routes) {\n\t\tif (!route.when || evaluateGate(route.when, s)) return route.to\n\t}\n\treturn undefined\n}\n\n// ── Pages ────────────────────────────────────────────────\n\nexport type PageType =\n\t| 'default' // plain content/step page (the baseline)\n\t| 'email-capture' // collects user.email — the mandatory identity step (validated)\n\t| 'paywall' // the offer/pricing page → drives paywall-view + paywall-CR\n\t| 'upsell' // post-purchase one-click → drives Upsell Rate + off-session charge\n\t| 'finish' // terminal success/thank-you page → completion analytics, ends the flow\n\nexport interface PageMeta {\n\t/** Page kind — drives behavior + analytics (e.g. `paywall`, `upsell`). */\n\ttype?: PageType\n\t/** URL slug; defaults to the page key. */\n\tslug?: string\n\t/**\n\t * Ordered routing edges out of this page (first match wins). Each has a static\n\t * `to` key + an optional `when` gate. Omit for the default linear flow.\n\t *\n\t * OPTIONAL per-variant routing: a `@variant` page (`paywall@b`) MAY carry its own\n\t * `next`. When that variant is the one served for its slot, its `next` governs\n\t * routing for that visitor; absent, the variant inherits the slot's routing (the\n\t * default — a pure superset, no behavior change for existing funnels). Assignment,\n\t * exposure, and progress still anchor on the slot; only the next-page lookup\n\t * consults the served variant's routes. See {@link FunnelPage}.\n\t */\n\tnext?: Route[]\n\t/**\n\t * Entry precondition for **deep-link / reload** restoration. When the runtime is\n\t * asked to start *on this page* (not via in-funnel navigation), it restores there\n\t * only if `guard` passes against the restored snapshot — otherwise it falls back\n\t * to the start page. e.g. an upsell page: `guard: s => s.data.purchased === true`.\n\t * Reaching the page via `next()` is unaffected (routing already gated it). Omit =\n\t * always restorable. Same gate kind as routing (`Condition` or predicate).\n\t */\n\tguard?: Gate\n\t/**\n\t * BUILD-TIME PRERENDER OPT-OUT (SSR-isolation Option B, FIX 2). Set `dynamic: true` (alias\n\t * `prerender: false`) on a page whose **structure** (which sections exist — not just their text\n\t * values) depends on the visitor's `sessionValues`. Such a page can't be prerendered flash-free:\n\t * the default-state markup would structurally differ from the value-applied render and reflow\n\t * after hydration. Opting out makes the build SKIP prerendering it, so the renderer serves it via\n\t * live SSR (the same fallback branch a build with no prerender entry already uses) — correct\n\t * first paint, no pop-in. Value-only variation (text/price into a fixed structure) does NOT need\n\t * this: deferred defaults make it flash-free. Omit = prerendered (the default).\n\t */\n\tdynamic?: boolean\n\t/** @see {@link PageMeta.dynamic} — `prerender: false` is the inverse alias (author preference). */\n\tprerender?: boolean\n}\n\n/**\n * Identity helper for a page's co-located metadata.\n * `export const meta = pageMeta({ type: 'paywall', next: s => … })`.\n */\nexport function pageMeta(meta: PageMeta): PageMeta {\n\treturn meta\n}\n\n/**\n * Default entry guard implied by a page **type** — a built-in precondition every\n * funnel inherits. `paywall` and `upsell` require a captured `user.email` (the\n * mandatory identity step), so a deep-link / reload straight into them without\n * email bounces to the start. Authors don't write this; an explicit `meta.guard`\n * **overrides** it (see {@link entryGuard}).\n */\nconst TYPE_GUARDS: Partial<Record<PageType, Gate>> = {\n\tpaywall: { field: 'user.email', op: 'exists' },\n\tupsell: { field: 'user.email', op: 'exists' },\n}\n\n/**\n * The effective entry guard for a page: an explicit `meta.guard` if the author set\n * one, **otherwise** the page-type default (e.g. paywall/upsell need email). The\n * explicit guard fully **overrides** the default — it's not combined. Returns\n * `undefined` when neither applies.\n */\nexport function entryGuard(meta?: PageMeta): Gate | undefined {\n\treturn meta?.guard ?? (meta?.type ? TYPE_GUARDS[meta.type] : undefined)\n}\n\n/**\n * Identity helper for a page component. The page is plain React that reaches the\n * runtime through hooks (`useResponse`, `useNavigation`, …) — there is no `sdk`\n * prop. `export default definePage(function Welcome() { … })`.\n */\nexport function definePage<P extends object = Record<string, never>>(\n\tcomponent: ComponentType<P>\n): ComponentType<P> {\n\treturn component\n}\n\n// ── Flow resolution ──────────────────────────────────────\n\n/** A page in the flow: its key + (optional) co-located meta. */\nexport interface FlowPage {\n\tkey: string\n\tmeta?: PageMeta\n}\n\n/**\n * A page as declared in `funnel.ts` — the key + its metadata, flattened. This is the\n * AUTHORED shape (funnel.ts owns the page list, order, and routing); the build generates\n * the code-split `mount.tsx` from it. Routing (`next`) must stay DECLARATIVE (Route[] with\n * `{ to, when }` conditions, no predicate functions) so the web builder UI can edit it.\n *\n * OPTIONAL variant routing (default off): a served variant's OWN routing is authored by\n * declaring the variant here with its `@` key and a `next`, e.g.\n * `{ key: 'paywall@b', next: [{ to: 'special-offer' }] }`. A variant declared this way keys\n * on the `@` marker, so it still collapses out of the linear flow (it is NOT a linear step);\n * its `next` is consulted only when that variant is the one served for its slot. Omit the\n * declaration (leave the variant an undeclared `pages/<slot>@<v>.tsx` file) to inherit the\n * slot's routing — the existing behavior, unchanged. The slot's control keeps owning\n * assignment/exposure/progress; only the next-page lookup for a branched variant differs.\n */\nexport interface FunnelPage extends PageMeta {\n\tkey: string\n}\n\n/**\n * Decide the next page from `currentKey`:\n * 1. the current page's `next` routes ({@link resolveRoute}), if one matches, else\n * 2. the next page in file order (the default linear flow), else\n * 3. `undefined` (end of funnel / current key not found).\n */\nexport function nextPage(\n\tpages: FlowPage[],\n\tcurrentKey: string,\n\ts: FunnelSnapshot\n): string | undefined {\n\tconst idx = pages.findIndex((p) => p.key === currentKey)\n\tif (idx === -1) return undefined\n\tconst routed = resolveRoute(pages[idx].meta?.next, s)\n\tif (routed) return routed\n\treturn pages[idx + 1]?.key\n}\n\n/**\n * Every page a visitor *could* go to next from `currentKey` — all route targets\n * (regardless of gate, since we don't know which will pass) plus the linear next.\n * Used to **prefetch** the likely-next page chunks; not for navigation.\n */\nexport function outgoingKeys(pages: FlowPage[], currentKey: string): string[] {\n\tconst idx = pages.findIndex((p) => p.key === currentKey)\n\tif (idx === -1) return []\n\tconst out = new Set<string>()\n\tfor (const route of pages[idx].meta?.next ?? []) out.add(route.to)\n\tconst linear = pages[idx + 1]?.key\n\tif (linear) out.add(linear)\n\treturn [...out]\n}\n\n/**\n * The number of pages on the path from `startKey` to a `finish` (or the end of\n * the flow) **given the current state** — the denominator for progress. It walks\n * the actual routing ({@link nextPage}) rather than counting all files, so a\n * branched funnel reaches 100% on whichever path the visitor's answers select.\n * Re-traced per navigation; a visited set guards against routing cycles.\n */\nexport function expectedPathLength(\n\tpages: FlowPage[],\n\tstartKey: string,\n\ts: FunnelSnapshot\n): number {\n\tconst seen = new Set<string>()\n\tlet key: string | undefined = startKey\n\tlet count = 0\n\twhile (key && !seen.has(key)) {\n\t\tseen.add(key)\n\t\tcount++\n\t\tif (pages.find((p) => p.key === key)?.meta?.type === 'finish') break\n\t\tkey = nextPage(pages, key, s)\n\t}\n\treturn count\n}\n\n// ── Funnel definition ────────────────────────────────────\n\nexport interface FunnelLocales {\n\tdefault: string\n\tsupported: string[]\n\tfallback?: string\n\t/**\n\t * When `true`, a visitor with no explicit language in the URL (no `/<locale>/` path prefix and no\n\t * `?language=`) is served the best match for their **browser** `Accept-Language` among `supported`\n\t * (base-matched, so `en-GB` → `en`); no match falls back to `default`. When `false`/absent (the\n\t * default), an unspecified visitor always gets `default` — the URL is the only way to switch.\n\t */\n\tautoDetectLanguage?: boolean\n}\n\n/**\n * The funnel-level spine. Flow is mostly inferred from page file order + each\n * page's `next`; this holds the funnel-wide config. Stays **thin** — routing\n * lives co-located on pages (doc 06: \"funnel.ts stays thin\").\n */\nexport interface FunnelDefinition {\n\tid: string\n\t/**\n\t * The funnel's pages — order, type, and declarative routing — the source of truth the\n\t * web builder edits and the build generates `mount.tsx` from. Each `key` maps to a\n\t * `pages/<key>.tsx` component. Omit `pages` on hand-written funnels that still ship their\n\t * own `mount.tsx` (back-compat); new/generated funnels declare them here.\n\t */\n\tpages?: FunnelPage[]\n\t/** Which checkout provider the paywall/checkout uses. The build wires the driver. */\n\tcheckout?: 'stripe' | 'paddle'\n\t/** `responses.*` runtime variables (default values). */\n\tresponses?: Record<string, VariableConfig>\n\t/** `data.*` working/scratch variables (default values). */\n\tdata?: Record<string, VariableConfig>\n\t/**\n\t * The catalog offerings this funnel sells, as SLOTS: a local, stable key each PAGE\n\t * references (`useOffering('primary')`, `<Checkout offering=\"primary\">`) → the catalog charge\n\t * KEY it's assigned to. Swap the assignment to change the offer WITHOUT touching page code;\n\t * `null` = a declared-but-unassigned slot. A bare `string[]` is legacy sugar for IDENTITY\n\t * slots (`['pro'] ≡ { pro: 'pro' }`) — every existing funnel keeps working. Prices resolve\n\t * from the project catalog per environment (Live/Test) at render.\n\t */\n\tofferings?: string[] | Record<string, string | null>\n\tlocales?: FunnelLocales\n\t/**\n\t * When `true`, the funnel shows the **geo-specific** currency/price the payment\n\t * provider resolves (Stripe `currency_options`, Paddle preview, Whop, SolidGate,\n\t * …). When `false` (default), a single fixed currency is used. Appfunnel does no\n\t * FX — this only toggles whether the platform asks the provider for the geo\n\t * price; the SDK just displays whatever resolved `{amount, currency}` it's handed.\n\t * (See docs/platform-v2 phase-3 §3.6.)\n\t */\n\tlocationAwareCurrency?: boolean\n}\n\n/** Identity helper for a funnel definition. */\nexport function defineFunnel(def: FunnelDefinition): FunnelDefinition {\n\treturn def\n}\n\n/** A funnel offering SLOT: the local key pages reference → the assigned catalog charge key (null = unassigned). */\nexport interface OfferingSlot {\n\tslot: string\n\tcatalogKey: string | null\n}\n\n/**\n * Normalize `FunnelDefinition.offerings` to a slot list. A legacy `string[]` becomes IDENTITY\n * slots (`['pro'] → [{ slot:'pro', catalogKey:'pro' }]`); a `{ slot: key|null }` map becomes its\n * entries (insertion order preserved, so `useOfferings()` is deterministic).\n */\nexport function normalizeOfferings(\n\tofferings: FunnelDefinition['offerings']\n): OfferingSlot[] {\n\tif (!offerings) return []\n\tif (Array.isArray(offerings))\n\t\treturn offerings.map((k) => ({ slot: k, catalogKey: k }))\n\treturn Object.entries(offerings).map(([slot, catalogKey]) => ({\n\t\tslot,\n\t\tcatalogKey: catalogKey ?? null,\n\t}))\n}\n\n/** The unique, ASSIGNED catalog keys a funnel charges — for the promote gate + catalog reverse-lookup. */\nexport function funnelCatalogKeys(\n\tofferings: FunnelDefinition['offerings']\n): string[] {\n\treturn [\n\t\t...new Set(\n\t\t\tnormalizeOfferings(offerings)\n\t\t\t\t.map((s) => s.catalogKey)\n\t\t\t\t.filter((k): k is string => !!k)\n\t\t),\n\t]\n}\n","/**\n * **Runtime page-level experiments** — A/B/n on a *single page inside one funnel*,\n * resolved at render time (phase-4). No funnel duplication: a slot (e.g. the page\n * `welcome`) has alternate versions filed as siblings (`welcome@b.tsx`), and the\n * runtime shows **one** of them per visitor, collapsing the losers out of the\n * linear flow. The flow keeps stable **slot keys** (the control's key); only the\n * rendered component swaps — so routing, the manifest, and analytics all key on the\n * slot, not the variant.\n *\n * **Where the wiring lives:** the *variant pages* are code (compiled into the\n * bundle). The *experiment wiring* — slot, variant→page map, weights, status — is\n * **operational data the platform owns** (a DB record, edited by the dashboard,\n * changed without recompiling the funnel). The SDK is storage-agnostic: the\n * platform hands the runtime experiment records to `FunnelProvider`, the same way\n * it hands in resolved product prices. This module just resolves them.\n *\n * **The only source-side marker** is the `@` in a variant file's key\n * (`welcome@b`): it tells the *build* (manifest, flow graph) that a page is an\n * off-flow variant of its slot, so the structure is correct without the DB. The\n * label/weight/experiment-id are not in source.\n *\n * Bucketing is a deterministic FNV-1a hash, **namespaced by experiment id** so\n * independent experiments bucket orthogonally (the basis for layering 100+ tests,\n * §4.3). The seed is the durable identity ({@link bucketingSeed}) — never the\n * session/fingerprint — so a returning visitor keeps their variant (landmine #4).\n * Stability across an *add-a-variant* edit is the platform's job: an experiment's\n * variant set is immutable while running (reweighting / adding an arm = a new\n * experiment version), so within one record the assignment never moves.\n *\n * This module is pure (no React, no I/O) → it unit-tests trivially and the\n * dashboard/server can reuse the same assignment math.\n */\n\nimport type { FunnelContext } from '../state/context'\n\n// ── Hashing ──────────────────────────────────────────────\n\n/**\n * FNV-1a 32-bit hash → unsigned int. Deterministic and isomorphic (no `crypto`,\n * runs the same in the browser, a worker, and a build). The same math v0 used,\n * kept because it's sound — only the *seed* changes (identity, not session).\n */\nexport function fnv1a(input: string): number {\n let h = 0x811c9dc5\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i)\n // h *= 16777619, in uint32, via shift-adds.\n h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0\n }\n return h >>> 0\n}\n\n/** Map a seed string to a stable float in `[0, 1)`. */\nexport function hashToUnit(seed: string): number {\n return fnv1a(seed) / 0x1_0000_0000\n}\n\n/**\n * Pick a variant key by weight from a stable unit position `u ∈ [0,1)`. Variants\n * are walked in declaration order and the first whose cumulative weight band\n * contains `u` wins, so the same `u` always lands in the same variant.\n */\nexport function pickByWeight(weights: Record<string, number>, u: number): string {\n const entries = Object.entries(weights).filter(([, w]) => w > 0)\n if (entries.length === 0) return Object.keys(weights)[0] ?? ''\n const total = entries.reduce((sum, [, w]) => sum + w, 0)\n const target = u * total\n let acc = 0\n for (const [key, w] of entries) {\n acc += w\n if (target < acc) return key\n }\n return entries[entries.length - 1][0]\n}\n\n/**\n * Deterministically assign a visitor (`seed`) to a variant of one experiment.\n * The hash is **namespaced by `experimentId`** so two experiments on the same\n * traffic don't correlate (orthogonal layering).\n */\nexport function assignVariant(\n experimentId: string,\n seed: string,\n weights: Record<string, number>,\n): string {\n return pickByWeight(weights, hashToUnit(`${experimentId}:${seed}`))\n}\n\n// ── Seed + slot parsing ──────────────────────────────────\n\n/**\n * The stable bucketing seed: the signed `visitorId`, else the known `customerId`.\n * Never the session id or fingerprint (landmine #4). `null` when neither is known\n * — the caller then serves control instead of bucketing on nothing.\n *\n * visitorId-FIRST (not customerId-first) is deliberate: the customerId injected for an\n * anonymous visitor is minted server-side AFTER the first tracked event, so it is absent on\n * visit 1 and present on visit 2 — seeding on it would flip a returning visitor's arm and\n * count them in two arms of the same version. The signed `af_vid` cookie is the durable\n * identity that's stable from the first pageload, so it seeds; customerId is only the fallback\n * for cookieless SDK embeds. This matches the server-side FUNNEL split, which already seeds on\n * the verified visitorId (resolve.ts). (Cross-device stable bucketing for IDENTIFIED customers\n * is P3's IdentitySDK job, not this anonymous path.)\n */\nexport function bucketingSeed(context: FunnelContext): string | null {\n return context.identity.visitorId ?? context.identity.customerId ?? null\n}\n\n/** Split a page key into its slot + optional variant: `welcome@b` → `{ slot, variant: 'b' }`. */\nexport function parseSlotKey(key: string): { slot: string; variant?: string } {\n const at = key.indexOf('@')\n return at === -1 ? { slot: key } : { slot: key.slice(0, at), variant: key.slice(at + 1) }\n}\n\n/** True if a page key is an off-flow variant (`welcome@b`), by the source-side `@` marker. */\nexport function isVariantKey(key: string): boolean {\n return parseSlotKey(key).variant !== undefined\n}\n\n// ── Runtime experiment records (platform/DB-sourced) ─────\n\n/** One arm of a running experiment: which page renders, at what weight. */\nexport interface ExperimentArm {\n /** The page key this arm renders (the slot's control, or a `@variant` sibling). */\n page: string\n /** Relative weight in the split (need not sum to 100; zero = paused arm). */\n weight: number\n}\n\n/**\n * A runtime experiment record — the operational wiring the **platform** owns and\n * hands to the SDK (not authored in the funnel source). Projected from the unified\n * `Experiment`/`ExperimentArm` graph (a RUNNING PAGE experiment + its arms): the\n * experiment's `slot` names the base page, and each arm becomes a `variants` entry\n * `{ page: arm.pageKey, weight: arm.weight }` keyed by `arm.label`. The variant\n * *pages* are code in the LIVE build; this is the live split over them.\n *\n * The serve join only ever hands over RUNNING experiments, and the server's\n * draft-write + serve guards make every active arm's page GUARANTEED present in the\n * LIVE build (an experiment owns its arm pages' lifecycle — you end the experiment to\n * remove a page, you can't drift it away). So there is no lifecycle/winner state and\n * no \"arm page missing\" case to resolve here.\n */\nexport interface RuntimeExperiment {\n id: string\n /** The page key holding the flow position (the anchor / the control arm's base page). */\n slot: string\n /** label → arm. The control arm's `page` is the `slot`; others are `@variant` siblings. */\n variants: Record<string, ExperimentArm>\n /** Primary metric (analytics only; not used for resolution). */\n metric?: string\n /** Platform record version (immutable-while-running; reweight = new version). Rides on\n * exposure events so results key on (experimentId, version, variant). */\n version?: number\n}\n\n// ── Flow resolution ──────────────────────────────────────\n\nexport interface ExperimentResolution {\n /** experiment id → assigned variant label. */\n assignments: Record<string, string>\n /** Page keys forming the effective linear flow (variant siblings removed), in order. */\n activeKeys: string[]\n /** Slot key → the page key whose component should render there. */\n render: Record<string, string>\n /** Variant page key → its slot key. For remapping a route that targets a variant. */\n slotOf: Record<string, string>\n /** Slot key → the experiment id it hosts (drives the exposure event). */\n experimentOf: Record<string, string>\n /** Experiment id → platform record version (rides on exposure events). */\n versionOf: Record<string, number>\n}\n\n/**\n * Weights map (label → weight) for one experiment's arms. Exported (via the pure\n * manifest entry) so the server-side FUNNEL split (renderer resolve) projects arms\n * the same way before calling {@link assignVariant}, instead of re-inlining it.\n */\nexport function weightsOf(variants: Record<string, { weight: number }>): Record<string, number> {\n const out: Record<string, number> = {}\n for (const [label, v] of Object.entries(variants)) out[label] = v.weight\n return out\n}\n\n/**\n * Resolve which page version each experiment slot shows for this visitor, and which\n * page keys remain in the linear flow.\n *\n * Variant pages are detected structurally by the `@` in their key, so they collapse\n * out of the linear flow even for a slot with no active experiment. Each served\n * experiment is RUNNING with all its arm pages guaranteed present in the LIVE build\n * (the server draft-write + serve guards enforce the experiment-owned lifecycle\n * invariant), so the visitor is bucketed deterministically on `seed` and the assigned\n * arm's page is swapped in with no presence check. With no `seed` there is nothing\n * stable to bucket on, so every slot renders its own control page.\n */\nexport function resolveExperiments(\n pages: { key: string }[],\n experiments: RuntimeExperiment[],\n seed: string | null,\n): ExperimentResolution {\n const assignments: Record<string, string> = {}\n const render: Record<string, string> = {}\n const experimentOf: Record<string, string> = {}\n const versionOf: Record<string, number> = {}\n\n if (seed) {\n for (const exp of experiments) {\n const label = assignVariant(exp.id, seed, weightsOf(exp.variants))\n const arm = exp.variants[label]\n if (!arm) continue\n assignments[exp.id] = label\n experimentOf[exp.slot] = exp.id\n if (exp.version !== undefined) versionOf[exp.id] = exp.version\n // Swap in the arm's page when a non-control arm won; the control arm renders the slot itself.\n if (arm.page !== exp.slot) render[exp.slot] = arm.page\n }\n }\n\n // Variant siblings (`@`) never stand alone in the linear flow (structural, by the\n // `@` filename marker — independent of any experiment record).\n const slotOf: Record<string, string> = {}\n const activeKeys: string[] = []\n for (const p of pages) {\n const { slot, variant } = parseSlotKey(p.key)\n if (variant !== undefined) slotOf[p.key] = slot\n else activeKeys.push(p.key)\n }\n\n return { assignments, activeKeys, render, slotOf, experimentOf, versionOf }\n}\n","/**\n * The **manifest** — the declarative IR a funnel project compiles to (doc 06).\n * It's the machine-readable artifact the platform operates on without executing\n * the funnel: the dashboard draws the flow graph from it, analytics binds to its\n * **stable ids**, validation runs against it, and the renderer reads it to resolve\n * routing.\n *\n * `compileManifest` evaluates the spine (the funnel config + each page's co-located\n * `meta`) into that IR. It's pure — no I/O — so it unit-tests trivially. **It runs\n * server-side**, as the IR step of the publish build over the canonical files in our\n * storage (R2). The client/CLI never produces the authoritative manifest — R2 is the\n * source of truth, the server compiles. (A local dev preview may run it for itself,\n * but that output is never published.)\n *\n * Edge model mirrors the runtime ({@link ../flow/spine}.`nextPage`): a page's\n * `meta.next` routes become **branch** edges (with a serialized condition — a\n * declarative {@link Condition}, or an opaque marker for a code predicate), and the\n * implicit file-order fall-through becomes a **linear** edge (unless an\n * unconditional route already covers it, or the page is a `finish`).\n *\n * Experiments are **not** compiled here. A variant page is recognised structurally\n * by the `@` in its key (`welcome@b`) and tagged `variantOf` + collapsed out of the\n * linear flow; the experiment *wiring* (labels/weights/status) is operational data\n * the platform owns and overlays at render time, not part of the funnel build.\n *\n * Stable ids: the page **key** is the source anchor, so `id === key` here. The\n * durable analytics id is the semantic page name (a slot survives a winner being\n * promoted into it); transient `@variant` pages only ever key analytics by\n * `(experimentId, variant)` in immutable results — a platform concern.\n */\n\nimport type {\n Condition,\n FunnelDefinition,\n FunnelLocales,\n Gate,\n PageMeta,\n PageType,\n} from '../flow/spine'\nimport { normalizeOfferings, funnelCatalogKeys, entryGuard, type OfferingSlot } from '../flow/spine'\nimport { isVariantKey, parseSlotKey } from '../flow/experiments'\n\nexport interface ManifestPage {\n id: string\n key: string\n type: PageType\n slug: string\n index: number\n /**\n * Set on a variant page (`welcome@b`) to its **slot** (`welcome`) — a structural\n * marker that this node is an off-flow alternate, not a linear step. The\n * experiment *wiring* (label/weight/id) is operational data the platform owns,\n * not the manifest.\n */\n variantOf?: string\n /**\n * The page's effective ENTRY guard, serialized (SSR-isolation Option B, FIX 1): a `declarative`\n * {@link Condition} the renderer can evaluate SERVER-SIDE against the visitor's session snapshot\n * to pick the right prerendered variant (target vs bounce) without running tenant code, or an\n * opaque `predicate` marker (author code — the renderer must fall back to live SSR for that\n * deep-link). Absent = no entry guard (always restorable). Mirrors {@link entryGuard}.\n */\n entryGuard?: EdgeCondition\n /**\n * BUILD-TIME PRERENDER OPT-OUT (SSR-isolation Option B, FIX 2). True when the page's `meta.dynamic`\n * (or `prerender: false`) opts it out of prerendering because its STRUCTURE depends on\n * sessionValues. The prerender stage skips it; the renderer serves it via live SSR.\n */\n dynamic?: boolean\n}\n\nexport type EdgeCondition =\n | { kind: 'declarative'; condition: Condition }\n /** A code predicate — opaque body; `label` may be supplied later by AST parsing. */\n | { kind: 'predicate'; label?: string }\n\nexport interface ManifestEdge {\n from: string\n to: string\n kind: 'branch' | 'linear'\n /** Absent = unconditional (a fallback route, or the linear fall-through). */\n condition?: EdgeCondition\n /**\n * True on a **variant-only branch**: an edge whose `from` is a `@variant` key,\n * emitted when that served variant carries its OWN `meta.next` (optional divergent\n * routing). Lets consumers (the editor's Flow canvas) tell a variant's private branch\n * apart from a normal slot edge. Optional/absent on every non-variant edge.\n */\n variant?: true\n}\n\nexport interface ManifestValidation {\n /**\n * `ok` = none of the hard errors: the original set (dead ends, unreachable\n * pages, bad targets, missing email capture) AND the structural errors added\n * later (duplicate keys, orphan variants, no reachable finish). Slug\n * collisions are a **warning** — reported but not folded into `ok` (slugs are\n * display/URL sugar; keys are the routing identity).\n */\n ok: boolean\n /** Page ids you can't proceed from (and that aren't a `finish`). */\n deadEnds: string[]\n /** Page ids not reachable from the start. */\n unreachable: string[]\n /** Routes whose target page key doesn't exist. */\n badTargets: { from: string; to: string }[]\n /** True if the funnel never writes `user.email` (the mandatory identity step). */\n missingEmailCapture: boolean\n /** Page keys that appear more than once (keys are the stable ids — hard error). */\n duplicateKeys: string[]\n /** Flow pages sharing a slug (URL ambiguity — warning, not folded into `ok`). */\n slugCollisions: { slug: string; pages: string[] }[]\n /** Variant pages (`x@b`) whose slot (`x`) doesn't exist as a flow page (hard error). */\n orphanVariants: string[]\n /**\n * True when no `finish` page is reachable from the start — e.g. the flow loops\n * (a cycle with no exit) or every path stalls before a terminal page. Dead ends\n * catch pages with no outgoing edge; this catches funnels that *never end* even\n * though every page can proceed. Hard error.\n */\n noReachableFinish: boolean\n /** Slot names a PAGE references (`useOffering`/`<Checkout offering>`) that the funnel doesn't declare — hard error. */\n unknownOfferingRefs: string[]\n /** Declared slots a page references but which have no catalog charge key assigned (map value `null`) — hard error. */\n unassignedSlots: string[]\n}\n\nexport interface FunnelManifest {\n id: string\n pages: ManifestPage[]\n flow: { start: string | null; nodes: string[]; edges: ManifestEdge[] }\n /** The unique, ASSIGNED catalog keys the funnel charges (for the promote gate + catalog reverse-lookup). */\n offerings: string[]\n /** Offering SLOTS: slot → assigned catalog key|null. `offerings` above is the unique assigned keys. */\n offeringSlots: OfferingSlot[]\n /** Slot names PAGES reference (from the build's scan); validated against `offeringSlots`. Absent = no scan ran. */\n offeringRefs?: string[]\n locales?: FunnelLocales\n validation: ManifestValidation\n}\n\nexport interface CompileInput {\n funnel: FunnelDefinition\n /** Pages in file order (the default flow); `meta` holds type/slug/next. */\n pages: { key: string; meta?: PageMeta }[]\n /** Slot names the funnel's PAGES reference (from `scanOfferingRefs`) — cross-checked against the declared slots. */\n offeringRefs?: string[]\n}\n\n/**\n * A **variant** node — a page filed with an `@variant` key (e.g. `welcome@b`).\n * It's an alternate of its slot, not a step in the linear spine, so it gets no\n * linear edge and is excluded from dead-end/reachability checks (the runtime\n * resolves it by bucketing, not by an edge). The `@` is the only source-side\n * signal; the experiment wiring is the platform's operational data. The slot's\n * control (no `@`) stays the flow node. Mirrors {@link resolveExperiments}.\n */\nfunction isVariantNode(page: { key: string }): boolean {\n return isVariantKey(page.key)\n}\n\n/** Serialize a route gate for the manifest (declarative → data; predicate → opaque). */\nfunction serializeGate(when: Gate | undefined): EdgeCondition | undefined {\n if (!when) return undefined\n if (typeof when === 'function') return { kind: 'predicate' }\n return { kind: 'declarative', condition: when }\n}\n\n/** Compile a funnel's spine into its declarative {@link FunnelManifest} IR. */\nexport function compileManifest(input: CompileInput): FunnelManifest {\n const { funnel, pages } = input\n const keys = new Set(pages.map((p) => p.key))\n\n const manifestPages: ManifestPage[] = pages.map((p, index) => ({\n id: p.key,\n key: p.key,\n type: p.meta?.type ?? 'default',\n slug: p.meta?.slug ?? p.key,\n index,\n variantOf: isVariantKey(p.key) ? parseSlotKey(p.key).slot : undefined,\n // The effective entry guard (explicit meta.guard, else the page-type default), serialized so\n // the renderer can evaluate a DECLARATIVE guard server-side (Option B, FIX 1). Predicate guards\n // serialize to an opaque marker → the renderer falls back to live SSR for that deep-link.\n entryGuard: serializeGate(entryGuard(p.meta)),\n // Prerender opt-out: `dynamic: true` OR `prerender: false` (a page whose STRUCTURE depends on\n // sessionValues — Option B, FIX 2). Undefined stays undefined (prerendered, the default).\n dynamic: p.meta?.dynamic === true || p.meta?.prerender === false ? true : undefined,\n }))\n\n const edges: ManifestEdge[] = []\n const badTargets: { from: string; to: string }[] = []\n\n // The next page in file order that is a real flow node (skip `@variant` siblings).\n const nextAnchor = (from: number) => {\n for (let j = from + 1; j < pages.length; j++) {\n if (!isVariantNode(pages[j])) return pages[j]\n }\n return undefined\n }\n\n pages.forEach((p, i) => {\n // Variant nodes are alternates of their slot, resolved at runtime by bucketing.\n // They carry NO linear fall-through (they aren't linear steps) — but a served\n // variant MAY declare its OWN `meta.next` routes (optional divergent routing).\n // When present, each route becomes a `branch` edge tagged `variant: true` so the\n // Flow canvas can draw B's private branch; a variant with no `next` emits nothing\n // (unchanged behaviour). Targets are validated exactly like a normal route.\n if (isVariantNode(p)) {\n for (const route of p.meta?.next ?? []) {\n if (!keys.has(route.to)) {\n badTargets.push({ from: p.key, to: route.to })\n continue\n }\n edges.push({ from: p.key, to: route.to, kind: 'branch', variant: true, condition: serializeGate(route.when) })\n }\n return\n }\n\n const routes = p.meta?.next ?? []\n let hasUnconditional = false\n for (const route of routes) {\n if (!keys.has(route.to)) {\n badTargets.push({ from: p.key, to: route.to })\n continue\n }\n edges.push({ from: p.key, to: route.to, kind: 'branch', condition: serializeGate(route.when) })\n if (!route.when) hasUnconditional = true\n }\n // Linear fall-through, unless an unconditional route already covers it,\n // this is a `finish` page, or there is no next page.\n const next = nextAnchor(i)\n if (!hasUnconditional && next && p.meta?.type !== 'finish') {\n edges.push({ from: p.key, to: next.key, kind: 'linear' })\n }\n })\n\n // The start is the first real flow node (a leading variant can't be the entry).\n const startPage = pages.find((p) => !isVariantNode(p))\n const start = startPage?.key ?? null\n const variantKeys = new Set(pages.filter(isVariantNode).map((p) => p.key))\n const offeringSlots = normalizeOfferings(funnel.offerings)\n const validation = validate(manifestPages, edges, badTargets, start, variantKeys, offeringSlots, input.offeringRefs)\n\n return {\n id: funnel.id,\n pages: manifestPages,\n flow: { start, nodes: manifestPages.map((p) => p.id), edges },\n offerings: funnelCatalogKeys(funnel.offerings),\n offeringSlots,\n offeringRefs: input.offeringRefs,\n locales: funnel.locales,\n validation,\n }\n}\n\nfunction validate(\n pages: ManifestPage[],\n edges: ManifestEdge[],\n badTargets: { from: string; to: string }[],\n start: string | null,\n variantKeys: Set<string>,\n slots: OfferingSlot[],\n offeringRefs: string[] | undefined,\n): ManifestValidation {\n const outgoing = new Map<string, number>()\n for (const e of edges) outgoing.set(e.from, (outgoing.get(e.from) ?? 0) + 1)\n\n // Variant nodes are resolved by bucketing, not edges — they're neither dead\n // ends nor unreachable in the flow-graph sense, so exclude them from both.\n const deadEnds = pages\n .filter((p) => p.type !== 'finish' && !variantKeys.has(p.id) && !(outgoing.get(p.id)! > 0))\n .map((p) => p.id)\n\n // Reachability from the start over the edge set.\n const reachable = new Set<string>()\n if (start) {\n const adj = new Map<string, string[]>()\n for (const e of edges) {\n const list = adj.get(e.from)\n if (list) list.push(e.to)\n else adj.set(e.from, [e.to])\n }\n // A variant is reached by BUCKETING from its slot, not by a flow edge — so for\n // reachability, treat a reachable slot as reaching its variants. Without this, a\n // page that ONLY a variant's own branch routes to (its slot has no such route)\n // would be wrongly flagged unreachable; with it, the variant's branch targets\n // ride the slot's reachability. (Variant keys stay excluded from `unreachable`.)\n for (const p of pages) {\n if (p.variantOf === undefined) continue\n const list = adj.get(p.variantOf)\n if (list) list.push(p.id)\n else adj.set(p.variantOf, [p.id])\n }\n const stack = [start]\n while (stack.length) {\n const id = stack.pop()!\n if (reachable.has(id)) continue\n reachable.add(id)\n for (const to of adj.get(id) ?? []) stack.push(to)\n }\n }\n const unreachable = pages\n .filter((p) => !variantKeys.has(p.id) && !reachable.has(p.id))\n .map((p) => p.id)\n\n // The funnel must capture user.email somewhere (doc 06). We can see the typed\n // `email-capture` page; deeper detection (any user.email write) is a build-time\n // AST concern. Treat presence of an `email-capture` page as satisfying it.\n const missingEmailCapture = !pages.some((p) => p.type === 'email-capture')\n\n // Duplicate page keys — keys are the stable analytics/routing ids, so two\n // pages sharing one is a hard error (edges/experiments become ambiguous).\n const seen = new Set<string>()\n const duplicateKeys: string[] = []\n for (const p of pages) {\n if (seen.has(p.key) && !duplicateKeys.includes(p.key)) duplicateKeys.push(p.key)\n seen.add(p.key)\n }\n\n // Slug collisions among FLOW pages (variants never route by their own slug —\n // they render under their slot's URL). Warning: keys stay unambiguous.\n const bySlug = new Map<string, string[]>()\n for (const p of pages) {\n if (variantKeys.has(p.id)) continue\n const list = bySlug.get(p.slug)\n if (list) list.push(p.id)\n else bySlug.set(p.slug, [p.id])\n }\n const slugCollisions = [...bySlug.entries()]\n .filter(([, ids]) => ids.length > 1)\n .map(([slug, ids]) => ({ slug, pages: ids }))\n\n // Orphan variants — a `x@b` page whose slot `x` doesn't exist as a flow page.\n // The runtime could never bucket into it (no anchor in the flow) → hard error.\n const flowKeys = new Set(pages.filter((p) => !variantKeys.has(p.id)).map((p) => p.key))\n const orphanVariants = pages\n .filter((p) => p.variantOf !== undefined && !flowKeys.has(p.variantOf))\n .map((p) => p.id)\n\n // A funnel must be able to END: at least one `finish` page reachable from the\n // start. Catches cycles with no exit (every page proceeds — so no dead end —\n // but no path ever terminates).\n const noReachableFinish =\n start !== null && !pages.some((p) => p.type === 'finish' && reachable.has(p.id))\n\n // Offering-ref validation: a page referencing a slot the funnel doesn't declare (unknown) or one\n // with no assigned catalog charge key (unassigned) can never resolve → hard error. Only runs when the\n // build passed a page scan (`offeringRefs`); absent scan = skip (back-compat, no false positives).\n const declaredSlots = new Set(slots.map((s) => s.slot))\n const assignedSlots = new Set(slots.filter((s) => s.catalogKey).map((s) => s.slot))\n const refs = offeringRefs ?? []\n const unknownOfferingRefs = [...new Set(refs.filter((r) => !declaredSlots.has(r)))]\n const unassignedSlots = [...new Set(refs.filter((r) => declaredSlots.has(r) && !assignedSlots.has(r)))]\n\n return {\n // Original hard errors AND the structural ones; slug collisions stay a warning.\n ok:\n deadEnds.length === 0 &&\n unreachable.length === 0 &&\n badTargets.length === 0 &&\n !missingEmailCapture &&\n duplicateKeys.length === 0 &&\n orphanVariants.length === 0 &&\n !noReachableFinish &&\n unknownOfferingRefs.length === 0 &&\n unassignedSlots.length === 0,\n deadEnds,\n unreachable,\n badTargets,\n missingEmailCapture,\n duplicateKeys,\n slugCollisions,\n orphanVariants,\n noReachableFinish,\n unknownOfferingRefs,\n unassignedSlots,\n }\n}\n"]}
|