@odla-ai/chapter 0.47.10 → 0.48.1
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/README.md +231 -19
- package/dist/{chunk-VWDEHUNI.js → chunk-KZ2AXEZW.js} +497 -204
- package/dist/chunk-KZ2AXEZW.js.map +1 -0
- package/dist/{chunk-7MEVZEL2.js → chunk-MQ4OPZCS.js} +969 -516
- package/dist/chunk-MQ4OPZCS.js.map +1 -0
- package/dist/{copy-context-Dorxp-WK.d.ts → copy-context-BveBZglM.d.ts} +18 -7
- package/dist/index.cjs +3842 -773
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +775 -90
- package/dist/index.d.ts +775 -90
- package/dist/index.js +3835 -766
- package/dist/index.js.map +1 -1
- package/dist/testing.cjs +144 -42
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +92 -2
- package/dist/testing.d.ts +92 -2
- package/dist/testing.js +144 -42
- package/dist/testing.js.map +1 -1
- package/dist/ui/admin/index.d.ts +75 -5
- package/dist/ui/admin/index.js +3 -1
- package/dist/ui/index.d.ts +2 -2
- package/dist/ui/index.js +4 -2
- package/dist/ui/member/index.d.ts +9 -2
- package/dist/ui/member/index.js +1 -1
- package/dist/worker/index.cjs +10549 -5504
- package/dist/worker/index.cjs.map +1 -1
- package/dist/worker/index.d.cts +509 -9
- package/dist/worker/index.d.ts +509 -9
- package/dist/worker/index.js +8607 -3563
- package/dist/worker/index.js.map +1 -1
- package/package.json +5 -5
- package/runbooks/adopt-existing.md +44 -8
- package/dist/chunk-7MEVZEL2.js.map +0 -1
- package/dist/chunk-VWDEHUNI.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/member.ts","../src/application-id.ts","../src/email-identity.ts","../src/schema-applications.ts","../src/schema-admission.ts","../src/schema-gifts.ts","../src/schema-stripe.ts","../src/schema-network-person.ts","../src/schema-network-commercial.ts","../src/schema.ts","../src/defaults.ts","../src/group.ts","../src/auth.ts","../src/pipeline.ts","../src/copy-defaults-admin.ts","../src/copy-defaults.ts","../src/copy-resolve.ts","../src/flow-fields.ts","../src/formation.ts","../src/network-contract.ts","../src/config-network.ts","../src/config-network-person.ts","../src/config-network-commercial.ts","../src/config-signup-control.ts","../src/config-member-content.ts","../src/config-builder-library.ts","../src/network-commercial.ts","../src/network-commercial-reconcile.ts","../src/network-commercial-parity.ts","../src/leader.ts","../src/descriptor.ts","../src/tiers.ts","../src/member-content-validation-helpers.ts","../src/member-content-validation.ts","../src/member-content.ts","../src/member-content-canonical.ts","../src/builder-library-validation.ts","../src/builder-library.ts","../src/builder-library-canonical.ts","../src/email.ts","../src/notify.ts","../src/payments.ts","../src/admission-grants-contract.ts","../src/signup-control-canonical.ts","../src/admission-grants.ts","../src/join-continuation.ts","../src/gift-offers.ts","../src/network.ts","../src/crm-sync.ts","../src/series.ts","../src/payments-stripe.ts","../src/clerk.ts","../src/clerk-roles.ts","../src/clerk-integration.ts","../src/session.ts","../src/brand.ts","../src/reconcile.ts","../src/scheduling.ts","../src/tiers-store.ts","../src/signup-control-contract.ts","../src/membership-page.ts","../src/signup-control-validate.ts","../src/signup-control-theme.ts","../src/membership-markdown.ts","../src/promotion.ts","../src/member-system-authority.ts","../src/member-system-contract.ts"],"sourcesContent":["// defineChapter — validate-at-import config, reusing @odla-ai/crm's defineCrm.\n// A bad config throws here (startup), never at request time.\nimport { defineCrm } from \"@odla-ai/crm\";\nimport type { CrmConfig, Crm } from \"@odla-ai/crm\";\nimport type {\n Chapter,\n ChapterConfig,\n ChapterMode,\n ResolvedOperations,\n} from \"./types\";\nimport { chapterDb } from \"./schema\";\nimport { defaultCrm } from \"./defaults\";\nimport { buildGroupSeed } from \"./group\";\nimport { resolveAuth } from \"./auth\";\nimport { resolvePipeline } from \"./pipeline\";\nimport { resolveApplication } from \"./member\";\nimport { resolveChapterCopy } from \"./copy\";\nimport { resolveLeaderFormation } from \"./formation\";\nimport { resolveNetwork } from \"./config-network\";\nimport { resolveNetworkPersonRegistry } from \"./config-network-person\";\nimport { resolveNetworkCommercialReadModel } from \"./config-network-commercial\";\nimport { resolveSignupControl } from \"./config-signup-control\";\nimport { resolveMemberContent } from \"./config-member-content\";\nimport { resolveBuilderLibrary } from \"./config-builder-library\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\nfunction isResolvedCrm(x: CrmConfig | Crm | undefined): x is Crm {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"prepare\" in x &&\n typeof (x as { prepare?: unknown }).prepare === \"function\"\n );\n}\n\n/**\n * Validate a chapter/hub config and resolve its engine — the CRM, the chapter's\n * odla-db schema/rules, and the seed groups row. Throws at import on a bad\n * config (bad slug, wrong mode, missing chapter-mode prices/emails), never at\n * request time.\n */\nexport function defineChapter(config: ChapterConfig): Chapter {\n if (!config || typeof config !== \"object\") throw new Error(\"defineChapter: a config object is required\");\n const { id, name } = config;\n if (typeof id !== \"string\" || !SLUG.test(id)) {\n throw new Error(`defineChapter.id: must be a lowercase slug [a-z0-9-] (2-63 chars) — got ${JSON.stringify(id)}`);\n }\n if (typeof name !== \"string\" || name.trim() === \"\") throw new Error(\"defineChapter.name: a non-empty name is required\");\n\n const mode: ChapterMode = config.mode ?? \"chapter\";\n if (mode !== \"chapter\" && mode !== \"hub\") throw new Error(`defineChapter.mode: must be \"chapter\" or \"hub\" — got ${JSON.stringify(config.mode)}`);\n\n const crm: Crm = isResolvedCrm(config.crm) ? config.crm : defineCrm(config.crm ?? defaultCrm(mode));\n\n if (mode === \"chapter\") {\n if (!config.emails || typeof config.emails.notificationEmail !== \"string\" || config.emails.notificationEmail === \"\") {\n throw new Error(\"defineChapter.emails.notificationEmail: required in chapter mode\");\n }\n if (!config.prices || typeof config.prices.standardCents !== \"number\") {\n throw new Error(\"defineChapter.prices.standardCents: required in chapter mode\");\n }\n if (config.account === undefined) {\n throw new Error('defineChapter.account: required in chapter mode; choose \"none\", \"create\", or \"invite\" explicitly');\n }\n }\n\n const auth = resolveAuth(mode, config.auth);\n const pipeline = resolvePipeline(config.pipeline);\n const application = resolveApplication(config.application);\n const brand = { ...config.brand, wordmark: config.brand?.wordmark ?? name };\n const copy = resolveChapterCopy(config.copy);\n const network = resolveNetwork(config, crm);\n const networkPersonRegistry = resolveNetworkPersonRegistry(\n mode,\n config.networkPersonRegistry,\n network.targets.map((target) => target.id),\n );\n const networkCommercialReadModel = resolveNetworkCommercialReadModel(\n mode,\n config.networkCommercialReadModel,\n network.targets.map((target) => target.id),\n );\n const signupControl = resolveSignupControl(config.signupControl);\n const memberContent = resolveMemberContent(config.memberContent);\n const builderLibrary = resolveBuilderLibrary(mode, config.builderLibrary, network);\n const formation = resolveLeaderFormation(config.formation, crm);\n if (signupControl && mode !== \"chapter\") {\n throw new Error(\"defineChapter.signupControl: only chapter-mode followers can receive signup control\");\n }\n if (memberContent && mode !== \"chapter\") {\n throw new Error(\"defineChapter.memberContent: only chapter-mode sites can serve member content\");\n }\n const { schema, rules } = chapterDb(\n mode,\n auth,\n network.targets.length > 0,\n application,\n Boolean(signupControl),\n Boolean(memberContent),\n Boolean(builderLibrary),\n network.targets.some((target) => target.admissionGrants),\n Boolean(networkPersonRegistry),\n Boolean(networkCommercialReadModel),\n );\n const services = config.services ?? [\"db\", \"calendar\", \"o11y\"];\n // Hub mode has no public application flow, so its inert resolved value remains\n // `none`. Chapter mode was required to make this decision above.\n const account = config.account ?? \"none\";\n if (account !== \"invite\" && account !== \"create\" && account !== \"none\") {\n throw new Error(`defineChapter.account: must be \"invite\", \"create\", or \"none\" — got \"${String(account)}\"`);\n }\n // crmFields not declared on the CRM person type are dropped by the projection at\n // runtime (the base person still lands), so a typo is invisible. Both the\n // resolved crmFields and the resolved crm are in hand here — cross-check the\n // names and fail at resolve time instead.\n if (application.crmFields.length > 0) {\n let personFields: string[] | null = null;\n try {\n personFields = Object.keys(crm.type(\"person\").fields ?? {});\n } catch {\n // No introspectable \"person\" type — leave it to the projection.\n }\n const unknown = personFields ? application.crmFields.filter((f) => !personFields.includes(f)) : [];\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.application.crmFields: ${unknown.map((f) => `\"${f}\"`).join(\", \")} not declared on the CRM \"person\" type ` +\n `(declared: ${personFields?.join(\", \")}). An undeclared field is silently dropped from the CRM projection — ` +\n `add it to your crm config's person fields, or remove it from crmFields.`,\n );\n }\n }\n const adminNotification = config.sends?.adminNotification ?? \"submit\";\n if (adminNotification !== \"submit\" && adminNotification !== \"payment\" && adminNotification !== \"never\") {\n throw new Error(\n `defineChapter.sends.adminNotification: must be \"submit\", \"payment\", or \"never\" — got \"${String(adminNotification)}\"`,\n );\n }\n const sends = { adminNotification };\n\n // Admin-operation policy. The escalation RULES are not here — they are\n // package-enforced in canChangeRole (gated on auth.superAdmins), so a site\n // cannot weaken them. These two are genuine per-site decisions.\n const onApproveCfg = config.operations?.onApprove ?? {};\n // Default promotion target: the rung directly below admin, so a custom ladder\n // gets the right answer instead of a hardcoded \"member\".\n const belowAdmin = auth.ladder[auth.ladder.length - 2] ?? auth.adminRole;\n const promoteTo = onApproveCfg.promoteTo === undefined ? belowAdmin : onApproveCfg.promoteTo;\n if (promoteTo !== false && !auth.ladder.includes(promoteTo)) {\n throw new Error(\n `defineChapter.operations.onApprove.promoteTo: \"${String(promoteTo)}\" is not in the auth ladder (${auth.ladder.join(\", \")})`,\n );\n }\n const refundCfg = config.operations?.refund ?? {};\n if (refundCfg.allowedFrom !== undefined) {\n const unknown = refundCfg.allowedFrom.filter((s) => !pipeline.stages.includes(s));\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.operations.refund.allowedFrom: ${unknown.map((s) => `\"${s}\"`).join(\", \")} not in the pipeline (${pipeline.stages.join(\", \")})`,\n );\n }\n }\n const operations: ResolvedOperations = {\n onApprove: { promoteTo, send: onApproveCfg.send === undefined ? \"onboardingInvite\" : onApproveCfg.send },\n refund: { allowedFrom: refundCfg.allowedFrom ?? null, cancelSubscription: refundCfg.cancelSubscription ?? true },\n };\n\n const chapter: Chapter = {\n config,\n id,\n name,\n mode,\n brand,\n copy,\n network,\n signupControl,\n memberContent,\n builderLibrary,\n networkPersonRegistry,\n networkCommercialReadModel,\n formation,\n crm,\n auth,\n pipeline,\n application,\n schema,\n rules,\n services,\n account,\n sends,\n operations,\n groupSeed: () => (mode === \"chapter\" ? buildGroupSeed(config) : null),\n };\n if (config.url !== undefined) chapter.url = config.url;\n return chapter;\n}\n","// The public member surface logic: the join config a site's join page reads (B1)\n// and the idempotent application submit (B2 validation + B3 exactly-once). Both\n// take the structural ChapterDb, so they're tested against an in-memory fake and\n// carry no runtime @odla-ai/db import. The worker builds the real db client, does\n// Clerk verification, enforces the body cap, and mounts these on chapter routes.\nimport type { Chapter, ChapterApplication, ChapterDb, ResolvedApplication } from \"./types\";\nimport { assertFieldCondition, resolveFieldStates } from \"@odla-ai/crm\";\nimport type { FieldConditions } from \"@odla-ai/crm\";\nimport { applicationIdForSubmission } from \"./application-id\";\nimport type { JoinConfigTier } from \"./tiers\";\nimport type { AdmissionGrantRow } from \"./admission-grants\";\nimport { normalizeChapterEmail } from \"./email-identity\";\n\n// The reference join form. `focus` (a json field) is always accepted.\nconst DEFAULT_REQUIRED = [\"firstName\", \"lastName\", \"email\", \"referral\", \"whoYouAre\", \"message\"];\nconst DEFAULT_OPTIONAL = [\"referralName\", \"linkedin\", \"phone\", \"state\"];\nconst SCHEMA_FIELD = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\n/** Apply defaults + validate the application config. Throws at import on bad shape. */\nexport function resolveApplication(a: ChapterApplication | undefined): ResolvedApplication {\n const required = a?.required ?? DEFAULT_REQUIRED;\n const optional = a?.optional ?? DEFAULT_OPTIONAL;\n for (const [name, arr] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(arr) || !arr.every((f) => typeof f === \"string\" && f !== \"\")) {\n throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);\n }\n const unsafe = arr.find((field) => !SCHEMA_FIELD.test(field));\n if (unsafe) {\n throw new Error(`defineChapter.application.${name}: field \"${unsafe}\" must match ${SCHEMA_FIELD.source}`);\n }\n }\n const duplicate = [...required, ...optional].find((field, index, fields) => fields.indexOf(field) !== index);\n if (duplicate) {\n throw new Error(`defineChapter.application: duplicate field \"${duplicate}\" across required/optional lists`);\n }\n if (a?.profileFields !== undefined && (!Array.isArray(a.profileFields) || !a.profileFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.profileFields: must be an array of field-name strings\");\n }\n if (a?.crmFields !== undefined && (!Array.isArray(a.crmFields) || !a.crmFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.crmFields: must be an array of field-name strings\");\n }\n // Conditions are checked when the chapter is defined, so a typo fails at\n // startup rather than quietly misbehaving on a live join page. Fields that\n // fail open at runtime are the deliberate second line of defence, not this.\n const conditions = a?.conditions ?? {};\n for (const [field, declared] of Object.entries(conditions)) {\n for (const key of [\"visibleWhen\", \"requiredWhen\"] as const) {\n const expression = declared?.[key];\n if (expression === undefined) continue;\n if (typeof expression !== \"string\" || !expression.trim()) {\n throw new Error(`defineChapter.application.conditions.${field}.${key}: must be a non-empty CEL condition`);\n }\n assertFieldCondition(expression, `defineChapter.application.conditions.${field}.${key}`);\n }\n }\n return {\n required,\n optional,\n conditions,\n maxLen: a?.maxLen ?? {},\n defaultMaxLen: a?.defaultMaxLen ?? 2000,\n bodyCap: a?.bodyCap ?? 32768,\n requireDisclaimerAck: a?.requireDisclaimerAck ?? true,\n profileFields: a?.profileFields ?? [],\n crmFields: a?.crmFields ?? [],\n maxArrayLen: a?.maxArrayLen ?? 100,\n validateEmail: a?.validateEmail ?? true,\n };\n}\n\n// A permissive email shape check: one @, a dot-bearing domain, no whitespace.\n// Deliberately not RFC-exhaustive — the goal is to reject \"notanemail\" before it\n// fails the downstream Clerk create, not to adjudicate exotic-but-valid addresses.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Whether a string looks like an email address (see {@link EMAIL_RE}). Exported\n * so a site building its own submit path applies the same rule chapter does. */\nexport function isValidEmail(value: unknown): boolean {\n return typeof value === \"string\" && EMAIL_RE.test(value);\n}\n\n/** Bound an array-valued field: drop non-primitive elements and cap the length,\n * so a client cannot post an unbounded array. Non-arrays pass through unchanged. */\nexport function clampArray(value: unknown, max: number): unknown {\n if (!Array.isArray(value)) return value;\n return value.filter((x) => typeof x === \"string\" || typeof x === \"number\" || typeof x === \"boolean\").slice(0, max);\n}\n\n/** Whether a submit body carries a genuine disclaimer acknowledgement. Accepts\n * the boolean an API client sends and the string a plain HTML form posts. */\nexport function hasDisclaimerAck(fields: Record<string, unknown>): boolean {\n return fields.disclaimerAck === true || fields.disclaimerAck === \"true\";\n}\n\n// Clerk carries these as first-class user fields, so repeating them in\n// public_metadata would be duplicated state that can drift.\nconst IDENTITY_FIELDS = new Set([\"email\", \"firstName\", \"lastName\"]);\n\n/**\n * The applicant profile written to the Clerk account's backend-only\n * `private_metadata.profile`. Projects each configured non-identity field, plus\n * `focus` (clamped), but ONLY those in `application.profileFields`. Derived\n * from config, so a site's own field names project without this package knowing\n * them. Pure; returns `undefined` when there is nothing to write.\n */\nexport function applicantProfile(\n chapter: Chapter,\n fields: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const app = chapter.application;\n const allowed = (f: string): boolean => app.profileFields.includes(f);\n const profile: Record<string, unknown> = {};\n for (const f of [...app.required, ...app.optional]) {\n if (IDENTITY_FIELDS.has(f) || !allowed(f)) continue;\n const v = fields[f];\n if (typeof v === \"string\" && v.trim() !== \"\") profile[f] = v.trim();\n }\n if (fields.focus !== undefined && allowed(\"focus\")) profile.focus = clampArray(fields.focus, app.maxArrayLen);\n return Object.keys(profile).length > 0 ? profile : undefined;\n}\n\n/** A validated submission, or a 400-worthy validation error the route returns.\n * `disclaimerAckAt` reports what THIS request recorded — a number when consent\n * was stamped, `null` when none was supplied. It is always present so a missing\n * consent record is visible in the response rather than silently absent from a\n * row nobody reads until an audit. */\nexport type SubmitResult =\n | { ok: true; id: string; duplicate: boolean; status: string; disclaimerAckAt: number | null }\n | { ok: false; error: string };\n\n/**\n * Submit a membership application (B2 + B3). Validates the configured required\n * fields + max lengths, writes the `applications` row at the pipeline's initial\n * status, and — when the client supplies a `submissionId` — stamps it as the\n * transaction's mutationId (`join:${submissionId}`) so a double-tap can never\n * create two applications. The application id is derived from that same stable\n * input, so the duplicate response returns the first request's canonical id\n * rather than a fresh, nonexistent one. Idempotency is package-enforced.\n * `now`/`newId` are injected (deterministic in tests).\n */\nexport async function submitApplication(\n db: ChapterDb,\n chapter: Chapter,\n fields: Record<string, unknown>,\n opts: {\n submissionId?: string;\n groupId?: string;\n now: number;\n newId: () => string;\n /** Tier ids this chapter offers. A posted `tierId` outside it is refused;\n * omit to accept any (pre-tier callers). */\n tierIds?: readonly string[];\n /** Effective one-use waiver selected by the server, never by the client. */\n admissionGrant?: AdmissionGrantRow;\n /** Server-validated gift offer selected from active signed control. */\n giftOfferId?: string;\n },\n): Promise<SubmitResult> {\n const app = chapter.application;\n // Requiredness is resolved against the answers, not read off a static list,\n // so a conditionally-hidden field is not demanded and a conditionally-\n // required one cannot be skipped by posting straight to this route. The\n // renderer calls the same resolver, so the form and the validator cannot\n // disagree. With no conditions declared this is exactly the old static loop.\n const fieldStates = resolveFieldStates(app.conditions ?? {}, fields, app.required);\n for (const [f, state] of Object.entries(fieldStates)) {\n if (!state.required) continue;\n const v = fields[f];\n if (typeof v !== \"string\" || v.trim() === \"\") return { ok: false, error: `${f} is required` };\n }\n for (const f of [...app.required, ...app.optional]) {\n const v = fields[f];\n const cap = app.maxLen[f] ?? app.defaultMaxLen;\n if (typeof v === \"string\" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };\n }\n // A malformed email can only fail the downstream Clerk create; reject it here\n // as a clean 400. A valid application always has a valid email, so no genuine\n // submission is newly rejected.\n if (app.validateEmail && typeof fields.email === \"string\" && !isValidEmail(fields.email.trim())) {\n return { ok: false, error: \"email must be a valid email address\" };\n }\n\n const acked = hasDisclaimerAck(fields);\n if (app.requireDisclaimerAck && !acked) {\n return { ok: false, error: \"disclaimerAck is required\" };\n }\n\n const id = opts.submissionId\n ? await applicationIdForSubmission(opts.submissionId)\n : opts.newId();\n const row: Record<string, unknown> = { id, status: chapter.pipeline.initial, createdAt: opts.now };\n for (const f of [...app.required, ...app.optional]) {\n // A field the conditions hid was never asked, so a value for it is stale\n // or forged. Storing it would answer a question on the applicant's behalf.\n if (fieldStates[f]?.visible === false) continue;\n if (typeof fields[f] === \"string\") row[f] = (fields[f] as string).trim();\n }\n if (fields.focus !== undefined) row.focus = clampArray(fields.focus, app.maxArrayLen);\n if (opts.groupId) row.groupId = opts.groupId;\n if (typeof fields.email === \"string\" && isValidEmail(fields.email.trim())) {\n row.emailNormalized = normalizeChapterEmail(fields.email);\n }\n if (opts.admissionGrant?.decision === \"waive_interview\") {\n row.admissionGrantId = opts.admissionGrant.id;\n row.admissionSource = opts.admissionGrant.sourceScope;\n row.interviewWaivedAt = opts.now;\n }\n if (opts.giftOfferId) row.giftOfferId = opts.giftOfferId;\n // A tier decides what this member is charged, so the posted id is checked\n // against what the chapter actually offers rather than trusted. An unknown\n // id is refused instead of silently dropped: dropping it would bill the\n // applicant whatever the fallback tier costs.\n if (typeof fields.tierId === \"string\" && fields.tierId) {\n if (opts.tierIds && !opts.tierIds.includes(fields.tierId)) {\n return { ok: false, error: \"tierId is not an offered tier\" };\n }\n row.tierId = fields.tierId;\n }\n // The disclaimer acknowledgement is a compliance record, so it is stamped from\n // the server clock on a genuine ack and left absent otherwise — a client-supplied\n // timestamp would be forgeable, and a row that always carries one would record\n // consent nobody gave.\n if (acked) row.disclaimerAckAt = opts.now;\n\n const ops: Parameters<ChapterDb[\"transact\"]>[0] = [\n { t: \"update\", ns: \"applications\", id, attrs: row },\n ];\n if (opts.admissionGrant?.decision === \"waive_interview\") {\n ops.push({ t: \"update\", ns: \"admissionGrants\", id: opts.admissionGrant.id, attrs: {\n consumedAt: opts.now,\n consumedApplicationId: id,\n } });\n }\n const { duplicate } = await db.transact(\n ops,\n opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : undefined,\n );\n return { ok: true, id, duplicate, status: chapter.pipeline.initial, disclaimerAckAt: acked ? opts.now : null };\n}\n\n/** The `groups`-row fields the join config exposes. */\nexport interface JoinConfigGroup {\n id: string;\n name: string;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n disclaimerText?: string;\n refundPolicyText?: string;\n merchantDisclosureText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/**\n * The public join config (B1) a site's join page reads: copy + prices from the\n * group row plus `paymentsReady`. When payments aren't wired the join flow drops\n * the payment step (C2) — the worker computes `paymentsReady` from the group's\n * Stripe keys + vault secret. Pure.\n *\n * `tiers` carries the offerable membership tiers. It is additive: the legacy\n * `standardPriceCents`/`foundingDiscountCents` fields still describe the first\n * tier, so a join page written before tiers keeps rendering unchanged. A free\n * tier appears here with `free: true` even when Stripe is unconfigured, because\n * nothing needs charging for it.\n */\nexport function joinConfig(\n group: JoinConfigGroup,\n paymentsReady: boolean,\n tiers: readonly JoinConfigTier[] = [],\n conditions: Readonly<Record<string, FieldConditions>> = {},\n): Record<string, unknown> {\n return {\n id: group.id,\n name: group.name,\n standardPriceCents: group.standardPriceCents ?? 0,\n foundingDiscountCents: group.foundingDiscountCents ?? 0,\n currency: group.currency ?? \"usd\",\n interval: group.interval ?? \"year\",\n tiers: [...tiers],\n // The browser evaluates the same conditions the server enforces.\n conditions,\n disclaimerText: group.disclaimerText ?? \"\",\n refundPolicyText: group.refundPolicyText ?? \"\",\n merchantDisclosureText: group.merchantDisclosureText ?? \"\",\n trustCopy: group.trustCopy ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n paymentsReady,\n };\n}\n","// Application creates use a caller-stable submission id as their database\n// mutation id. The entity id must be derived from that same stable input: if a\n// committed request is retried, the database correctly skips the new ops and\n// Chapter must still return the id of the row written by the first request.\n\nconst APPLICATION_ID_DOMAIN = \"odla-ai/chapter/application/v1:\";\n\n/**\n * Derive the UUID-shaped capability for an idempotent application submission.\n * SHA-256 prevents a caller from choosing a submission id that overwrites a\n * known application id; UUIDv8 bits preserve the identifier shape consumers\n * already expect.\n */\nexport async function applicationIdForSubmission(submissionId: string): Promise<string> {\n const input = new TextEncoder().encode(`${APPLICATION_ID_DOMAIN}${submissionId}`);\n const bytes = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", input)).slice(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Normalize an email address for Chapter identity lookups.\n *\n * Chapter treats the address literally: surrounding whitespace and ASCII case\n * are insignificant, but the local part is otherwise preserved. In\n * particular, provider-specific aliases are never collapsed, so\n * `foo+bar@gmail.com` and `foo@gmail.com` remain distinct applicants,\n * admission decisions, purchasers, and beneficiaries.\n */\nexport function normalizeChapterEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n","import type { Attr, AttrType, Entity, ResolvedApplication } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\n\nconst APPLICATION_INPUT_FIELDS = new Set([\n \"firstName\", \"lastName\", \"email\", \"referral\", \"referralName\", \"whoYouAre\",\n \"focus\", \"linkedin\", \"message\", \"phone\", \"state\",\n]);\n\nconst applicationAttrs: Record<string, Attr> = {\n id: attr(\"string\", { unique: true, indexed: true }), firstName: attr(\"string\"), lastName: attr(\"string\"),\n email: attr(\"string\", { indexed: true }), referral: attr(\"string\"), referralName: attr(\"string\", { optional: true }),\n whoYouAre: attr(\"string\"), focus: attr(\"json\"), linkedin: attr(\"string\", { optional: true }), message: attr(\"string\"),\n status: attr(\"string\", { indexed: true }), createdAt: attr(\"number\", { indexed: true }),\n meetingAt: attr(\"number\", { indexed: true, optional: true }), meetingLink: attr(\"string\", { optional: true }),\n clerkUserId: attr(\"string\", { indexed: true, optional: true }), clerkPrivateMetadataSyncedAt: attr(\"number\", { optional: true }),\n phone: attr(\"string\", { optional: true }), state: attr(\"string\", { optional: true }),\n groupId: attr(\"string\", { indexed: true, optional: true }), tierId: attr(\"string\", { indexed: true, optional: true }),\n stripeCustomerId: attr(\"string\", { indexed: true, optional: true }),\n stripeSubscriptionId: attr(\"string\", { indexed: true, optional: true }),\n stripeRuntime: attr(\"string\", { indexed: true, optional: true }), renewalAt: attr(\"number\", { optional: true }),\n disclaimerAckAt: attr(\"number\", { optional: true }), refundPolicyAckAt: attr(\"number\", { optional: true }),\n prepEmailSentAt: attr(\"number\", { optional: true }), canceled: attr(\"boolean\", { optional: true }),\n emailNormalized: attr(\"string\", { indexed: true, optional: true }),\n admissionGrantId: attr(\"string\", { unique: true, indexed: true, optional: true }),\n admissionSource: attr(\"string\", { indexed: true, optional: true }), interviewWaivedAt: attr(\"number\", { optional: true }),\n giftOfferId: attr(\"string\", { optional: true, indexed: true }),\n giftIntentId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n giftClaimId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n giftOrderId: attr(\"string\", { optional: true, indexed: true }), giftPaidAt: attr(\"number\", { optional: true, indexed: true }),\n giftRevokedAt: attr(\"number\", { optional: true, indexed: true }),\n giftCheckoutStartedAt: attr(\"number\", { optional: true, indexed: true }),\n};\n\n/** Resolve the site-configurable application inputs without exposing operational fields. */\nexport function applicationsFor(application: ResolvedApplication): Entity {\n const attrs: Record<string, Attr> = {};\n for (const [name, spec] of Object.entries(applicationAttrs)) {\n attrs[name] = { ...spec, optional: APPLICATION_INPUT_FIELDS.has(name) ? true : spec.optional };\n }\n const apply = (field: string, optional: boolean): void => {\n const existing = Object.hasOwn(attrs, field) ? attrs[field] : undefined;\n if (existing && !APPLICATION_INPUT_FIELDS.has(field)) throw new Error(`defineChapter.application: field \"${field}\" is reserved by the applications schema`);\n if (existing && existing.type !== \"string\") throw new Error(`defineChapter.application: field \"${field}\" is not a configurable string field`);\n Object.defineProperty(attrs, field, {\n value: existing ? { ...existing, optional } : attr(\"string\", { optional }),\n enumerable: true, configurable: true, writable: true,\n });\n };\n for (const field of application.required) apply(field, false);\n for (const field of application.optional) apply(field, true);\n return { attrs };\n}\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n/** Operational Parent and Chapter admission decisions, never publicly readable. */\nexport const admissionGrantsEntity: Entity = {\n attrs: {\n id: id(),\n sourceGrantId: attr(\"string\", { indexed: true }),\n sourceScope: attr(\"string\", { indexed: true }),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n email: attr(\"string\"),\n emailNormalized: attr(\"string\", { indexed: true }),\n decision: attr(\"string\", { indexed: true }),\n note: attr(\"string\", { optional: true }),\n active: attr(\"boolean\", { indexed: true }),\n sourceRevision: attr(\"number\", { optional: true, indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n createdBy: attr(\"string\", { optional: true, indexed: true }),\n updatedAt: attr(\"number\", { optional: true, indexed: true }),\n updatedBy: attr(\"string\", { optional: true, indexed: true }),\n expiresAt: attr(\"number\", { optional: true, indexed: true }),\n revokedAt: attr(\"number\", { optional: true, indexed: true }),\n revokedBy: attr(\"string\", { optional: true, indexed: true }),\n consumedAt: attr(\"number\", { optional: true, indexed: true }),\n consumedApplicationId: attr(\"string\", { optional: true, indexed: true }),\n },\n};\n\n/** Immutable acknowledgements for signed Parent admission documents. */\nexport const admissionGrantRevisionsEntity: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** Leader-owned assignment of an existing CRM person to one Chapter target. */\nexport const leaderAdmissionAssignmentsEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n personId: attr(\"string\", { indexed: true }),\n grantId: attr(\"string\", { indexed: true }),\n decision: attr(\"string\", { indexed: true }),\n note: attr(\"string\", { optional: true }),\n expiresAt: attr(\"number\", { optional: true, indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n lastMutationId: attr(\"string\", { indexed: true }),\n lastRequestDigest: attr(\"string\"),\n createdAt: attr(\"number\", { indexed: true }),\n createdBy: attr(\"string\", { indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { indexed: true }),\n },\n};\n\n/** Durable desired document plus its latest delivery/acknowledgement state. */\nexport const leaderAdmissionDeliveriesEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n envelope: attr(\"json\"),\n status: attr(\"string\", { indexed: true }),\n attempts: attr(\"number\", { indexed: true }),\n lastAttemptAt: attr(\"number\", { optional: true, indexed: true }),\n lastError: attr(\"string\", { optional: true }),\n acknowledgedAt: attr(\"number\", { optional: true, indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** Stable mutation receipts prevent an old retry from becoming a new revision\n * after later assignments changed the target's desired set. */\nexport const leaderAdmissionMutationsEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n personId: attr(\"string\", { indexed: true }),\n requestDigest: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n/** Pre-payment gift checkout state. It holds only a code hash, never plaintext. */\nexport const giftPurchaseIntentsEntity: Entity = { attrs: {\n id: id(), chapterId: attr(\"string\", { indexed: true }), environment: attr(\"string\", { indexed: true }),\n runtime: attr(\"string\", { optional: true, indexed: true }),\n purchaserType: attr(\"string\", { indexed: true }), purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }),\n purchaserUserId: attr(\"string\", { optional: true, indexed: true }), purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n offerId: attr(\"string\", { indexed: true }), offerSnapshot: attr(\"json\"), status: attr(\"string\", { indexed: true }),\n codeHash: attr(\"string\", { indexed: true }), codeVersion: attr(\"number\"), codeIssuedAt: attr(\"number\"),\n providerObjectId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n providerCustomerId: attr(\"string\", { optional: true, indexed: true }), checkoutStartedAt: attr(\"number\", { optional: true }),\n paidAt: attr(\"number\", { optional: true, indexed: true }), claimId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n createdAt: attr(\"number\", { indexed: true }), updatedAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Immutable provider-authorized gift purchase evidence. */\nexport const giftOrdersEntity: Entity = { attrs: {\n id: id(), intentId: attr(\"string\", { unique: true, indexed: true }), chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }), offerId: attr(\"string\", { indexed: true }), offerSnapshot: attr(\"json\"),\n purchaserType: attr(\"string\", { indexed: true }), purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }),\n purchaserUserId: attr(\"string\", { optional: true, indexed: true }), purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n providerEventId: attr(\"string\", { unique: true, indexed: true }), providerObjectId: attr(\"string\", { indexed: true }),\n amountCents: attr(\"number\"), currency: attr(\"string\"), billingMode: attr(\"string\"), createdAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Single-use beneficiary bearer claim. Buyer list routes never return its hash. */\nexport const giftClaimsEntity: Entity = { attrs: {\n id: id(), orderId: attr(\"string\", { unique: true, indexed: true }), intentId: attr(\"string\", { unique: true, indexed: true }),\n chapterId: attr(\"string\", { indexed: true }), offerId: attr(\"string\", { indexed: true }), target: attr(\"json\"),\n purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }), purchaserUserId: attr(\"string\", { optional: true, indexed: true }),\n purchaserEmailNormalized: attr(\"string\", { indexed: true }), codeHash: attr(\"string\", { unique: true, indexed: true }),\n codeVersion: attr(\"number\"), rotationCount: attr(\"number\"), codeIssuedAt: attr(\"number\"), codeExpiresAt: attr(\"number\", { indexed: true }),\n attemptCount: attr(\"number\"), attemptWindowStartedAt: attr(\"number\"), status: attr(\"string\", { indexed: true }),\n redeemedAt: attr(\"number\", { optional: true, indexed: true }), beneficiaryEmailNormalized: attr(\"string\", { optional: true, indexed: true }),\n beneficiaryUserId: attr(\"string\", { optional: true, indexed: true }), applicationId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n entitlementId: attr(\"string\", { optional: true, unique: true, indexed: true }), rotatedAt: attr(\"number\", { optional: true }),\n revokedAt: attr(\"number\", { optional: true, indexed: true }), revokedReason: attr(\"string\", { optional: true }), createdAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Non-membership beneficiary entitlements created by redeemed gift claims. */\nexport const giftEntitlementsEntity: Entity = { attrs: {\n id: id(), claimId: attr(\"string\", { unique: true, indexed: true }), orderId: attr(\"string\", { indexed: true }),\n chapterId: attr(\"string\", { indexed: true }), entitlementKey: attr(\"string\", { indexed: true }),\n beneficiaryEmailNormalized: attr(\"string\", { indexed: true }), beneficiaryUserId: attr(\"string\", { optional: true, indexed: true }),\n active: attr(\"boolean\", { indexed: true }), createdAt: attr(\"number\", { indexed: true }), revokedAt: attr(\"number\", { optional: true }),\n} };\n\n/** Coarse requester buckets that bound public redemption attempts. */\nexport const giftRedemptionAttemptsEntity: Entity = { attrs: {\n id: id(), chapterId: attr(\"string\", { indexed: true }), bucket: attr(\"string\", { indexed: true }),\n attemptCount: attr(\"number\"), windowStartedAt: attr(\"number\", { indexed: true }), updatedAt: attr(\"number\"),\n} };\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\n\n// Content-free Stripe ingress evidence. Sibling endpoints never write it.\nexport const stripeEventReceiptsEntity: Entity = {\n attrs: {\n id: attr(\"string\", { unique: true, indexed: true }),\n eventId: attr(\"string\", { unique: true, indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n disposition: attr(\"string\", { indexed: true }),\n kind: attr(\"string\", { indexed: true }),\n matched: attr(\"boolean\", { indexed: true }),\n appId: attr(\"string\", { indexed: true, optional: true }),\n environment: attr(\"string\", { indexed: true, optional: true }),\n dataEnvironment: attr(\"string\", { indexed: true, optional: true }),\n runtime: attr(\"string\", { indexed: true, optional: true }),\n chapterId: attr(\"string\", { indexed: true, optional: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Durable, non-secret checkout intent written before the Chapter calls Stripe.\n// A retry must match this exact commercial/identity snapshot; provider ids are\n// attached only when the checkout and application row can be committed together.\nexport const subscriptionCheckoutIntentsEntity: Entity = {\n attrs: {\n id: attr(\"string\", { unique: true, indexed: true }),\n applicationId: attr(\"string\", { unique: true, indexed: true }),\n appId: attr(\"string\", { indexed: true }),\n chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n runtime: attr(\"string\", { indexed: true, optional: true }),\n groupId: attr(\"string\", { indexed: true }),\n tierId: attr(\"string\", { indexed: true }),\n priceId: attr(\"string\", { indexed: true }),\n priceCents: attr(\"number\"),\n currency: attr(\"string\", { indexed: true }),\n interval: attr(\"string\", { indexed: true }),\n purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n requestedCustomerId: attr(\"string\", { indexed: true, optional: true }),\n providerCustomerId: attr(\"string\", { indexed: true, optional: true }),\n providerSubscriptionId: attr(\"string\", { unique: true, indexed: true, optional: true }),\n status: attr(\"string\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n },\n};\n","import type { Entity } from \"./types\";\n\nconst string = (flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"string\" as const,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\nconst number = (flags: { indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"number\" as const, unique: false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst json = (flags: { optional?: boolean } = {}) => ({\n type: \"json\" as const, unique: false, indexed: false, optional: flags.optional ?? false,\n});\nconst id = () => string({ unique: true, indexed: true });\n\n/** Canonical identity only. Chapter Journey, notes, consent, and billing stay elsewhere. */\nexport const networkPersonsEntity: Entity = { attrs: {\n id: id(), displayName: string({ indexed: true }), state: string({ indexed: true }),\n mergedIntoId: string({ indexed: true, optional: true }), contactPolicy: json(),\n revision: number({ indexed: true }), createdAt: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} };\n\n/** One verified identifier digest may belong to only one preserved Person row. */\nexport const networkIdentityClaimsEntity: Entity = { attrs: {\n id: id(), personId: string({ indexed: true }), kind: string({ indexed: true }),\n value: string(), hint: string({ optional: true }), verifiedAt: number({ indexed: true }), createdAt: number({ indexed: true }),\n} };\n\n/** Immutable source identity plus a reviewable linking decision. */\nexport const networkPersonAliasesEntity: Entity = { attrs: {\n id: id(), sourceSystem: string({ indexed: true }), sourceRecordId: string({ indexed: true }),\n sourceKey: string({ unique: true, indexed: true }), displayName: string({ indexed: true }),\n provenance: string(), consent: json(), status: string({ indexed: true }), personId: string({ indexed: true, optional: true }),\n candidatePersonIds: json({ optional: true }), identityClaims: json(), chapterLinks: json(),\n revision: number({ indexed: true }), createdAt: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} };\n\n/** Chapter-local record identity remains a link, never copied authority. */\nexport const networkChapterPersonLinksEntity: Entity = { attrs: {\n id: id(), personId: string({ indexed: true }), chapterId: string({ indexed: true }),\n chapterPersonId: string({ indexed: true }),\n // Optional for additive compatibility with links written before 0.47.5.\n // New and reactivated links claim this unique one-way source identity so\n // concurrent reviewers cannot attach one chapter row to two Persons.\n sourceKey: string({ unique: true, indexed: true, optional: true }),\n state: string({ indexed: true }), createdAt: number({ indexed: true }),\n} };\n\n/** Append-only, PII-free lifecycle evidence. No route updates or deletes it. */\nexport const networkPersonEventsEntity: Entity = { attrs: {\n id: id(), kind: string({ indexed: true }), personId: string({ indexed: true, optional: true }),\n aliasId: string({ indexed: true, optional: true }), actorId: string({ indexed: true }),\n mutationId: string({ unique: true, indexed: true }), detail: json(), createdAt: number({ indexed: true }),\n} };\n\nexport const networkPersonEntities = {\n networkPersons: networkPersonsEntity,\n networkIdentityClaims: networkIdentityClaimsEntity,\n networkPersonAliases: networkPersonAliasesEntity,\n networkChapterPersonLinks: networkChapterPersonLinksEntity,\n networkPersonEvents: networkPersonEventsEntity,\n};\n","import type { Entity } from \"./types\";\n\nconst string = (flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"string\" as const, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst number = (flags: { indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"number\" as const, unique: false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst boolean = (flags: { indexed?: boolean } = {}) => ({\n type: \"boolean\" as const, unique: false, indexed: flags.indexed ?? false, optional: false,\n});\nconst json = () => ({ type: \"json\" as const, unique: false, indexed: false, optional: false });\nconst id = () => string({ unique: true, indexed: true });\n\n/** Append-only verified Stripe facts. `fact` is allowlisted and contains no customer PII. */\nconst events: Entity = { attrs: {\n id: id(), eventId: string({ unique: true, indexed: true }), digest: string({ indexed: true }),\n eventType: string({ indexed: true }), eventCreated: number({ indexed: true }), livemode: boolean({ indexed: true }),\n fact: json(), receivedAt: number({ indexed: true }),\n} };\n\nconst projection = (): Entity => ({ attrs: {\n id: id(), providerId: string({ indexed: true }), sourceKey: string({ indexed: true }),\n status: string({ indexed: true }), snapshot: json(), eventCreated: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} });\n\n/** Current, rebuildable projections plus explained reconciliation exceptions. */\nconst exceptions: Entity = { attrs: {\n id: id(), eventId: string({ indexed: true }), kind: string({ indexed: true }),\n sourceKey: string({ indexed: true, optional: true }), status: string({ indexed: true }),\n detail: json(), updatedAt: number({ indexed: true }),\n} };\n\nexport const networkCommercialEntities = {\n networkCommercialEvents: events,\n networkCommercialCustomers: projection(),\n networkCommercialSubscriptions: projection(),\n networkCommercialInvoices: projection(),\n networkCommercialRefunds: projection(),\n networkCommercialExceptions: exceptions,\n};\n","// The chapter's own odla-db namespaces: the operational membership tables\n// (applications, groups, meetings, emailLog) plus the auth tables the resolved\n// auth policy selects — the `admins` allowlist (source \"table\") and/or the\n// legacy read-only `superAdmins` tier. All deny-all. The `crm_*` namespaces are\n// contributed separately by @odla-ai/crm's integration and merged by the CLI.\nimport type {\n Attr,\n AttrType,\n DbRules,\n DbSchema,\n Entity,\n ChapterMode,\n ResolvedApplication,\n ResolvedAuth,\n} from \"./types\";\nimport { resolveApplication } from \"./member\";\nimport { applicationsFor } from \"./schema-applications\";\nimport { admissionGrantRevisionsEntity, admissionGrantsEntity, leaderAdmissionAssignmentsEntity, leaderAdmissionDeliveriesEntity, leaderAdmissionMutationsEntity } from \"./schema-admission\";\nimport {\n giftClaimsEntity, giftEntitlementsEntity, giftOrdersEntity,\n giftPurchaseIntentsEntity, giftRedemptionAttemptsEntity,\n} from \"./schema-gifts\";\nimport { stripeEventReceiptsEntity, subscriptionCheckoutIntentsEntity } from \"./schema-stripe\";\nimport { networkPersonEntities } from \"./schema-network-person\";\nimport { networkCommercialEntities } from \"./schema-network-commercial\";\n\nfunction attr(type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr {\n return {\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n };\n}\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n// The allowlist that gates admin access in BOTH modes. Studio-write-only:\n// deny-all, and no worker route ever writes it. Creation time is odla-db's\n// built-in $createdAt. One row per admin, keyed by lowercased email.\nconst admins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n name: attr(\"string\", { optional: true }),\n note: attr(\"string\", { optional: true }),\n },\n};\n\n// The super-admin tier: the ONLY tier that may create or modify admins. A\n// separate, app-READ-ONLY entity — deny-all like every namespace AND no worker\n// route ever writes it, so membership can only be set in the odla Studio data\n// browser, never from the app or an injected page script. One row per\n// super-admin, keyed by lowercased email.\nconst superAdmins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n note: attr(\"string\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Leader-private annotations on records that remain authoritative in a\n// follower CRM. `recordKey` is the stable target/type/id tuple used for bounded\n// reads; notes never cross the federation edge or mutate the follower.\nconst networkNotes: Entity = {\n attrs: {\n id: id(),\n recordKey: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n recordType: attr(\"string\", { indexed: true }),\n recordId: attr(\"string\", { indexed: true }),\n body: attr(\"string\"),\n authorId: attr(\"string\", { indexed: true }),\n authorEmail: attr(\"string\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Immutable signup-control revisions. Exactly one row is active; older rows are\n// retained for audit/rollback while applicant traffic reads local state only.\nconst signupControls: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n document: attr(\"json\"),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Immutable Parent member-content revisions. Exactly one row is active per\n// environment; Chapter-owned content lives in a separate singleton below so a\n// replay or replacement from the Parent cannot overwrite local authority.\nconst memberContentControls: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n document: attr(\"json\"),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One complete Chapter-owned authoring layer per environment. Admin writes are\n// revision-guarded and never share a row with inherited Parent content.\nconst memberContentLocal: Entity = {\n attrs: {\n id: id(),\n chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n document: attr(\"json\"),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { optional: true }),\n },\n};\n\n// Immutable signed Builder Library revisions received from Chapters or Built\n// Not Found. Source layers remain separate so sibling material is never joined\n// accidentally and global promotion retains exact provenance.\nconst builderLibraryControls: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n document: attr(\"json\"),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One complete locally authored layer per app/environment. Chapter mode permits\n// only its own Chapter scope; hub mode permits Built Not Found and global scope.\nconst builderLibraryLocal: Entity = {\n attrs: {\n id: id(),\n appId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n document: attr(\"json\"),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { optional: true }),\n },\n};\n\n// Per-group settings — prices, policy copy, email templates, scheduling — never\n// in code. Seeded once from the defineChapter config (see group.ts).\nconst groups: Entity = {\n attrs: {\n id: id(),\n name: attr(\"string\"),\n standardPriceCents: attr(\"number\"),\n foundingDiscountCents: attr(\"number\"),\n currency: attr(\"string\", { optional: true }), interval: attr(\"string\", { optional: true }),\n stripePriceId: attr(\"string\", { optional: true }),\n stripePublishableKey: attr(\"string\", { optional: true }),\n notificationEmail: attr(\"string\"),\n replyTo: attr(\"string\"),\n debugEmail: attr(\"string\", { optional: true }),\n calendarLink: attr(\"string\", { optional: true }),\n disclaimerText: attr(\"string\"),\n refundPolicyText: attr(\"string\"),\n merchantDisclosureText: attr(\"string\", { optional: true }),\n trustCopy: attr(\"string\"),\n commitmentText: attr(\"string\", { optional: true }),\n normsText: attr(\"string\", { optional: true }),\n emailTemplates: attr(\"json\"),\n schedulingJson: attr(\"json\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One row per membership tier a group offers. The price lives here rather than\n// on the group so a chapter can offer several, and so a free tier (priceCents\n// 0, no stripePriceId) is expressible at all. Deny-all like every namespace:\n// tiers are set in Studio or seeded from the chapter config, never written by a\n// join-flow route.\nconst tiers: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n name: attr(\"string\"),\n priceCents: attr(\"number\"),\n currency: attr(\"string\", { optional: true }), interval: attr(\"string\", { optional: true }),\n stripePriceId: attr(\"string\", { optional: true }),\n blurb: attr(\"string\", { optional: true }),\n sortOrder: attr(\"number\", { indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Intro-call meetings: the source of truth for scheduling; Google Calendar is a\n// projection. Drift fields record when Google disagrees with us.\nconst meetings: Entity = {\n attrs: {\n id: id(),\n applicationId: attr(\"string\", { indexed: true }),\n groupId: attr(\"string\", { indexed: true }),\n startAt: attr(\"number\", { indexed: true }),\n endAt: attr(\"number\"),\n timezone: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n googleEventId: attr(\"string\", { indexed: true, optional: true }),\n meetUrl: attr(\"string\", { optional: true }),\n htmlLink: attr(\"string\", { optional: true }),\n drift: attr(\"string\", { indexed: true, optional: true }),\n driftGoogleStartAt: attr(\"number\", { optional: true }),\n driftDetectedAt: attr(\"number\", { optional: true }),\n adoptedFromGoogleAt: attr(\"number\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Audit of every transactional send.\nconst emailLog: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n applicationId: attr(\"string\", { indexed: true, optional: true }),\n to: attr(\"string\", { indexed: true }),\n template: attr(\"string\", { indexed: true }),\n subject: attr(\"string\"),\n body: attr(\"string\", { optional: true }),\n transport: attr(\"string\"),\n messageId: attr(\"string\", { optional: true }),\n redirected: attr(\"boolean\", { optional: true }),\n dedupeKey: attr(\"string\", { indexed: true, optional: true }),\n error: attr(\"string\", { optional: true }),\n sentAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** The chapter's own schema + deny-all rules for a mode + auth policy.\n *\n * In chapter mode, the optional {@link ResolvedApplication} supplies the exact\n * required/optional application string attrs. Omit it for the reference form.\n * Built-in attrs retain their types/indexes; site-defined fields become string\n * attrs, while package-owned operational attrs cannot be repurposed as inputs.\n *\n * Operational tables (`applications`/`groups`/`meetings`/`emailLog`) are added in\n * `chapter` mode only. The auth tables follow {@link ResolvedAuth}: `source:\n * \"table\"` adds the `admins` allowlist (hub/BNF); `superAdminSource: \"table\"`\n * adds the legacy read-only super-admin tier (the backward-compatible default).\n * `superAdminSource: \"odla\"` uses reserved `$users` and adds no app namespace. A `\"claim\"`\n * chapter therefore emits the reference namespace set — `applications`,\n * `groups`, `meetings`, `emailLog`, `stripeEventReceipts`,\n * `subscriptionCheckoutIntents`, `superAdmins` — with\n * no `admins` table. */\nexport function chapterDb(\n mode: ChapterMode,\n auth: ResolvedAuth,\n includeNetworkNotes = false,\n application: ResolvedApplication = resolveApplication(undefined),\n includeSignupControl = false,\n includeMemberContent = false,\n includeBuilderLibrary = false,\n includeLeaderAdmissions = false,\n includeNetworkPersonRegistry = false,\n includeNetworkCommercialReadModel = false,\n): { schema: DbSchema; rules: DbRules } {\n const entities: Record<string, Entity> = {};\n if (mode === \"chapter\") {\n entities.applications = applicationsFor(application);\n entities.groups = groups;\n entities.tiers = tiers;\n entities.meetings = meetings;\n entities.emailLog = emailLog;\n entities.stripeEventReceipts = stripeEventReceiptsEntity;\n entities.subscriptionCheckoutIntents = subscriptionCheckoutIntentsEntity;\n entities.admissionGrants = admissionGrantsEntity;\n entities.admissionGrantRevisions = admissionGrantRevisionsEntity;\n entities.giftPurchaseIntents = giftPurchaseIntentsEntity;\n entities.giftOrders = giftOrdersEntity;\n entities.giftClaims = giftClaimsEntity;\n entities.giftEntitlements = giftEntitlementsEntity;\n entities.giftRedemptionAttempts = giftRedemptionAttemptsEntity;\n if (includeSignupControl) entities.signupControls = signupControls;\n if (includeMemberContent) {\n entities.memberContentControls = memberContentControls;\n entities.memberContentLocal = memberContentLocal;\n }\n }\n if (auth.source === \"table\") entities.admins = admins;\n if (auth.superAdminSource === \"table\") entities.superAdmins = superAdmins;\n if (includeNetworkNotes) entities.networkNotes = networkNotes;\n if (includeBuilderLibrary) {\n entities.builderLibraryControls = builderLibraryControls;\n entities.builderLibraryLocal = builderLibraryLocal;\n }\n if (includeLeaderAdmissions) {\n entities.leaderAdmissionAssignments = leaderAdmissionAssignmentsEntity;\n entities.leaderAdmissionDeliveries = leaderAdmissionDeliveriesEntity;\n entities.leaderAdmissionMutations = leaderAdmissionMutationsEntity;\n }\n if (includeNetworkPersonRegistry) {\n Object.assign(entities, networkPersonEntities);\n }\n if (includeNetworkCommercialReadModel) Object.assign(entities, networkCommercialEntities);\n const schema: DbSchema = { entities, links: {} };\n const rules: DbRules = {};\n for (const ns of Object.keys(entities)) {\n rules[ns] = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n }\n return { schema, rules };\n}\n","// Per-mode default CRM configs. Consumers pass their own via defineChapter's\n// `crm`; these are sensible starting points. Both modes share the canonical\n// people + businesses graph, while `chapter` additionally feeds the person\n// pipeline from applications through the operational package routes.\nimport type { CrmConfig } from \"@odla-ai/crm\";\nimport type { ChapterMode } from \"./types\";\n\nconst TEMPLATES: CrmConfig[\"templates\"] = {\n personal: {\n class: \"transactional\",\n vars: [\"firstName\", \"subject\", \"body\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\" },\n },\n announcement: {\n class: \"marketing\",\n vars: [\"firstName\", \"subject\", \"body\", \"unsubscribeUrl\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\\n\\n{{unsubscribeUrl}}\" },\n },\n};\n\nfunction personType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Person\",\n labelPlural: \"People\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n email: { type: \"email\", label: \"Email\" },\n firstName: { type: \"string\", label: \"First name\" },\n lastName: { type: \"string\", label: \"Last name\" },\n phone: { type: \"string\", label: \"Phone\" },\n state: { type: \"string\", label: \"State\", slot: \"s1\" },\n whoYouAre: { type: \"string\", label: \"Who they are\", slot: \"s2\" },\n referral: { type: \"string\", label: \"Referral source\", slot: \"s3\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n focus: { type: \"json\", label: \"Focus areas\" },\n message: { type: \"string\", label: \"Intro message\" },\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"paid_pending_vetting\", label: \"Paid, pending vetting\" },\n { id: \"call_scheduled\", label: \"Call scheduled\" },\n { id: \"interviewed\", label: \"Interviewed\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"declined\", label: \"Declined\" },\n { id: \"refunded\", label: \"Refunded\" },\n ],\n },\n facets: { identity: true, email: true, rank: \"manual\" },\n };\n}\n\nfunction companyType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Business\",\n labelPlural: \"Businesses\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n domain: { type: \"string\", label: \"Domain / website\", slot: \"s1\" },\n industry: { type: \"string\", label: \"Industry\", slot: \"s2\" },\n location: { type: \"string\", label: \"Location\", slot: \"s3\" },\n chapter: { type: \"string\", label: \"Chapter\", slot: \"s4\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n facets: { rank: \"manual\" },\n };\n}\n\n/** The default shared CRM graph: people (with the application/member pipeline)\n * plus businesses and the `works_at` relation, in both modes. */\nexport function defaultCrm(_mode: ChapterMode): CrmConfig {\n return {\n types: { person: personType(), company: companyType() },\n relations: { works_at: { from: \"person\", to: \"company\", label: \"works at\", reverseLabel: \"team\" } },\n templates: TEMPLATES,\n };\n}\n","// Build the seed `groups` row from a defineChapter config. This is the whole\n// per-chapter payload the worker reads at runtime (prices/policy/emails/\n// scheduling), so nothing brand-specific is hardcoded in the worker. createdAt\n// is stamped by the integration/seed layer, not here.\nimport type { ChapterConfig, ChapterScheduling } from \"./types\";\n\nconst DEFAULT_SCHEDULING: Required<Omit<ChapterScheduling, \"summaryTemplate\">> = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n};\n\nfunction defaultEmailTemplates(name: string): Record<string, { subject: string; text: string }> {\n const sign = `\\n\\nWarmly,\\n${name}`;\n return {\n adminNotification: {\n subject: `New application: {{firstName}} {{lastName}}`,\n text: `A new application came in for ${name}.\\n\\nName: {{firstName}} {{lastName}}\\nEmail: {{email}}`,\n },\n paymentConfirmation: {\n subject: `Welcome to ${name}`,\n text: `Hi {{firstName}},\\n\\nYour membership payment is confirmed. We'll be in touch to schedule your intro call.${sign}`,\n },\n prepEmail: {\n subject: `Your ${name} intro call`,\n text: `Hi {{firstName}},\\n\\nLooking forward to our call at {{meetingTime}}. {{meetingLink}}${sign}`,\n },\n onboardingInvite: {\n subject: `You're in, ${name}`,\n text: `Hi {{firstName}},\\n\\nWelcome to ${name}. Your member area is here: {{membersUrl}}${sign}`,\n },\n };\n}\n\n/** The `groups` row (attrs) for `chapter` mode. Missing config falls back to\n * empty copy / defaults, so a minimal config still provisions cleanly. */\nexport function buildGroupSeed(config: ChapterConfig): Record<string, unknown> {\n const prices = config.prices;\n const emails = config.emails;\n const policy = config.policy ?? {};\n const scheduling = {\n ...DEFAULT_SCHEDULING,\n ...(config.scheduling ?? {}),\n summaryTemplate:\n config.scheduling?.summaryTemplate ?? `${config.name}: introduction call with {{firstName}} {{lastName}}`,\n };\n const row: Record<string, unknown> = {\n id: config.id,\n name: config.name,\n standardPriceCents: prices?.standardCents ?? 0,\n foundingDiscountCents: prices?.foundingDiscountCents ?? 0,\n currency: prices?.currency ?? \"usd\",\n interval: prices?.interval ?? \"year\",\n notificationEmail: emails?.notificationEmail ?? \"\",\n replyTo: emails?.replyTo ?? emails?.notificationEmail ?? \"\",\n disclaimerText: policy.disclaimerText ?? \"\",\n refundPolicyText: policy.refundPolicyText ?? \"\",\n merchantDisclosureText: policy.merchantDisclosureText ?? \"\",\n trustCopy: policy.trustCopy ?? \"\",\n emailTemplates: emails?.templates ?? defaultEmailTemplates(config.name),\n schedulingJson: scheduling,\n };\n if (emails?.debugEmail) row.debugEmail = emails.debugEmail;\n if (policy.commitmentText) row.commitmentText = policy.commitmentText;\n if (policy.normsText) row.normsText = policy.normsText;\n return row;\n}\n","// Identity + authorization for a chapter/hub site — the pieces every membership\n// site needs and none should re-derive: a resolved role policy, role resolution\n// from a JWT claim, the privilege-escalation guard, and a tenant-vault read.\n// Everything here is pure or structural (no runtime @odla-ai/db import), so it is\n// trivially testable and the worker stays the only thing that talks to odla-db.\nimport type { ChapterAuth, ChapterMode, ResolvedAuth } from \"./types\";\n\n/**\n * Apply defaults + validate the auth config into a {@link ResolvedAuth}. Defaults\n * by mode: `chapter` → the `provisional/member/admin` claim ladder with the\n * `superAdmins` tier; `hub` → the `admins` allowlist table with no super tier.\n * Existing sites retain the legacy `superAdmins` table unless they explicitly\n * select protected odla user roles.\n * Throws at import on a bad policy.\n */\nexport function resolveAuth(mode: ChapterMode, auth: ChapterAuth | undefined): ResolvedAuth {\n const a = auth ?? {};\n const source = a.source ?? (mode === \"hub\" ? \"table\" : \"claim\");\n if (source !== \"claim\" && source !== \"table\") {\n throw new Error(`defineChapter.auth.source: must be \"claim\" or \"table\" — got ${JSON.stringify(a.source)}`);\n }\n const claim = a.claim ?? \"role\";\n if (typeof claim !== \"string\" || claim === \"\") {\n throw new Error(\"defineChapter.auth.claim: must be a non-empty string\");\n }\n const ladder = a.ladder ?? [\"provisional\", \"member\", \"admin\"];\n if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === \"string\" && r !== \"\")) {\n throw new Error(\"defineChapter.auth.ladder: must be a non-empty array of role strings\");\n }\n const adminRole = ladder[ladder.length - 1] as string;\n const superAdmins = a.superAdmins ?? source === \"claim\";\n const configuredSuperSource = a.superAdminSource ?? \"table\";\n if (configuredSuperSource !== \"table\" && configuredSuperSource !== \"odla\") {\n throw new Error(`defineChapter.auth.superAdminSource: must be \"table\" or \"odla\" — got ${JSON.stringify(a.superAdminSource)}`);\n }\n const superAdminSource = superAdmins ? configuredSuperSource : \"none\";\n return { source, claim, ladder, adminRole, superAdmins, superAdminSource };\n}\n\n/** The role from a verified JWT payload, per the resolved policy. An unknown or\n * missing claim falls back to the lowest ladder rung (fail safe, never admin). */\nexport function roleFromClaim(payload: Record<string, unknown>, auth: ResolvedAuth): string {\n const raw = payload[auth.claim];\n return typeof raw === \"string\" && auth.ladder.includes(raw) ? raw : (auth.ladder[0] as string);\n}\n\n/** Does a role meet the admin bar (the highest ladder rung)? */\nexport function isAdminRole(role: string, auth: ResolvedAuth): boolean {\n return role === auth.adminRole;\n}\n\n/** Inputs to the role-change guard — resolved by the caller (route) from the\n * identity provider + the configured Studio-managed super-admin authority. */\nexport interface RoleChangeContext {\n actorId: string;\n actorIsSuper: boolean;\n targetId: string;\n targetCurrentRole: string;\n targetIsSuper: boolean;\n newRole: string;\n auth: ResolvedAuth;\n}\n\n/** The result of {@link canChangeRole}: allow, or deny with the HTTP status +\n * message the route should return. */\nexport type GuardResult = { ok: true } | { ok: false; status: number; error: string };\n\n/**\n * The privilege-escalation guard — package-enforced so every site gets it and\n * none re-derives it. Denies: an out-of-ladder role; changing your own role;\n * touching a super-admin unless you are one; and (when a `superAdmins` tier\n * exists) creating or altering an admin unless you are a super-admin. Note the\n * super-admin tier itself is never writable here — it is set only in odla\n * Studio, either as a protected `$users.role` or in the legacy allowlist.\n */\nexport function canChangeRole(ctx: RoleChangeContext): GuardResult {\n const { auth } = ctx;\n if (!auth.ladder.includes(ctx.newRole)) {\n return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(\", \")}` };\n }\n if (ctx.actorId === ctx.targetId) {\n return { ok: false, status: 400, error: \"you cannot change your own role\" };\n }\n if (ctx.targetIsSuper && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: \"this person is a super-admin; their access is managed in odla Studio\" };\n }\n const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;\n if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };\n }\n return { ok: true };\n}\n\n/** Structural view of odla-db's tenant-vault read, so chapter takes no runtime\n * dependency on @odla-ai/db. The worker's admin client satisfies this. */\nexport interface SecretStore {\n secrets: { get(name: string): Promise<string> };\n}\n\n/**\n * Read a tenant-vault secret by name; `undefined` when it is absent or the vault\n * errors, so callers degrade gracefully (e.g. `paymentsReady: false`) rather than\n * throwing. Never logs the value.\n */\nexport async function getVaultSecret(db: SecretStore, name: string): Promise<string | undefined> {\n try {\n const value = await db.secrets.get(name);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","// The application status pipeline — config, not code. Which statuses exist, which\n// a member can book an intro call from, and which an admin can approve from\n// differ per site; the one invariant every site wants is that status never moves\n// backwards. All of this is pure + tested here; the worker enforces it on every\n// status write, and the CRM record.stage mirrors application.status (never the\n// reverse). Defaults reproduce the proven membership pipeline exactly.\nimport type { ChapterPipeline, ResolvedPipeline } from \"./types\";\n\nconst DEFAULT_STAGES = [\n \"submitted\",\n \"paid_pending_vetting\",\n \"call_scheduled\",\n \"interviewed\",\n \"approved\",\n \"declined\",\n \"refunded\",\n] as const;\nconst DEFAULT_BOOKABLE = [\"submitted\", \"paid_pending_vetting\", \"call_scheduled\"] as const;\nconst DEFAULT_APPROVABLE = [\"paid_pending_vetting\", \"call_scheduled\", \"interviewed\"] as const;\n\n/**\n * Apply defaults + validate the pipeline config. With no config, the complete\n * reference pipeline. With `stages` given but the subsets omitted, the subsets\n * default to empty (a site opts in to bookable/approvable states explicitly).\n * Throws at import on a bad pipeline (empty/duplicate stages, an initial or a\n * subset entry not on the ladder).\n */\nexport function resolvePipeline(p: ChapterPipeline | undefined): ResolvedPipeline {\n const usingDefaults = !p?.stages;\n const stages = p?.stages ?? [...DEFAULT_STAGES];\n if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === \"string\" && s !== \"\")) {\n throw new Error(\"defineChapter.pipeline.stages: must be a non-empty array of status strings\");\n }\n if (new Set(stages).size !== stages.length) {\n throw new Error(\"defineChapter.pipeline.stages: statuses must be unique\");\n }\n const initial = p?.initial ?? (stages[0] as string);\n if (!stages.includes(initial)) {\n throw new Error(`defineChapter.pipeline.initial: \"${initial}\" is not one of the stages`);\n }\n const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);\n const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);\n for (const [name, subset] of [\n [\"bookableFrom\", bookableFrom],\n [\"approvableFrom\", approvableFrom],\n ] as const) {\n for (const s of subset) {\n if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: \"${s}\" is not one of the stages`);\n }\n }\n return { stages, bookableFrom, approvableFrom, initial };\n}\n\n/** The ordinal of a status in the ladder, or -1 if unknown. */\nexport function stageIndex(status: string, p: ResolvedPipeline): number {\n return p.stages.indexOf(status);\n}\n\n/**\n * The status-never-moves-backwards invariant: a transition is allowed only when\n * both statuses are on the ladder and `to` is at or ahead of `from`. The worker\n * calls this before every status write; a violation is a 409, never a silent\n * downgrade.\n */\nexport function canTransition(from: string, to: string, p: ResolvedPipeline): boolean {\n const fi = p.stages.indexOf(from);\n const ti = p.stages.indexOf(to);\n return fi >= 0 && ti >= 0 && ti >= fi;\n}\n\n/** May an intro call be booked from this status? */\nexport function canBook(status: string, p: ResolvedPipeline): boolean {\n return p.bookableFrom.includes(status);\n}\n\n/** May an application be approved (→ member) from this status? */\nexport function canApprove(status: string, p: ResolvedPipeline): boolean {\n return p.approvableFrom.includes(status);\n}\n","import type { ChapterCopy } from \"./copy.js\";\n\nexport const DEFAULT_ADMIN_COPY: ChapterCopy[\"admin\"] = {\n auth: {\n checking: \"Checking access…\",\n notAuthorized: \"Not authorized\",\n accountNotAuthorized: \"{account} isn't on the admin list.\",\n thisAccount: \"This account\",\n signOut: \"Sign out\",\n loading: \"Loading…\",\n signInNotConfigured: \"Sign-in not configured\",\n missingPublishableKey: \"No Clerk publishable key is set for this environment yet.\",\n noWorkspaces: \"No admin workspaces are configured.\",\n signInTagline: \"Admin sign-in, invite only\",\n },\n shell: {\n adminRole: \"admin\",\n adminConsole: \"Admin Console\",\n adminName: \"Admin\",\n navigationLabel: \"Admin navigation\",\n },\n workspaces: {\n dashboard: \"Dashboard\",\n overview: \"Overview\",\n billing: \"Billing\",\n people: \"People\",\n admission: \"Admission\",\n network: \"Network\",\n portfolio: \"Portfolio\",\n settings: \"Settings\",\n calendar: \"Calendar\",\n email: \"Email\",\n chapters: \"Chapters\",\n formations: \"Formation applications\",\n dealFlow: \"Deal flow\",\n dashboardViewsLabel: \"Dashboard views\",\n settingsViewsLabel: \"Settings views\",\n collectionsLabel: \"CRM collections\",\n portfolioViewsLabel: \"Portfolio views\",\n },\n dashboard: {\n loading: \"Loading dashboard…\",\n loadFailed: \"Couldn't load the dashboard\",\n upcomingCalls: \"Upcoming calls\",\n callsNeedAttention: \"{count} need attention\",\n noUpcomingCalls: \"No upcoming calls.\",\n drift: \"drift\",\n open: \"Open\",\n meet: \"Meet\",\n applications: \"Applications\",\n newMembers: \"New members\",\n newMembersUnavailable: \"Appears once billing is connected.\",\n revenueAdded: \"Revenue · annual run rate added\",\n revenue: \"Revenue\",\n revenueUnavailable: \"Appears once billing is connected.\",\n pipeline: \"Pipeline\",\n pipelineLabel: \"Membership pipeline\",\n thisWeek: \"+{count} this week\",\n noChange: \"no change\",\n activeMemberships: \"Active memberships\",\n annualRunRate: \"Annual run rate\",\n testMode: \"test mode\",\n },\n billing: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load billing\",\n notConfigured: \"Billing isn't configured. No Stripe key is vaulted for this group.\",\n active: \"Active\",\n annualized: \"Annualized\",\n renewingSoon: \"Renewing within 60 days\",\n pastDue: \"Past due\",\n subscriptions: \"Subscriptions\",\n testMode: \"Stripe test mode\",\n truncated: \"Showing the first 100 subscriptions. The list is truncated.\",\n name: \"Name\",\n email: \"Email\",\n application: \"Application\",\n subscription: \"Subscription\",\n cancelling: \"cancelling\",\n amount: \"Amount\",\n renews: \"Renews\",\n },\n availability: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load availability\",\n saved: \"Saved.\",\n title: \"Booking availability\",\n days: \"Days\",\n startHour: \"Start hour (0–24)\",\n endHour: \"End hour (0–24)\",\n slotMinutes: \"Slot length (minutes)\",\n minNoticeHours: \"Minimum notice (hours)\",\n windowDays: \"Booking window (days)\",\n timezone: \"Timezone\",\n summaryTemplate: \"Event summary template\",\n save: \"Save availability\",\n dayLabels: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n },\n email: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load email config\",\n saved: \"Saved.\",\n sent: \"Sent {template} to {address}{redirected}.\",\n testFailed: \"Test send did not deliver.\",\n delivery: \"Delivery\",\n notificationAddress: \"Notification address\",\n replyTo: \"Reply-to\",\n debugInbox: \"Debug inbox\",\n debugInboxHint: \"Non-production sends redirect here.\",\n sendTest: \"Send test\",\n enabled: \"Enabled\",\n subject: \"Subject\",\n body: \"Body\",\n save: \"Save changes\",\n sendLog: \"Send log\",\n sentColumn: \"Sent\",\n templateColumn: \"Template\",\n statusColumn: \"Status\",\n toColumn: \"To\",\n failed: \"failed\",\n redirected: \"redirected\",\n delivered: \"delivered\",\n },\n meetings: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load meetings\",\n cancelConfirm: \"Cancel this call? The calendar provider notifies the attendee.\",\n newStartPrompt: \"New start time (for example, 2026-08-01 14:00):\",\n parseFailed: \"Couldn't parse that time.\",\n agenda: \"Agenda\",\n empty: \"No meetings.\",\n unknown: \"(unknown)\",\n drift: \"drift\",\n meet: \"Meet\",\n reschedule: \"Reschedule\",\n cancel: \"Cancel\",\n },\n admission: {\n title: \"Interview decisions\",\n description: \"Local decisions override Parent decisions. Requiring an interview locally suppresses a Parent waiver for the same email.\",\n email: \"Email\",\n decision: \"Decision\",\n expires: \"Expires\",\n note: \"Internal note\",\n waive: \"Waive interview\",\n require: \"Require interview\",\n add: \"Add decision\",\n ledger: \"Effective grant ledger\",\n loading: \"Loading…\",\n consumed: \"consumed\",\n revoked: \"revoked\",\n expired: \"expired\",\n active: \"active\",\n local: \"local\",\n parent: \"Parent\",\n revoke: \"Revoke\",\n },\n network: {\n title: \"Share to a follower\",\n allowlistDescription: \"Sends the target's allowlisted fields. Its pipeline and account state remain local.\",\n sharing: \"Sharing…\",\n shareWith: \"Share with {target}\",\n shared: \"Shared with {target}.\",\n shareFailed: \"Could not share with {target}.\",\n deliveryFailed: \"Delivery failed.\",\n loadingRollup: \"Loading network overview…\",\n loadRollupFailed: \"Couldn't load the network overview\",\n overview: \"Network overview\",\n configuredFollowers: \"Configured followers\",\n reachableFollowers: \"Reachable followers\",\n recordsAcrossFollowers: \"Records across followers\",\n noFollowers: \"No follower sites are configured.\",\n followers: \"Followers\",\n available: \"available\",\n unavailable: \"unavailable\",\n transportReachable: \"transport reachable\",\n transportUnavailable: \"transport unavailable\",\n transportNotChecked: \"transport not checked\",\n bindingTransport: \"service binding {binding}\",\n urlTransport: \"public URL transport\",\n activeConfiguration: \"active configuration r{revision}\",\n noActiveConfiguration: \"no active managed configuration\",\n publicSiteAvailable: \"public site reachable\",\n publicSiteUnavailable: \"public site unavailable\",\n publicSiteNotChecked: \"public site not probed\",\n recordTotals: \"Portfolio records\",\n noRecordTotals: \"No aggregate records are available yet.\",\n },\n records: {\n workflowMissing: \"This record is not linked to an application workflow.\",\n comms: \"Comms\",\n commsHistory: \"Comms history\",\n scheduling: \"Scheduling\",\n billing: \"Billing\",\n notes: \"Notes\",\n access: \"Access\",\n sharing: \"Sharing\",\n lifecycle: \"Access & lifecycle\",\n role: \"Role\",\n superAdminHint: \"Super-admin, managed in odla Studio.\",\n noAccount: \"No linked account yet. The role is set once they sign in.\",\n approve: \"Approve\",\n refund: \"Refund\",\n approved: \"Approved.\",\n refunded: \"Refund issued.\",\n roleSet: \"Role set to {role}.\",\n messageSent: \"Message sent.\",\n messageNotSent: \"Message was not sent.\",\n loadingTemplates: \"Loading templates…\",\n template: \"Template\",\n chooseTemplate: \"Choose a template…\",\n sending: \"Sending…\",\n send: \"Send\",\n noMessages: \"No messages recorded.\",\n message: \"Message\",\n newStartPrompt: \"New start time:\",\n parseFailed: \"Couldn't parse that time.\",\n cancelConfirm: \"Cancel this call?\",\n callCancelled: \"Call cancelled.\",\n callRescheduled: \"Call rescheduled.\",\n noApplication: \"No application is linked to this record.\",\n loadingMeetings: \"Loading meetings…\",\n noMeetings: \"No meetings recorded.\",\n joinMeeting: \"Join meeting\",\n openCalendar: \"Open calendar\",\n reschedule: \"Reschedule\",\n cancel: \"Cancel\",\n },\n};\n","import type { ChapterCopy } from \"./copy.js\";\n\nexport const DEFAULT_COMMON_COPY: ChapterCopy[\"common\"] = {\n loading: \"Loading…\",\n saved: \"Saved.\",\n unknown: \"(unknown)\",\n};\n\nexport const DEFAULT_JOIN_COPY: ChapterCopy[\"join\"] = {\n form: {\n submit: \"Submit application\",\n submitting: \"Submitting…\",\n submitFailed: \"Your application could not be submitted.\",\n unexpectedFailure: \"Something went wrong. Please try again.\",\n },\n booking: {\n unavailable: \"Scheduling is briefly unavailable. We'll reach out by email to arrange your call.\",\n loadFailed: \"Times are briefly unavailable. Please try again.\",\n slotTaken: \"That time was just taken. Here are the current openings.\",\n failed: \"The booking could not be completed.\",\n loading: \"Loading available times…\",\n book: \"Book this time\",\n booking: \"Booking…\",\n },\n payment: {\n setupFailed: \"Payment could not be set up. Please try again.\",\n preparing: \"Preparing secure payment…\",\n pending: \"Confirming your payment…\",\n processing: \"Processing…\",\n payAndContinue: \"Pay and continue\",\n incomplete: \"The payment did not complete. Please try again.\",\n consent: \"I have read and agree to the pricing and refund policy above.\",\n },\n done: {\n label: \"You're booked\",\n calendarInvite: \"A calendar invitation with the video call link is on its way to your email.\",\n memberArea: \"Go to your member area\",\n },\n accepted: {\n label: \"You're approved\",\n body: \"Your membership is approved. No introduction call is required.\",\n },\n gift: {\n chooseSelf: \"Buy membership for myself\",\n optionsLabel: \"Or give access to someone else\",\n label: \"Your gift code\",\n body: \"Share this one-time code with the recipient. It becomes active after payment is confirmed.\",\n save: \"Save it now. For security, this code is shown only once.\",\n rotate: \"Generate a new code\",\n rotateFailed: \"A new code could not be generated.\",\n claimTitle: \"Have a gift code?\",\n claimBody: \"Use it here instead of paying by card.\",\n code: \"One-time code\",\n redeem: \"Use gift code\",\n redeemed: \"Gift code applied.\",\n redeemFailed: \"The code is invalid, unavailable, or does not match this membership.\",\n },\n};\n\nexport const DEFAULT_MEMBERS_COPY: ChapterCopy[\"members\"] = {\n loadFailed: \"Sign in is briefly unavailable. Please refresh.\",\n account: {\n signOut: \"Sign out\",\n adminConsole: \"Admin console\",\n },\n provisional: {\n cardLabel: \"Your Application\",\n applicationNeeded: \"One step remains\",\n applicationNeededBody: \"Your account is ready, and the application that completes it takes a few minutes.\",\n apply: \"Apply for membership\",\n refunded: \"Membership refunded\",\n refundedBody: \"Your fee has been refunded in full and your membership is canceled.\",\n active: \"Your membership is active.\",\n renews: \"Your membership is active and renews {date}.\",\n introductionCall: \"Your introduction call\",\n calendarInvite: \"A calendar invitation with the video call link is in your email.\",\n joinCall: \"Join the video call\",\n bookCall: \"Book your introduction call\",\n bookCallBody: \"Your application is in. Choose a time below, and a calendar invitation will reach your email.\",\n chooseTime: \"Choose a time\",\n },\n full: {\n welcome: \"Welcome back.\",\n },\n gifts: {\n title: \"Give access\",\n body: \"Purchase access for someone else and share the one-time claim code.\",\n noneAvailable: \"No gift options are available right now.\",\n paid: \"Payment submitted. Save the code below while it is visible.\",\n saveCode: \"This code is shown once. Save it before leaving this page.\",\n purchases: \"Your gifts\",\n noPurchases: \"No gift purchases yet.\",\n pending: \"Pending\",\n redeemed: \"Redeemed\",\n expired: \"Expired\",\n revoked: \"Revoked\",\n rotate: \"Rotate code\",\n rotated: \"A new code was generated. Save it now.\",\n rotateFailed: \"The code could not be rotated.\",\n redeemTitle: \"Redeem a gift\",\n code: \"One-time code\",\n redeem: \"Redeem\",\n redeemFailed: \"The code is invalid or unavailable.\",\n },\n reschedule: {\n changeTime: \"Change your time\",\n unavailable: \"Scheduling is briefly unavailable. We'll reach out by email to arrange your call.\",\n loadFailed: \"Times are briefly unavailable. Please try again.\",\n slotGone: \"That time is no longer available. Please pick another.\",\n loading: \"Loading available times…\",\n noTimes: \"No open times right now. Please check back soon.\",\n rescheduling: \"Rescheduling…\",\n keepTime: \"Keep my current time\",\n },\n};\n","import { DEFAULT_ADMIN_COPY } from \"./copy-defaults-admin.js\";\nimport {\n DEFAULT_COMMON_COPY,\n DEFAULT_JOIN_COPY,\n DEFAULT_MEMBERS_COPY,\n} from \"./copy-defaults.js\";\nimport type { ChapterCopy, ChapterCopyInput } from \"./copy.js\";\n\n/** Complete default language resolved beneath partial Chapter copy overrides. */\nexport const DEFAULT_CHAPTER_COPY: ChapterCopy = {\n common: DEFAULT_COMMON_COPY,\n join: DEFAULT_JOIN_COPY,\n members: DEFAULT_MEMBERS_COPY,\n admin: DEFAULT_ADMIN_COPY,\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nfunction mergeCopy<T>(base: T, input: unknown, path: string): T {\n if (typeof base === \"string\") {\n if (input === undefined) return base;\n if (typeof input !== \"string\") throw new Error(`${path}: must be a string`);\n return input as T;\n }\n if (Array.isArray(base)) {\n if (input === undefined) return [...base] as T;\n if (!Array.isArray(input) || !input.every((item) => typeof item === \"string\")) {\n throw new Error(`${path}: must be an array of strings`);\n }\n return [...input] as T;\n }\n if (!isObject(base)) return base;\n if (input !== undefined && !isObject(input)) throw new Error(`${path}: must be an object`);\n const overrides = input as Record<string, unknown> | undefined;\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(base)) {\n result[key] = mergeCopy(value, overrides?.[key], `${path}.${key}`);\n }\n return result as T;\n}\n\n/** Resolve a partial copy contract and validate every supplied leaf. */\nexport function resolveChapterCopy(input?: ChapterCopyInput): ChapterCopy {\n return mergeCopy(DEFAULT_CHAPTER_COPY, input, \"defineChapter.copy\");\n}\n\n/** Replace `{name}` placeholders without interpreting the resulting text as HTML. */\nexport function formatChapterCopy(\n template: string,\n values: Readonly<Record<string, string | number>>,\n): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, key: string) =>\n Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : match,\n );\n}\n","import type { Crm, FieldConditions, FieldDef, FieldType } from \"@odla-ai/crm\";\nimport type { Chapter, ResolvedApplication, ResolvedLeaderFormation } from \"./types\";\n\n/** Current public schema version for Chapter flow-field contracts. */\nexport const CHAPTER_FLOW_FIELDS_SCHEMA_VERSION = 1 as const;\n\n/** Configurable Chapter intake journeys that publish field contracts. */\nexport type ChapterFieldFlow = \"join\" | \"formation\";\n\n/** Email comparison policy advertised by an email field. */\nexport type ChapterEmailIdentity = \"literal\";\n\n/**\n * One effective field in a Chapter intake journey.\n *\n * IDs, value types, and options come from the follower-declared schema. A hub\n * or CMS may select, order, and configure only those declared fields; it cannot\n * use this presentation document to add storage or widen follower authority.\n */\nexport interface ChapterFlowField {\n id: string;\n label: string;\n type: FieldType;\n required: boolean;\n order: number;\n maxLength?: number;\n options?: readonly string[];\n conditions?: FieldConditions;\n /** Present only for an email identity field. Aliases such as `+tag` remain significant. */\n emailIdentity?: ChapterEmailIdentity;\n}\n\n/** Ordered, versioned effective field state for one Chapter journey. */\nexport interface ChapterFlowFieldContract {\n schemaVersion: typeof CHAPTER_FLOW_FIELDS_SCHEMA_VERSION;\n flow: ChapterFieldFlow;\n fields: readonly ChapterFlowField[];\n}\n\nconst APPLICATION_LABELS: Readonly<Record<string, string>> = {\n firstName: \"First name\",\n lastName: \"Last name\",\n email: \"Email\",\n referral: \"Referral source\",\n referralName: \"Referral name\",\n whoYouAre: \"Who you are\",\n linkedin: \"LinkedIn\",\n message: \"Intro message\",\n phone: \"Phone\",\n state: \"State\",\n};\n\nfunction humanize(id: string): string {\n const text = id.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/[_-]+/g, \" \").trim();\n return text ? `${text[0]!.toUpperCase()}${text.slice(1)}` : id;\n}\n\nfunction applicationDefs(chapter: Chapter): Record<string, FieldDef> {\n try {\n return chapter.crm.type(\"person\").fields;\n } catch {\n return {};\n }\n}\n\nfunction applicationType(id: string, def: FieldDef | undefined): FieldType {\n // Application rows accept configurable strings. Preserve the richer\n // string-like CRM hints without claiming that a numeric/date/json CRM field\n // changes the application storage contract.\n if (def && [\"string\", \"email\", \"url\", \"enum\"].includes(def.type)) return def.type;\n return id === \"email\" ? \"email\" : id === \"linkedin\" ? \"url\" : \"string\";\n}\n\n/** Resolve the exact ordered fields accepted by the membership application flow. */\nexport function applicationFlowFields(\n chapter: Chapter,\n application: ResolvedApplication = chapter.application,\n): ChapterFlowField[] {\n const defs = applicationDefs(chapter);\n return [...application.required, ...application.optional].map((id, order) => {\n const def = defs[id];\n const conditions = application.conditions[id];\n const type = applicationType(id, def);\n return {\n id,\n label: def?.label ?? APPLICATION_LABELS[id] ?? humanize(id),\n type,\n required: application.required.includes(id),\n order,\n maxLength: application.maxLen[id] ?? application.defaultMaxLen,\n ...(type === \"enum\" && def?.options ? { options: [...def.options] } : {}),\n ...(conditions ? { conditions: { ...conditions } } : {}),\n ...(type === \"email\" ? { emailIdentity: \"literal\" as const } : {}),\n };\n });\n}\n\n/** Common resolver retained separately so the legacy formationFields helper cannot drift. */\nexport function resolveFormationFlowFields(\n crm: Crm,\n formation: ResolvedLeaderFormation,\n): ChapterFlowField[] {\n if (!formation.enabled) return [];\n const def = crm.type(formation.type);\n return [...formation.required, ...formation.optional].map((id, order) => {\n const field = def.fields[id]!;\n return {\n id,\n label: field.label ?? humanize(id),\n type: field.type,\n required: formation.required.includes(id),\n order,\n maxLength: formation.maxLen[id] ?? formation.defaultMaxLen,\n ...(field.options ? { options: [...field.options] } : {}),\n ...(id === def.emailField || field.type === \"email\" ? { emailIdentity: \"literal\" as const } : {}),\n };\n });\n}\n\n/** Resolve the exact ordered fields accepted by the chapter-formation flow. */\nexport function formationFlowFields(\n chapter: Chapter,\n formation: ResolvedLeaderFormation = chapter.formation,\n): ChapterFlowField[] {\n return resolveFormationFlowFields(chapter.crm, formation);\n}\n\n/**\n * Build the public field contract consumed by follower forms and CMS previews.\n * The optional application is the already-authorized effective selection from\n * signup control; it never expands the follower's declared application schema.\n */\nexport function chapterFlowFieldContract(\n chapter: Chapter,\n flow: ChapterFieldFlow,\n application: ResolvedApplication = chapter.application,\n): ChapterFlowFieldContract {\n return {\n schemaVersion: CHAPTER_FLOW_FIELDS_SCHEMA_VERSION,\n flow,\n fields: flow === \"join\"\n ? applicationFlowFields(chapter, application)\n : formationFlowFields(chapter),\n };\n}\n","import type { Crm } from \"@odla-ai/crm\";\nimport type { LeaderFormationConfig, ResolvedLeaderFormation } from \"./types\";\nimport { resolveFormationFlowFields } from \"./flow-fields\";\n\nconst DEFAULT_REQUIRED = [\"name\", \"email\", \"location\", \"thesis\"];\nconst DEFAULT_OPTIONAL = [\"proposedChapter\", \"experience\", \"collaborators\"];\n\n/** Resolve and validate the public chapter-formation intake contract. */\nexport function resolveLeaderFormation(\n input: LeaderFormationConfig | undefined,\n crm: Crm,\n): ResolvedLeaderFormation {\n const type = input?.type ?? \"chapter_application\";\n if (!input) {\n return {\n enabled: false,\n type,\n required: [],\n optional: [],\n maxLen: {},\n defaultMaxLen: 4000,\n bodyCap: 32768,\n };\n }\n const def = crm.config.types[type];\n if (!def) throw new Error(`defineChapter.formation.type: unknown CRM type \"${type}\"`);\n const required = input.required ?? (type === \"chapter_application\" ? DEFAULT_REQUIRED : []);\n const optional = input.optional ?? (type === \"chapter_application\" ? DEFAULT_OPTIONAL : []);\n for (const [name, values] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(values) || !values.every((field) => typeof field === \"string\" && field !== \"\")) {\n throw new Error(`defineChapter.formation.${name}: must be an array of field-name strings`);\n }\n }\n const duplicates = [...required, ...optional].filter((field, index, fields) => fields.indexOf(field) !== index);\n if (duplicates.length) throw new Error(`defineChapter.formation: duplicate public field \"${duplicates[0]}\"`);\n const unknown = [...required, ...optional].filter((field) => !def.fields[field]);\n if (unknown.length) throw new Error(`defineChapter.formation: field \"${unknown[0]}\" is not declared on CRM type \"${type}\"`);\n const missingRequired = Object.entries(def.fields)\n .filter(([, field]) => field.required)\n .map(([field]) => field)\n .filter((field) => !required.includes(field));\n if (missingRequired.length) {\n throw new Error(`defineChapter.formation.required: must include required CRM field \"${missingRequired[0]}\"`);\n }\n const unsupportedRequired = required.find((field) =>\n ![\"string\", \"email\", \"url\", \"enum\"].includes(def.fields[field]!.type));\n if (unsupportedRequired) {\n throw new Error(`defineChapter.formation.required: field \"${unsupportedRequired}\" must be string-like`);\n }\n if (required.length === 0) throw new Error(\"defineChapter.formation.required: must not be empty\");\n const defaultMaxLen = input.defaultMaxLen ?? 4000;\n const bodyCap = input.bodyCap ?? 32768;\n if (!Number.isSafeInteger(defaultMaxLen) || defaultMaxLen < 1 || defaultMaxLen > 32768) {\n throw new Error(\"defineChapter.formation.defaultMaxLen: must be an integer from 1 to 32768\");\n }\n if (!Number.isSafeInteger(bodyCap) || bodyCap < 1024 || bodyCap > 131072) {\n throw new Error(\"defineChapter.formation.bodyCap: must be an integer from 1024 to 131072\");\n }\n for (const [field, cap] of Object.entries(input.maxLen ?? {})) {\n if (![...required, ...optional].includes(field) || !Number.isSafeInteger(cap) || cap < 1 || cap > 32768) {\n throw new Error(`defineChapter.formation.maxLen.${field}: must name a public field and be an integer from 1 to 32768`);\n }\n }\n return {\n enabled: true,\n type,\n required,\n optional,\n maxLen: input.maxLen ?? {},\n defaultMaxLen,\n bodyCap,\n };\n}\n\n/** Public, presentational field metadata for a host-owned intake form. */\nexport function formationFields(\n crm: Crm,\n formation: ResolvedLeaderFormation,\n): import(\"./flow-fields\").ChapterFlowField[] {\n return resolveFormationFlowFields(crm, formation);\n}\n","import type { Crm, FieldType, TypeSummary } from \"@odla-ai/crm\";\nimport type { ChapterDb } from \"./types\";\n\n/** The contact data the hub shares for a prospect. `hubRecordId` is the stable\n * idempotency key (the hub's crm_record id). */\nexport interface SharedPerson {\n email: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n hubRecordId: string;\n}\n\n/** Convenience wire shape for sharing the default `company` CRM type. */\nexport interface SharedBusiness {\n type: \"company\";\n name: string;\n domain?: string;\n industry?: string;\n location?: string;\n linkedin?: string;\n notes?: string;\n hubRecordId: string;\n}\n\n/** Versioned generic wire shape. `input` is validated against the follower's\n * own CRM type before any write, so a leader cannot smuggle undeclared fields. */\nexport interface SharedRecordV1 {\n version: 1;\n type: string;\n hubRecordId: string;\n input: Record<string, unknown>;\n}\n\n/** Current wire envelope. `source.siteId` prevents records from two leaders\n * with the same local id from colliding in a follower CRM. */\nexport interface SharedRecordV2 {\n version: 2;\n source: { siteId: string; recordId: string };\n type: string;\n input: Record<string, unknown>;\n}\n\n/** Accepted generic share envelopes. Version 1 remains readable for migration. */\nexport type SharedRecord = SharedRecordV1 | SharedRecordV2;\n\n/** Privacy-bounded follower status returned to an authenticated leader. */\nexport interface NetworkSnapshot {\n version: 1;\n site: { id: string; name: string; mode: string };\n generatedAt: number;\n /** Active follower-owned receipt for the managed signup configuration.\n * Optional on the wire so a newer leader can still inspect an older follower. */\n configuration?: { activeRevision: number | null; digest?: string };\n types: TypeSummary[];\n}\n\n/** Server-side route used for the signed follower snapshot. `reachable: null`\n * means the request could not be attempted (for example, a missing edge secret). */\nexport interface NetworkTargetTransportStatus {\n kind: \"binding\" | \"url\";\n binding?: string;\n reachable: boolean | null;\n error?: {\n code: \"binding_unavailable\" | \"binding_request_failed\" | \"url_request_failed\" | \"edge_secret_missing\";\n message: string;\n };\n}\n\n/** One configured target's latest live result in a leader rollup. */\nexport interface NetworkRollupTarget {\n id: string;\n name: string;\n url: string;\n available: boolean;\n /** Signed snapshot transport; independent of public-origin availability. */\n transport: NetworkTargetTransportStatus;\n /** Last active managed configuration reported by the authenticated follower. */\n configuration: { activeRevision: number | null; digest?: string };\n /** `null` when a service binding was authoritative and the public origin was\n * deliberately not probed. */\n publicSite: { available: boolean | null };\n generatedAt?: number;\n types?: TypeSummary[];\n error?: string;\n}\n\n/** Cross-target totals returned to the local leader admin. */\nexport interface NetworkRollup {\n configured: number;\n available: number;\n totalRecords: number;\n types: Array<{ type: string; total: number; stages: Record<string, number> }>;\n targets: NetworkRollupTarget[];\n}\n\n/** Privacy-bounded CRM record returned by a follower to one configured,\n * authenticated reader. */\nexport interface NetworkRecord {\n id: string;\n type: string;\n name: string;\n stage?: string;\n fields: Record<string, unknown>;\n createdAt: number;\n updatedAt: number;\n /** Optimistic concurrency token authored by the follower. */\n revision: number;\n /** Follower-authored edit contract. Omitted when this edge is read-only. */\n edit?: NetworkRecordEdit;\n}\n\n/** One follower CRM field a leader may patch. */\nexport interface NetworkEditableField {\n id: string;\n label: string;\n type: FieldType;\n required: boolean;\n options?: readonly string[];\n}\n\n/** One follower-authoritative lifecycle destination currently allowed. */\nexport interface NetworkStageTransition {\n id: string;\n label: string;\n}\n\n/** Edit metadata computed from the follower schema, pipeline, and record. */\nexport interface NetworkRecordEdit {\n fields: NetworkEditableField[];\n allowedStages: NetworkStageTransition[];\n}\n\n/** Signed follower mutation dispatched by a leader admin. Exactly one of\n * `fields` or `stage` is present. */\nexport interface NetworkRecordMutation {\n type: string;\n expectedRevision: number;\n expectedStage?: string | null;\n mutationId: string;\n fields?: Record<string, unknown>;\n stage?: string;\n actor: { id: string; email?: string };\n}\n\n/** Successful follower mutation response. */\nexport interface NetworkRecordMutationResult {\n version: 1;\n site: { id: string; name: string };\n record: NetworkRecord;\n duplicate: boolean;\n}\n\n/** One bounded, offset-paged follower record window. */\nexport interface NetworkRecordPage {\n version: 1;\n site: { id: string; name: string };\n type: string;\n records: NetworkRecord[];\n total: number;\n limit: number;\n offset: number;\n /** Follower-authored options that may safely be used for this type. Older\n * followers omit this, so leaders must not offer source-side filters unless\n * the capability is present. */\n filters?: {\n stages: Array<{ id: string; label: string }>;\n sorts: Array<{ id: NetworkRecordSort; label: string }>;\n };\n /** Normalized query the follower actually applied. A leader checks this\n * echo before presenting filtered results, preventing an older follower\n * from silently ignoring newer query parameters. */\n appliedQuery?: {\n stage?: string;\n sort: NetworkRecordSort;\n };\n}\n\n/** Bounded source-side ordering supported by the federated record route. */\nexport type NetworkRecordSort = \"updated_desc\" | \"updated_asc\" | \"name_asc\" | \"name_desc\";\n\n/** Leader-private note attached to a stable remote record identity. */\nexport interface NetworkRecordNote {\n id: string;\n targetId: string;\n recordType: string;\n recordId: string;\n body: string;\n authorId: string;\n authorEmail?: string;\n createdAt: number;\n}\n\n/** A note deliberately shared across the federation edge and stored in the\n * follower CRM activity feed. Unlike NetworkRecordNote, this is visible to\n * the follower's own CRM admins. */\nexport interface NetworkSharedNote {\n id: string;\n sourceId: string;\n recordType: string;\n recordId: string;\n body: string;\n createdAt: number;\n}\n\nexport interface NormalizedSharedRecord {\n version: 1 | 2;\n sourceId: string;\n sourceRecordId: string;\n type: string;\n input: Record<string, unknown>;\n}\n\n/** Dependencies for applying a shared projection. */\nexport interface ProjectionDeps {\n crm: Crm;\n db: ChapterDb;\n now: () => number;\n newId: () => string;\n}\n\n/** Safe defaults when a target does not declare an explicit field allowlist. */\nexport const DEFAULT_SHARE_FIELDS: Readonly<Record<string, readonly string[]>> = {\n person: [\"name\", \"email\", \"firstName\", \"lastName\", \"phone\", \"linkedin\"],\n company: [\"name\", \"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"],\n};\n","import type { Crm } from \"@odla-ai/crm\";\nimport type {\n ChapterConfig,\n ResolvedNetwork,\n ResolvedNetworkReader,\n ResolvedNetworkTarget,\n} from \"./types\";\nimport { DEFAULT_SHARE_FIELDS } from \"./network-contract\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst FIELD = /^[a-z][a-zA-Z0-9_]*$/;\nconst BINDING = /^[A-Z][A-Z0-9_]{0,127}$/;\n\nfunction validateSharedNotes(opts: {\n path: string;\n values: readonly string[];\n crm: Crm;\n fields?: Record<string, readonly string[]>;\n}) {\n const duplicate = opts.values.some((type, index) => opts.values.indexOf(type) !== index);\n const invalid = opts.values.some((type) =>\n !FIELD.test(type) || !opts.crm.config.types[type] || (opts.fields ? !opts.fields[type] : false));\n if (duplicate || invalid) {\n throw new Error(`${opts.path}: must contain unique CRM types allowed by fields`);\n }\n}\n\nfunction validateEditableFields(opts: {\n path: string;\n values: Record<string, readonly string[]>;\n crm: Crm;\n readable?: Record<string, readonly string[]>;\n}) {\n for (const [type, names] of Object.entries(opts.values)) {\n const readable = opts.readable?.[type];\n const def = opts.crm.config.types[type];\n const duplicate = names.some((name, index) => names.indexOf(name) !== index);\n const unknown = names.some((name) => !FIELD.test(name) || !def?.fields[name]);\n const hidden = opts.readable\n ? !readable || names.some((name) => !readable.includes(name))\n : false;\n if (!FIELD.test(type) || names.length === 0 || duplicate || !def || unknown || hidden) {\n throw new Error(\n `${opts.path}.${type}: must contain unique, readable fields declared on CRM type \"${type}\"`,\n );\n }\n }\n}\n\nfunction validateStageTransitions(opts: {\n path: string;\n values: readonly string[];\n crm: Crm;\n readable?: Record<string, readonly string[]>;\n}) {\n const duplicate = opts.values.some((type, index) => opts.values.indexOf(type) !== index);\n const invalid = opts.values.some((type) =>\n !FIELD.test(type) || !opts.crm.config.types[type]?.pipeline || (opts.readable ? !opts.readable[type] : false));\n if (duplicate || invalid) {\n throw new Error(`${opts.path}: must contain unique, readable CRM types with pipelines`);\n }\n}\n\nfunction validateAdmissionCapability(path: string, enabled: boolean | undefined, crm: Crm) {\n if (!enabled) return;\n const person = crm.config.types.person;\n if (!person?.emailField || person.fields[person.emailField]?.type !== \"email\") {\n throw new Error(`${path}: requires a CRM person type with an emailField`);\n }\n}\n\n/** Resolve the two-sided federation contract. Targets are leader-owned\n * outbound policy; readers are follower-owned disclosure/write policy. */\nexport function resolveNetwork(config: ChapterConfig, crm: Crm): ResolvedNetwork {\n const seen = new Set<string>();\n const targets: ResolvedNetworkTarget[] = [];\n for (const target of config.network?.targets ?? []) {\n if (!SLUG.test(target.id)) {\n throw new Error(`defineChapter.network.targets.id: must be a lowercase slug — got ${JSON.stringify(target.id)}`);\n }\n if (seen.has(target.id)) throw new Error(`defineChapter.network.targets: duplicate target \"${target.id}\"`);\n seen.add(target.id);\n let url: URL;\n try {\n url = new URL(target.url);\n } catch {\n throw new Error(`defineChapter.network.targets.${target.id}.url: must be an absolute URL`);\n }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"::1\";\n if (url.protocol !== \"https:\" && !(local && url.protocol === \"http:\")) {\n throw new Error(`defineChapter.network.targets.${target.id}.url: must use https (http is allowed only for localhost)`);\n }\n const fields = target.fields;\n for (const [type, names] of Object.entries(fields ?? {})) {\n if (!FIELD.test(type) || names.length === 0 || names.some((name) => !FIELD.test(name))) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: type and field names must be non-empty CRM identifiers`,\n );\n }\n const def = crm.config.types[type];\n if (!def) throw new Error(`defineChapter.network.targets.${target.id}.fields: unknown leader CRM type \"${type}\"`);\n const unknown = names.filter((field) => !def.fields[field]);\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: ${unknown.map((field) => `\"${field}\"`).join(\", \")} ` +\n \"not declared on the leader CRM type\",\n );\n }\n const nameField = def.nameField ?? \"name\";\n if (!names.includes(nameField)) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: must include required name field \"${nameField}\"`,\n );\n }\n }\n const secretName = target.secretName?.trim() || `network_share_${target.id.replaceAll(\"-\", \"_\")}`;\n if (!/^[a-zA-Z][a-zA-Z0-9_-]{1,127}$/.test(secretName)) {\n throw new Error(`defineChapter.network.targets.${target.id}.secretName: must be a vault-key identifier`);\n }\n const binding = target.binding?.trim();\n if (binding && !BINDING.test(binding)) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.binding: must be an uppercase Worker binding identifier`,\n );\n }\n const sharedNotes = target.sharedNotes ?? [];\n validateSharedNotes({\n path: `defineChapter.network.targets.${target.id}.sharedNotes`,\n values: sharedNotes,\n crm,\n fields,\n });\n const readableFields = fields ?? DEFAULT_SHARE_FIELDS;\n const editableFields = target.editableFields ?? {};\n validateEditableFields({\n path: `defineChapter.network.targets.${target.id}.editableFields`,\n values: editableFields,\n crm,\n readable: readableFields,\n });\n const stageTransitions = target.stageTransitions ?? [];\n validateStageTransitions({\n path: `defineChapter.network.targets.${target.id}.stageTransitions`,\n values: stageTransitions,\n crm,\n readable: readableFields,\n });\n validateAdmissionCapability(\n `defineChapter.network.targets.${target.id}.admissionGrants`,\n target.admissionGrants,\n crm,\n );\n targets.push({\n id: target.id,\n name: target.name?.trim() || target.id,\n url: url.origin,\n ...(binding ? { binding } : {}),\n secretName,\n ...(fields ? { fields } : {}),\n sharedNotes,\n editableFields,\n stageTransitions,\n ...(target.admissionGrants === true ? { admissionGrants: true } : {}),\n ...(target.commercialParity === true ? { commercialParity: true } : {}),\n });\n }\n const readerIds = new Set<string>();\n const readers: ResolvedNetworkReader[] = [];\n for (const reader of config.network?.readers ?? []) {\n if (!SLUG.test(reader.id)) {\n throw new Error(`defineChapter.network.readers.id: must be a lowercase slug — got ${JSON.stringify(reader.id)}`);\n }\n if (readerIds.has(reader.id)) {\n throw new Error(`defineChapter.network.readers: duplicate reader \"${reader.id}\"`);\n }\n readerIds.add(reader.id);\n const readerFields = reader.fields ?? {};\n const entries = Object.entries(readerFields);\n if (entries.length === 0 && !reader.admissionGrants && !reader.commercialParity) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields: at least one CRM type is required unless this is an admission-only or commercial-parity reader`,\n );\n }\n for (const [type, names] of entries) {\n if (!FIELD.test(type) || names.length === 0 || names.some((name) => !FIELD.test(name))) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: type and field names must be non-empty CRM identifiers`,\n );\n }\n const def = crm.config.types[type];\n if (!def) {\n throw new Error(`defineChapter.network.readers.${reader.id}.fields: unknown local CRM type \"${type}\"`);\n }\n const unknown = names.filter((field) => !def.fields[field]);\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: ` +\n `${unknown.map((field) => `\"${field}\"`).join(\", \")} not declared on the local CRM type`,\n );\n }\n const nameField = def.nameField ?? \"name\";\n if (!names.includes(nameField)) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: must include required name field \"${nameField}\"`,\n );\n }\n }\n const sharedNotes = reader.sharedNotes ?? [];\n validateSharedNotes({\n path: `defineChapter.network.readers.${reader.id}.sharedNotes`,\n values: sharedNotes,\n crm,\n fields: readerFields,\n });\n const editableFields = reader.editableFields ?? {};\n validateEditableFields({\n path: `defineChapter.network.readers.${reader.id}.editableFields`,\n values: editableFields,\n crm,\n readable: readerFields,\n });\n const stageTransitions = reader.stageTransitions ?? [];\n validateStageTransitions({\n path: `defineChapter.network.readers.${reader.id}.stageTransitions`,\n values: stageTransitions,\n crm,\n readable: readerFields,\n });\n validateAdmissionCapability(\n `defineChapter.network.readers.${reader.id}.admissionGrants`,\n reader.admissionGrants,\n crm,\n );\n readers.push({\n id: reader.id,\n fields: readerFields,\n sharedNotes,\n editableFields,\n stageTransitions,\n ...(reader.admissionGrants === true ? { admissionGrants: true } : {}),\n ...(reader.commercialParity === true ? { commercialParity: true } : {}),\n });\n }\n return { targets, readers };\n}\n","import type { ChapterMode } from \"./types\";\nimport type { ChapterNetworkPersonRegistry, ResolvedNetworkPersonRegistry } from \"./types-network-person\";\n\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/** Validate the opt-in, hub-only shadow Person registry. */\nexport function resolveNetworkPersonRegistry(\n mode: ChapterMode,\n input: ChapterNetworkPersonRegistry | undefined,\n targetIds: readonly string[],\n): ResolvedNetworkPersonRegistry | null {\n if (!input) return null;\n if (mode !== \"hub\") throw new Error(\"defineChapter.networkPersonRegistry: only hub mode may own network Person authority\");\n if (input.mode !== \"shadow\") throw new Error('defineChapter.networkPersonRegistry.mode: must be \"shadow\"');\n const chapterIds = input.chapterIds ? [...input.chapterIds] : [...targetIds];\n if (chapterIds.length === 0) throw new Error(\"defineChapter.networkPersonRegistry.chapterIds: at least one chapter is required\");\n if (new Set(chapterIds).size !== chapterIds.length || chapterIds.some((id) => !SLUG.test(id))) {\n throw new Error(\"defineChapter.networkPersonRegistry.chapterIds: expected distinct lowercase slugs\");\n }\n const unknown = chapterIds.filter((id) => !targetIds.includes(id));\n if (unknown.length) {\n throw new Error(`defineChapter.networkPersonRegistry.chapterIds: ${unknown.map((id) => `\"${id}\"`).join(\", \")} are not configured network targets`);\n }\n return { mode: \"shadow\", chapterIds };\n}\n","import type { ChapterMode } from \"./types\";\nimport type {\n ChapterNetworkCommercialReadModel,\n NetworkCommercialSource,\n ResolvedNetworkCommercialReadModel,\n} from \"./types-network-commercial\";\n\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst TOKEN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\n/** Stable, PII-free identity for one accepted Stripe partition. */\nexport function networkCommercialSourceKey(source: NetworkCommercialSource): string {\n return [source.stripeMode, source.appId, source.environment, source.dataEnvironment, source.runtime, source.chapterId].join(\":\");\n}\n\n/** Validate the opt-in hub-only commercial shadow. */\nexport function resolveNetworkCommercialReadModel(\n mode: ChapterMode,\n input: ChapterNetworkCommercialReadModel | undefined,\n targetIds: readonly string[],\n): ResolvedNetworkCommercialReadModel | null {\n if (!input) return null;\n if (mode !== \"hub\") throw new Error(\"defineChapter.networkCommercialReadModel: only hub mode may own the network commercial projection\");\n if (input.mode !== \"shadow\") throw new Error('defineChapter.networkCommercialReadModel.mode: must be \"shadow\"');\n if (!Array.isArray(input.sources) || input.sources.length === 0) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: at least one exact source is required\");\n }\n const sources = input.sources.map((source) => ({ ...source }));\n for (const source of sources) {\n if (!SLUG.test(source.appId) || !SLUG.test(source.chapterId) ||\n !TOKEN.test(source.environment) || !TOKEN.test(source.dataEnvironment) || !TOKEN.test(source.runtime) ||\n (source.stripeMode !== \"test\" && source.stripeMode !== \"live\")) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: every source requires valid app, chapter, environment, data-environment, runtime, and Stripe mode values\");\n }\n if (!targetIds.includes(source.chapterId)) {\n throw new Error(`defineChapter.networkCommercialReadModel.sources: chapter \"${source.chapterId}\" is not a configured network target`);\n }\n }\n if (new Set(sources.map(networkCommercialSourceKey)).size !== sources.length) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: exact source partitions must be distinct\");\n }\n return { mode: \"shadow\", sources };\n}\n","import type { ChapterSignupControl, ResolvedSignupControl } from \"./types-signup-control\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst SECRET_NAME = /^[a-z][a-z0-9_]{1,127}$/;\n\n/** Validate one deliberately separate signup-control edge. */\nexport function resolveSignupControl(\n input: ChapterSignupControl | undefined,\n): ResolvedSignupControl | null {\n if (!input) return null;\n if (!SLUG.test(input.sourceId)) {\n throw new Error(\"defineChapter.signupControl.sourceId: must be a lowercase app slug\");\n }\n if (input.stripeMode !== \"test\" && input.stripeMode !== \"live\") {\n throw new Error('defineChapter.signupControl.stripeMode: must be \"test\" or \"live\"');\n }\n const secretName = input.secretName?.trim() || \"signup_control_secret\";\n if (!SECRET_NAME.test(secretName)) {\n throw new Error(\"defineChapter.signupControl.secretName: must be a vault-key identifier\");\n }\n return { sourceId: input.sourceId, secretName, stripeMode: input.stripeMode };\n}\n","import type { ChapterMemberContent, ResolvedMemberContent } from \"./types-member-content\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst SECRET_NAME = /^[a-z][a-z0-9_]{1,127}$/;\n\n/** Validate the deliberately separate member-content authoring boundary. */\nexport function resolveMemberContent(input: ChapterMemberContent | undefined): ResolvedMemberContent | null {\n if (!input) return null;\n const parent = input.parent;\n if (parent && !SLUG.test(parent.sourceId)) {\n throw new Error(\"defineChapter.memberContent.parent.sourceId: must be a lowercase app slug\");\n }\n const secretName = parent?.secretName?.trim() || \"member_content_control_secret\";\n if (parent && !SECRET_NAME.test(secretName)) {\n throw new Error(\"defineChapter.memberContent.parent.secretName: must be a vault-key identifier\");\n }\n return {\n enabled: true,\n localAuthoring: input.localAuthoring !== false,\n parent: parent ? { sourceId: parent.sourceId, secretName } : null,\n };\n}\n","import type { ChapterMode, ResolvedNetwork } from \"./types\";\nimport type { ChapterBuilderLibrary, ResolvedBuilderLibrary } from \"./types-builder-library\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\n/** Validate the private Builder Library boundary against Chapter's existing\n * network peers. Builder Library never introduces a second edge credential. */\nexport function resolveBuilderLibrary(\n mode: ChapterMode,\n input: ChapterBuilderLibrary | undefined,\n network: ResolvedNetwork = { targets: [], readers: [] },\n): ResolvedBuilderLibrary | null {\n if (!input) return null;\n if (input.sources !== undefined && !Array.isArray(input.sources)) {\n throw new Error(\"defineChapter.builderLibrary.sources: must be an array\");\n }\n const seen = new Set<string>();\n const sources = (input.sources ?? []).map((source, index) => {\n if (!source || typeof source !== \"object\" || !SLUG.test(source.sourceId)) {\n throw new Error(`defineChapter.builderLibrary.sources[${index}].sourceId: must be a lowercase app slug`);\n }\n if (source.sourceId === \"built-not-found\" && mode === \"hub\") {\n throw new Error(`defineChapter.builderLibrary.sources[${index}]: a hub accepts Chapter sources, not itself`);\n }\n if (mode === \"chapter\" && source.sourceId !== \"built-not-found\") {\n throw new Error(`defineChapter.builderLibrary.sources[${index}]: Chapters may accept only the built-not-found source`);\n }\n if (seen.has(source.sourceId)) {\n throw new Error(`defineChapter.builderLibrary.sources: duplicate source \"${source.sourceId}\"`);\n }\n seen.add(source.sourceId);\n if (\"secretName\" in source) {\n throw new Error(\n `defineChapter.builderLibrary.sources[${index}].secretName: remove this field; Builder Library reuses the Chapter network edge`,\n );\n }\n const networkPeer = mode === \"hub\"\n ? network.targets.some((target) => target.id === source.sourceId)\n : network.readers.some((reader) => reader.id === source.sourceId);\n if (!networkPeer) {\n const side = mode === \"hub\" ? \"targets\" : \"readers\";\n throw new Error(\n `defineChapter.builderLibrary.sources[${index}]: \"${source.sourceId}\" must already be configured in network.${side}`,\n );\n }\n return { sourceId: source.sourceId };\n });\n return { enabled: true, localAuthoring: input.localAuthoring !== false, sources };\n}\n","import { networkCommercialSourceKey } from \"./config-network-commercial\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\nimport type { CommercialIdentity, NetworkCommercialException, NetworkCommercialFact, NetworkCommercialProjectedRow, NetworkCommercialProjection } from \"./types-network-commercial-projection\";\n\ntype Raw = Record<string, unknown>;\nconst raw = (value: unknown): Raw => value && typeof value === \"object\" && !Array.isArray(value) ? value as Raw : {};\nconst text = (value: unknown): string | undefined => typeof value === \"string\" && value.length > 0 && value.length <= 255 ? value : undefined;\nconst integer = (value: unknown): number | undefined => typeof value === \"number\" && Number.isSafeInteger(value) ? value : undefined;\nconst bool = (value: unknown): boolean | undefined => typeof value === \"boolean\" ? value : undefined;\nconst providerId = (value: unknown, prefix?: string): string | undefined => {\n const valueText = text(value);\n return valueText && (!prefix || valueText.startsWith(prefix)) ? valueText : undefined;\n};\n\nfunction metadataCandidates(object: Raw): Raw[] {\n const parent = raw(object.parent);\n const subscriptionDetails = raw(object.subscription_details);\n const parentSubscription = raw(parent.subscription_details);\n return [raw(object.metadata), raw(subscriptionDetails.metadata), raw(parentSubscription.metadata)];\n}\n\nfunction metadataValue(candidates: Raw[], key: string): string | undefined {\n return candidates.map((candidate) => text(candidate[key])).find(Boolean);\n}\n\nfunction refId(value: unknown, prefix: string): string | undefined {\n if (typeof value === \"string\") return providerId(value, prefix);\n return providerId(raw(value).id, prefix);\n}\n\nfunction subscriptionRef(object: Raw): string | undefined {\n return refId(object.subscription, \"sub_\")\n ?? refId(raw(object.subscription_details).subscription, \"sub_\")\n ?? refId(raw(raw(object.parent).subscription_details).subscription, \"sub_\");\n}\n\nfunction firstPrice(object: Raw): { priceId?: string; quantity?: number } {\n const data = raw(object.items).data;\n const item = Array.isArray(data) ? raw(data[0]) : {};\n const priceId = refId(item.price, \"price_\");\n const quantity = integer(item.quantity);\n return { ...(priceId ? { priceId } : {}), ...(quantity !== undefined ? { quantity } : {}) };\n}\n\n/** Reduce a verified Stripe event to a bounded, PII-free fact. */\nexport function normalizeNetworkCommercialStripeEvent(input: unknown, digest: string): NetworkCommercialFact {\n const event = raw(input);\n const eventId = providerId(event.id, \"evt_\") ?? \"\";\n const eventType = text(event.type) ?? \"\";\n const object = raw(raw(event.data).object);\n const objectId = providerId(object.id) ?? \"\";\n const candidates = metadataCandidates(object);\n const identity: CommercialIdentity = {};\n const identityKeys = {\n appId: \"odlaAppId\", chapterId: \"chapterId\", environment: \"odlaEnvironment\",\n dataEnvironment: \"odlaDataEnvironment\", runtime: \"odlaRuntime\",\n } as const;\n for (const [target, source] of Object.entries(identityKeys)) {\n const value = metadataValue(candidates, source);\n if (value) identity[target as keyof CommercialIdentity] = value;\n }\n let objectKind: NetworkCommercialFact[\"objectKind\"] = \"ignored\";\n if (eventType.startsWith(\"customer.subscription.\")) objectKind = \"subscription\";\n else if (eventType.startsWith(\"customer.\")) objectKind = \"customer\";\n else if (eventType.startsWith(\"invoice.\")) objectKind = \"invoice\";\n else if (eventType.startsWith(\"refund.\")) objectKind = \"refund\";\n else if (eventType === \"charge.refunded\") objectKind = \"refund\";\n\n const customerId = refId(object.customer, \"cus_\");\n const subscriptionId = objectKind === \"subscription\" ? providerId(objectId, \"sub_\") : subscriptionRef(object);\n const invoiceId = objectKind === \"invoice\" ? providerId(objectId, \"in_\") : refId(object.invoice, \"in_\");\n const chargeId = eventType === \"charge.refunded\" ? providerId(objectId, \"ch_\") : refId(object.charge, \"ch_\");\n const paymentIntentId = refId(object.payment_intent, \"pi_\");\n const price = firstPrice(object);\n const amountCents = integer(eventType === \"charge.refunded\" ? object.amount_refunded : object.amount);\n const currency = text(object.currency)?.toLowerCase();\n const status = text(object.status);\n return {\n eventId, digest, eventType, eventCreated: integer(event.created) ?? 0,\n livemode: event.livemode === true, objectKind, objectId, identity,\n ...(metadataValue(candidates, \"applicationId\") ? { applicationId: metadataValue(candidates, \"applicationId\") } : {}),\n ...(metadataValue(candidates, \"personId\") ? { personId: metadataValue(candidates, \"personId\") } : {}),\n ...(metadataValue(candidates, \"membershipId\") ? { membershipId: metadataValue(candidates, \"membershipId\") } : {}),\n ...(customerId ? { customerId } : {}), ...(subscriptionId ? { subscriptionId } : {}),\n ...(invoiceId ? { invoiceId } : {}), ...(chargeId ? { chargeId } : {}),\n ...(paymentIntentId ? { paymentIntentId } : {}), ...price,\n ...(status ? { status } : {}), ...(currency ? { currency } : {}),\n ...(amountCents !== undefined ? { amountCents } : {}),\n ...(integer(object.amount_paid) !== undefined ? { amountPaidCents: integer(object.amount_paid) } : {}),\n ...(integer(object.amount_remaining) !== undefined ? { amountRemainingCents: integer(object.amount_remaining) } : {}),\n ...(integer(object.current_period_start) !== undefined ? { currentPeriodStart: integer(object.current_period_start) } : {}),\n ...(integer(object.current_period_end) !== undefined ? { currentPeriodEnd: integer(object.current_period_end) } : {}),\n ...(bool(object.cancel_at_period_end) !== undefined ? { cancelAtPeriodEnd: bool(object.cancel_at_period_end) } : {}),\n };\n}\n\nconst identityFields = [\"appId\", \"chapterId\", \"environment\", \"dataEnvironment\", \"runtime\"] as const;\nfunction directSource(fact: NetworkCommercialFact, sources: readonly NetworkCommercialSource[]): NetworkCommercialSource | null | \"wrong\" {\n const mode = fact.livemode ? \"live\" : \"test\";\n const supplied = identityFields.filter((field) => fact.identity[field] !== undefined);\n const candidates = sources.filter((source) => source.stripeMode === mode && supplied.every((field) => source[field] === fact.identity[field]));\n if (supplied.length === identityFields.length) return candidates.length === 1 ? candidates[0]! : \"wrong\";\n if (supplied.length > 0 && candidates.length === 0) return \"wrong\";\n return null;\n}\n\nconst objectRefs = (fact: NetworkCommercialFact): string[] => [\n fact.customerId && `customer:${fact.customerId}`, fact.subscriptionId && `subscription:${fact.subscriptionId}`,\n fact.invoiceId && `invoice:${fact.invoiceId}`, fact.chargeId && `charge:${fact.chargeId}`,\n fact.paymentIntentId && `payment_intent:${fact.paymentIntentId}`,\n].filter((value): value is string => Boolean(value));\n\nfunction ownRef(fact: NetworkCommercialFact): string | null {\n if (!fact.objectId) return null;\n if (fact.objectKind === \"customer\") return `customer:${fact.objectId}`;\n if (fact.objectKind === \"subscription\") return `subscription:${fact.objectId}`;\n if (fact.objectKind === \"invoice\") return `invoice:${fact.objectId}`;\n if (fact.eventType.startsWith(\"refund.\")) return `refund:${fact.objectId}`;\n return fact.eventType === \"charge.refunded\" ? `charge:${fact.objectId}` : null;\n}\n\nconst order = (left: NetworkCommercialFact, right: NetworkCommercialFact) =>\n left.eventCreated - right.eventCreated || left.eventId.localeCompare(right.eventId);\n\n/** Deterministically rebuild the network commercial projection from its event log. */\nexport function projectNetworkCommercialEvents(\n input: readonly NetworkCommercialFact[], sources: readonly NetworkCommercialSource[],\n): NetworkCommercialProjection {\n const facts = [...input].sort(order);\n const exceptions: NetworkCommercialException[] = [];\n const unique: NetworkCommercialFact[] = [];\n const digests = new Map<string, string>();\n for (const fact of facts) {\n const prior = digests.get(fact.eventId);\n if (prior === undefined) { digests.set(fact.eventId, fact.digest); unique.push(fact); }\n else if (prior !== fact.digest) exceptions.push({ eventId: fact.eventId, kind: \"collision\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n }\n const assignments = new Map<string, NetworkCommercialSource>();\n const refs = new Map<string, Set<string>>();\n for (const fact of unique) {\n const direct = directSource(fact, sources);\n if (direct && direct !== \"wrong\") assignments.set(fact.eventId, direct);\n }\n let changed = true;\n while (changed) {\n changed = false;\n for (const fact of unique) {\n const assigned = assignments.get(fact.eventId);\n if (assigned) {\n const key = networkCommercialSourceKey(assigned);\n for (const ref of [...objectRefs(fact), ownRef(fact)].filter((value): value is string => Boolean(value))) {\n const keys = refs.get(ref) ?? new Set<string>();\n const before = keys.size;\n keys.add(key); refs.set(ref, keys);\n if (keys.size !== before) changed = true;\n }\n continue;\n }\n if (directSource(fact, sources) === \"wrong\") continue;\n const keys = new Set(objectRefs(fact).flatMap((ref) => [...(refs.get(ref) ?? [])]));\n if (keys.size !== 1) continue;\n const candidate = sources.find((source) => networkCommercialSourceKey(source) === [...keys][0]);\n if (candidate && directSource({ ...fact, identity: fact.identity }, [candidate]) !== \"wrong\") {\n assignments.set(fact.eventId, candidate); changed = true;\n }\n }\n }\n const latest = new Map<string, NetworkCommercialProjectedRow>();\n for (const fact of unique) {\n if (fact.objectKind === \"ignored\" || !fact.eventId || !fact.objectId) {\n exceptions.push({ eventId: fact.eventId, kind: \"unsupported\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n continue;\n }\n const source = assignments.get(fact.eventId);\n if (!source) {\n const direct = directSource(fact, sources);\n const keys = new Set(objectRefs(fact).flatMap((ref) => [...(refs.get(ref) ?? [])]));\n exceptions.push({ eventId: fact.eventId, kind: direct === \"wrong\" ? \"wrong_partition\" : keys.size > 1 ? \"ambiguous_partition\" : \"unmatched_partition\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n continue;\n }\n const row = { ...fact, sourceKey: networkCommercialSourceKey(source) };\n const key = `${fact.objectKind}:${fact.objectId}`;\n const prior = latest.get(key);\n if (!prior || order(prior, fact) <= 0) latest.set(key, row);\n }\n const rows = [...latest.values()];\n const customers = rows.filter((row) => row.objectKind === \"customer\");\n const subscriptions = rows.filter((row) => row.objectKind === \"subscription\");\n const invoices = rows.filter((row) => row.objectKind === \"invoice\");\n const refunds = rows.filter((row) => row.objectKind === \"refund\" && row.eventType.startsWith(\"refund.\"));\n for (const charge of rows.filter((row) => row.eventType === \"charge.refunded\")) {\n if (!refunds.some((refund) => refund.chargeId === charge.objectId)) {\n exceptions.push({ eventId: charge.eventId, kind: \"charge_refund_without_refund_object\", sourceKey: charge.sourceKey, detail: { eventType: charge.eventType, objectId: charge.objectId } });\n }\n }\n const totalsMap = new Map<string, { sourceKey: string; currency: string; paidCents: number; refundedCents: number; netCents: number }>();\n const add = (row: NetworkCommercialProjectedRow, field: \"paidCents\" | \"refundedCents\", amount: number) => {\n if (!row.currency) return;\n const key = `${row.sourceKey}:${row.currency}`;\n const total = totalsMap.get(key) ?? { sourceKey: row.sourceKey, currency: row.currency, paidCents: 0, refundedCents: 0, netCents: 0 };\n total[field] += amount; total.netCents = total.paidCents - total.refundedCents; totalsMap.set(key, total);\n };\n for (const row of invoices) add(row, \"paidCents\", row.amountPaidCents ?? 0);\n for (const row of refunds) add(row, \"refundedCents\", row.amountCents ?? 0);\n return { customers, subscriptions, invoices, refunds, exceptions, totals: [...totalsMap.values()].sort((a, b) => `${a.sourceKey}:${a.currency}`.localeCompare(`${b.sourceKey}:${b.currency}`)) };\n}\n","import type { StripeClient } from \"@odla-ai/stripe\";\nimport { normalizeNetworkCommercialStripeEvent, projectNetworkCommercialEvents } from \"./network-commercial\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\nimport type { NetworkCommercialProjectedRow, NetworkCommercialProjection } from \"./types-network-commercial-projection\";\n\ntype Raw = Record<string, unknown>;\n\ninterface ProviderPage { data?: unknown; has_more?: unknown }\n\nexport interface StripeObjectSnapshot {\n objects: Raw[];\n complete: boolean;\n}\n\nexport interface StripeCommercialReconciliation {\n ok: boolean;\n complete: boolean;\n ignoredObjects: number;\n exceptions: Array<{\n kind: \"missing_from_stripe\" | \"missing_from_shadow\" | \"object_mismatch\" | \"totals_mismatch\" | \"stripe_snapshot_truncated\";\n sourceKey?: string;\n objectKind?: string;\n providerId?: string;\n detail: Record<string, unknown>;\n }>;\n stripeTotals: NetworkCommercialProjection[\"totals\"];\n}\n\nconst asRaw = (value: unknown): Raw | null =>\n value && typeof value === \"object\" && !Array.isArray(value) ? value as Raw : null;\n\n/** Read a bounded current-object snapshot through the typed Stripe client. */\nexport async function listStripeObjects(\n client: StripeClient,\n path: string,\n params: Record<string, unknown> = {},\n maxPages = 20,\n): Promise<StripeObjectSnapshot> {\n const objects: Raw[] = [];\n let startingAfter: string | undefined;\n for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {\n const page = await client.request<ProviderPage>(\"GET\", path, {\n ...params, limit: 100, ...(startingAfter ? { starting_after: startingAfter } : {}),\n });\n if (!Array.isArray(page.data) || typeof page.has_more !== \"boolean\") {\n throw new Error(\"Stripe returned an invalid commercial list response\");\n }\n const rows = page.data.map(asRaw).filter((row): row is Raw => row !== null);\n if (rows.length !== page.data.length) throw new Error(\"Stripe returned a malformed commercial object\");\n objects.push(...rows);\n if (!page.has_more) return { objects, complete: true };\n const cursor = rows.at(-1)?.id;\n if (typeof cursor !== \"string\" || !cursor) throw new Error(\"Stripe pagination did not provide a cursor\");\n startingAfter = cursor;\n }\n return { objects, complete: false };\n}\n\nfunction facts(\n snapshots: { customers: StripeObjectSnapshot; subscriptions: StripeObjectSnapshot; invoices: StripeObjectSnapshot; refunds: StripeObjectSnapshot },\n) {\n const groups = [\n [\"customer.updated\", snapshots.customers.objects],\n [\"customer.subscription.updated\", snapshots.subscriptions.objects],\n [\"invoice.updated\", snapshots.invoices.objects],\n [\"refund.updated\", snapshots.refunds.objects],\n ] as const;\n return groups.flatMap(([eventType, objects]) => objects.map((object) => {\n const id = typeof object.id === \"string\" ? object.id : \"invalid\";\n return normalizeNetworkCommercialStripeEvent({\n id: `evt_snapshot_${eventType.replaceAll(\".\", \"_\")}_${id}`,\n type: eventType,\n created: typeof object.created === \"number\" ? object.created : 0,\n livemode: object.livemode === true,\n data: { object },\n }, `stripe-snapshot:${eventType}:${id}`);\n }));\n}\n\nconst selected = (row: NetworkCommercialProjectedRow) => ({\n status: row.status ?? null,\n currency: row.currency ?? null,\n amountCents: row.amountCents ?? null,\n amountPaidCents: row.amountPaidCents ?? null,\n amountRemainingCents: row.amountRemainingCents ?? null,\n customerId: row.customerId ?? null,\n subscriptionId: row.subscriptionId ?? null,\n invoiceId: row.invoiceId ?? null,\n priceId: row.priceId ?? null,\n quantity: row.quantity ?? null,\n applicationId: row.applicationId ?? null,\n personId: row.personId ?? null,\n membershipId: row.membershipId ?? null,\n currentPeriodStart: row.currentPeriodStart ?? null,\n currentPeriodEnd: row.currentPeriodEnd ?? null,\n cancelAtPeriodEnd: row.cancelAtPeriodEnd ?? null,\n});\n\nconst index = (projection: NetworkCommercialProjection) => new Map(\n ([...projection.customers, ...projection.subscriptions, ...projection.invoices, ...projection.refunds])\n .map((row) => [`${row.sourceKey}:${row.objectKind}:${row.objectId}`, row]),\n);\n\n/** Compare the event shadow with an independent current-object Stripe read. */\nexport function reconcileStripeSnapshot(\n shadow: NetworkCommercialProjection,\n snapshots: { customers: StripeObjectSnapshot; subscriptions: StripeObjectSnapshot; invoices: StripeObjectSnapshot; refunds: StripeObjectSnapshot },\n sources: readonly NetworkCommercialSource[],\n): StripeCommercialReconciliation {\n const stripe = projectNetworkCommercialEvents(facts(snapshots), sources);\n const shadowRows = index(shadow);\n const stripeRows = index(stripe);\n const exceptions: StripeCommercialReconciliation[\"exceptions\"] = [];\n const complete = Object.values(snapshots).every((snapshot) => snapshot.complete);\n if (!complete) exceptions.push({ kind: \"stripe_snapshot_truncated\", detail: {} });\n for (const [key, row] of shadowRows) {\n const other = stripeRows.get(key);\n if (!other) {\n exceptions.push({ kind: \"missing_from_stripe\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: {} });\n } else if (JSON.stringify(selected(row)) !== JSON.stringify(selected(other))) {\n exceptions.push({ kind: \"object_mismatch\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: { shadow: selected(row), stripe: selected(other) } });\n }\n }\n for (const [key, row] of stripeRows) {\n if (!shadowRows.has(key)) exceptions.push({ kind: \"missing_from_shadow\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: {} });\n }\n if (JSON.stringify(shadow.totals) !== JSON.stringify(stripe.totals)) {\n exceptions.push({ kind: \"totals_mismatch\", detail: { shadow: shadow.totals, stripe: stripe.totals } });\n }\n return {\n ok: exceptions.length === 0,\n complete,\n ignoredObjects: stripe.exceptions.filter((item) => item.kind === \"wrong_partition\" || item.kind === \"unmatched_partition\").length,\n exceptions,\n stripeTotals: stripe.totals,\n };\n}\n","import { networkCommercialSourceKey } from \"./config-network-commercial\";\nimport type { NetworkCommercialProjection } from \"./types-network-commercial-projection\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\n\ntype Row = Record<string, unknown>;\n\n/** Exact chapter/runtime partition that binds every parity digest. */\nexport interface CommercialParityPartition {\n appId: string;\n chapterId: string;\n environment: string;\n dataEnvironment: string;\n runtime: string;\n}\n\n/** PII-free chapter membership identity and lifecycle disclosure. */\nexport interface ChapterCommercialParityRecord {\n applicationDigest: string;\n customerDigest: string | null;\n subscriptionDigest: string | null;\n status: string | null;\n canceled: boolean;\n}\n\n/** Bounded, signed-response payload produced by an opted-in chapter. */\nexport interface ChapterCommercialParitySnapshot {\n version: 1;\n site: { id: string };\n partition: CommercialParityPartition;\n generatedAt: number;\n complete: boolean;\n truncated: boolean;\n counts: { scanned: number; eligible: number; returned: number };\n records: ChapterCommercialParityRecord[];\n}\n\n/** Reconciliation exception categories that never expose raw identifiers. */\nexport type CommercialParityExceptionKind =\n | \"chapter_only\"\n | \"shadow_only\"\n | \"cancellation_mismatch\"\n | \"chapter_truncated\"\n | \"count_mismatch\";\n\n/** One privacy-preserving mismatch between a chapter and its Stripe shadow. */\nexport interface CommercialParityException {\n kind: CommercialParityExceptionKind;\n applicationDigest?: string;\n detail: Record<string, string | number | boolean | null>;\n}\n\n/** Read-only result of comparing one chapter snapshot with one exact shadow partition. */\nexport interface CommercialParityResult {\n ok: boolean;\n complete: boolean;\n counts: { chapter: number; shadow: number; matched: number };\n records: Array<ChapterCommercialParityRecord & {\n stripeStatus: string | null;\n stripeCanceled: boolean;\n }>;\n exceptions: CommercialParityException[];\n}\n\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst MAX_RECORDS = 500;\nconst text = (value: unknown, max = 255): string | null =>\n typeof value === \"string\" && value.length > 0 && value.length <= max ? value : null;\n\nfunction parityMessage(partition: CommercialParityPartition, kind: string, value: string): string {\n return [\n \"chapter-commercial-parity\", \"v1\", partition.appId, partition.chapterId,\n partition.environment, partition.dataEnvironment, partition.runtime, kind, value,\n ].join(\"\\u001f\");\n}\n\n/** Import the edge secret once so a bounded snapshot does not repeat key setup. */\nasync function parityKey(secret: string): Promise<CryptoKey> {\n const encoder = new TextEncoder();\n return crypto.subtle.importKey(\n \"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"],\n );\n}\n\nasync function digestWithKey(\n key: CryptoKey,\n partition: CommercialParityPartition,\n kind: \"application\" | \"customer\" | \"subscription\",\n value: string,\n): Promise<string> {\n const encoder = new TextEncoder();\n const signed = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(parityMessage(partition, kind, value)));\n return [...new Uint8Array(signed)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Edge-keyed, domain-separated digest. Raw identifiers never enter a response. */\nexport async function commercialParityDigest(\n secret: string,\n partition: CommercialParityPartition,\n kind: \"application\" | \"customer\" | \"subscription\",\n value: string,\n): Promise<string> {\n return digestWithKey(await parityKey(secret), partition, kind, value);\n}\n\n/** Build the bounded disclosure from already-bounded local application rows. */\nexport async function buildChapterCommercialParitySnapshot(input: {\n rows: readonly Row[];\n secret: string;\n partition: CommercialParityPartition;\n siteId: string;\n scanned: number;\n scanTruncated: boolean;\n maxRecords?: number;\n now?: number;\n}): Promise<ChapterCommercialParitySnapshot> {\n const requestedMax = input.maxRecords ?? MAX_RECORDS;\n const maxRecords = Number.isSafeInteger(requestedMax)\n ? Math.max(0, Math.min(requestedMax, MAX_RECORDS))\n : MAX_RECORDS;\n const eligible = input.rows.filter((row) =>\n text(row.id) && (text(row.stripeCustomerId) || text(row.stripeSubscriptionId)));\n const selected = eligible.slice(0, maxRecords);\n const key = await parityKey(input.secret);\n const records = await Promise.all(selected.map(async (row): Promise<ChapterCommercialParityRecord> => {\n const applicationId = text(row.id)!;\n const customerId = text(row.stripeCustomerId);\n const subscriptionId = text(row.stripeSubscriptionId);\n return {\n applicationDigest: await digestWithKey(key, input.partition, \"application\", applicationId),\n customerDigest: customerId\n ? await digestWithKey(key, input.partition, \"customer\", customerId)\n : null,\n subscriptionDigest: subscriptionId\n ? await digestWithKey(key, input.partition, \"subscription\", subscriptionId)\n : null,\n status: text(row.status, 64),\n canceled: row.canceled === true,\n };\n }));\n records.sort((left, right) => left.applicationDigest.localeCompare(right.applicationDigest));\n const truncated = input.scanTruncated || eligible.length > maxRecords;\n return {\n version: 1,\n site: { id: input.siteId },\n partition: input.partition,\n generatedAt: input.now ?? Date.now(),\n complete: !truncated,\n truncated,\n counts: { scanned: input.scanned, eligible: eligible.length, returned: records.length },\n records,\n };\n}\n\nfunction recordKey(record: Pick<ChapterCommercialParityRecord, \"applicationDigest\" | \"customerDigest\" | \"subscriptionDigest\">): string {\n return `${record.applicationDigest}:${record.customerDigest ?? \"-\"}:${record.subscriptionDigest ?? \"-\"}`;\n}\n\nfunction validSnapshot(snapshot: ChapterCommercialParitySnapshot, source: NetworkCommercialSource): boolean {\n const partition = snapshot?.partition;\n const records = snapshot?.records;\n if (\n snapshot?.version !== 1 || snapshot.site?.id !== source.chapterId || !partition || !Array.isArray(records) ||\n records.length > MAX_RECORDS ||\n partition.appId !== source.appId || partition.chapterId !== source.chapterId ||\n partition.environment !== source.environment || partition.dataEnvironment !== source.dataEnvironment ||\n partition.runtime !== source.runtime || typeof snapshot.complete !== \"boolean\" ||\n typeof snapshot.truncated !== \"boolean\" || !snapshot.counts\n ) return false;\n const seen = new Set<string>();\n for (const record of records) {\n if (\n !DIGEST.test(record.applicationDigest) ||\n (record.customerDigest !== null && !DIGEST.test(record.customerDigest)) ||\n (record.subscriptionDigest !== null && !DIGEST.test(record.subscriptionDigest)) ||\n (record.status !== null && text(record.status, 64) === null) ||\n typeof record.canceled !== \"boolean\"\n ) return false;\n const key = recordKey(record);\n if (seen.has(key)) return false;\n seen.add(key);\n }\n return Number.isSafeInteger(snapshot.counts.scanned) && Number.isSafeInteger(snapshot.counts.eligible) &&\n Number.isSafeInteger(snapshot.counts.returned) && snapshot.counts.returned === records.length &&\n snapshot.counts.scanned >= snapshot.counts.eligible && snapshot.counts.eligible >= snapshot.counts.returned;\n}\n\n/** Compare one follower disclosure to the matching Stripe shadow partition. */\nexport async function reconcileCommercialParitySnapshot(input: {\n projection: NetworkCommercialProjection;\n source: NetworkCommercialSource;\n snapshot: ChapterCommercialParitySnapshot;\n secret: string;\n}): Promise<CommercialParityResult> {\n if (!validSnapshot(input.snapshot, input.source)) throw new Error(\"invalid chapter commercial parity snapshot\");\n const sourceKey = networkCommercialSourceKey(input.source);\n const key = await parityKey(input.secret);\n const shadow = await Promise.all(input.projection.subscriptions\n .filter((row) => row.sourceKey === sourceKey && text(row.applicationId) && text(row.objectId))\n .map(async (row): Promise<ChapterCommercialParityRecord & { stripeStatus: string | null; stripeCanceled: boolean }> => {\n const customerId = text(row.customerId);\n const subscriptionId = text(row.subscriptionId) ?? text(row.objectId);\n return {\n applicationDigest: await digestWithKey(key, input.snapshot.partition, \"application\", row.applicationId!),\n customerDigest: customerId\n ? await digestWithKey(key, input.snapshot.partition, \"customer\", customerId)\n : null,\n subscriptionDigest: subscriptionId\n ? await digestWithKey(key, input.snapshot.partition, \"subscription\", subscriptionId)\n : null,\n status: null,\n canceled: false,\n stripeStatus: text(row.status, 64),\n stripeCanceled: row.status === \"canceled\",\n };\n }));\n const chapterByKey = new Map(input.snapshot.records.map((record) => [recordKey(record), record]));\n const shadowByKey = new Map(shadow.map((record) => [recordKey(record), record]));\n const exceptions: CommercialParityException[] = [];\n const records: CommercialParityResult[\"records\"] = [];\n for (const [key, chapter] of chapterByKey) {\n const stripe = shadowByKey.get(key);\n if (!stripe) {\n exceptions.push({ kind: \"chapter_only\", applicationDigest: chapter.applicationDigest, detail: { chapterStatus: chapter.status } });\n continue;\n }\n const compared = { ...chapter, stripeStatus: stripe.stripeStatus, stripeCanceled: stripe.stripeCanceled };\n records.push(compared);\n if (chapter.canceled !== stripe.stripeCanceled) {\n exceptions.push({\n kind: \"cancellation_mismatch\",\n applicationDigest: chapter.applicationDigest,\n detail: { chapterCanceled: chapter.canceled, stripeCanceled: stripe.stripeCanceled },\n });\n }\n }\n for (const [key, stripe] of shadowByKey) {\n if (!chapterByKey.has(key)) {\n exceptions.push({ kind: \"shadow_only\", applicationDigest: stripe.applicationDigest, detail: { stripeStatus: stripe.stripeStatus } });\n }\n }\n if (!input.snapshot.complete || input.snapshot.truncated) {\n exceptions.push({\n kind: \"chapter_truncated\",\n detail: { scanned: input.snapshot.counts.scanned, eligible: input.snapshot.counts.eligible, returned: input.snapshot.counts.returned },\n });\n }\n if (chapterByKey.size !== shadowByKey.size) {\n exceptions.push({ kind: \"count_mismatch\", detail: { chapter: chapterByKey.size, shadow: shadowByKey.size } });\n }\n records.sort((left, right) => left.applicationDigest.localeCompare(right.applicationDigest));\n return {\n ok: input.snapshot.complete && exceptions.length === 0,\n complete: input.snapshot.complete,\n counts: { chapter: chapterByKey.size, shadow: shadowByKey.size, matched: records.length },\n records,\n exceptions,\n };\n}\n","// Reusable CRM records for a leader that forms and operates a portfolio of\n// chapters. This is configuration, not a second data engine: every record still\n// uses @odla-ai/crm's normal CRUD, pipelines, activities, views, and relations.\nimport { composeCrmConfigs, type CrmConfig, type TypeDef } from \"@odla-ai/crm\";\nimport { defaultCrm } from \"./defaults\";\n\n/** Options for {@link leaderCrmConfig}. */\nexport interface LeaderCrmOptions {\n /** Existing host CRM config to preserve. Defaults to Chapter's people +\n * businesses graph for hub mode. */\n base?: CrmConfig;\n /** Host-owned additions or replacements for the durable chapter record.\n * Fields and facets merge with the preset; a supplied pipeline replaces the\n * generic proposed/forming/active lifecycle. The final composed CRM still\n * goes through defineCrm's normal validation. */\n chapter?: Partial<TypeDef>;\n}\n\n/**\n * Add generic chapter-formation, portfolio, and deal-flow records to an\n * existing CRM. Collisions fail through `composeCrmConfigs`, so this preset\n * never silently replaces a host's people pipeline or templates.\n */\nexport function leaderCrmConfig(options: LeaderCrmOptions = {}): CrmConfig {\n const base = options.base ?? defaultCrm(\"hub\");\n const defaultChapter: TypeDef = {\n label: \"Chapter\",\n labelPlural: \"Chapters\",\n workspace: \"portfolio\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n slug: { type: \"string\", label: \"Slug\", slot: \"s1\" },\n region: { type: \"string\", label: \"Region\", slot: \"s2\" },\n url: { type: \"url\", label: \"Website\" },\n thesis: { type: \"string\", label: \"Investment thesis\" },\n launchedAt: { type: \"date\", label: \"Launch date\", slot: \"d1\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n pipeline: {\n stages: [\n { id: \"proposed\", label: \"Proposed\" },\n { id: \"forming\", label: \"Forming\" },\n { id: \"active\", label: \"Active\" },\n { id: \"paused\", label: \"Paused\" },\n { id: \"closed\", label: \"Closed\", terminal: true },\n ],\n transitions: {\n proposed: [\"forming\", \"closed\"],\n forming: [\"active\", \"paused\", \"closed\"],\n active: [\"paused\", \"closed\"],\n paused: [\"forming\", \"active\", \"closed\"],\n },\n },\n facets: { rank: \"manual\" },\n };\n const chapterOverride = options.chapter ?? {};\n const chapterType: TypeDef = {\n ...defaultChapter,\n ...chapterOverride,\n fields: {\n ...defaultChapter.fields,\n ...(chapterOverride.fields ?? {}),\n // The preset's natural identity is not optional even when the host adds\n // its own fields or relabels the name input.\n name: {\n ...defaultChapter.fields.name,\n ...(chapterOverride.fields?.name ?? {}),\n type: \"string\",\n required: true,\n },\n },\n facets: {\n ...defaultChapter.facets,\n ...(chapterOverride.facets ?? {}),\n },\n };\n const portfolio: CrmConfig = {\n types: {\n chapter: chapterType,\n chapter_application: {\n label: \"Chapter application\",\n labelPlural: \"Formation applications\",\n workspace: \"portfolio\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Applicant name\", required: true },\n email: { type: \"email\", label: \"Email\", required: true },\n location: { type: \"string\", label: \"Location\", required: true, slot: \"s1\" },\n proposedChapter: { type: \"string\", label: \"Proposed chapter\", slot: \"s2\" },\n thesis: { type: \"string\", label: \"Proposed thesis\", required: true },\n experience: { type: \"string\", label: \"Relevant experience\" },\n collaborators: { type: \"json\", label: \"Collaborators\" },\n notes: { type: \"string\", label: \"Internal notes\" },\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"reviewing\", label: \"Reviewing\" },\n { id: \"interviewing\", label: \"Interviewing\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"forming\", label: \"Forming\" },\n { id: \"declined\", label: \"Declined\", terminal: true },\n ],\n transitions: {\n submitted: [\"reviewing\", \"declined\"],\n reviewing: [\"interviewing\", \"approved\", \"declined\"],\n interviewing: [\"approved\", \"declined\"],\n approved: [\"forming\", \"declined\"],\n },\n },\n facets: { email: true, rank: \"manual\" },\n },\n deal: {\n label: \"Deal\",\n labelPlural: \"Deal flow\",\n workspace: \"portfolio\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Company or deal\", required: true },\n chapter: { type: \"string\", label: \"Source chapter\", slot: \"s1\" },\n sector: { type: \"string\", label: \"Sector\", slot: \"s2\" },\n source: { type: \"string\", label: \"Source\", slot: \"s3\" },\n website: { type: \"url\", label: \"Website\" },\n amount: { type: \"number\", label: \"Target amount\", slot: \"n1\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n pipeline: {\n stages: [\n { id: \"sourced\", label: \"Sourced\" },\n { id: \"screening\", label: \"Screening\" },\n { id: \"diligence\", label: \"Diligence\" },\n { id: \"committee\", label: \"Committee\" },\n { id: \"offered\", label: \"Offered\" },\n { id: \"invested\", label: \"Invested\", terminal: true },\n { id: \"passed\", label: \"Passed\", terminal: true },\n ],\n transitions: {\n sourced: [\"screening\", \"passed\"],\n screening: [\"diligence\", \"committee\", \"passed\"],\n diligence: [\"committee\", \"offered\", \"passed\"],\n committee: [\"offered\", \"passed\"],\n offered: [\"invested\", \"passed\"],\n passed: [\"sourced\"],\n },\n },\n facets: { rank: \"manual\" },\n },\n },\n relations: {\n formation_result: {\n from: \"chapter_application\",\n to: \"chapter\",\n label: \"formed as\",\n reverseLabel: \"formation application\",\n },\n chapter_deal: {\n from: \"deal\",\n to: \"chapter\",\n label: \"sourced by\",\n reverseLabel: \"deal flow\",\n },\n },\n };\n if (base.types.company) {\n portfolio.relations!.deal_company = {\n from: \"deal\",\n to: \"company\",\n label: \"concerns\",\n reverseLabel: \"deals\",\n };\n }\n if (base.types.person) {\n portfolio.relations!.application_contact = {\n from: \"person\",\n to: \"chapter_application\",\n label: \"submitted\",\n reverseLabel: \"applicant\",\n };\n }\n return composeCrmConfigs(base, portfolio);\n}\n","// The CLI-consumable provisioning descriptor. It composes @odla-ai/crm's\n// integration (crm_* namespaces + crm_config seed + route probe) with the\n// chapter's own namespaces and a guarded `groups`-row seed, so a site's\n// odla.config.mjs lists ONE integration. The CLI reads it structurally\n// (matching OdlaIntegration) and merges schema/rules by namespace.\nimport { createCrmIntegration } from \"@odla-ai/crm\";\nimport { buildTierSeeds } from \"./tiers\";\nimport type { Chapter } from \"./types\";\n\n/** Options for {@link createChapterIntegration}. */\nexport interface ChapterIntegrationOptions {\n /** CRM route mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\ninterface IntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\ninterface IntegrationSecret {\n name: string;\n description: string;\n required: boolean;\n}\n\n/** Structural match for the CLI's `OdlaIntegration`. */\nexport interface ChapterIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n schema: { entities: Record<string, unknown>; links: Record<string, unknown> };\n rules: Record<string, unknown>;\n seeds: IntegrationSeed[];\n probes: Array<{ path: string; expectedStatus: number }>;\n /** Tenant-vault secret names read by configured Chapter capabilities. */\n secrets: IntegrationSecret[];\n /** Runbooks that bear on THIS chapter's role, so tooling can point at the\n * right procedure without the operator knowing it exists. A chapter declaring\n * `network.targets` is a leader hub; one with no targets is a follower site\n * (and may declare `network.readers` for bounded CRM browsing). */\n runbooks: ChapterRunbookHints;\n}\n\n/** Which runbooks apply, and why. */\nexport interface ChapterRunbookHints {\n role: \"leader\" | \"follower\";\n /** Platform runbook slugs, most relevant first. */\n slugs: string[];\n /** One line a human or agent can act on. */\n guidance: string;\n}\n\n/**\n * Build the one CLI-consumable integration for a chapter/hub: the crm_*\n * namespaces + crm_config seed + route probe, merged with the chapter's own\n * namespaces and a guarded `groups`-row seed. Drop it in odla.config.mjs's\n * `integrations` array.\n */\nexport function createChapterIntegration(\n chapter: Chapter,\n options: ChapterIntegrationOptions = {},\n): ChapterIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n const now = options.now ?? Date.now();\n const emails = chapter.config.emails;\n\n const crmDesc = createCrmIntegration(chapter.crm, {\n basePath,\n now,\n ...(emails?.notificationEmail ? { notificationEmail: emails.notificationEmail } : {}),\n ...(emails?.replyTo ? { replyTo: emails.replyTo } : {}),\n ...(emails?.debugEmail ? { debugEmail: emails.debugEmail } : {}),\n });\n\n const seeds: IntegrationSeed[] = [...(crmDesc.seeds ?? [])];\n const group = chapter.groupSeed();\n if (group) {\n seeds.push({ id: \"group\", ns: \"groups\", key: { attr: \"id\", value: chapter.id }, attrs: { ...group, createdAt: now } });\n // One insert-only seed per declared tier, keyed by its own id so re-running\n // provisioning never duplicates a tier or overwrites a price an owner has\n // since changed in Studio.\n for (const tier of buildTierSeeds(chapter.id, chapter.config.tiers, now)) {\n seeds.push({\n id: `tier:${String(tier.id)}`,\n ns: \"tiers\",\n key: { attr: \"id\", value: String(tier.id) },\n attrs: tier,\n });\n }\n }\n\n // A leader declares where it pushes records. A follower declares no targets;\n // it may still declare readers for bounded record browsing.\n const isLeader = (chapter.config.network?.targets?.length ?? 0) > 0;\n const runbooks: ChapterRunbookHints = isLeader\n ? {\n role: \"leader\",\n slugs: [\"chapter-leader\", \"chapter-network\", \"crm\", ...(chapter.networkCommercialReadModel ? [\"stripe-network-shadow\"] : [])],\n guidance:\n `${chapter.name} is a LEADER hub: it holds the CRM and shares records with its chapters. ` +\n `Read it with \\`odla-ai runbook get chapter-leader\\`.`,\n }\n : {\n role: \"follower\",\n slugs: [\"chapter-follower\", \"chapter-network\"],\n guidance:\n `${chapter.name} is a FOLLOWER site: it receives people and records from a leader hub. ` +\n `Read it with \\`odla-ai runbook get chapter-follower\\`.`,\n };\n const secrets: IntegrationSecret[] = [];\n if (chapter.account !== \"none\") secrets.push({\n // Released Chapter workers request this effective name. odla-db maps it to\n // the canonical reserved `$clerk_secret` value written by the CLI.\n name: \"clerk_secret_key\",\n description: \"Clerk backend key (set with odla-ai secrets set-clerk-key) required by the configured Chapter account model.\",\n required: true,\n });\n if (chapter.networkCommercialReadModel) secrets.push({\n name: \"network_commercial_stripe_webhook_secret\",\n description: \"Signing secret for the read-only network commercial Stripe webhook endpoint.\",\n required: true,\n });\n\n return {\n id: \"chapter\",\n title: `Chapter: ${chapter.name}`,\n npm: \"@odla-ai/chapter\",\n schema: {\n entities: { ...crmDesc.schema.entities, ...chapter.schema.entities },\n links: { ...crmDesc.schema.links, ...chapter.schema.links },\n },\n rules: { ...crmDesc.rules, ...chapter.rules },\n seeds,\n secrets,\n probes: [\n ...(crmDesc.probes ?? []),\n // The snapshot route is deliberately private. A credential-free smoke\n // request must prove that the route is mounted and closed.\n { path: \"/api/network/snapshot\", expectedStatus: 401 },\n ...(chapter.network.readers.length > 0\n ? [{ path: \"/api/network/records\", expectedStatus: 401 }]\n : []),\n ...(chapter.network.readers.some((reader) => reader.sharedNotes.length > 0)\n ? [{\n path: \"/api/network/shared-notes\",\n expectedStatus: 401,\n }]\n : []),\n ...(chapter.network.readers.some((reader) => reader.commercialParity)\n ? [{ path: \"/api/network/commercial-parity\", expectedStatus: 401 }]\n : []),\n // Formation metadata is public only when the host explicitly enables\n // the bounded intake contract.\n ...(chapter.formation.enabled\n ? [{ path: \"/api/formation/config\", expectedStatus: 200 }]\n : []),\n ...(chapter.memberContent\n ? [\n { path: \"/api/member-content\", expectedStatus: 401 },\n { path: \"/api/admin/member-content\", expectedStatus: 401 },\n ]\n : []),\n ...(chapter.builderLibrary\n ? [\n { path: \"/api/builder-library-control\", expectedStatus: 401 },\n { path: \"/api/admin/builder-library\", expectedStatus: 401 },\n { path: \"/api/admin/builder-library/manifest\", expectedStatus: 401 },\n ]\n : []),\n ...(chapter.networkPersonRegistry\n ? [{ path: \"/api/admin/network-person-registry\", expectedStatus: 401 }]\n : []),\n ...(chapter.networkCommercialReadModel\n ? [\n { path: \"/api/network-commercial/stripe-webhook\", expectedStatus: 405 },\n { path: \"/api/admin/network-commercial-read-model\", expectedStatus: 401 },\n ]\n : []),\n ],\n runbooks,\n };\n}\n","// Membership tiers. A chapter offers one or more tiers, and a tier — not the\n// group — decides what a member pays. Keeping the price on the tier is what\n// makes a free tier expressible: `paymentsReady` used to gate the whole join\n// flow on the group holding a Stripe price, so a £0 membership was unjoinable.\n//\n// Everything here is pure so the join page, the checkout route and the seeder\n// agree about which tiers exist and which of them can actually be bought.\n\n/** One membership tier a chapter offers. `priceCents: 0` means free. */\nexport interface ChapterTier {\n /** Stable slug, referenced by `applications.tierId`. Never renumbered. */\n id: string;\n /** The group this tier belongs to. */\n groupId: string;\n /** Display name, e.g. \"Founding\". */\n name: string;\n /** Price in minor units. `0` is free and needs no Stripe price. */\n priceCents: number;\n /** ISO currency inherited from the group for legacy rows. */\n currency?: string;\n /** Recurring interval inherited from the group for legacy rows. */\n interval?: \"year\" | \"month\";\n /** Stripe price to subscribe. Required only when `priceCents > 0`. */\n stripePriceId?: string | null;\n /** Short description shown beside the tier on the join page. */\n blurb?: string;\n /** Ascending display order; ties fall back to `id` for a stable sort. */\n sortOrder: number;\n /** An inactive tier is retained for existing members but never offered. */\n active: boolean;\n}\n\n/**\n * A tier as declared in `defineChapter`, before it becomes a row.\n *\n * `groupId` is absent here because the chapter owns exactly one group at seed\n * time; the seeder fills it in.\n */\nexport interface ChapterTierConfig {\n id: string;\n name: string;\n priceCents: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n stripePriceId?: string;\n blurb?: string;\n /** Defaults to declaration order when omitted. */\n sortOrder?: number;\n /** Defaults to true; set false to retire a tier without deleting it. */\n active?: boolean;\n}\n\n/** Build the seed rows for a chapter's declared tiers. */\nexport function buildTierSeeds(\n groupId: string,\n configured: readonly ChapterTierConfig[] = [],\n now = 0,\n): Array<Record<string, unknown>> {\n return configured.map((tier, index) => ({\n id: tier.id,\n groupId,\n name: tier.name,\n priceCents: tier.priceCents,\n ...(tier.currency ? { currency: tier.currency } : {}),\n ...(tier.interval ? { interval: tier.interval } : {}),\n ...(tier.stripePriceId ? { stripePriceId: tier.stripePriceId } : {}),\n ...(tier.blurb ? { blurb: tier.blurb } : {}),\n sortOrder: tier.sortOrder ?? index,\n active: tier.active !== false,\n createdAt: now,\n }));\n}\n\n/** The `groups`-row fields tier payability depends on. */\nexport interface TierGroup {\n id?: string;\n stripePublishableKey?: string | null;\n /** Legacy single price, used only to synthesize an implicit tier. */\n stripePriceId?: string | null;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n}\n\n/**\n * Whether this tier costs nothing. A free tier never touches Stripe.\n *\n * Free means both no price AND no Stripe price to charge against. The second\n * half matters for chapters that predate tiers: a group can carry a real\n * `stripePriceId` while `standardPriceCents` is 0, because the cents field is\n * display copy and the amount actually lives in Stripe. Reading such a group as\n * free would silently stop charging an existing paying chapter.\n */\nexport function tierIsFree(\n tier: Pick<ChapterTier, \"priceCents\"> & { stripePriceId?: string | null },\n): boolean {\n return !(tier.priceCents > 0) && !tier.stripePriceId;\n}\n\n/**\n * Whether a tier can actually be joined right now.\n *\n * A free tier is always joinable — there is nothing to charge, so Stripe being\n * unconfigured is irrelevant to it. A paid tier needs the group's publishable\n * key, its own Stripe price, and the vault secret; missing any of those drops\n * the tier rather than half-charging for it.\n */\nexport function tierPayable(\n tier: Pick<ChapterTier, \"priceCents\" | \"stripePriceId\">,\n group: TierGroup,\n hasSecretKey: boolean,\n): boolean {\n if (tierIsFree(tier)) return true;\n return Boolean(group.stripePublishableKey && tier.stripePriceId && hasSecretKey);\n}\n\n/** Sort by `sortOrder`, then `id`, so a page never reorders between reads. */\nfunction byOrder(a: ChapterTier, b: ChapterTier): number {\n return a.sortOrder - b.sortOrder || a.id.localeCompare(b.id);\n}\n\n/**\n * The tiers a chapter offers, given the stored rows.\n *\n * A chapter that predates tiers has no rows, and must keep working untouched:\n * one implicit `\"standard\"` tier is synthesized from the group's legacy\n * `standardPriceCents`/`stripePriceId` columns. That is why there is no\n * migration — an existing chapter reads exactly as it did before, and writing\n * its first real tier row takes over.\n */\nexport function resolveTiers(group: TierGroup, rows: readonly ChapterTier[] = []): ChapterTier[] {\n const stored = rows.filter((tier) => tier.active);\n if (stored.length) return [...stored].sort(byOrder);\n return [{\n id: \"standard\",\n groupId: String(group.id ?? \"\"),\n name: \"Membership\",\n priceCents: group.standardPriceCents ?? 0,\n currency: group.currency ?? \"usd\",\n interval: group.interval ?? \"year\",\n ...(group.stripePriceId ? { stripePriceId: group.stripePriceId } : {}),\n sortOrder: 0,\n active: true,\n }];\n}\n\n/** The tiers to show on the join page: active, and joinable as configured. */\nexport function offerableTiers(\n tiers: readonly ChapterTier[],\n group: TierGroup,\n hasSecretKey: boolean,\n): ChapterTier[] {\n return tiers.filter((tier) => tier.active && tierPayable(tier, group, hasSecretKey));\n}\n\n/**\n * Resolve the tier an application chose.\n *\n * An absent `tierId` is the pre-tier case and selects the only offered tier\n * when exactly one exists; with several it is genuinely ambiguous and returns\n * `null`, because guessing would charge someone the wrong price.\n */\nexport function findTier(\n tiers: readonly ChapterTier[],\n tierId: string | null | undefined,\n): ChapterTier | null {\n if (!tierId) return tiers.length === 1 ? tiers[0]! : null;\n return tiers.find((tier) => tier.id === tierId) ?? null;\n}\n\n/** The public shape of a tier on the join config. Never exposes Stripe ids. */\nexport interface JoinConfigTier {\n id: string;\n name: string;\n priceCents: number;\n currency: string;\n interval: \"year\" | \"month\";\n blurb: string;\n free: boolean;\n}\n\n/** Project tiers for the public join config, dropping provider identifiers. */\nexport function joinConfigTiers(\n tiers: readonly ChapterTier[],\n defaults: { currency?: string; interval?: \"year\" | \"month\" } = {},\n): JoinConfigTier[] {\n return tiers.map((tier) => ({\n id: tier.id,\n name: tier.name,\n priceCents: tier.priceCents,\n currency: tier.currency ?? defaults.currency ?? \"usd\",\n interval: tier.interval ?? defaults.interval ?? \"year\",\n blurb: tier.blurb ?? \"\",\n free: tierIsFree(tier),\n }));\n}\n","import type { MemberPageAudience, MemberPageUpsellOffer } from \"./member-content\";\n\nexport const ID = /^[a-z][a-z0-9-]{0,79}$/;\nexport const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nexport const ROOT_KEYS = new Set([\"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"pages\", \"upsellOverrides\"]);\nexport const SOURCE_KEYS = new Set([\"type\", \"appId\"]);\nexport const TARGET_KEYS = new Set([\"chapterId\", \"environment\"]);\nexport const PAGE_KEYS = new Set([\"id\", \"slug\", \"title\", \"summary\", \"navigation\", \"audience\", \"teaserMarkdown\", \"bodyMarkdown\", \"upsell\"]);\nexport const NAV_KEYS = new Set([\"section\", \"order\", \"parentId\"]);\nexport const AUDIENCE_KEYS = new Set([\"kind\", \"tierIds\"]);\nexport const UPSELL_KEYS = new Set([\"owner\", \"offer\"]);\nexport const OFFER_KEYS = new Set([\"tierId\", \"label\", \"bodyMarkdown\", \"ctaLabel\"]);\nexport const OVERRIDE_KEYS = new Set([\"pageId\", \"offer\"]);\nexport const MAX_PAGES = 100;\nexport const MAX_MARKDOWN = 65_536;\nexport const MAX_TEXT = 240;\n\nexport const record = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nexport function unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]): void {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nexport function textValue(value: unknown, path: string, errors: string[], max = MAX_TEXT, required = false): string | undefined {\n if (value === undefined) {\n if (required) errors.push(`${path} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") {\n errors.push(`${path} must be a string`);\n return undefined;\n }\n const valueText = value.trim();\n if (required && !valueText) errors.push(`${path} is required`);\n if (valueText.length > max) errors.push(`${path} must be at most ${max.toLocaleString(\"en-US\")} characters`);\n return valueText;\n}\n\nexport function offerValue(\n value: unknown,\n path: string,\n errors: string[],\n tiers: ReadonlySet<string>,\n audience?: MemberPageAudience,\n): MemberPageUpsellOffer | undefined {\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n return undefined;\n }\n unknownKeys(raw, OFFER_KEYS, path, errors);\n const tierId = textValue(raw.tierId, `${path}.tierId`, errors, 80, true) ?? \"\";\n if (tierId && !ID.test(tierId)) errors.push(`${path}.tierId must be a lowercase kebab-case id`);\n if (tiers.size && !tiers.has(tierId)) errors.push(`${path}.tierId must reference a declared tier`);\n if (audience?.kind === \"tiers\" && tierId && !audience.tierIds.includes(tierId)) {\n errors.push(`${path}.tierId must grant access to this page`);\n }\n const label = textValue(raw.label, `${path}.label`, errors);\n const bodyMarkdown = textValue(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN);\n const ctaLabel = textValue(raw.ctaLabel, `${path}.ctaLabel`, errors);\n return {\n tierId,\n ...(label ? { label } : {}),\n ...(bodyMarkdown ? { bodyMarkdown } : {}),\n ...(ctaLabel ? { ctaLabel } : {}),\n };\n}\n","import {\n MEMBER_CONTENT_SCHEMA_VERSION,\n type MemberContentDocument,\n type MemberContentPage,\n type MemberContentSource,\n type MemberContentTarget,\n type MemberContentValidationOptions,\n type MemberContentValidationResult,\n type MemberPageAudience,\n type MemberPageNavigation,\n type MemberPageUpsell,\n type MemberPageUpsellOverride,\n} from \"./member-content\";\nimport {\n AUDIENCE_KEYS,\n ID,\n MAX_MARKDOWN,\n MAX_PAGES,\n MAX_TEXT,\n NAV_KEYS,\n OVERRIDE_KEYS,\n PAGE_KEYS,\n ROOT_KEYS,\n SLUG,\n SOURCE_KEYS,\n TARGET_KEYS,\n UPSELL_KEYS,\n offerValue,\n record,\n textValue,\n unknownKeys,\n} from \"./member-content-validation-helpers\";\n\n/** Validate one complete parent or chapter authoring layer with actionable paths. */\nexport function validateMemberContentDocument(\n input: unknown,\n options: MemberContentValidationOptions = {},\n): MemberContentValidationResult {\n const errors: string[] = [];\n const root = record(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== MEMBER_CONTENT_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n if (!Number.isInteger(root.revision) || Number(root.revision) < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isInteger(root.generatedAt) || Number(root.generatedAt) < 0) errors.push(\"document.generatedAt must be a non-negative integer timestamp\");\n\n const sourceRaw = record(root.source);\n let source: MemberContentSource = { type: \"chapter\", appId: \"invalid\" };\n if (!sourceRaw) errors.push(\"document.source must be an object\");\n else {\n unknownKeys(sourceRaw, SOURCE_KEYS, \"document.source\", errors);\n const type = sourceRaw.type;\n const appId = textValue(sourceRaw.appId, \"document.source.appId\", errors, 63, true) ?? \"\";\n if (type !== \"parent\" && type !== \"chapter\") errors.push(\"document.source.type must be parent or chapter\");\n if (appId && !ID.test(appId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (options.sourceType && type !== options.sourceType) errors.push(`document.source.type must be ${options.sourceType}`);\n if (options.sourceAppId && appId !== options.sourceAppId) errors.push(`document.source.appId must be ${options.sourceAppId}`);\n if (type === \"parent\" || type === \"chapter\") source = { type, appId };\n }\n\n let target: MemberContentTarget | undefined;\n if (root.target !== undefined) {\n const targetRaw = record(root.target);\n if (!targetRaw) errors.push(\"document.target must be an object\");\n else {\n unknownKeys(targetRaw, TARGET_KEYS, \"document.target\", errors);\n const chapterId = textValue(targetRaw.chapterId, \"document.target.chapterId\", errors, 63, true) ?? \"\";\n const environment = textValue(targetRaw.environment, \"document.target.environment\", errors, 80, true) ?? \"\";\n target = { chapterId, environment };\n }\n }\n if (source.type === \"parent\" && !target) errors.push(\"document.target is required for parent content\");\n if (source.type === \"chapter\" && target) errors.push(\"document.target is not supported for chapter content\");\n\n if (!Array.isArray(root.pages)) errors.push(\"document.pages must be an array\");\n const rawPages = Array.isArray(root.pages) ? root.pages : [];\n if (rawPages.length > MAX_PAGES) errors.push(`document.pages supports at most ${MAX_PAGES} entries`);\n const tierIds = new Set((options.tiers ?? []).map((tier) => tier.id));\n const knownParentIds = new Set((options.parentPages ?? []).map((page) => page.id));\n const ids = new Set<string>();\n const slugs = new Set<string>();\n const pages: MemberContentPage[] = [];\n for (const [index, value] of rawPages.slice(0, MAX_PAGES).entries()) {\n const path = `document.pages[${index}]`;\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n continue;\n }\n unknownKeys(raw, PAGE_KEYS, path, errors);\n const id = textValue(raw.id, `${path}.id`, errors, 80, true) ?? \"\";\n const slug = textValue(raw.slug, `${path}.slug`, errors, 120, true) ?? \"\";\n const title = textValue(raw.title, `${path}.title`, errors, MAX_TEXT, true) ?? \"\";\n if (id && !ID.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (slug && !SLUG.test(slug)) errors.push(`${path}.slug must be a lowercase URL slug`);\n if (ids.has(id) || knownParentIds.has(id)) errors.push(`${path}.id duplicates page \"${id}\"`);\n if (slugs.has(slug) || (options.parentPages ?? []).some((page) => page.slug === slug)) errors.push(`${path}.slug duplicates \"${slug}\"`);\n ids.add(id);\n slugs.add(slug);\n\n const navRaw = record(raw.navigation);\n let navigation: MemberPageNavigation = { section: \"General\", order: index };\n if (!navRaw) errors.push(`${path}.navigation must be an object`);\n else {\n unknownKeys(navRaw, NAV_KEYS, `${path}.navigation`, errors);\n const section = textValue(navRaw.section, `${path}.navigation.section`, errors, 120, true) ?? \"\";\n const order = navRaw.order;\n if (!Number.isInteger(order) || Number(order) < 0 || Number(order) > 1_000_000) {\n errors.push(`${path}.navigation.order must be an integer from 0 to 1,000,000`);\n }\n const parentId = textValue(navRaw.parentId, `${path}.navigation.parentId`, errors, 80);\n navigation = { section, order: Number.isInteger(order) ? Number(order) : index, ...(parentId ? { parentId } : {}) };\n }\n\n const audienceRaw = record(raw.audience);\n let audience: MemberPageAudience = { kind: \"all-members\" };\n if (!audienceRaw) errors.push(`${path}.audience must be an object`);\n else {\n unknownKeys(audienceRaw, AUDIENCE_KEYS, `${path}.audience`, errors);\n if (audienceRaw.kind === \"all-members\") {\n if (audienceRaw.tierIds !== undefined) errors.push(`${path}.audience.tierIds is not supported for all-members`);\n } else if (audienceRaw.kind === \"tiers\") {\n if (!Array.isArray(audienceRaw.tierIds) || audienceRaw.tierIds.length === 0) {\n errors.push(`${path}.audience.tierIds must be a non-empty array`);\n }\n const values = Array.isArray(audienceRaw.tierIds) ? audienceRaw.tierIds : [];\n const normalized: string[] = [];\n for (const [tierIndex, value] of values.entries()) {\n const tier = textValue(value, `${path}.audience.tierIds[${tierIndex}]`, errors, 80, true) ?? \"\";\n if (normalized.includes(tier)) errors.push(`${path}.audience.tierIds duplicates \"${tier}\"`);\n if (tierIds.size && !tierIds.has(tier)) errors.push(`${path}.audience.tierIds references undeclared tier \"${tier}\"`);\n normalized.push(tier);\n }\n audience = { kind: \"tiers\", tierIds: normalized };\n } else errors.push(`${path}.audience.kind must be all-members or tiers`);\n }\n\n const summary = textValue(raw.summary, `${path}.summary`, errors, 2_000);\n const teaserMarkdown = textValue(raw.teaserMarkdown, `${path}.teaserMarkdown`, errors, MAX_MARKDOWN);\n const bodyMarkdown = textValue(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN, true) ?? \"\";\n let upsell: MemberPageUpsell | undefined;\n if (raw.upsell !== undefined) {\n const upsellRaw = record(raw.upsell);\n if (!upsellRaw) errors.push(`${path}.upsell must be an object`);\n else {\n unknownKeys(upsellRaw, UPSELL_KEYS, `${path}.upsell`, errors);\n const owner = upsellRaw.owner;\n if (owner !== \"parent\" && owner !== \"chapter\") errors.push(`${path}.upsell.owner must be parent or chapter`);\n if (source.type === \"chapter\" && owner === \"parent\") errors.push(`${path}.upsell.owner cannot be parent on a chapter page`);\n if (source.type === \"parent\" && owner === \"parent\" && upsellRaw.offer === undefined) errors.push(`${path}.upsell.offer is required when the parent owns the offer`);\n if (source.type === \"parent\" && owner === \"chapter\" && upsellRaw.offer !== undefined) errors.push(`${path}.upsell.offer must be set by the chapter after delegation`);\n const offer = upsellRaw.offer === undefined ? undefined : offerValue(upsellRaw.offer, `${path}.upsell.offer`, errors, tierIds, audience);\n if (owner === \"parent\") upsell = { owner, offer: offer ?? { tierId: \"\" } };\n else if (owner === \"chapter\") upsell = { owner, ...(offer ? { offer } : {}) };\n }\n }\n pages.push({ id, slug, title, ...(summary ? { summary } : {}), navigation, audience, ...(teaserMarkdown ? { teaserMarkdown } : {}), bodyMarkdown, ...(upsell ? { upsell } : {}) });\n }\n\n const allIds = new Set([...knownParentIds, ...ids]);\n for (const [index, page] of pages.entries()) {\n const parentId = page.navigation.parentId;\n if (parentId && !allIds.has(parentId)) errors.push(`document.pages[${index}].navigation.parentId references unknown page \"${parentId}\"`);\n if (parentId === page.id) errors.push(`document.pages[${index}].navigation.parentId cannot reference itself`);\n }\n for (const page of pages) {\n const seen = new Set([page.id]);\n let parentId = page.navigation.parentId;\n while (parentId) {\n if (seen.has(parentId)) {\n errors.push(`document.pages contains a navigation cycle at \"${page.id}\"`);\n break;\n }\n seen.add(parentId);\n parentId = pages.find((candidate) => candidate.id === parentId)?.navigation.parentId;\n }\n }\n\n let upsellOverrides: MemberPageUpsellOverride[] | undefined;\n if (root.upsellOverrides !== undefined) {\n if (source.type !== \"chapter\") errors.push(\"document.upsellOverrides is supported only for chapter content\");\n if (!Array.isArray(root.upsellOverrides)) errors.push(\"document.upsellOverrides must be an array\");\n const values = Array.isArray(root.upsellOverrides) ? root.upsellOverrides : [];\n const seen = new Set<string>();\n upsellOverrides = [];\n for (const [index, value] of values.entries()) {\n const path = `document.upsellOverrides[${index}]`;\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n continue;\n }\n unknownKeys(raw, OVERRIDE_KEYS, path, errors);\n const pageId = textValue(raw.pageId, `${path}.pageId`, errors, 80, true) ?? \"\";\n if (seen.has(pageId)) errors.push(`${path}.pageId duplicates \"${pageId}\"`);\n seen.add(pageId);\n const parentPage = (options.parentPages ?? []).find((page) => page.id === pageId);\n if (!parentPage) errors.push(`${path}.pageId must reference a parent page`);\n else if (parentPage.upsell?.owner !== \"chapter\") errors.push(`${path}.pageId does not delegate upsell authority to the chapter`);\n const offer = offerValue(raw.offer, `${path}.offer`, errors, tierIds, parentPage?.audience);\n if (offer) upsellOverrides.push({ pageId, offer });\n }\n }\n if (errors.length) return { ok: false, errors };\n return { ok: true, value: {\n schemaVersion: MEMBER_CONTENT_SCHEMA_VERSION,\n revision: Number(root.revision),\n generatedAt: Number(root.generatedAt),\n source,\n ...(target ? { target } : {}),\n pages,\n ...(upsellOverrides ? { upsellOverrides } : {}),\n } };\n}\n\n/** Validate or fail closed with every actionable document error. */\nexport function memberContentDocument(input: unknown, options: MemberContentValidationOptions = {}): MemberContentDocument {\n const result = validateMemberContentDocument(input, options);\n if (!result.ok) throw new TypeError(`Invalid member content document: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","/** Versioned contract for authenticated member content. */\nexport const MEMBER_CONTENT_SCHEMA_VERSION = 1 as const;\n/** Authenticated member projection endpoint. */\nexport const MEMBER_CONTENT_PATH = \"/api/member-content\" as const;\n/** Dedicated signed Parent → Chapter content-delivery endpoint. */\nexport const MEMBER_CONTENT_CONTROL_PATH = \"/api/member-content-control\" as const;\n\n/** Authority that authored one independently stored member-content layer. */\nexport type MemberContentSourceType = \"parent\" | \"chapter\";\n/** Stable author identity attached to every member-content document and page. */\nexport interface MemberContentSource { type: MemberContentSourceType; appId: string }\n/** Chapter deployment that a parent member-content revision is intended for. */\nexport interface MemberContentTarget { chapterId: string; environment: string }\n\n/** Navigation is data, so agents do not have to coordinate route code. */\nexport interface MemberPageNavigation {\n section: string;\n order: number;\n parentId?: string;\n}\n\n/** Explicit sets avoid unsafe assumptions that commercial tiers form a ladder. */\nexport type MemberPageAudience =\n | { kind: \"all-members\" }\n | { kind: \"tiers\"; tierIds: readonly string[] };\n\n/** Authored offer copy. Price and provider identity deliberately do not live here. */\nexport interface MemberPageUpsellOffer {\n tierId: string;\n label?: string;\n bodyMarkdown?: string;\n ctaLabel?: string;\n}\n\n/** Parent offer authority is explicit; a Chapter can edit only a delegated offer. */\nexport type MemberPageUpsell =\n | { owner: \"parent\"; offer: MemberPageUpsellOffer }\n | { owner: \"chapter\"; offer?: MemberPageUpsellOffer };\n\n/** Authored member page whose body is disclosed only after server-side projection. */\nexport interface MemberContentPage {\n id: string;\n slug: string;\n title: string;\n summary?: string;\n navigation: MemberPageNavigation;\n audience: MemberPageAudience;\n /** Safe Markdown shown while the body is withheld. */\n teaserMarkdown?: string;\n /** Never serialized to a viewer whose audience does not match. */\n bodyMarkdown: string;\n upsell?: MemberPageUpsell;\n}\n\n/** Chapter-owned offer attached to a Parent page that delegated offer authority. */\nexport interface MemberPageUpsellOverride { pageId: string; offer: MemberPageUpsellOffer }\n\n/** One complete source layer. Parent and Chapter layers are stored independently. */\nexport interface MemberContentDocument {\n schemaVersion: typeof MEMBER_CONTENT_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: MemberContentSource;\n target?: MemberContentTarget;\n pages: readonly MemberContentPage[];\n upsellOverrides?: readonly MemberPageUpsellOverride[];\n}\n\n/** Provider-neutral tier facts used to validate access and resolve safe offers. */\nexport interface MemberContentTierAuthority {\n id: string;\n name?: string;\n priceCents?: number;\n active?: boolean;\n}\n\n/** Local authority supplied while validating a member-content document. */\nexport interface MemberContentValidationOptions {\n sourceType?: MemberContentSourceType;\n sourceAppId?: string;\n tiers?: readonly MemberContentTierAuthority[];\n parentPages?: readonly MemberContentPage[];\n}\n\n/** Validated document or an actionable collection of contract errors. */\nexport type MemberContentValidationResult =\n | { ok: true; value: MemberContentDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Composed member page retaining the identity of its authoring layer. */\nexport interface EffectiveMemberContentPage extends MemberContentPage { source: MemberContentSource }\n/** Deterministically ordered parent and chapter layers with their source revisions. */\nexport interface EffectiveMemberContent {\n pages: readonly EffectiveMemberContentPage[];\n parentRevision: number | null;\n chapterRevision: number | null;\n}\n/** Server-authoritative identity facts used for member-content disclosure. */\nexport interface MemberContentViewer { tierId: string | null; admin: boolean }\n/** Authored upsell joined to active chapter tier name and price authority. */\nexport interface ResolvedMemberPageUpsell extends MemberPageUpsellOffer { tierName: string; priceCents: number }\n\n/** Viewer-safe page result; locked projections never carry bodyMarkdown. */\nexport interface MemberContentPageProjection {\n id: string;\n slug: string;\n title: string;\n summary?: string;\n navigation: MemberPageNavigation;\n audience: MemberPageAudience;\n source: MemberContentSource;\n access: \"allowed\" | \"locked\";\n teaserMarkdown?: string;\n bodyMarkdown?: string;\n upsell?: ResolvedMemberPageUpsell;\n}\n\n/** Complete viewer-safe member navigation and revision projection. */\nexport interface MemberContentProjection {\n pages: readonly MemberContentPageProjection[];\n viewer: { tierId: string | null; admin: boolean };\n revisions: { parent: number | null; chapter: number | null };\n}\n\n/** Canonical parent document and digest transmitted over the signed control edge. */\nexport interface MemberContentEnvelope { digest: string; document: MemberContentDocument }\n/** Durable Chapter acknowledgement for an accepted or idempotently replayed revision. */\nexport interface MemberContentReceipt {\n ok: true;\n target: MemberContentTarget;\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable rejection reasons returned by the signed member-content control endpoint. */\nexport type MemberContentRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n\nexport { memberContentDocument, validateMemberContentDocument } from \"./member-content-validation\";\n\nconst pageOrder = (a: EffectiveMemberContentPage, b: EffectiveMemberContentPage): number =>\n a.navigation.section.localeCompare(b.navigation.section)\n || a.navigation.order - b.navigation.order\n || a.title.localeCompare(b.title)\n || a.id.localeCompare(b.id);\n\n/** Compose immutable Parent content with independently stored Chapter content. */\nexport function composeMemberContent(\n parent: MemberContentDocument | null | undefined,\n chapter: MemberContentDocument | null | undefined,\n): EffectiveMemberContent {\n const pages: EffectiveMemberContentPage[] = [];\n const parentPages = new Map<string, EffectiveMemberContentPage>();\n for (const page of parent?.pages ?? []) {\n const effective = { ...page, source: parent!.source };\n parentPages.set(page.id, effective);\n pages.push(effective);\n }\n for (const override of chapter?.upsellOverrides ?? []) {\n const page = parentPages.get(override.pageId);\n if (page?.upsell?.owner === \"chapter\") page.upsell = { owner: \"chapter\", offer: override.offer };\n }\n for (const page of chapter?.pages ?? []) {\n if (parentPages.has(page.id) || pages.some((candidate) => candidate.slug === page.slug)) {\n throw new TypeError(`Chapter member page \"${page.id}\" conflicts with parent content`);\n }\n pages.push({ ...page, source: chapter!.source });\n }\n return {\n pages: pages.sort(pageOrder),\n parentRevision: parent?.revision ?? null,\n chapterRevision: chapter?.revision ?? null,\n };\n}\n\nconst allowed = (page: MemberContentPage, viewer: MemberContentViewer): boolean =>\n viewer.admin\n || page.audience.kind === \"all-members\"\n || (viewer.tierId !== null && page.audience.tierIds.includes(viewer.tierId));\n\n/** Restricted bodies are omitted and authored offers are joined to live tier authority. */\nexport function projectMemberContent(\n content: EffectiveMemberContent,\n viewer: MemberContentViewer,\n tiers: readonly MemberContentTierAuthority[],\n): MemberContentProjection {\n const authority = new Map(tiers.filter((tier) => tier.active !== false).map((tier) => [tier.id, tier]));\n return {\n viewer: { ...viewer },\n revisions: { parent: content.parentRevision, chapter: content.chapterRevision },\n pages: content.pages.map((page) => {\n const canRead = allowed(page, viewer);\n const offer = !canRead ? page.upsell?.offer : undefined;\n const tier = offer ? authority.get(offer.tierId) : undefined;\n const upsell = offer && tier && typeof tier.name === \"string\" && typeof tier.priceCents === \"number\"\n ? { ...offer, tierName: tier.name, priceCents: tier.priceCents }\n : undefined;\n return {\n id: page.id,\n slug: page.slug,\n title: page.title,\n ...(page.summary ? { summary: page.summary } : {}),\n navigation: page.navigation,\n audience: page.audience,\n source: page.source,\n access: canRead ? \"allowed\" as const : \"locked\" as const,\n ...(page.teaserMarkdown ? { teaserMarkdown: page.teaserMarkdown } : {}),\n ...(canRead ? { bodyMarkdown: page.bodyMarkdown } : {}),\n ...(upsell ? { upsell } : {}),\n };\n }),\n };\n}\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"member content contains an unsupported value\");\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record).sort().flatMap((key) => {\n const item = record[key];\n return item === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(item)}`];\n });\n return `{${entries.join(\",\")}}`;\n}\n\n/** Serialize JSON-like member content with recursively sorted object keys. */\nexport function canonicalMemberContent(value: unknown): string {\n return canonicalValue(value);\n}\n\n/** Compute the canonical SHA-256 digest for one Parent content revision. */\nexport async function memberContentDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalMemberContent(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one content document with the exact digest the follower acknowledges. */\nexport async function createMemberContentEnvelope(document: import(\"./member-content\").MemberContentDocument) {\n return { document, digest: await memberContentDigest(document) };\n}\n","import {\n BUILDER_LIBRARY_SCHEMA_VERSION,\n type BuilderLibraryDocument,\n type BuilderLibraryResource,\n type BuilderLibraryScope,\n type BuilderLibraryValidationOptions,\n type BuilderLibraryValidationResult,\n} from \"./builder-library\";\n\nconst ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst APP_ID = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst MAX_RESOURCES = 200;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_TEXT = 500;\nconst MAX_TAGS = 20;\nconst KINDS = new Set([\"document\", \"note\", \"link\", \"inspiration\", \"image\", \"file\"]);\nconst STATUSES = new Set([\"draft\", \"published\", \"archived\"]);\nconst ROOT_KEYS = new Set([\"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"resources\"]);\nconst SOURCE_KEYS = new Set([\"type\", \"appId\"]);\nconst TARGET_KEYS = new Set([\"appId\", \"environment\"]);\nconst RESOURCE_KEYS = new Set([\"id\", \"kind\", \"title\", \"summary\", \"tags\", \"scope\", \"status\", \"revision\", \"bodyMarkdown\", \"url\", \"brandAsset\", \"provenance\"]);\nconst SCOPE_KEYS = new Set([\"kind\", \"chapterId\"]);\nconst ASSET_KEYS = new Set([\"bookId\", \"assetId\", \"filename\"]);\nconst PROVENANCE_KEYS = new Set([\"createdBy\", \"createdAt\", \"updatedBy\", \"updatedAt\", \"promotedFrom\"]);\nconst PROMOTION_KEYS = new Set([\"chapterId\", \"resourceId\", \"resourceRevision\", \"documentRevision\", \"promotedBy\", \"promotedAt\"]);\n\nconst record = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\n\nfunction unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]) {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nfunction text(value: unknown, path: string, errors: string[], max = MAX_TEXT, required = true): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\" || (required && !value.trim())) {\n errors.push(`${path} must be a non-empty string`);\n return undefined;\n }\n const result = value.trim();\n if (result.length > max) errors.push(`${path} must be at most ${max} characters`);\n return result;\n}\n\nfunction integer(value: unknown, path: string, errors: string[], minimum = 1): number {\n if (!Number.isSafeInteger(value) || Number(value) < minimum) errors.push(`${path} must be an integer >= ${minimum}`);\n return Number(value);\n}\n\nfunction scopeValue(value: unknown, path: string, errors: string[]): BuilderLibraryScope | null {\n const raw = record(value);\n if (!raw) { errors.push(`${path} must be an object`); return null; }\n unknownKeys(raw, SCOPE_KEYS, path, errors);\n if (raw.kind === \"global\" || raw.kind === \"built_not_found\") {\n if (raw.chapterId !== undefined) errors.push(`${path}.chapterId is allowed only for chapter scope`);\n return { kind: raw.kind };\n }\n if (raw.kind === \"chapter\") {\n const chapterId = text(raw.chapterId, `${path}.chapterId`, errors, 63) ?? \"\";\n if (chapterId && !APP_ID.test(chapterId)) errors.push(`${path}.chapterId must be a lowercase app slug`);\n return { kind: \"chapter\", chapterId };\n }\n errors.push(`${path}.kind must be chapter, built_not_found, or global`);\n return null;\n}\n\nfunction resourceValue(value: unknown, path: string, errors: string[]): BuilderLibraryResource | null {\n const raw = record(value);\n if (!raw) { errors.push(`${path} must be an object`); return null; }\n unknownKeys(raw, RESOURCE_KEYS, path, errors);\n const id = text(raw.id, `${path}.id`, errors, 80) ?? \"\";\n if (id && !ID.test(id)) errors.push(`${path}.id must be lowercase kebab-case`);\n const kind = text(raw.kind, `${path}.kind`, errors) ?? \"\";\n if (!KINDS.has(kind)) errors.push(`${path}.kind is unsupported`);\n const title = text(raw.title, `${path}.title`, errors, 240) ?? \"\";\n const summary = text(raw.summary, `${path}.summary`, errors, 1_000, false);\n const status = text(raw.status, `${path}.status`, errors) ?? \"\";\n if (!STATUSES.has(status)) errors.push(`${path}.status must be draft, published, or archived`);\n const revision = integer(raw.revision, `${path}.revision`, errors);\n const scope = scopeValue(raw.scope, `${path}.scope`, errors) ?? { kind: \"global\" as const };\n const tags = Array.isArray(raw.tags) ? raw.tags.map((tag, index) => text(tag, `${path}.tags[${index}]`, errors, 80) ?? \"\") : [];\n if (!Array.isArray(raw.tags)) errors.push(`${path}.tags must be an array`);\n if (tags.length > MAX_TAGS) errors.push(`${path}.tags may contain at most ${MAX_TAGS} items`);\n if (new Set(tags).size !== tags.length) errors.push(`${path}.tags must be unique`);\n const bodyMarkdown = text(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN, false);\n const url = text(raw.url, `${path}.url`, errors, 2_048, false);\n if (url) {\n try { if (new URL(url).protocol !== \"https:\") errors.push(`${path}.url must use https`); }\n catch { errors.push(`${path}.url must be a valid https URL`); }\n }\n const asset = raw.brandAsset === undefined ? null : record(raw.brandAsset);\n if (raw.brandAsset !== undefined && !asset) errors.push(`${path}.brandAsset must be an object`);\n if (asset) unknownKeys(asset, ASSET_KEYS, `${path}.brandAsset`, errors);\n const brandAsset = asset ? {\n bookId: text(asset.bookId, `${path}.brandAsset.bookId`, errors, 160) ?? \"\",\n assetId: text(asset.assetId, `${path}.brandAsset.assetId`, errors, 160) ?? \"\",\n ...(asset.filename === undefined ? {} : { filename: text(asset.filename, `${path}.brandAsset.filename`, errors, 240) ?? \"\" }),\n } : undefined;\n if ((kind === \"document\" || kind === \"note\") && !bodyMarkdown) errors.push(`${path}.bodyMarkdown is required for ${kind}`);\n if ((kind === \"link\" || kind === \"inspiration\") && !url) errors.push(`${path}.url is required for ${kind}`);\n if ((kind === \"image\" || kind === \"file\") && !brandAsset) errors.push(`${path}.brandAsset is required for ${kind}`);\n if (!([\"document\", \"note\"].includes(kind)) && bodyMarkdown) errors.push(`${path}.bodyMarkdown is not allowed for ${kind}`);\n if (!([\"link\", \"inspiration\"].includes(kind)) && url) errors.push(`${path}.url is not allowed for ${kind}`);\n if (!([\"image\", \"file\"].includes(kind)) && brandAsset) errors.push(`${path}.brandAsset is not allowed for ${kind}`);\n const provenanceRaw = record(raw.provenance);\n if (!provenanceRaw) errors.push(`${path}.provenance must be an object`);\n if (provenanceRaw) unknownKeys(provenanceRaw, PROVENANCE_KEYS, `${path}.provenance`, errors);\n const promotedRaw = provenanceRaw?.promotedFrom === undefined ? null : record(provenanceRaw.promotedFrom);\n if (provenanceRaw?.promotedFrom !== undefined && !promotedRaw) errors.push(`${path}.provenance.promotedFrom must be an object`);\n if (promotedRaw) unknownKeys(promotedRaw, PROMOTION_KEYS, `${path}.provenance.promotedFrom`, errors);\n const promotedFrom = promotedRaw ? {\n chapterId: text(promotedRaw.chapterId, `${path}.provenance.promotedFrom.chapterId`, errors, 63) ?? \"\",\n resourceId: text(promotedRaw.resourceId, `${path}.provenance.promotedFrom.resourceId`, errors, 80) ?? \"\",\n resourceRevision: integer(promotedRaw.resourceRevision, `${path}.provenance.promotedFrom.resourceRevision`, errors),\n documentRevision: integer(promotedRaw.documentRevision, `${path}.provenance.promotedFrom.documentRevision`, errors),\n promotedBy: text(promotedRaw.promotedBy, `${path}.provenance.promotedFrom.promotedBy`, errors, 320) ?? \"\",\n promotedAt: integer(promotedRaw.promotedAt, `${path}.provenance.promotedFrom.promotedAt`, errors, 0),\n } : undefined;\n const provenance = {\n createdBy: text(provenanceRaw?.createdBy, `${path}.provenance.createdBy`, errors, 320) ?? \"\",\n createdAt: integer(provenanceRaw?.createdAt, `${path}.provenance.createdAt`, errors, 0),\n updatedBy: text(provenanceRaw?.updatedBy, `${path}.provenance.updatedBy`, errors, 320) ?? \"\",\n updatedAt: integer(provenanceRaw?.updatedAt, `${path}.provenance.updatedAt`, errors, 0),\n ...(promotedFrom ? { promotedFrom } : {}),\n };\n return { id, kind: kind as BuilderLibraryResource[\"kind\"], title, ...(summary ? { summary } : {}), tags, scope, status: status as BuilderLibraryResource[\"status\"], revision, ...(bodyMarkdown ? { bodyMarkdown } : {}), ...(url ? { url } : {}), ...(brandAsset ? { brandAsset } : {}), provenance };\n}\n\n/** Strictly validate size, shape, authority, and the closed scope enum. */\nexport function validateBuilderLibraryDocument(\n value: unknown,\n options: BuilderLibraryValidationOptions = {},\n): BuilderLibraryValidationResult {\n const errors: string[] = [];\n const raw = record(value);\n if (!raw) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(raw, ROOT_KEYS, \"document\", errors);\n if (raw.schemaVersion !== BUILDER_LIBRARY_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n const revision = integer(raw.revision, \"document.revision\", errors);\n const generatedAt = integer(raw.generatedAt, \"document.generatedAt\", errors, 0);\n const sourceRaw = record(raw.source);\n if (!sourceRaw) errors.push(\"document.source must be an object\");\n if (sourceRaw) unknownKeys(sourceRaw, SOURCE_KEYS, \"document.source\", errors);\n const sourceType = sourceRaw?.type;\n if (sourceType !== \"chapter\" && sourceType !== \"built_not_found\") errors.push(\"document.source.type must be chapter or built_not_found\");\n const sourceAppId = text(sourceRaw?.appId, \"document.source.appId\", errors, 63) ?? \"\";\n if (sourceAppId && !APP_ID.test(sourceAppId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (options.sourceType && sourceType !== options.sourceType) errors.push(`document.source.type must be ${options.sourceType}`);\n if (options.sourceAppId && sourceAppId !== options.sourceAppId) errors.push(`document.source.appId must be ${options.sourceAppId}`);\n const targetRaw = raw.target === undefined ? null : record(raw.target);\n if (raw.target !== undefined && !targetRaw) errors.push(\"document.target must be an object\");\n if (targetRaw) unknownKeys(targetRaw, TARGET_KEYS, \"document.target\", errors);\n const target = targetRaw ? {\n appId: text(targetRaw.appId, \"document.target.appId\", errors, 63) ?? \"\",\n environment: text(targetRaw.environment, \"document.target.environment\", errors, 80) ?? \"\",\n } : undefined;\n if (options.targetAppId && target?.appId !== options.targetAppId) errors.push(`document.target.appId must be ${options.targetAppId}`);\n if (!Array.isArray(raw.resources)) errors.push(\"document.resources must be an array\");\n const inputs = Array.isArray(raw.resources) ? raw.resources : [];\n if (inputs.length > MAX_RESOURCES) errors.push(`document.resources may contain at most ${MAX_RESOURCES} items`);\n const resources = inputs.map((item, index) => resourceValue(item, `document.resources[${index}]`, errors)).filter(Boolean) as BuilderLibraryResource[];\n const ids = resources.map(({ id }) => id);\n if (new Set(ids).size !== ids.length) errors.push(\"document.resources ids must be unique\");\n for (const resource of resources) {\n if (sourceType === \"chapter\" && (resource.scope.kind !== \"chapter\" || resource.scope.chapterId !== sourceAppId)) {\n errors.push(`document.resources.${resource.id}: Chapter sources may author only their own chapter scope`);\n }\n if (sourceType === \"built_not_found\" && resource.scope.kind === \"chapter\"\n && !(options.allowedChapterIds ?? []).includes(resource.scope.chapterId)) {\n errors.push(`document.resources.${resource.id}: Built Not Found may target only configured Chapters`);\n }\n }\n if (errors.length) return { ok: false, errors };\n return { ok: true, value: { schemaVersion: 1, revision, generatedAt, source: { type: sourceType as BuilderLibraryDocument[\"source\"][\"type\"], appId: sourceAppId }, ...(target ? { target } : {}), resources } };\n}\n","/** Versioned contract for private Builder Library source material. */\nexport const BUILDER_LIBRARY_SCHEMA_VERSION = 1 as const;\n/** Authenticated admin inventory and local-authoring endpoint. */\nexport const BUILDER_LIBRARY_ADMIN_PATH = \"/api/admin/builder-library\" as const;\n/** Authenticated, published-only agent manifest endpoint. */\nexport const BUILDER_LIBRARY_MANIFEST_PATH = \"/api/admin/builder-library/manifest\" as const;\n/** Built Not Found-only audited Chapter-to-global promotion endpoint. */\nexport const BUILDER_LIBRARY_PROMOTE_PATH = \"/api/admin/builder-library/promote\" as const;\n/** Dedicated signed federation receiver for Builder Library documents. */\nexport const BUILDER_LIBRARY_CONTROL_PATH = \"/api/builder-library-control\" as const;\n\n/** Authority kind attached to one complete Builder Library document. */\nexport type BuilderLibrarySourceType = \"chapter\" | \"built_not_found\";\n/** Stable authority identity attached to a Builder Library document. */\nexport interface BuilderLibrarySource { type: BuilderLibrarySourceType; appId: string }\n/** Exact app deployment that a signed Builder Library revision targets. */\nexport interface BuilderLibraryTarget { appId: string; environment: string }\n\n/** Exactly one visibility scope. There are deliberately no groups or audience arrays. */\nexport type BuilderLibraryScope =\n | { kind: \"chapter\"; chapterId: string }\n | { kind: \"built_not_found\" }\n | { kind: \"global\" };\n\n/** Supported private source-material representations. */\nexport type BuilderLibraryResourceKind = \"document\" | \"note\" | \"link\" | \"inspiration\" | \"image\" | \"file\";\n/** Explicit authoring lifecycle; only published resources enter agent manifests. */\nexport type BuilderLibraryResourceStatus = \"draft\" | \"published\" | \"archived\";\n\n/** Durable Brand identity only; URLs, bytes, and storage credentials never enter a manifest. */\nexport interface BuilderLibraryBrandAssetRef {\n bookId: string;\n assetId: string;\n filename?: string;\n}\n\n/** Immutable origin recorded when Built Not Found promotes Chapter material. */\nexport interface BuilderLibraryPromotionProvenance {\n chapterId: string;\n resourceId: string;\n resourceRevision: number;\n documentRevision: number;\n promotedBy: string;\n promotedAt: number;\n}\n\n/** Server-authored creation/update history for one resource. */\nexport interface BuilderLibraryResourceProvenance {\n createdBy: string;\n createdAt: number;\n updatedBy: string;\n updatedAt: number;\n promotedFrom?: BuilderLibraryPromotionProvenance;\n}\n\n/** One bounded, revisioned private source item. */\nexport interface BuilderLibraryResource {\n id: string;\n kind: BuilderLibraryResourceKind;\n title: string;\n summary?: string;\n tags: readonly string[];\n scope: BuilderLibraryScope;\n status: BuilderLibraryResourceStatus;\n revision: number;\n bodyMarkdown?: string;\n url?: string;\n brandAsset?: BuilderLibraryBrandAssetRef;\n provenance: BuilderLibraryResourceProvenance;\n}\n\n/** Complete local or federated authoring layer. */\nexport interface BuilderLibraryDocument {\n schemaVersion: typeof BUILDER_LIBRARY_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: BuilderLibrarySource;\n target?: BuilderLibraryTarget;\n resources: readonly BuilderLibraryResource[];\n}\n\n/** Validation constraints that bind a document to its trusted source and target. */\nexport interface BuilderLibraryValidationOptions {\n sourceType?: BuilderLibrarySourceType;\n sourceAppId?: string;\n targetAppId?: string;\n /** Chapter IDs a Built Not Found document may address. An empty or omitted\n * allowlist keeps the historical global-or-private-only behavior. */\n allowedChapterIds?: readonly string[];\n}\n\n/** A validated document or actionable strict-contract errors. */\nexport type BuilderLibraryValidationResult =\n | { ok: true; value: BuilderLibraryDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Principal whose closed-scope visibility is projected. */\nexport type BuilderLibraryViewer =\n | { kind: \"built_not_found\" }\n | { kind: \"chapter\"; chapterId: string };\n\n/** Bounded agent input. It contains references, never private asset bytes or credentials. */\nexport interface BuilderLibraryManifest {\n schemaVersion: typeof BUILDER_LIBRARY_SCHEMA_VERSION;\n generatedAt: number;\n viewer: BuilderLibraryViewer;\n revisions: readonly { source: BuilderLibrarySource; revision: number }[];\n resources: readonly BuilderLibraryResource[];\n truncated: boolean;\n}\n\n/** Canonical document and digest transmitted over the signed library edge. */\nexport interface BuilderLibraryEnvelope { digest: string; document: BuilderLibraryDocument }\n/** Durable acknowledgement for an accepted or idempotently replayed revision. */\nexport interface BuilderLibraryReceipt {\n ok: true;\n target: BuilderLibraryTarget;\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\nexport { validateBuilderLibraryDocument } from \"./builder-library-validation\";\n\n/** Apply the closed visibility matrix. */\nexport function canViewBuilderLibraryResource(\n resource: BuilderLibraryResource,\n viewer: BuilderLibraryViewer,\n): boolean {\n if (viewer.kind === \"built_not_found\") return true;\n return resource.scope.kind === \"global\"\n || (resource.scope.kind === \"chapter\" && resource.scope.chapterId === viewer.chapterId);\n}\n\n/** Produce deterministic, published-only input for a site-building agent. */\nexport function buildBuilderLibraryManifest(\n documents: readonly BuilderLibraryDocument[],\n viewer: BuilderLibraryViewer,\n generatedAt = Date.now(),\n limit = 100,\n): BuilderLibraryManifest {\n const ordered = documents\n .flatMap((document) => document.resources.map((resource) => ({ document, resource })))\n .filter(({ resource }) => resource.status === \"published\" && canViewBuilderLibraryResource(resource, viewer))\n .sort((a, b) => a.resource.title.localeCompare(b.resource.title)\n || a.document.source.appId.localeCompare(b.document.source.appId)\n || a.resource.id.localeCompare(b.resource.id));\n return {\n schemaVersion: BUILDER_LIBRARY_SCHEMA_VERSION,\n generatedAt,\n viewer,\n revisions: documents.map(({ source, revision }) => ({ source, revision })),\n resources: ordered.slice(0, limit).map(({ resource }) => resource),\n truncated: ordered.length > limit,\n };\n}\n\n/** Build the exact signed layer for one peer; private and sibling material\n * never crosses to a Chapter. */\nexport function projectBuilderLibraryDelivery(\n document: BuilderLibraryDocument,\n target: BuilderLibraryTarget,\n): BuilderLibraryDocument {\n return {\n ...document,\n target,\n resources: document.source.type === \"built_not_found\"\n ? document.resources.filter((resource) => resource.scope.kind === \"global\"\n || (resource.scope.kind === \"chapter\" && resource.scope.chapterId === target.appId))\n : document.resources,\n };\n}\n\n/** Copy a Chapter item into global authority while preserving its exact origin. */\nexport function promoteBuilderLibraryResource(input: {\n resource: BuilderLibraryResource;\n chapterDocumentRevision: number;\n actor: string;\n promotedAt: number;\n globalId?: string;\n}): BuilderLibraryResource {\n if (input.resource.scope.kind !== \"chapter\") throw new TypeError(\"only a Chapter-scoped resource can be promoted\");\n const chapterId = input.resource.scope.chapterId;\n return {\n ...input.resource,\n id: input.globalId ?? `${chapterId}-${input.resource.id}`,\n scope: { kind: \"global\" },\n revision: 1,\n provenance: {\n createdBy: input.actor,\n createdAt: input.promotedAt,\n updatedBy: input.actor,\n updatedAt: input.promotedAt,\n promotedFrom: {\n chapterId,\n resourceId: input.resource.id,\n resourceRevision: input.resource.revision,\n documentRevision: input.chapterDocumentRevision,\n promotedBy: input.actor,\n promotedAt: input.promotedAt,\n },\n },\n };\n}\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"Builder Library contains an unsupported value\");\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).sort().flatMap((key) => record[key] === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(record[key])}`]).join(\",\")}}`;\n}\n\n/** Serialize Builder Library JSON with recursively sorted object keys. */\nexport function canonicalBuilderLibrary(value: unknown): string { return canonicalValue(value); }\n\n/** Compute a canonical SHA-256 digest for one signed library revision. */\nexport async function builderLibraryDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalBuilderLibrary(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one validated document with the exact digest its target acknowledges. */\nexport async function createBuilderLibraryEnvelope(document: import(\"./builder-library\").BuilderLibraryDocument) {\n return { document, digest: await builderLibraryDigest(document) };\n}\n","// The chapter email pipeline: exactly-once delivery, a non-production fail-safe,\n// and template rendering. Every property here is easy to get wrong and expensive\n// to get wrong, so the correctness-critical decisions — the dedupe check (E1),\n// the dev-redirect / log-only fail-safe (E2), and template rendering (E4) — are\n// PURE and fully tested in this module. The worker supplies the transport +\n// odla-db and performs the actual send + emailLog write around these decisions.\n//\n// Chapter's operational templates ({ subject, text, enabled? }) are\n// transactional lifecycle mail by construction — a site owner edits the copy in\n// Settings but cannot reclassify one as marketing. Consent-gated marketing blasts\n// go through @odla-ai/crm, which owns the transactional-vs-marketing template\n// class as code (E3), so relabeling copy can never bypass the consent gate.\n\n/** One owner-editable template row on the group. `enabled` absent = enabled. */\nexport interface EmailTemplateRow {\n subject: string;\n text: string;\n enabled?: boolean;\n}\n\n/** The `groups`-row fields the email pipeline reads. */\nexport interface EmailGroup {\n id: string;\n name: string;\n replyTo: string;\n /** Non-prod debug inbox: all mail redirects here outside prod (E2). */\n debugEmail?: string;\n refundPolicyText?: string;\n commitmentText?: string;\n normsText?: string;\n emailTemplates: Record<string, EmailTemplateRow>;\n}\n\n/** `{{placeholder}}` substitution; unknown placeholders render empty. */\nexport function render(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => vars[key] ?? \"\");\n}\n\n/** Group-level vars every template receives, under the caller's vars. */\nfunction groupVars(group: EmailGroup, vars: Record<string, string>): Record<string, string> {\n return {\n ...vars,\n refundPolicyText: group.refundPolicyText ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n };\n}\n\n/**\n * Re-render a template's body for history/preview (E4): the CRM comms history\n * reads back emails whose body predates `emailLog.body` by rendering the current\n * template with the recipient's vars. Same substitution + group vars as the send\n * path. `null` for an unknown template. Reflects the copy as it reads today, not\n * necessarily the exact bytes originally sent (only `emailLog.body` is byte-exact).\n */\nexport function renderTemplateBody(group: EmailGroup, template: string, vars: Record<string, string>): string | null {\n const tpl = group.emailTemplates?.[template];\n if (!tpl) return null;\n return render(tpl.text, groupVars(group, vars));\n}\n\n/**\n * E1 (exactly-once): given the prior `emailLog` rows for a `dedupeKey`, has the\n * mail already been delivered? A prior row with **no error** means yes — the\n * caller short-circuits the resend. Failure rows (which carry an `error` and are\n * written without the dedupe mutationId) do not count, so a retry after a failure\n * can still succeed.\n */\nexport function isAlreadySent(priorRows: ReadonlyArray<{ error?: unknown }>): boolean {\n return priorRows.some((row) => !row.error);\n}\n\n/** The pure delivery decision produced by {@link planDelivery}. */\nexport type DeliveryDecision =\n | { deliver: false; reason: \"template-missing\" | \"disabled\" }\n | {\n deliver: true;\n /** Which transport to use — `log-only` records the send but delivers nothing. */\n transport: \"cloudflare\" | \"log-only\";\n to: string;\n subject: string;\n text: string;\n /** True when redirected to the non-prod debug inbox. */\n redirected: boolean;\n };\n\n/**\n * The pure delivery decision (E2 fail-safe + E3 enabled). Given the env, group,\n * template, recipient, and whether a real Cloudflare transport is wired:\n * - missing template → not delivered (`template-missing`);\n * - disabled template and not forced → not delivered (`disabled`);\n * - **non-prod with a debug inbox** → REDIRECT to it, `\"[dev] \"` subject prefix,\n * a dev-redirect note in the body, so test applicants never receive real mail;\n * - **non-prod with NO debug inbox** → force `log-only` (deliver nothing) — the\n * fail-safe that protects every site's test data;\n * - prod → deliver via the real transport (`cloudflare` if wired, else `log-only`).\n */\nexport function planDelivery(input: {\n envName: string;\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n /** Whether a Cloudflare Email Service transport (binding + verified from) is wired. */\n cloudflareReady: boolean;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}): DeliveryDecision {\n const tpl = input.group.emailTemplates?.[input.template];\n if (!tpl) return { deliver: false, reason: \"template-missing\" };\n if (tpl.enabled === false && !input.force) return { deliver: false, reason: \"disabled\" };\n\n const vars = groupVars(input.group, input.vars);\n const isProd = input.envName === \"prod\";\n const redirect = !isProd && !!input.group.debugEmail;\n const transport: \"cloudflare\" | \"log-only\" =\n !isProd && !redirect ? \"log-only\" : input.cloudflareReady ? \"cloudflare\" : \"log-only\";\n const to = redirect ? (input.group.debugEmail as string) : input.to;\n const subject = (redirect ? \"[dev] \" : \"\") + render(tpl.subject, vars);\n const text = redirect\n ? `(dev redirect; original recipient: ${input.to})\\n\\n` + render(tpl.text, vars)\n : render(tpl.text, vars);\n return { deliver: true, transport, to, subject, text, redirected: redirect };\n}\n","// sendTemplated — the operational-email orchestration that wires the pure email\n// decisions (./email: isAlreadySent E1, planDelivery E2/E3) to odla-db + a\n// transport. Structural (takes a ChapterDb + a sender), so it's FakeDb-testable\n// like submitApplication/projectSharedRecord. The worker's lifecycle routes call\n// it to send the prep / payment-confirmation / admin-alert mail.\n//\n// Exactly-once is enforced twice: a prior successful emailLog row short-circuits\n// the resend (query + isAlreadySent), AND the success row is written under the\n// `email:${dedupeKey}` mutationId so a racing double-send dedupes at the db layer.\n// Failure rows omit the mutationId, so a retry after a transient failure can send.\nimport { isAlreadySent, planDelivery } from \"./email\";\nimport type { EmailGroup } from \"./email\";\nimport type { ChapterDb } from \"./types\";\n\n/** The canonical lifecycle email templates chapter fires, in send-order. Owner-\n * editable copy lives on the group row; this is the fixed set the admin email\n * editor + test route iterate. */\nexport const EMAIL_TEMPLATE_NAMES = [\"adminNotification\", \"paymentConfirmation\", \"prepEmail\", \"onboardingInvite\"] as const;\n\n/** One of {@link EMAIL_TEMPLATE_NAMES}. */\nexport type EmailTemplateName = (typeof EMAIL_TEMPLATE_NAMES)[number];\n\n/** The mail transport (the worker's Cloudflare SEND_EMAIL binding). */\nexport interface MailSender {\n send(payload: { from: string; to: string[]; subject: string; text?: string; replyTo?: string }): Promise<{ messageId: string }>;\n}\n\n/** Deps for {@link sendTemplated} — the db, the env name (drives the fail-safe),\n * the transport + from (absent ⇒ log-only), and injected clock/id. */\nexport interface NotifyDeps {\n db: ChapterDb;\n envName: string;\n sender?: MailSender;\n from?: string;\n now: () => number;\n newId: () => string;\n}\n\n/** One templated send. `dedupeKey` is the exactly-once key. */\nexport interface NotifyInput {\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n dedupeKey: string;\n applicationId?: string;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}\n\n/** The outcome. `sent:true` includes the already-sent short-circuit. */\nexport interface NotifyResult {\n sent: boolean;\n reason?: string;\n}\n\n/**\n * Send a templated lifecycle email exactly once. Short-circuits on a prior\n * successful send; otherwise plans delivery (dev fail-safe applies), sends via the\n * transport when one is wired and the plan calls for it, and records an emailLog\n * row either way (success keyed for exactly-once, failure unkeyed for retry).\n */\nexport async function sendTemplated(deps: NotifyDeps, input: NotifyInput): Promise<NotifyResult> {\n const { emailLog } = await deps.db.query({ emailLog: { $: { where: { dedupeKey: input.dedupeKey } } } });\n const prior = (Array.isArray(emailLog) ? emailLog : []) as Array<{ error?: unknown }>;\n if (isAlreadySent(prior)) return { sent: true, reason: \"already-sent\" };\n\n const cloudflareReady = Boolean(deps.sender && deps.from);\n const decision = planDelivery({\n envName: deps.envName,\n group: input.group,\n template: input.template,\n to: input.to,\n vars: input.vars,\n cloudflareReady,\n force: input.force,\n });\n if (!decision.deliver) return { sent: false, reason: decision.reason };\n\n let error: string | undefined;\n let messageId: string | undefined;\n if (decision.transport === \"cloudflare\" && deps.sender && deps.from) {\n try {\n const res = await deps.sender.send({\n from: deps.from,\n to: [decision.to],\n subject: decision.subject,\n text: decision.text,\n replyTo: input.group.replyTo,\n });\n messageId = res.messageId;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n const id = deps.newId();\n const row: Record<string, unknown> = {\n id,\n groupId: input.group.id,\n to: decision.to,\n template: input.template,\n subject: decision.subject,\n body: decision.text,\n transport: decision.transport,\n redirected: decision.redirected,\n dedupeKey: input.dedupeKey,\n sentAt: deps.now(),\n ...(input.applicationId ? { applicationId: input.applicationId } : {}),\n ...(messageId ? { messageId } : {}),\n ...(error ? { error } : {}),\n };\n await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: row }], error ? undefined : { mutationId: `email:${input.dedupeKey}` });\n return error ? { sent: false, reason: error } : { sent: true };\n}\n\n/** Project a `groups` row into the {@link EmailGroup} the email pipeline reads. */\nexport function emailGroupFrom(row: Record<string, unknown>): EmailGroup {\n const str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n const templates = row.emailTemplates && typeof row.emailTemplates === \"object\" ? row.emailTemplates : {};\n return {\n id: String(row.id),\n name: String(row.name ?? \"\"),\n replyTo: str(row.replyTo) ?? \"\",\n debugEmail: str(row.debugEmail),\n refundPolicyText: str(row.refundPolicyText),\n commitmentText: str(row.commitmentText),\n normsText: str(row.normsText),\n emailTemplates: templates as EmailGroup[\"emailTemplates\"],\n };\n}\n","// Payments primitives. Generic Stripe form encoding and webhook authenticity\n// live in @odla-ai/stripe; Chapter keeps only membership-specific readiness,\n// event normalization, and write sets. This preserves Chapter's public exports\n// while making the provider plumbing reusable by every app.\nexport { stripeForm, verifyStripeSignature } from \"@odla-ai/stripe\";\n\n// ── readiness + Stripe wire helpers ──\n\n/** A group row's payment configuration, as far as readiness cares. */\nexport interface PaymentsGroup {\n stripePublishableKey?: string | null;\n stripePriceId?: string | null;\n}\n\n/** Whether a group can take payment: a publishable key + a price id (both on the\n * group row) AND a secret key (the vault). Anything missing drops the join\n * flow's payment step (paymentsReady:false) rather than half-charging. */\nexport function paymentsReady(group: PaymentsGroup, hasSecretKey: boolean): boolean {\n return Boolean(group.stripePublishableKey && group.stripePriceId && hasSecretKey);\n}\n\n/** The Stripe idempotency key for creating an application's subscription — one\n * per application, so a client retry can't orphan a second subscription. */\nexport function subscriptionIdempotencyKey(applicationId: string): string {\n return `sub:${applicationId}`;\n}\n\n/** The db mutationId for a webhook-driven application write. A separate signed\n * event receipt fences replays and event-id collisions across every write in\n * the route; this id keeps the application mutation itself idempotent. */\nexport function webhookMutationId(eventId: string): string {\n return `stripe:${eventId}`;\n}\n\n// ── webhook normalization (pure; the worker owns the db lookup + writes) ──\n\n/** A raw Stripe event, as far as normalization cares. */\nexport interface StripeEvent {\n id: string;\n type: string;\n data?: { object?: Record<string, unknown> };\n}\n\n/** A normalized, provider-agnostic webhook event. `kind` drives the db write;\n * the application is resolved from `applicationId` (metadata) or `customerId`. */\nexport type WebhookEvent = (\n | { kind: \"gift_paid\"; giftIntentId: string; providerObjectId: string }\n | { kind: \"gift_revoked\"; giftIntentId: string; reason: \"refunded\" | \"canceled\" }\n | { kind: \"first_payment\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"renewal\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"refunded\"; applicationId?: string; customerId?: string }\n | { kind: \"canceled\"; applicationId?: string; customerId?: string }\n | { kind: \"ignored\"; type: string }\n) & { appId?: string; environment?: string; dataEnvironment?: string; runtime?: string; chapterId?: string };\n\n/** Resolve the application reference on a Stripe object: `applicationId` from\n * metadata (direct, then subscription_details, then nested\n * parent.subscription_details), plus the customer id for the db fallback. */\nexport function findApplicationRef(obj: Record<string, unknown>): {\n applicationId?: string;\n customerId?: string;\n appId?: string;\n environment?: string;\n dataEnvironment?: string;\n runtime?: string;\n chapterId?: string;\n} {\n const metaOf = (v: unknown): Record<string, unknown> =>\n v && typeof v === \"object\" ? ((v as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (m: Record<string, unknown>): string | undefined =>\n typeof m.applicationId === \"string\" ? m.applicationId : undefined;\n const candidates = [\n metaOf(obj),\n metaOf(obj.subscription_details),\n metaOf((obj.parent as Record<string, unknown> | undefined)?.subscription_details),\n ];\n const applicationId = candidates.map(pick).find(Boolean);\n const appId = candidates.map((metadata) => typeof metadata.odlaAppId === \"string\" ? metadata.odlaAppId : undefined).find(Boolean);\n const environment = candidates.map((metadata) => typeof metadata.odlaEnvironment === \"string\" ? metadata.odlaEnvironment : undefined).find(Boolean);\n const dataEnvironment = candidates.map((metadata) => typeof metadata.odlaDataEnvironment === \"string\" ? metadata.odlaDataEnvironment : undefined).find(Boolean);\n const runtime = candidates.map((metadata) => typeof metadata.odlaRuntime === \"string\" ? metadata.odlaRuntime : undefined).find(Boolean);\n const chapterId = candidates.map((metadata) => typeof metadata.chapterId === \"string\" ? metadata.chapterId : undefined).find(Boolean);\n const customerId = typeof obj.customer === \"string\" ? obj.customer : undefined;\n return {\n ...(applicationId ? { applicationId } : {}),\n ...(customerId ? { customerId } : {}),\n ...(appId ? { appId } : {}),\n ...(environment ? { environment } : {}),\n ...(dataEnvironment ? { dataEnvironment } : {}),\n ...(runtime ? { runtime } : {}),\n ...(chapterId ? { chapterId } : {}),\n };\n}\n\n/** Resolve gift purchase metadata from direct or invoice subscription metadata. */\nexport function findGiftRef(obj: Record<string, unknown>): {\n giftIntentId?: string; providerObjectId: string; appId?: string;\n environment?: string; dataEnvironment?: string; runtime?: string;\n chapterId?: string;\n} {\n const metaOf = (value: unknown): Record<string, unknown> =>\n value && typeof value === \"object\" ? ((value as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (metadata: Record<string, unknown>): string | undefined =>\n typeof metadata.giftIntentId === \"string\" ? metadata.giftIntentId : undefined;\n const parent = obj.parent as Record<string, unknown> | undefined;\n const subscription = obj.subscription_details ?? parent?.subscription_details;\n const giftIntentId = pick(metaOf(obj)) ?? pick(metaOf(subscription));\n const subscriptionId = typeof obj.subscription === \"string\"\n ? obj.subscription\n : typeof (subscription as Record<string, unknown> | undefined)?.subscription === \"string\"\n ? String((subscription as Record<string, unknown>).subscription)\n : undefined;\n const candidates = [metaOf(obj), metaOf(subscription)];\n const pickIdentity = (name: string) => candidates\n .map((metadata) => typeof metadata[name] === \"string\" ? String(metadata[name]) : undefined).find(Boolean);\n const appId = pickIdentity(\"odlaAppId\");\n const environment = pickIdentity(\"odlaEnvironment\");\n const dataEnvironment = pickIdentity(\"odlaDataEnvironment\");\n const runtime = pickIdentity(\"odlaRuntime\");\n const chapterId = pickIdentity(\"chapterId\");\n return {\n ...(giftIntentId ? { giftIntentId } : {}),\n providerObjectId: subscriptionId ?? String(obj.id ?? \"\"),\n ...(appId ? { appId } : {}),\n ...(environment ? { environment } : {}),\n ...(dataEnvironment ? { dataEnvironment } : {}),\n ...(runtime ? { runtime } : {}),\n ...(chapterId ? { chapterId } : {}),\n };\n}\n\n/** Normalize a verified Stripe event into a {@link WebhookEvent}. `invoice.paid`\n * splits into first_payment vs renewal by `billing_reason`; refunds and\n * cancellations map directly; everything else is ignored (acked, not retried). */\nexport function normalizeWebhookEvent(event: StripeEvent): WebhookEvent {\n const obj = event.data?.object ?? {};\n const gift = findGiftRef(obj);\n if (gift.giftIntentId) {\n const { giftIntentId, providerObjectId, ...identity } = gift;\n if (event.type === \"payment_intent.succeeded\" ||\n (event.type === \"invoice.paid\" && obj.billing_reason === \"subscription_create\")) {\n return { kind: \"gift_paid\", giftIntentId, providerObjectId, ...identity };\n }\n if (event.type === \"charge.refunded\") return { kind: \"gift_revoked\", giftIntentId, ...identity, reason: \"refunded\" };\n if (event.type === \"customer.subscription.deleted\") return { kind: \"gift_revoked\", giftIntentId, ...identity, reason: \"canceled\" };\n return { kind: \"ignored\", type: event.type };\n }\n const ref = findApplicationRef(obj);\n switch (event.type) {\n case \"invoice.paid\": {\n const lines = ((obj.lines as Record<string, unknown> | undefined)?.data as Array<Record<string, unknown>> | undefined) ?? [];\n const periodEnd = (lines[0]?.period as Record<string, unknown> | undefined)?.end;\n const renewalAt = typeof periodEnd === \"number\" ? periodEnd * 1000 : undefined;\n const kind = obj.billing_reason === \"subscription_create\" ? \"first_payment\" : \"renewal\";\n return { kind, ...ref, ...(renewalAt !== undefined ? { renewalAt } : {}) };\n }\n case \"charge.refunded\":\n return { kind: \"refunded\", ...ref };\n case \"customer.subscription.deleted\":\n return { kind: \"canceled\", ...ref };\n default:\n return { kind: \"ignored\", type: event.type };\n }\n}\n\n// ── webhook write-set builders (the authoritative writers of paid/refunded) ──\n\n/** First-payment patch: advance submitted→paid_pending_vetting (never any other\n * transition) and record the renewal date. Empty when nothing changed, so the\n * caller can skip the write. */\nexport function firstPaymentPatch(currentStatus: string, renewalAt?: number): { status?: \"paid_pending_vetting\"; renewalAt?: number } {\n return {\n ...(currentStatus === \"submitted\" ? { status: \"paid_pending_vetting\" as const } : {}),\n ...(renewalAt !== undefined ? { renewalAt } : {}),\n };\n}\n\n/** Renewal-invoice patch: just the new renewal date. */\nexport function renewalPatch(renewalAt: number): { renewalAt: number } {\n return { renewalAt };\n}\n\n/** Refund patch — the SOLE writer of status \"refunded\" (the admin refund route\n * issues the Stripe refund but never sets this; the webhook does). */\nexport function refundedPatch(): { status: \"refunded\" } {\n return { status: \"refunded\" };\n}\n\n/** Subscription-cancellation patch. */\nexport function canceledPatch(): { canceled: true } {\n return { canceled: true };\n}\n","/** Current wire version for parent-authored admission decisions. */\nexport const ADMISSION_GRANTS_SCHEMA_VERSION = 1 as const;\n/** Dedicated signed Parent → Chapter delivery endpoint. */\nexport const ADMISSION_GRANTS_PATH = \"/api/admission-grants\" as const;\n\n/** Whether an exact email can skip or must retain the Chapter interview. */\nexport type AdmissionDecision = \"waive_interview\" | \"require_interview\";\n\n/** One bounded admission decision. Email is PII and never enters public config. */\nexport interface AdmissionGrantInput {\n id: string;\n email: string;\n decision: AdmissionDecision;\n note?: string;\n expiresAt?: number;\n}\n\n/** Complete desired Parent state for one Chapter and environment. */\nexport interface AdmissionGrantDocument {\n schemaVersion: typeof ADMISSION_GRANTS_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: { appId: string; actor: string };\n target: { chapterId: string; environment: string };\n grants: readonly AdmissionGrantInput[];\n}\n\n/** Canonical desired-state document paired with its integrity digest. */\nexport interface AdmissionGrantEnvelope {\n digest: string;\n document: AdmissionGrantDocument;\n}\n\n/** Chapter acknowledgement for an accepted or idempotently replayed revision. */\nexport interface AdmissionGrantReceipt {\n ok: true;\n target: { chapterId: string; environment: string };\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable machine-readable rejection reasons returned by a Chapter receiver. */\nexport type AdmissionGrantRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"signup control contains an unsupported value\");\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record).sort().flatMap((key) => {\n const item = record[key];\n return item === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(item)}`];\n });\n return `{${entries.join(\",\")}}`;\n}\n\n/** Serialize JSON-like signup state with recursively sorted object keys. */\nexport function canonicalSignupControl(value: unknown): string {\n return canonicalValue(value);\n}\n\n/** Compute the protocol's canonical SHA-256 digest for desired signup state. */\nexport async function signupControlDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalSignupControl(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one desired-state document with its canonical digest for delivery. */\nexport async function createSignupControlEnvelope(document: import(\"./signup-control-contract\").SignupControlDocument) {\n return { document, digest: await signupControlDigest(document) };\n}\n","import type {\n AdmissionDecision,\n AdmissionGrantDocument,\n AdmissionGrantEnvelope,\n AdmissionGrantInput,\n} from \"./admission-grants-contract\";\nimport { ADMISSION_GRANTS_SCHEMA_VERSION } from \"./admission-grants-contract\";\nimport type { ChapterDb, DbOp } from \"./types\";\nimport { signupControlDigest } from \"./signup-control-canonical\";\nimport { normalizeChapterEmail } from \"./email-identity\";\n\nconst ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;\nconst MAX_GRANTS = 2_000;\nconst MAX_NOTE = 2_000;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst isAdmissionEmail = (value: string): boolean => EMAIL_RE.test(value);\n\n/** Exact email natural key: trim and lowercase, with no provider alias rules. */\nexport function normalizeAdmissionEmail(email: string): string {\n return normalizeChapterEmail(email);\n}\n\n/** Validated normalized admission document or all contract errors. */\nexport type AdmissionGrantValidation =\n | { ok: true; value: AdmissionGrantDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Validate and normalize a complete Parent admission document. */\nexport function validateAdmissionGrantDocument(input: unknown): AdmissionGrantValidation {\n const errors: string[] = [];\n const root = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (root.schemaVersion !== ADMISSION_GRANTS_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n const revision = Number(root.revision);\n const generatedAt = Number(root.generatedAt);\n if (!Number.isSafeInteger(revision) || revision < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isFinite(generatedAt) || generatedAt <= 0) errors.push(\"document.generatedAt must be epoch milliseconds\");\n const source = root.source && typeof root.source === \"object\" ? root.source as Record<string, unknown> : {};\n const target = root.target && typeof root.target === \"object\" ? root.target as Record<string, unknown> : {};\n const sourceId = typeof source.appId === \"string\" ? source.appId : \"\";\n const sourceActor = typeof source.actor === \"string\" ? source.actor.trim() : \"\";\n const chapterId = typeof target.chapterId === \"string\" ? target.chapterId : \"\";\n const environment = typeof target.environment === \"string\" ? target.environment : \"\";\n if (!ID.test(sourceId)) errors.push(\"document.source.appId must be an identifier\");\n if (!sourceActor || sourceActor.length > 256) errors.push(\"document.source.actor must be 1-256 characters\");\n if (!ID.test(chapterId)) errors.push(\"document.target.chapterId must be an identifier\");\n if (!ID.test(environment)) errors.push(\"document.target.environment must be an identifier\");\n if (!Array.isArray(root.grants)) errors.push(\"document.grants must be an array\");\n const rawGrants = Array.isArray(root.grants) ? root.grants : [];\n if (rawGrants.length > MAX_GRANTS) errors.push(`document.grants supports at most ${MAX_GRANTS} entries`);\n const grants: AdmissionGrantInput[] = [];\n const seenIds = new Set<string>();\n const seenEmails = new Set<string>();\n for (const [index, raw] of rawGrants.slice(0, MAX_GRANTS).entries()) {\n const grant = raw && typeof raw === \"object\" ? raw as Record<string, unknown> : {};\n const id = typeof grant.id === \"string\" ? grant.id : \"\";\n const email = typeof grant.email === \"string\" ? grant.email.trim() : \"\";\n const normalized = normalizeAdmissionEmail(email);\n const decision = grant.decision;\n const note = typeof grant.note === \"string\" ? grant.note.trim() : undefined;\n const expiresAt = grant.expiresAt === undefined ? undefined : Number(grant.expiresAt);\n if (!ID.test(id)) errors.push(`document.grants[${index}].id must be an identifier`);\n if (seenIds.has(id)) errors.push(`document.grants repeats id \"${id}\"`);\n if (!isAdmissionEmail(normalized)) errors.push(`document.grants[${index}].email must be valid`);\n if (seenEmails.has(normalized)) errors.push(`document.grants repeats email \"${normalized}\"`);\n if (decision !== \"waive_interview\" && decision !== \"require_interview\") {\n errors.push(`document.grants[${index}].decision is invalid`);\n }\n if (note && note.length > MAX_NOTE) errors.push(`document.grants[${index}].note is too long`);\n if (expiresAt !== undefined && (!Number.isFinite(expiresAt) || expiresAt <= 0)) {\n errors.push(`document.grants[${index}].expiresAt must be epoch milliseconds`);\n }\n seenIds.add(id);\n seenEmails.add(normalized);\n grants.push({\n id,\n email,\n decision: decision as AdmissionDecision,\n ...(note ? { note } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n });\n }\n if (errors.length) return { ok: false, errors };\n return {\n ok: true,\n value: {\n schemaVersion: ADMISSION_GRANTS_SCHEMA_VERSION,\n revision,\n generatedAt,\n source: { appId: sourceId, actor: sourceActor },\n target: { chapterId, environment },\n grants,\n },\n };\n}\n\n/** Pair a validated desired-state document with its canonical digest. */\nexport async function createAdmissionGrantEnvelope(document: AdmissionGrantDocument): Promise<AdmissionGrantEnvelope> {\n const checked = validateAdmissionGrantDocument(document);\n if (!checked.ok) throw new TypeError(`Invalid admission grant document: ${checked.errors.join(\"; \")}`);\n return { document: checked.value, digest: await signupControlDigest(checked.value) };\n}\n\n/** Materialized local or Parent admission decision stored by a Chapter. */\nexport interface AdmissionGrantRow {\n id: string;\n sourceGrantId: string;\n sourceScope: \"local\" | \"parent\";\n sourceId: string;\n targetId: string;\n email: string;\n emailNormalized: string;\n decision: AdmissionDecision;\n active: boolean;\n createdAt: number;\n note?: string;\n expiresAt?: number;\n revokedAt?: number;\n consumedAt?: number;\n consumedApplicationId?: string;\n}\n\nconst rows = (value: unknown): Array<Record<string, unknown>> => Array.isArray(value) ? value : [];\n\nfunction asGrant(row: Record<string, unknown>): AdmissionGrantRow | null {\n if (typeof row.id !== \"string\" || typeof row.emailNormalized !== \"string\") return null;\n if (row.sourceScope !== \"local\" && row.sourceScope !== \"parent\") return null;\n if (row.decision !== \"waive_interview\" && row.decision !== \"require_interview\") return null;\n return row as unknown as AdmissionGrantRow;\n}\n\n/** Resolve the effective current decision. Local rows always outrank Parent rows. */\nexport async function findAdmissionGrant(\n db: ChapterDb,\n targetId: string,\n email: string,\n now: number,\n): Promise<AdmissionGrantRow | null> {\n const emailNormalized = normalizeAdmissionEmail(email);\n if (!isAdmissionEmail(emailNormalized)) return null;\n const result = await db.query({ admissionGrants: { $: { where: { emailNormalized }, limit: 100 } } });\n const active = rows(result.admissionGrants)\n .map(asGrant)\n .filter((grant): grant is AdmissionGrantRow => Boolean(\n grant && grant.targetId === targetId && grant.active === true && !grant.revokedAt &&\n (!grant.expiresAt || grant.expiresAt > now) && !grant.consumedApplicationId,\n ))\n .sort((a, b) => {\n const scope = Number(b.sourceScope === \"local\") - Number(a.sourceScope === \"local\");\n return scope || b.createdAt - a.createdAt;\n });\n return active[0] ?? null;\n}\n\n/** Stored receipt for one signed Parent admission revision. */\nexport interface AdmissionGrantRevisionRow {\n id: string;\n sourceId: string;\n targetId: string;\n environment: string;\n revision: number;\n digest: string;\n active: boolean;\n receivedAt: number;\n}\n\nasync function hasAdmissionRevision(\n db: ChapterDb,\n sourceId: string,\n targetId: string,\n environment: string,\n): Promise<boolean> {\n const where = { sourceId, targetId, environment };\n if (db.aggregate) {\n return Number((await db.aggregate(\"admissionGrantRevisions\", { count: true }, { where })).count ?? 0) > 0;\n }\n const found = await db.query({ admissionGrantRevisions: {} });\n return rows(found.admissionGrantRevisions).some((row) =>\n row.sourceId === sourceId && row.targetId === targetId && row.environment === environment);\n}\n\n/** Read the newest received revision without issuing an ordered query over empty history. */\nexport async function loadLatestAdmissionRevision(\n db: ChapterDb,\n sourceId: string,\n targetId: string,\n environment: string,\n): Promise<AdmissionGrantRevisionRow | null> {\n if (!await hasAdmissionRevision(db, sourceId, targetId, environment)) return null;\n const result = await db.query({ admissionGrantRevisions: { $: {\n where: { sourceId, targetId, environment }, order: { revision: \"desc\" }, limit: 1,\n } } });\n const row = rows(result.admissionGrantRevisions)\n .sort((a, b) => Number(b.revision ?? 0) - Number(a.revision ?? 0))[0];\n return row ? row as unknown as AdmissionGrantRevisionRow : null;\n}\n\n/** Replace only Parent-authored rows; local Chapter decisions remain untouched. */\nexport async function materializeAdmissionGrants(\n db: ChapterDb,\n envelope: AdmissionGrantEnvelope,\n previous: AdmissionGrantRevisionRow | null,\n receivedAt: number,\n): Promise<void> {\n const { document, digest } = envelope;\n const current = rows((await db.query({ admissionGrants: { $: {\n where: { sourceScope: \"parent\", sourceId: document.source.appId, targetId: document.target.chapterId },\n limit: MAX_GRANTS,\n } } })).admissionGrants);\n const incomingIds = new Set(document.grants.map((grant) => `admission:parent:${document.source.appId}:${grant.id}`));\n const ops: DbOp[] = [];\n for (const row of current) {\n const id = String(row.id ?? \"\");\n if (id && !incomingIds.has(id)) ops.push({ t: \"update\", ns: \"admissionGrants\", id, attrs: {\n active: false, revokedAt: receivedAt, revokedBy: document.source.actor,\n updatedAt: receivedAt, updatedBy: document.source.actor,\n } });\n }\n for (const grant of document.grants) {\n const id = `admission:parent:${document.source.appId}:${grant.id}`;\n const existing = current.find((row) => row.id === id);\n ops.push({ t: \"update\", ns: \"admissionGrants\", id, attrs: {\n id,\n sourceGrantId: grant.id,\n sourceScope: \"parent\",\n sourceId: document.source.appId,\n targetId: document.target.chapterId,\n email: grant.email,\n emailNormalized: normalizeAdmissionEmail(grant.email),\n decision: grant.decision,\n ...(grant.note ? { note: grant.note } : {}),\n ...(grant.expiresAt ? { expiresAt: grant.expiresAt } : {}),\n active: true,\n sourceRevision: document.revision,\n createdAt: Number(existing?.createdAt ?? receivedAt),\n createdBy: String(existing?.createdBy ?? document.source.actor),\n updatedAt: receivedAt,\n updatedBy: document.source.actor,\n } });\n const retract = [\n ...(!grant.note && existing?.note !== undefined ? [\"note\"] : []),\n ...(grant.expiresAt === undefined && existing?.expiresAt !== undefined ? [\"expiresAt\"] : []),\n ];\n if (retract.length) ops.push({ t: \"retract\", ns: \"admissionGrants\", id, attrs: retract });\n }\n if (previous?.active) ops.push({ t: \"update\", ns: \"admissionGrantRevisions\", id: previous.id, attrs: { active: false } });\n const revisionId = `admission-revision:${document.source.appId}:${document.target.environment}:${document.revision}`;\n ops.push({ t: \"update\", ns: \"admissionGrantRevisions\", id: revisionId, attrs: {\n id: revisionId,\n sourceId: document.source.appId,\n targetId: document.target.chapterId,\n environment: document.target.environment,\n revision: document.revision,\n digest,\n active: true,\n receivedAt,\n } });\n await db.transact(ops, { mutationId: `admission-grants:${document.source.appId}:${document.target.environment}:${document.revision}:${digest}` });\n}\n","import { canBook } from \"./pipeline\";\nimport type { ResolvedPipeline } from \"./types\";\n\n/** Canonical next action or browser-visible step after application submission. */\nexport type JoinContinuation = \"payment\" | \"paymentPending\" | \"booking\" | \"approve\" | \"accepted\";\n\n/** One server-side decision for submit, resume, and payment completion. */\nexport function resolveJoinContinuation(input: {\n status: string;\n initialStatus: string;\n pipeline: ResolvedPipeline;\n payable: boolean;\n subscriptionStarted: boolean;\n interviewWaived: boolean;\n}): JoinContinuation | null {\n if (input.status === \"approved\") return \"accepted\";\n if (input.interviewWaived) {\n if (!input.payable) return \"approve\";\n if (input.status === input.initialStatus) {\n return input.subscriptionStarted ? \"paymentPending\" : \"payment\";\n }\n return \"approve\";\n }\n if (!input.payable) return \"booking\";\n if (input.status === input.initialStatus) {\n return input.subscriptionStarted ? \"paymentPending\" : \"payment\";\n }\n if (canBook(input.status, input.pipeline)) return \"booking\";\n return null;\n}\n","/** Current nested gift-catalog version inside signup-control. */\nexport const GIFT_OFFER_CATALOG_VERSION = 1 as const;\n/** Maximum signed gift SKUs accepted in one catalog revision. */\nexport const MAX_GIFT_OFFERS = 20;\n\n/** Membership tier or standalone entitlement fulfilled by redemption. */\nexport type GiftOfferTarget =\n | { type: \"tier\"; tierId: string }\n | { type: \"entitlement\"; entitlementKey: string };\n\n/** Server-authored gift SKU; provider identifiers never reach public config. */\nexport interface GiftOffer {\n id: string;\n target: GiftOfferTarget;\n billingMode: \"one_time\" | \"subscription\";\n stripePriceId: string;\n priceCents: number;\n currency: string;\n redemptionLifetimeHours: number;\n activeFrom?: number;\n activeUntil?: number;\n title: string;\n description: string;\n ctaLabel: string;\n}\n\n/** Versioned bounded collection delegated through signed signup control. */\nexport interface GiftOfferCatalog {\n schemaVersion: typeof GIFT_OFFER_CATALOG_VERSION;\n offers: readonly GiftOffer[];\n}\n\n/** Provider-free gift offer shape rendered by Chapter and exact CMS previews. */\nexport type PublicGiftOffer = Omit<GiftOffer, \"stripePriceId\" | \"target\">;\n\n/** Result of validating and normalizing an untrusted gift catalog. */\nexport type GiftOfferValidation =\n | { ok: true; value: GiftOfferCatalog }\n | { ok: false; errors: readonly string[] };\n\nconst ID = /^[a-z][a-z0-9-]{1,79}$/;\nconst PRICE = /^price_[A-Za-z0-9]{12,}$/;\nconst CURRENCY = /^[a-z]{3}$/;\nconst record = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\nconst text = (value: unknown, path: string, errors: string[], max: number): string => {\n if (typeof value !== \"string\" || !value.trim()) { errors.push(`${path} is required`); return \"\"; }\n if (value.trim().length > max) errors.push(`${path} must be at most ${max} characters`);\n return value.trim();\n};\n\n/** Validate and normalize gift offers against the same document's tier ids. */\nexport function validateGiftOfferCatalog(input: unknown, tierIds: ReadonlySet<string>): GiftOfferValidation {\n const errors: string[] = [];\n const root = record(input);\n if (!root) return { ok: false, errors: [\"document.giftOffers must be an object\"] };\n for (const key of Object.keys(root)) if (key !== \"schemaVersion\" && key !== \"offers\") errors.push(`document.giftOffers.${key} is not supported`);\n if (root.schemaVersion !== GIFT_OFFER_CATALOG_VERSION) errors.push(\"document.giftOffers.schemaVersion must be 1\");\n if (!Array.isArray(root.offers)) errors.push(\"document.giftOffers.offers must be an array\");\n const rawOffers = Array.isArray(root.offers) ? root.offers : [];\n if (rawOffers.length > MAX_GIFT_OFFERS) errors.push(`document.giftOffers.offers supports at most ${MAX_GIFT_OFFERS} entries`);\n const ids = new Set<string>();\n const offers: GiftOffer[] = [];\n for (const [index, raw] of rawOffers.slice(0, MAX_GIFT_OFFERS).entries()) {\n const path = `document.giftOffers.offers[${index}]`;\n const item = record(raw);\n if (!item) { errors.push(`${path} must be an object`); continue; }\n const allowed = new Set([\"id\", \"target\", \"billingMode\", \"stripePriceId\", \"priceCents\", \"currency\", \"redemptionLifetimeHours\", \"activeFrom\", \"activeUntil\", \"title\", \"description\", \"ctaLabel\"]);\n for (const key of Object.keys(item)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n const id = text(item.id, `${path}.id`, errors, 80);\n if (id && !ID.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (ids.has(id)) errors.push(`${path}.id duplicates \"${id}\"`);\n ids.add(id);\n const targetRaw = record(item.target);\n let target: GiftOfferTarget = { type: \"entitlement\", entitlementKey: \"invalid\" };\n if (targetRaw?.type === \"tier\") {\n const tierId = text(targetRaw.tierId, `${path}.target.tierId`, errors, 80);\n if (!tierIds.has(tierId)) errors.push(`${path}.target.tierId must reference a declared tier`);\n target = { type: \"tier\", tierId };\n } else if (targetRaw?.type === \"entitlement\") {\n const entitlementKey = text(targetRaw.entitlementKey, `${path}.target.entitlementKey`, errors, 80);\n if (entitlementKey && !ID.test(entitlementKey)) errors.push(`${path}.target.entitlementKey must be a lowercase kebab-case id`);\n target = { type: \"entitlement\", entitlementKey };\n } else errors.push(`${path}.target.type must be tier or entitlement`);\n if (item.billingMode !== \"one_time\" && item.billingMode !== \"subscription\") errors.push(`${path}.billingMode must be one_time or subscription`);\n const stripePriceId = text(item.stripePriceId, `${path}.stripePriceId`, errors, 128);\n if (stripePriceId && !PRICE.test(stripePriceId)) errors.push(`${path}.stripePriceId must be a real Stripe Price id`);\n if (!Number.isSafeInteger(item.priceCents) || Number(item.priceCents) < 1 || Number(item.priceCents) > 100_000_000) errors.push(`${path}.priceCents must be an integer from 1 to 100,000,000`);\n const currency = typeof item.currency === \"string\" ? item.currency.trim().toLowerCase() : \"\";\n if (!CURRENCY.test(currency)) errors.push(`${path}.currency must be a lowercase ISO currency code`);\n const lifetime = Number(item.redemptionLifetimeHours);\n if (!Number.isSafeInteger(lifetime) || lifetime < 1 || lifetime > 8_760) errors.push(`${path}.redemptionLifetimeHours must be an integer from 1 to 8760`);\n const activeFrom = item.activeFrom === undefined ? undefined : Number(item.activeFrom);\n const activeUntil = item.activeUntil === undefined ? undefined : Number(item.activeUntil);\n if (activeFrom !== undefined && (!Number.isSafeInteger(activeFrom) || activeFrom < 1)) errors.push(`${path}.activeFrom must be epoch milliseconds`);\n if (activeUntil !== undefined && (!Number.isSafeInteger(activeUntil) || activeUntil < 1)) errors.push(`${path}.activeUntil must be epoch milliseconds`);\n if (activeFrom !== undefined && activeUntil !== undefined && activeUntil <= activeFrom) errors.push(`${path}.activeUntil must follow activeFrom`);\n offers.push({\n id, target, billingMode: item.billingMode as GiftOffer[\"billingMode\"], stripePriceId,\n priceCents: Number(item.priceCents), currency, redemptionLifetimeHours: lifetime,\n ...(activeFrom !== undefined ? { activeFrom } : {}), ...(activeUntil !== undefined ? { activeUntil } : {}),\n title: text(item.title, `${path}.title`, errors, 160), description: text(item.description, `${path}.description`, errors, 2_000),\n ctaLabel: text(item.ctaLabel, `${path}.ctaLabel`, errors, 120),\n });\n }\n return errors.length ? { ok: false, errors } : { ok: true, value: { schemaVersion: 1, offers } };\n}\n\n/** Whether an offer is active at an exact server time. */\nexport const giftOfferActive = (offer: GiftOffer, now: number): boolean =>\n (!offer.activeFrom || offer.activeFrom <= now) && (!offer.activeUntil || offer.activeUntil > now);\n\n/** Public provider-free active catalog projection. */\nexport function publicGiftOffers(catalog: GiftOfferCatalog | undefined, now: number): PublicGiftOffer[] {\n return (catalog?.offers ?? []).filter((offer) => giftOfferActive(offer, now)).map(({ stripePriceId: _stripe, target: _target, ...offer }) => offer);\n}\n\n/** Resolve one currently active server-authoritative offer. */\nexport function findGiftOffer(catalog: GiftOfferCatalog | undefined, offerId: string, now: number): GiftOffer | null {\n return catalog?.offers.find((offer) => offer.id === offerId && giftOfferActive(offer, now)) ?? null;\n}\n","// Leader → follower projection of a deliberately allowlisted CRM field set.\n//\n// Invariants (package-enforced so no site re-derives them):\n// - One-way: the chapter never writes back to the hub through this path.\n// - Idempotent: every received record carries the leader's stable site +\n// record identity. A structured crm_record_origin row maps that identity to\n// the local CRM record, so a re-share updates instead of duplicating even\n// after an email/domain changes. Legacy tags remain as a migration bridge.\n// - Natural-key convergence: a person unifies by primary email and a business\n// by its configured domain slot (then name), so an arriving applicant and a\n// prior leader share compose into one person.\n// - Operational state stays local. Pipeline/account/billing state is not copied\n// into another site's authority; the push transfers the shared record fields.\n//\n// Reuses @odla-ai/crm's record ops (full validation via crm.prepare), driven by\n// the resolved chapter CRM engine + the structural ChapterDb.\nimport {\n createRecord,\n getRecordByOrigin,\n updateRecord,\n upsertRecordOrigin,\n} from \"@odla-ai/crm\";\nimport type { Crm, CrmRecord } from \"@odla-ai/crm\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\nimport {\n DEFAULT_SHARE_FIELDS,\n type NormalizedSharedRecord,\n type ProjectionDeps,\n type SharedBusiness,\n type SharedPerson,\n type SharedRecord,\n} from \"./network-contract\";\nexport { DEFAULT_SHARE_FIELDS } from \"./network-contract\";\nexport type {\n NetworkRollup, NetworkRollupTarget,\n NetworkSnapshot,\n ProjectionDeps,\n SharedBusiness,\n SharedPerson,\n SharedRecord,\n SharedRecordV1,\n SharedRecordV2,\n} from \"./network-contract\";\n\n/** Map a shared prospect to a crm `person` input (only the fields the default\n * person type accepts). Name falls back to first+last, then the email. */\nexport function sharedPersonInput(person: SharedPerson): Record<string, unknown> {\n const email = person.email.toLowerCase();\n const fullName = [person.firstName, person.lastName].filter(Boolean).join(\" \").trim();\n const input: Record<string, unknown> = { name: person.name ?? fullName ?? email, email };\n if (input.name === \"\") input.name = email;\n if (person.firstName) input.firstName = person.firstName;\n if (person.lastName) input.lastName = person.lastName;\n if (person.phone) input.phone = person.phone;\n if (person.linkedin) input.linkedin = person.linkedin;\n return input;\n}\n\nfunction shortHash(value: string): string {\n let a = 0x811c9dc5;\n let b = 0x9e3779b9;\n for (let i = 0; i < value.length; i += 1) {\n const n = value.charCodeAt(i);\n a = Math.imul(a ^ n, 0x01000193);\n b = Math.imul(b ^ n, 0x85ebca6b);\n }\n return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;\n}\n\n/** Backward-compatible display tag retained while structured origin rows are\n * the durable leader-id → local-record mapping. */\nexport function networkSourceTag(type: string, hubRecordId: string, sourceId?: string): string {\n const typeKey = type.toLowerCase();\n const readable = /^[a-z0-9_-]+$/.test(hubRecordId);\n const prefix = sourceId ? `network:${sourceId.toLowerCase()}:${typeKey}` : `network:${typeKey}`;\n const raw = `${prefix}:${hubRecordId}`;\n if (readable && raw.length <= 64) return raw;\n return `network:${typeKey.slice(0, 16)}:${shortHash(`${sourceId ?? \"\"}\\u0000${type}\\u0000${hubRecordId}`)}`;\n}\n\n/** Normalize the backwards-compatible person/business shapes into the versioned\n * generic record envelope the receiver writes. */\nexport function normalizeSharedRecord(\n record: SharedPerson | SharedBusiness | SharedRecord,\n fallbackSourceId = \"legacy-source\",\n): NormalizedSharedRecord {\n if (\"input\" in record && record.version === 2) {\n return {\n version: 2,\n sourceId: record.source.siteId,\n sourceRecordId: record.source.recordId,\n type: record.type,\n input: record.input,\n };\n }\n if (\"input\" in record) {\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: record.type,\n input: record.input,\n };\n }\n if (\"type\" in record && record.type === \"company\") {\n const input: Record<string, unknown> = { name: record.name };\n for (const key of [\"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"] as const) {\n if (record[key]) input[key] = record[key];\n }\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: \"company\",\n input,\n };\n }\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: \"person\",\n input: sharedPersonInput(record),\n };\n}\n\n/** Build the allowlisted payload sent from one leader CRM record to a target.\n * A target with an explicit `fields` map only accepts the types it lists. */\nexport function sharedRecordFromCrm(\n crm: Crm,\n record: CrmRecord,\n target: ResolvedNetworkTarget,\n sourceId?: string,\n): SharedRecord {\n if (target.fields && !target.fields[record.type]) {\n throw new Error(`${target.name} does not accept \"${record.type}\" records`);\n }\n const def = crm.type(record.type);\n const fields = target.fields?.[record.type] ?? DEFAULT_SHARE_FIELDS[record.type];\n if (!fields) {\n throw new Error(`${target.name} requires an explicit field allowlist for \"${record.type}\" records`);\n }\n const nameField = def.nameField ?? \"name\";\n const input: Record<string, unknown> = {};\n for (const field of new Set([nameField, ...fields])) {\n const value = record.fields?.[field];\n if (value !== undefined) input[field] = value;\n }\n if (input[nameField] === undefined) input[nameField] = record.name;\n return sourceId\n ? { version: 2, source: { siteId: sourceId, recordId: record.id }, type: record.type, input }\n : { version: 1, type: record.type, hubRecordId: record.id, input };\n}\n\n// Resolve an existing crm_record person by lowercased primaryEmail and update it,\n// else create one under the given mutationId. The shared core of every one-way\n// person projection (hub share, arriving applicant).\nasync function upsertPerson(\n deps: ProjectionDeps,\n opts: { email: string; input: Record<string, unknown>; mutationId: string },\n): Promise<{ recordId: string }> {\n const email = opts.email.toLowerCase();\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const { crm_record } = await deps.db.query({ crm_record: { $: { where: { type: \"person\", primaryEmail: email }, limit: 1 } } });\n const existing = crm_record?.[0];\n if (existing && typeof existing.id === \"string\") {\n await updateRecord(crmDeps, { id: existing.id, input: opts.input });\n return { recordId: existing.id };\n }\n const created = await createRecord(crmDeps, { type: \"person\", input: opts.input, mutationId: opts.mutationId });\n return { recordId: created.id };\n}\n\nasync function findSharedRecord(\n deps: ProjectionDeps,\n record: NormalizedSharedRecord,\n tag: string,\n): Promise<Record<string, unknown> | undefined> {\n const structured = await getRecordByOrigin(\n { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId },\n record.sourceId,\n record.sourceRecordId,\n );\n if (structured) return structured as unknown as Record<string, unknown>;\n const mapped = await deps.db.query({ crm_tag: { $: { where: { tag }, limit: 1 } } });\n const mappedId = mapped.crm_tag?.[0]?.recordId;\n if (typeof mappedId === \"string\") {\n const found = await deps.db.query({ crm_record: { $: { where: { id: mappedId }, limit: 1 } } });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const def = deps.crm.type(record.type);\n const emailField = def.emailField;\n if (emailField && typeof record.input[emailField] === \"string\") {\n const primaryEmail = record.input[emailField].toLowerCase();\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, primaryEmail }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const domain = record.input.domain;\n const domainSlot = def.fields.domain?.slot;\n if (typeof domain === \"string\" && domainSlot) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, [domainSlot]: domain }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const nameField = def.nameField ?? \"name\";\n const name = record.input[nameField];\n if (record.type === \"company\" && typeof name === \"string\" && name.trim()) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, name: name.trim() }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n return undefined;\n}\n\n/**\n * Upsert a leader-shared CRM record into this follower. Accepts the original\n * person wire shape plus the versioned generic shape. Re-shares resolve through\n * a durable provenance tag; people/businesses also converge by natural key.\n */\nexport async function projectSharedRecord(\n deps: ProjectionDeps,\n shared: SharedPerson | SharedBusiness | SharedRecord,\n options: { sourceId?: string; sourceUrl?: string } = {},\n): Promise<{ recordId: string }> {\n const record = normalizeSharedRecord(shared, options.sourceId);\n if (!record.type.trim() || !record.sourceId.trim() || !record.sourceRecordId.trim()) {\n throw new Error(\"type, source site id, and source record id must be non-empty\");\n }\n if (options.sourceId && options.sourceId !== record.sourceId) {\n throw new Error(\"signed sender does not match payload source\");\n }\n const tag = networkSourceTag(record.type, record.sourceRecordId, record.version === 2 ? record.sourceId : undefined);\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const existing = await findSharedRecord(deps, record, tag);\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n // Do not use one permanent mutation id for updates: a later leader edit is a\n // new desired state and must not be mistaken for a retry of an older push.\n await updateRecord(crmDeps, { id: existing.id, input: record.input });\n recordId = existing.id;\n } else {\n // A deterministic id makes concurrent first deliveries converge even when\n // both requests observe no provenance row before either transaction lands.\n recordId = `network_${shortHash(`${record.sourceId}\\u0000${record.type}\\u0000${record.sourceRecordId}`)}`;\n await createRecord({ ...crmDeps, newId: () => recordId }, {\n type: record.type,\n input: record.input,\n mutationId: `share-create:${tag}`,\n });\n }\n await deps.db.transact(\n [{ t: \"update\", ns: \"crm_tag\", id: tag, attrs: { key: `${recordId}:${tag}`, recordId, tag, createdAt: deps.now() } }],\n { mutationId: `share-map:${tag}:${recordId}` },\n );\n await upsertRecordOrigin(crmDeps, {\n recordId,\n sourceId: record.sourceId,\n sourceRecordId: record.sourceRecordId,\n ...(options.sourceUrl ? { sourceUrl: options.sourceUrl } : {}),\n payloadVersion: record.version,\n });\n return { recordId };\n}\n\n/** An arriving applicant, as far as the CRM projection cares. `extra` carries the\n * site-configured `crmFields` (values from the application), merged on top of the\n * built-in identity/contact set. */\nexport interface Applicant {\n applicationId: string;\n email: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Project an arriving applicant into this chapter's `crm_record`, so a new\n * application shows up in the CRM immediately, unified by email with any prior\n * record. Idempotent per application (`apply:${applicationId}`). Best-effort at\n * the call site — a projection failure never fails the application.\n *\n * `extra` fields (a site's `crmFields`) are merged on top of the base person. If\n * an extra field is not on the crm person type, crm validation throws — so the\n * projection retries with the base person alone, ensuring a misconfigured\n * enrichment never silently drops the applicant from the CRM entirely.\n */\nexport async function projectApplicant(deps: ProjectionDeps, applicant: Applicant): Promise<{ recordId: string }> {\n const base = sharedPersonInput({\n email: applicant.email,\n firstName: applicant.firstName,\n lastName: applicant.lastName,\n phone: applicant.phone,\n linkedin: applicant.linkedin,\n hubRecordId: applicant.applicationId,\n });\n const mutationId = `apply:${applicant.applicationId}`;\n const extra = applicant.extra ?? {};\n if (Object.keys(extra).length === 0) return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n try {\n return await upsertPerson(deps, { email: applicant.email, input: { ...base, ...extra }, mutationId });\n } catch {\n return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n }\n}\n","// The OPERATIONAL slice of the one-way person projection: applications + $users\n// -> crm_record, mirroring pipeline stage, a billing snapshot, and the Clerk\n// identity link. `network.ts` projects identity/contact on submit; this adds the\n// operational state the admin surface and the hub read from, so the pipeline\n// stays authoritative in `applications.status` while the CRM carries one\n// relationship surface over the person. Fired AFTER the authoritative write and\n// wrapped in `.catch` at every call site: a CRM hiccup never 5xxs a lifecycle op.\n//\n// Idempotent by construction — every sync resolves the person by lowercased\n// primary email first, so re-running (including the backfill route) updates in\n// place. Generalized from the reference site: the field set is the site's\n// configured `crmFields`, not a hardcoded list.\nimport { createRecord, updateRecord, setStage, linkIdentity } from \"@odla-ai/crm\";\nimport { sharedPersonInput } from \"./network\";\nimport type { ProjectionDeps } from \"./network\";\nimport type { Chapter, ChapterDb } from \"./types\";\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\n\n/** Build the projection deps from a worker request's db + context.\n *\n * Shared so every route that writes `applications.status` mirrors it the same\n * way. Status is written from four places (admin approve, admin PATCH, the\n * Stripe webhook, and booking) and the admin dashboard reads its pipeline from\n * `crm_record.stage`, so a route that skips the mirror silently reports the\n * wrong funnel. */\nexport const crmDeps = (\n db: ChapterDb,\n ctx: { chapter: Chapter },\n): ProjectionDeps & { chapter: Chapter } => ({\n crm: ctx.chapter.crm,\n db,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n chapter: ctx.chapter,\n});\n\n/** The crm `person` input for one application row: the built-in identity/contact\n * fields plus each configured `crmFields` value present on the row. */\nexport function personInputFromApp(chapter: Chapter, app: Record<string, unknown>): Record<string, unknown> {\n const input = sharedPersonInput({\n email: str(app.email),\n firstName: str(app.firstName) || undefined,\n lastName: str(app.lastName) || undefined,\n phone: str(app.phone) || undefined,\n linkedin: str(app.linkedin) || undefined,\n hubRecordId: str(app.id),\n });\n for (const f of chapter.application.crmFields) {\n if (app[f] !== undefined) input[f] = app[f];\n }\n if (app.id !== undefined) input.applicationId = str(app.id);\n return input;\n}\n\n// Promoted billing-facet columns derived from the application's Stripe fields +\n// status. Written directly (not through createRecord/updateRecord, which never\n// touch promoted columns), so they never clobber the person input.\nfunction billingColumns(app: Record<string, unknown>): Record<string, unknown> {\n const status = str(app.status);\n const paid = Boolean(app.stripeSubscriptionId) && status !== \"refunded\";\n const billingStatus = status === \"refunded\" ? \"refunded\" : app.canceled === true ? \"canceled\" : paid ? \"active\" : \"none\";\n const cols: Record<string, unknown> = { billingStatus };\n if (app.stripeCustomerId) cols.stripeCustomerId = str(app.stripeCustomerId);\n if (app.stripeSubscriptionId) cols.subscriptionId = str(app.stripeSubscriptionId);\n if (typeof app.renewalAt === \"number\") cols.renewalAt = app.renewalAt;\n return cols;\n}\n\n/** Upsert the person record for one application (or a synthetic `{ email,\n * firstName }` account row) and mirror its stage, billing snapshot, and Clerk\n * identity. `stage` is the `applications.status` to mirror — omit for\n * account-only rows not in the pipeline. Throws on failure (the backfill route\n * counts; the operational call sites wrap in `.catch`). */\nexport async function syncApplicationToCrm(\n deps: ProjectionDeps & { chapter: Chapter },\n opts: { app: Record<string, unknown>; stage?: string },\n): Promise<string | null> {\n const emailKey = str(opts.app.email).toLowerCase();\n if (!emailKey) return null;\n // The narrower shape the crm record helpers take (no chapter).\n const recordDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const input = personInputFromApp(deps.chapter, opts.app);\n\n const { crm_record } = await deps.db.query({\n crm_record: { $: { where: { type: \"person\", primaryEmail: emailKey }, limit: 1 } },\n });\n const existing = crm_record?.[0] ?? null;\n const stage = opts.stage || undefined;\n\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n recordId = existing.id;\n await updateRecord(recordDeps, { id: recordId, input });\n } else {\n const created = await createRecord(recordDeps, { type: \"person\", input, ...(stage ? { stage } : {}) });\n recordId = created.id;\n }\n\n // Stage mirror: move only on an actual change, under a stable mutationId so a\n // replay never piles up duplicate stage_change activities. Best-effort — a\n // stage not on the crm person type must not fail the whole sync.\n if (existing && stage && existing.stage !== stage) {\n await setStage(recordDeps, { id: recordId, to: stage, authorId: \"system\", mutationId: `crm:stage:${recordId}:${stage}` }).catch(() => undefined);\n }\n\n await deps.db.transact([{ t: \"update\", ns: \"crm_record\", id: recordId, attrs: billingColumns(opts.app) }]);\n\n // Identity link: stamps clerkUserId when a $users row matches the email; a\n // no-op until the person has an account. Best-effort — a just-created record\n // can briefly lag the read, and the link retries on the next sync.\n await linkIdentity(recordDeps, { recordId, email: emailKey, mutationId: `crm:link:${recordId}:${emailKey}` }).catch(() => undefined);\n\n return recordId;\n}\n\n/** Backfill / repair: project every application (newest per person) and every\n * account-only `$users` row into the CRM. Idempotent (safe to re-run). Dev\n * volumes fit one 1000-row page. Returns `{ synced, errors }`. */\nexport async function backfillCrm(deps: ProjectionDeps & { chapter: Chapter }): Promise<{ synced: number; errors: Array<{ email: string; error: string }> }> {\n const data = await deps.db.query({\n applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } },\n $users: { $: { limit: 1000 } },\n });\n const seen = new Set<string>();\n let synced = 0;\n const errors: Array<{ email: string; error: string }> = [];\n\n const run = async (app: Record<string, unknown>, stage?: string): Promise<void> => {\n const key = str(app.email).toLowerCase();\n if (!key || seen.has(key)) return; // newest-first: one record per person\n seen.add(key);\n try {\n await syncApplicationToCrm(deps, { app, stage });\n synced += 1;\n } catch (err) {\n errors.push({ email: key, error: err instanceof Error ? err.message : String(err) });\n }\n };\n\n for (const a of (data.applications ?? []) as Array<Record<string, unknown>>) await run(a, str(a.status));\n for (const u of (data.$users ?? []) as Array<Record<string, unknown>>) {\n if (u.deleted === true) continue;\n await run({ email: u.email, firstName: str(u.name) });\n }\n return { synced, errors };\n}\n","// Pure aggregation helpers for the admin dashboard: a weekly time-series bucketer\n// and the annualized-run-rate math for a Stripe subscription. Kept out of the\n// route so both dashboard and billing share one definition and it is unit-tested\n// without a network call.\n\n/** Bucket `{ t, v }` points into the last `weeks` weekly buckets ending at `now`\n * (epoch ms), summing `v` per bucket. Returns oldest→newest `{ weekStart, value\n * }`, so a caller renders a sparkline directly. Points outside the window are\n * ignored. */\nexport function bucketSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n weeks = 12,\n): Array<{ weekStart: number; value: number }> {\n const WEEK = 7 * 86_400_000;\n const end = now;\n const start = end - weeks * WEEK;\n const buckets = Array.from({ length: weeks }, (_, i) => ({ weekStart: start + i * WEEK, value: 0 }));\n for (const p of points) {\n if (!Number.isFinite(p.t) || p.t < start || p.t > end) continue;\n const idx = Math.min(weeks - 1, Math.floor((p.t - start) / WEEK));\n const bucket = buckets[idx];\n if (bucket) bucket.value += Number.isFinite(p.v) ? p.v : 0;\n }\n return buckets;\n}\n\n/** Labels and current/previous values for one dashboard comparison window. */\nexport interface DashboardMetricSeries {\n labels: string[];\n current: number[];\n previous: number[];\n}\n\n/** Week-over-week and month-over-month series consumed by MetricWidget. */\nexport interface DashboardMetricData {\n wow: DashboardMetricSeries;\n mom: DashboardMetricSeries;\n}\n\nfunction periodSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n count: number,\n periodMs: number,\n): DashboardMetricSeries {\n const start = now - count * periodMs;\n const previousStart = start - count * periodMs;\n const current = Array.from({ length: count }, () => 0);\n const previous = Array.from({ length: count }, () => 0);\n for (const point of points) {\n if (!Number.isFinite(point.t) || !Number.isFinite(point.v)) continue;\n if (point.t >= start && point.t <= now) {\n const index = Math.min(count - 1, Math.floor((point.t - start) / periodMs));\n current[index] = (current[index] ?? 0) + point.v;\n } else if (point.t >= previousStart && point.t < start) {\n const index = Math.min(count - 1, Math.floor((point.t - previousStart) / periodMs));\n previous[index] = (previous[index] ?? 0) + point.v;\n }\n }\n const labels = current.map((_, index) =>\n new Date(start + index * periodMs).toISOString().slice(5, 10));\n return { labels, current, previous };\n}\n\n/** MetricWidget-ready daily and weekly comparison windows. */\nexport function dashboardMetricData(\n points: Array<{ t: number; v: number }>,\n now: number,\n): DashboardMetricData {\n const DAY = 86_400_000;\n return {\n wow: periodSeries(points, now, 7, DAY),\n mom: periodSeries(points, now, 4, 7 * DAY),\n };\n}\n\n/** Annualized cents for a Stripe subscription: sum each item's\n * `unit_amount * quantity`, ×12 for monthly intervals. A yearly interval is\n * taken as-is. Returns 0 for a shape with no priced items. */\nexport function subAnnualCents(sub: Record<string, unknown>): number {\n const items = ((sub.items as { data?: Array<Record<string, unknown>> } | undefined)?.data ?? []);\n let cents = 0;\n for (const it of items) {\n const price = (it.price ?? {}) as { unit_amount?: number; recurring?: { interval?: string } };\n const per = (price.unit_amount ?? 0) * ((it.quantity as number) ?? 1);\n cents += price.recurring?.interval === \"month\" ? per * 12 : per;\n }\n return cents;\n}\n","// The Stripe payments provider — the only I/O half of payments. Talks to the\n// Stripe REST API over @odla-ai/stripe's fetch transport, and maps 1:1 onto the\n// membership-specific event normalization in ./payments. The worker\n// resolves secrets from the vault per request and constructs this; the routes own\n// every db write so idempotency stays at the db layer.\nimport { stripeRequest, verifyStripeSignature, type StripeRequestResult } from \"@odla-ai/stripe\";\nimport { normalizeWebhookEvent } from \"./payments\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport type { StripeEvent, WebhookEvent } from \"./payments\";\n\n/** Inputs to create an application's founding-member subscription. */\nexport interface CreateSubscriptionInput {\n appId: string;\n chapterId: string;\n environment: string;\n runtime?: string;\n applicationId: string;\n groupId: string;\n email: string;\n name: string;\n priceId: string;\n existingCustomerId?: string;\n}\n\n/** The client secret to confirm card entry, plus the ids to persist. */\nexport interface CreateSubscriptionResult {\n customerId: string;\n subscriptionId: string;\n clientSecret: string;\n}\n\n/** The outcome of a full refund. */\nexport interface RefundResult {\n refundedCents: number | null;\n subscriptionCanceled: boolean;\n}\n\n/** The capabilities the payment routes depend on — Stripe is one impl. */\nexport interface PaymentsProvider {\n createSubscription(input: CreateSubscriptionInput): Promise<CreateSubscriptionResult>;\n ingestWebhook(\n rawBody: string,\n sigHeader: string,\n ): Promise<{ ok: true; eventId: string; event: WebhookEvent } | { ok: false; reason: \"bad_signature\" }>;\n refund(input: { customerId: string; subscriptionId: string }): Promise<RefundResult>;\n}\n\n/** The result of a Stripe Backend API call: ok + status + parsed JSON body. */\nexport type StripeResult = StripeRequestResult<Record<string, unknown>>;\n\n/** Call the Stripe Backend API (form-encoded, Bearer sk_). Exposed so the admin\n * billing/dashboard reads and the refund route share one Stripe client instead\n * of each re-deriving the auth + encoding. */\nexport async function stripeCall(\n sk: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n params?: Record<string, unknown>,\n idempotencyKey?: string,\n): Promise<StripeResult> {\n return stripeRequest(\n { secretKey: sk },\n method,\n path,\n params,\n idempotencyKey ? { idempotencyKey } : {},\n );\n}\n\nfunction fail(op: string, r: StripeResult): never {\n const err = new Error(`stripe ${op} failed: ${r.status}`) as Error & { code: string };\n err.code = \"stripe_error\";\n throw err;\n}\n\nfunction clientSecretOf(sub: Record<string, unknown>): string | undefined {\n const inv = sub.latest_invoice as Record<string, unknown> | undefined;\n const confirmation = inv?.confirmation_secret as Record<string, unknown> | undefined;\n const intent = inv?.payment_intent as Record<string, unknown> | undefined;\n const secret = confirmation?.client_secret ?? intent?.client_secret;\n return typeof secret === \"string\" ? secret : undefined;\n}\n\nfunction requireSecret(secretKey: string | undefined): string {\n if (!secretKey) {\n const err = new Error(\"stripe secret key missing\") as Error & { code: string };\n err.code = \"not_configured\";\n throw err;\n }\n return secretKey;\n}\n\n/** Build the Stripe provider. `secretKey` powers charging/refunds; `webhookSecret`\n * powers webhook ingest. Each is resolved from the vault per request, so the\n * webhook route can construct an ingest-only provider without the secret key. */\nexport function createStripeProvider(config: { secretKey?: string; webhookSecret?: string }): PaymentsProvider {\n const { secretKey, webhookSecret } = config;\n return {\n async createSubscription(input) {\n const sk = requireSecret(secretKey);\n const meta = {\n applicationId: input.applicationId,\n groupId: input.groupId,\n email: input.email,\n ...stripePartitionMetadata(input),\n };\n let customerId = input.existingCustomerId;\n if (!customerId) {\n const cust = await stripeCall(\n sk,\n \"POST\",\n \"/v1/customers\",\n { email: input.email, name: input.name, metadata: meta },\n `cus:${input.applicationId}`,\n );\n if (!cust.ok) fail(\"customer create\", cust);\n customerId = String(cust.body.id);\n }\n const sub = await stripeCall(\n sk,\n \"POST\",\n \"/v1/subscriptions\",\n {\n customer: customerId,\n \"items[0][price]\": input.priceId,\n payment_behavior: \"default_incomplete\",\n \"payment_settings[save_default_payment_method]\": \"on_subscription\",\n \"payment_settings[payment_method_types][0]\": \"card\",\n \"expand[0]\": \"latest_invoice.confirmation_secret\",\n \"expand[1]\": \"latest_invoice.payment_intent\",\n metadata: meta,\n },\n // Hardening: one subscription per application, so a client\n // retry between create and the db write can't orphan a second one.\n `sub:${input.applicationId}`,\n );\n if (!sub.ok) fail(\"subscription create\", sub);\n const invoice = sub.body.latest_invoice as Record<string, unknown> | undefined;\n const paymentIntent = invoice?.payment_intent;\n const paymentIntentId = typeof paymentIntent === \"string\"\n ? paymentIntent\n : paymentIntent && typeof paymentIntent === \"object\"\n ? String((paymentIntent as Record<string, unknown>).id ?? \"\")\n : \"\";\n if (paymentIntentId) {\n const tagged = await stripeCall(\n sk,\n \"POST\",\n `/v1/payment_intents/${encodeURIComponent(paymentIntentId)}`,\n { metadata: meta },\n `payment-partition:${input.applicationId}`,\n );\n if (!tagged.ok) fail(\"payment intent metadata\", tagged);\n }\n const clientSecret = clientSecretOf(sub.body);\n if (!clientSecret) fail(\"subscription confirmation-secret missing\", sub);\n return { customerId, subscriptionId: String(sub.body.id), clientSecret };\n },\n\n async ingestWebhook(rawBody, sigHeader) {\n if (!webhookSecret || !(await verifyStripeSignature(rawBody, sigHeader, webhookSecret))) {\n return { ok: false, reason: \"bad_signature\" };\n }\n const event = JSON.parse(rawBody) as StripeEvent;\n return { ok: true, eventId: event.id, event: normalizeWebhookEvent(event) };\n },\n\n async refund(input) {\n const sk = requireSecret(secretKey);\n const charges = await stripeCall(sk, \"GET\", \"/v1/charges\", { customer: input.customerId, limit: 100 });\n if (!charges.ok) fail(\"charges list\", charges);\n const rows = (charges.body.data as Array<Record<string, unknown>> | undefined) ?? [];\n const paid = rows.filter((c) => c.status === \"succeeded\" && c.refunded !== true);\n const charge = paid[paid.length - 1]; // Stripe returns newest-first; refund the earliest.\n if (!charge) {\n const err = new Error(\"no paid charge to refund\") as Error & { code: string };\n err.code = \"no_charge\";\n throw err;\n }\n const refund = await stripeCall(sk, \"POST\", \"/v1/refunds\", { charge: String(charge.id) });\n if (!refund.ok) fail(\"refund\", refund);\n const cancel = await stripeCall(sk, \"DELETE\", `/v1/subscriptions/${input.subscriptionId}`);\n const amount = refund.body.amount;\n return { refundedCents: typeof amount === \"number\" ? amount : null, subscriptionCanceled: cancel.ok };\n },\n };\n}\n","// Apply-time account provisioning. When an application arrives, the worker mints\n// a Clerk invitation so the applicant gets a path into their member area — the\n// generalized server-side account step. Chapter calls the Clerk\n// Backend API directly over fetch (the effective vault name\n// `clerk_secret_key`, resolved by odla-db from reserved `$clerk_secret`), mirroring\n// @odla-ai/auth-clerk's createInvitation but self-contained, so it never pulls the\n// auth-clerk UI package into the worker bundle. A configured account model is a\n// required application-side effect; its caller surfaces failure and retries it.\n\n/** The outcome of a Clerk provisioning call. `existed` marks the heal case: Clerk\n * rejected it because the account/invitation is already there, which is the end\n * state we wanted anyway. */\nexport interface ClerkResult {\n ok: boolean;\n status: number;\n /** Stable Clerk user id returned by a successful fresh account create. */\n userId?: string;\n existed?: boolean;\n /** Set when an `existed` heal also refreshed the account's metadata. */\n refreshed?: boolean;\n}\n\n// Clerk answers 422 when the email already has a user (or a pending invitation).\n// For apply-time provisioning that's success, not failure — the account exists.\nconst heal = (status: number): ClerkResult =>\n status === 422 ? { ok: true, status, existed: true } : { ok: false, status };\n\n/** Inputs for a Clerk invitation. */\nexport interface ClerkInviteInput {\n email: string;\n /** Where the accept-invitation link lands (usually the member area). */\n redirectUrl?: string;\n /** Written to the invitation's `public_metadata`. Clerk application\n * invitations cannot carry private metadata, so never put applicant profile\n * fields here. Chapter completes that backend-only write after acceptance. */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API invitation request (path + JSON body). Pure, so\n * the wire shape is testable without a network call. */\nexport function clerkInviteRequest(input: ClerkInviteInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/invitations\",\n body: {\n email_address: input.email,\n notify: true,\n ...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n/** POST the invitation to the Clerk Backend API. A repeat invite for an\n * already-invited email heals to `{ ok: true, existed: true }` rather than\n * reporting a failure the caller would have to special-case. */\nexport async function createClerkInvitation(\n secretKey: string,\n input: ClerkInviteInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkInviteRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return res.ok ? { ok: true, status: res.status } : heal(res.status);\n}\n\n/** Inputs for a server-side Clerk user create. */\nexport interface ClerkUserInput {\n email: string;\n firstName?: string;\n lastName?: string;\n /** Backend-authored, browser-readable claims such as `role`. */\n publicMetadata?: Record<string, unknown>;\n /** Backend-only account signals and profile data. */\n privateMetadata?: Record<string, unknown>;\n /** Optional metadata merge used only when create returns 422 for an existing\n * account. This lets migrations remove legacy keys without putting tombstone\n * values on a newly-created user. Defaults to the create metadata. */\n repairMetadata?: ClerkMetadataInput;\n}\n\n/** Build the Clerk Backend API user-create request. The account is created\n * passwordless (the member signs in via the site's Clerk flow), so join step 3\n * can say the account is ready — the \"create\" alternative to an invitation. */\nexport function clerkUserRequest(input: ClerkUserInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/users\",\n body: {\n email_address: [input.email],\n skip_password_requirement: true,\n ...(input.firstName ? { first_name: input.firstName } : {}),\n ...(input.lastName ? { last_name: input.lastName } : {}),\n ...(input.publicMetadata !== undefined ? { public_metadata: input.publicMetadata } : {}),\n ...(input.privateMetadata !== undefined ? { private_metadata: input.privateMetadata } : {}),\n },\n };\n}\n\n/** One merge-PATCH to the metadata fields Clerk exposes on its Backend API. */\nexport interface ClerkMetadataInput {\n publicMetadata?: Record<string, unknown>;\n privateMetadata?: Record<string, unknown>;\n}\n\n/** Merge metadata into an existing Clerk user. Nested `null` values remove old\n * keys, which Chapter uses to migrate its former public profile into private\n * metadata without disturbing the public `role` claim. */\nexport async function updateClerkUserMetadata(\n secretKey: string,\n userId: string,\n input: ClerkMetadataInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<boolean> {\n const res = await fetchImpl(`https://api.clerk.com/v1/users/${encodeURIComponent(userId)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...(input.publicMetadata !== undefined ? { public_metadata: input.publicMetadata } : {}),\n ...(input.privateMetadata !== undefined ? { private_metadata: input.privateMetadata } : {}),\n }),\n });\n return res.ok;\n}\n\n/** Look a Clerk account up by email and merge its metadata.\n *\n * Returns `false` when no matching user can be resolved or Clerk rejects the\n * lookup or update. Chapter uses this for create-healing and invitation\n * adoption so a repeated application repairs the private account snapshot.\n */\nexport async function updateClerkUserMetadataByEmail(\n secretKey: string,\n email: string,\n input: ClerkMetadataInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<boolean> {\n const auth = { authorization: `Bearer ${secretKey}` };\n const found = await fetchImpl(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, { headers: auth });\n if (!found.ok) return false;\n const users = (await found.json().catch(() => null)) as Array<{ id?: unknown }> | null;\n const id = Array.isArray(users) && typeof users[0]?.id === \"string\" ? users[0].id : undefined;\n if (!id) return false;\n return updateClerkUserMetadata(secretKey, id, input, fetchImpl);\n}\n\n/** Create the applicant's Clerk account server-side. A repeat for an email that\n * already has an account heals to `{ ok: true, existed: true }` — the account\n * exists, which is the state apply-time provisioning wanted — and refreshes\n * supplied public/private metadata on the existing account so a re-application\n * repairs a previously missed create (`refreshed: true`). */\nexport async function createClerkUser(\n secretKey: string,\n input: ClerkUserInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkUserRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (res.ok) {\n const body = (typeof res.json === \"function\"\n ? await res.json().catch(() => null)\n : null) as { id?: unknown } | null;\n return {\n ok: true,\n status: res.status,\n ...(typeof body?.id === \"string\" && body.id ? { userId: body.id } : {}),\n };\n }\n const healed = heal(res.status);\n const repair = input.repairMetadata ?? {\n ...(input.publicMetadata !== undefined ? { publicMetadata: input.publicMetadata } : {}),\n ...(input.privateMetadata !== undefined ? { privateMetadata: input.privateMetadata } : {}),\n };\n if (\n !healed.existed ||\n (repair.publicMetadata === undefined && repair.privateMetadata === undefined)\n ) return healed;\n const refreshed = await updateClerkUserMetadataByEmail(secretKey, input.email, {\n ...(repair.publicMetadata !== undefined ? { publicMetadata: repair.publicMetadata } : {}),\n ...(repair.privateMetadata !== undefined ? { privateMetadata: repair.privateMetadata } : {}),\n }, fetchImpl).catch(() => false);\n return { ...healed, refreshed };\n}\n","// The odla->Clerk write half: server-side Clerk role read/list/write, the gap\n// beside clerk.ts's create/invite/heal. Roles live in `public_metadata.role`; an\n// absent role means the lowest rung (\"provisional\") — chapter never writes it at\n// create. Account profile signals live in backend-only `private_metadata`; the\n// role write is a MERGE-PATCH of only `{ role }`, so it cannot clobber them.\n// Chapter calls the Clerk Backend API over fetch with the vault\n// `clerk_secret_key`.\n\nconst CLERK_API = \"https://api.clerk.com\";\nconst DEFAULT_ROLE = \"provisional\";\nconst PAGE = 100;\n\n/** A Clerk user as chapter's role layer sees it. `role` defaults to the lowest\n * rung when `public_metadata` carries none. Raw public/private metadata is\n * returned only from this backend helper; `profile` and `applicationId` are the\n * normalized Chapter-owned private signals. */\nexport interface ClerkUserRecord {\n id: string;\n email?: string;\n role: string;\n publicMetadata: Record<string, unknown>;\n privateMetadata: Record<string, unknown>;\n profile: Record<string, unknown>;\n applicationId?: string;\n}\n\n// The Clerk Backend API user object — only the fields chapter reads.\ninterface ClerkApiUser {\n id?: unknown;\n email_addresses?: Array<{ email_address?: unknown }>;\n public_metadata?: Record<string, unknown>;\n private_metadata?: Record<string, unknown>;\n}\n\nfunction toRecord(u: ClerkApiUser): ClerkUserRecord | null {\n if (typeof u.id !== \"string\") return null;\n const pm = (u.public_metadata ?? {}) as Record<string, unknown>;\n const privateMetadata = (u.private_metadata ?? {}) as Record<string, unknown>;\n const rawProfile = privateMetadata.profile;\n const profile = rawProfile && typeof rawProfile === \"object\" && !Array.isArray(rawProfile)\n ? rawProfile as Record<string, unknown>\n : {};\n const applicationId = typeof privateMetadata.applicationId === \"string\"\n ? privateMetadata.applicationId\n : undefined;\n const role = typeof pm.role === \"string\" && pm.role ? pm.role : DEFAULT_ROLE;\n const email = u.email_addresses?.[0]?.email_address;\n return {\n id: u.id,\n email: typeof email === \"string\" ? email : undefined,\n role,\n publicMetadata: pm,\n privateMetadata,\n profile,\n ...(applicationId ? { applicationId } : {}),\n };\n}\n\nasync function clerkGet(path: string, secretKey: string, fetchImpl: typeof fetch): Promise<unknown> {\n const res = await fetchImpl(`${CLERK_API}${path}`, { headers: { authorization: `Bearer ${secretKey}` } });\n if (!res.ok) throw new Error(`clerk GET ${path} → ${res.status}`);\n return res.json();\n}\n\n/** Look a Clerk user up by email. `null` when no such user — or when the lookup\n * fails (a role gate treats an unresolvable user as absent, matching the site's\n * own fallback). Role defaults to provisional when unset. */\nexport async function clerkGetUserByEmail(secretKey: string, email: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, secretKey, fetchImpl).catch(() => null);\n const user = Array.isArray(data) ? (data[0] as ClerkApiUser | undefined) : undefined;\n return user ? toRecord(user) : null;\n}\n\n/** Fetch a Clerk user by id, for role-change gating. `null` when missing or on a\n * failed lookup. Role defaults to provisional when unset. */\nexport async function clerkGetUser(secretKey: string, id: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users/${encodeURIComponent(id)}`, secretKey, fetchImpl).catch(() => null);\n return data ? toRecord(data as ClerkApiUser) : null;\n}\n\n/** List ALL Clerk users with their roles, auto-paginating. A membership community\n * outgrows one page, and a fixed `limit=100` would silently drop members from the\n * admin roster with no error — so this pages (offset in steps of {@link PAGE})\n * until a short page. A page fetch that fails THROWS rather than returning a\n * partial list, so the caller never mistakes a truncated roster for the whole. */\nexport async function clerkListUsers(secretKey: string, fetchImpl: typeof fetch = fetch): Promise<ClerkUserRecord[]> {\n const out: ClerkUserRecord[] = [];\n for (let offset = 0; ; offset += PAGE) {\n const data = await clerkGet(`/v1/users?limit=${PAGE}&offset=${offset}`, secretKey, fetchImpl);\n const page = Array.isArray(data) ? (data as ClerkApiUser[]) : [];\n for (const u of page) {\n const record = toRecord(u);\n if (record) out.push(record);\n }\n if (page.length < PAGE) break;\n }\n return out;\n}\n\n/** Write a user's role: a MERGE-PATCH of only `{ role }` on `public_metadata`.\n * The backend-only profile lives in `private_metadata`, so the two signals\n * cannot overwrite each other. Returns whether the role write stuck. */\nexport async function clerkSetRole(secretKey: string, id: string, role: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const res = await fetchImpl(`${CLERK_API}/v1/users/${encodeURIComponent(id)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({ public_metadata: { role } }),\n });\n return res.ok;\n}\n","// The Clerk capability descriptor: documentation-as-data — \"what settings/secrets\n// does turning Clerk on need?\", \"what must the CLI provision?\", and \"what data\n// syncs, in which direction?\". It lives here (not in the browser package\n// @odla-ai/auth-clerk) because the sync contract is implemented by odla-db + the\n// platform webhook (provider->odla) and by chapter's clerk.ts (odla->provider),\n// neither of which is browser code. auth-clerk stays a pure UI package. Data only:\n// it describes the capability, it performs none of it.\n\n/** Which auth mode a secret is required for: `\"client\"` (publishable key only) or\n * `\"full\"` (server-side profile/role reads + writes, needing the vault secret). */\nexport type SecretMode = \"client\" | \"full\";\n\n/** A configuration value the capability needs (e.g. the publishable key). */\nexport interface IntegrationSetting {\n key: string;\n description: string;\n /** Safe to ship to the browser? (publishable keys are; secrets are not). */\n public: boolean;\n /** Expected value shape, e.g. a \"pk_\" prefix. */\n pattern?: string;\n /** Stored per environment (dev/prod)? */\n perEnv: boolean;\n /** Where the value is stored and read from. */\n source: string;\n}\n\n/**\n * A secret the capability needs, held in the tenant vault.\n *\n * Structurally the odla CLI's `IntegrationSecret`: `name` is the effective\n * runtime vault name, so `odla-ai doctor`, `odla-ai secrets status`, and the\n * repo's `check:secrets` gate can hold this declaration against the name the\n * package requests. The Clerk backend key is stored once in the reserved\n * `$clerk_secret` slot and odla-db resolves its released `clerk_secret_key`\n * compatibility name. `mode` is chapter's own addition and the CLI ignores it.\n */\nexport interface IntegrationSecret {\n /** Effective runtime vault name. Dedicated platform commands may keep the\n * canonical value in a reserved slot and resolve this compatibility name. */\n name: string;\n description: string;\n pattern?: string;\n /** Auth mode that requires this secret (\"full\" pulls user profiles). */\n mode: SecretMode;\n /** Whether the capability is broken without it. Both Clerk secrets are\n * needed only by auth mode \"full\", so both are optional. */\n required?: boolean;\n}\n\n/** One data-sync contract. A capability may declare several (e.g. an inbound\n * webhook mirror AND an outbound write), so {@link IntegrationDescriptor.syncs}\n * is a list. The mechanism is declared, not reimplemented here. */\nexport interface IntegrationSync {\n engine: string;\n direction: \"provider->odla\" | \"odla->provider\" | \"bidirectional\";\n entity: string;\n fields: string[];\n webhook?: string;\n onDelete?: string;\n}\n\n/** The provisioning split: human, CLI, and doctor-assertable steps. */\nexport interface IntegrationProvision {\n /** Steps a human performs (out-of-band, e.g. in the Clerk dashboard). */\n human: string[];\n /** Steps the odla CLI automates. */\n cli: string[];\n /** Checks `odla doctor` should assert. */\n doctor: string[];\n}\n\n/** Documentation-as-data for a provider capability, consumed by the odla CLI,\n * `odla doctor`, and the docs. */\nexport interface IntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n settings: IntegrationSetting[];\n secrets: IntegrationSecret[];\n /** Every data-sync contract the capability declares, each with its direction. */\n syncs: IntegrationSync[];\n provision: IntegrationProvision;\n}\n\n/**\n * The concrete {@link IntegrationDescriptor} for the Clerk capability. Declares\n * the one public `setting` (the `pk_*` publishable key, served to the SPA), the\n * `secrets` auth mode `\"full\"` needs in the tenant vault, BOTH sync directions —\n * the inbound `$users` webhook mirror (`provider->odla`) and the outbound\n * public role/private profile write via `clerk_secret_key` (`odla->provider`,\n * chapter's `clerk.ts`) — and the `provision` split. Data only; it performs\n * none of it.\n */\nexport const clerkIntegration: IntegrationDescriptor = {\n id: \"clerk\",\n title: \"Clerk end-user auth\",\n npm: \"@odla-ai/chapter\",\n settings: [\n {\n key: \"publishableKey\",\n description: \"Clerk publishable key (pk_*). Public by design; served to the SPA (loads clerk-js from Clerk's CDN via @odla-ai/auth-clerk).\",\n public: true,\n pattern: \"pk_\",\n perEnv: true,\n source: \"apps-registry auth[env].publishableKey (from odla.config.mjs auth.clerk.<env>)\",\n },\n ],\n secrets: [\n {\n // odla-db reads this exact name (CLERK_WEBHOOK_SECRET_NAME in the\n // platform's clerk-webhook.ts); it is also what `odla-ai secrets set`\n // writes. It read \"CLERK_WEBHOOK_SECRET\" until 0.30.0, which sent\n // adopters to store the value under a name nothing looks up.\n name: \"clerk_webhook_secret\",\n description: \"Svix signing secret for Clerk user webhooks — verifies $users sync events.\",\n pattern: \"whsec_\",\n mode: \"full\",\n required: false,\n },\n {\n name: \"clerk_secret_key\",\n description: \"Effective Clerk backend key (sk_*), stored canonically by set-clerk-key in reserved $clerk_secret — powers account creation, the public role claim, backend-only private profile signals, and odla-db user resolution.\",\n pattern: \"sk_\",\n mode: \"full\",\n required: false,\n },\n ],\n syncs: [\n {\n engine: \"@odla-ai/db $users (Clerk webhook -> tenant graph)\",\n direction: \"provider->odla\",\n entity: \"$users\",\n // Matches the webhook mapper: the mirror carries id + primary email + name + avatar.\n fields: [\"id\", \"email\", \"name\", \"imageUrl\"],\n webhook: \"whsec_ (svix-signed)\",\n onDelete: \"tombstone (never row-delete)\",\n },\n {\n engine: \"@odla-ai/chapter clerk.ts (Clerk Backend API via vault clerk_secret_key)\",\n direction: \"odla->provider\",\n entity: \"clerk user\",\n // Separate metadata fields so a public role write cannot expose or\n // clobber backend-only account/profile signals.\n fields: [\n \"public_metadata.role\",\n \"private_metadata.applicationId\",\n \"private_metadata.profile\",\n ],\n onDelete: \"n/a (writes only)\",\n },\n ],\n provision: {\n human: [\n \"Run `npx clerk auth login` — the one interactive step; the agent then creates + configures the Clerk app with the Clerk CLI (no pk_ to hand-paste).\",\n 'For auth mode \"full\": create the Clerk user-sync webhook, store its whsec_, and transfer the sk_ with `odla-ai secrets set-clerk-key --env <env> --stdin` (write-only).',\n ],\n cli: [\n \"Clerk CLI (`npx clerk apps create/link/config patch`) creates + configures the instance and pulls the pk_.\",\n \"odla `provision` records it: setAuth(env, publishableKey) -> apps-registry (issuer/JWKS derived from the key).\",\n \"odla `secrets set-clerk-key` stores one environment-scoped reserved credential consumed by odla-db and Chapter.\",\n ],\n doctor: [\n \"registry auth[env] present when the app mounts <SignIn>?\",\n 'auth mode \"full\" => whsec_ present and the effective clerk_secret_key reports set via the reserved Clerk credential status?',\n ],\n },\n};\n","// The member session — what GET /api/me returns to a signed-in applicant/member.\n// Ported from the reference application's summary + /api/me reconciliation. The\n// SHAPING is pure and package-enforced so no site re-derives it; the worker owns\n// only the I/O around it (locating the application by email, reconciling the\n// meeting against the calendar) and hands the resolved rows here.\n//\n// Two invariants live here, not in a site:\n// - `paid` is DERIVED, never a stored flag: a subscription exists and the\n// application wasn't refunded. Sites can't drift a stale boolean out of sync\n// with Stripe.\n// - the live meeting row wins: its startAt/meetUrl/timezone override whatever\n// the application row cached, and a non-scheduled meeting (a cancellation\n// adopted from the calendar) forces meetingAt back to null.\n\n/** An application row, as far as the session cares about it. */\nexport interface ApplicationRecord {\n id: string;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n status: string;\n meetingAt?: number | null;\n meetingLink?: string | null;\n createdAt?: number | null;\n stripeSubscriptionId?: string | null;\n renewalAt?: number | null;\n canceled?: boolean;\n tierId?: string | null;\n}\n\n/** The reconciled meeting row (already adopted against the calendar), or null. */\nexport interface MeetingRecord {\n status: string;\n startAt?: number | null;\n meetUrl?: string | null;\n timezone?: string | null;\n}\n\n/** The stable, non-meeting fields of an application (safe to expose to its own\n * owner). */\nexport interface ApplicationSummary {\n id: string;\n firstName: string | null;\n lastName: string | null;\n email: string | null;\n status: string;\n createdAt: number | null;\n meetingLink: string | null;\n paid: boolean;\n renewalAt: number | null;\n canceled: boolean;\n /** Server-authoritative membership tier selected on this application. */\n tierId: string | null;\n}\n\n/** A summary plus the reconciled meeting fields — the `application` the member\n * area renders. */\nexport interface MemberApplication extends ApplicationSummary {\n meetingAt: number | null;\n meetUrl: string | null;\n timezone: string;\n}\n\n/** The full GET /api/me payload for a signed-in user. */\nexport interface MemberSession {\n userId: string;\n email: string | null;\n role: string;\n superAdmin: boolean;\n application: MemberApplication | null;\n}\n\n/** Derive the summary fields from an application row. `paid` is computed, not\n * read, so it can never contradict Stripe. */\nexport function applicationSummary(app: ApplicationRecord): ApplicationSummary {\n return {\n id: app.id,\n firstName: app.firstName ?? null,\n lastName: app.lastName ?? null,\n email: app.email ?? null,\n status: app.status,\n createdAt: app.createdAt ?? null,\n meetingLink: app.meetingLink ?? null,\n paid: Boolean(app.stripeSubscriptionId) && app.status !== \"refunded\",\n renewalAt: app.renewalAt ?? null,\n canceled: app.canceled === true,\n tierId: app.tierId ?? null,\n };\n}\n\n/** Fold a (possibly absent, already-reconciled) meeting into the application the\n * member area renders. The live meeting overrides the application's cached\n * meeting fields; a non-`scheduled` meeting clears the booking. */\nexport function memberApplication(\n app: ApplicationRecord,\n meeting: MeetingRecord | null | undefined,\n defaultTimezone: string,\n): MemberApplication {\n const summary = applicationSummary(app);\n let meetingAt = app.meetingAt ?? null;\n let meetUrl: string | null = null;\n let timezone = defaultTimezone;\n if (meeting) {\n timezone = meeting.timezone ?? timezone;\n if (meeting.status === \"scheduled\") {\n meetingAt = meeting.startAt ?? null;\n meetUrl = meeting.meetUrl ?? null;\n } else {\n meetingAt = null;\n }\n }\n return { ...summary, meetingAt, meetUrl, timezone };\n}\n\n/** Identity of the signed-in user, from the verified session. */\nexport interface SessionUser {\n userId: string;\n email?: string | null;\n role: string;\n}\n\n/** Assemble the GET /api/me payload. `application` is null when the user has no\n * application on file (an admin who never applied, or a brand-new account). */\nexport function memberSession(\n user: SessionUser,\n opts: { application: MemberApplication | null; superAdmin: boolean },\n): MemberSession {\n return {\n userId: user.userId,\n email: user.email ?? null,\n role: user.role,\n superAdmin: opts.superAdmin,\n application: opts.application,\n };\n}\n","// Brand tokens (H4). defineChapter accepts a `brand` block; this turns it into a\n// `:root { --…: … }` CSS block, so a chapter re-skins the WHOLE UI — the\n// @odla-ai/ui components, the admin shell, and the member islands, which all read\n// --ui-* design tokens — from one config instead of hand-writing inline CSS.\n//\n// Pure string generation, so it is unit-testable and can be emitted at\n// build/SSR time into the page <head> (no flash of unstyled content), or via the\n// <BrandStyle> component from @odla-ai/chapter/ui.\nimport type { ChapterBrand, ChapterBrandTokens } from \"./types\";\n\n// A palette entry is either a direct custom property (already `--…`, e.g.\n// `--ui-accent` to retheme components) or a bare name we expose as `--<name>`\n// (e.g. `moss` → `--moss`, for a site to reference in its own CSS).\nfunction paletteVar(key: string): string {\n return key.startsWith(\"--\") ? key : `--${key}`;\n}\n\n// Strip characters that could break out of a `--var: value;` declaration or the\n// surrounding <style>. Brand config is trusted author input, so this is a\n// belt-and-suspenders guard, not a security boundary.\nfunction cleanValue(value: string): string {\n return value.replace(/[<>{};]/g, \"\").trim();\n}\n\nfunction paletteDecls(palette: Record<string, string> | undefined): string[] {\n const decls: string[] = [];\n for (const [key, value] of Object.entries(palette ?? {})) {\n if (typeof value === \"string\" && value.trim()) decls.push(`${paletteVar(key)}: ${cleanValue(value)};`);\n }\n return decls;\n}\n\nconst TOKEN_VARS: Record<keyof ChapterBrandTokens, string> = {\n background: \"--ui-bg\",\n surface: \"--ui-surface\",\n surface2: \"--ui-surface-2\",\n text: \"--ui-text\",\n textMuted: \"--ui-text-muted\",\n textFaint: \"--ui-text-faint\",\n border: \"--ui-border\",\n borderStrong: \"--ui-border-strong\",\n accent: \"--ui-accent\",\n accentStrong: \"--ui-accent-strong\",\n accentSoft: \"--ui-accent-soft\",\n onAccent: \"--ui-on-accent\",\n good: \"--ui-good\",\n warn: \"--ui-warn\",\n danger: \"--ui-danger\",\n chart1: \"--ui-chart-1\",\n chart2: \"--ui-chart-2\",\n chart3: \"--ui-chart-3\",\n chart4: \"--ui-chart-4\",\n chart5: \"--ui-chart-5\",\n chart6: \"--ui-chart-6\",\n chartPositive: \"--ui-chart-pos\",\n chartNegative: \"--ui-chart-neg\",\n contentWidth: \"--ui-content-width\",\n panelRadius: \"--ui-radius-lg\",\n panelShadow: \"--ui-shadow\",\n masterDetailColumns: \"--ui-master-detail-columns\",\n masterDetailMinHeight: \"--ui-master-detail-min-height\",\n pagePadding: \"--chapter-admin-page-padding\",\n workspacePadding: \"--chapter-admin-workspace-padding\",\n};\n\nfunction semanticDecls(tokens: ChapterBrandTokens | undefined): string[] {\n return Object.entries(tokens ?? {}).flatMap(([key, value]) =>\n typeof value === \"string\" && value.trim()\n ? [`${TOKEN_VARS[key as keyof ChapterBrandTokens]}: ${cleanValue(value)};`]\n : [],\n );\n}\n\n/**\n * Build the CSS that maps a chapter's brand onto the design tokens the UI reads:\n * each `palette` entry becomes a custom property (light, and dark unless\n * `paletteDark` overrides), and `fonts` (display/body/numeral) map to\n * `--ui-font-display` / `--ui-font-sans` / `--ui-font-numeral`. The dark block is\n * emitted under both `:root[data-theme=\"dark\"]` (the odla-ui theme toggle) and\n * `@media (prefers-color-scheme: dark)`. Returns \"\" when there is nothing to\n * theme. These are brand OVERRIDES on top of a base theme — they do not replace\n * the theme layer the components need (see {@link brandTokens} usage in the docs).\n */\nexport function brandTokens(\n brand: ChapterBrand | undefined,\n options: { selector?: string } = {},\n): string {\n if (!brand) return \"\";\n const light = [...paletteDecls(brand.palette), ...semanticDecls(brand.tokens)];\n const fonts = brand.fonts;\n if (fonts?.display) light.push(`--ui-font-display: ${cleanValue(fonts.display)};`);\n if (fonts?.body) light.push(`--ui-font-sans: ${cleanValue(fonts.body)};`);\n if (fonts?.numeral) light.push(`--ui-font-numeral: ${cleanValue(fonts.numeral)};`);\n const dark = [...paletteDecls(brand.paletteDark), ...semanticDecls(brand.tokensDark)];\n const invert = paletteDecls(brand.paletteInvert);\n const selector = options.selector ?? \":root\";\n const darkSelector = selector === \":root\" ? ':root[data-theme=\"dark\"]' : `${selector}[data-theme=\"dark\"]`;\n const systemSelector = selector === \":root\"\n ? ':root:not([data-theme=\"light\"])'\n : `${selector}:not([data-theme=\"light\"])`;\n\n let css = light.length ? `${selector} {\\n ${light.join(\"\\n \")}\\n}\\n` : \"\";\n if (dark.length) {\n const block = `{\\n ${dark.join(\"\\n \")}\\n}`;\n css += `${darkSelector} ${block}\\n@media (prefers-color-scheme: dark) {\\n ${systemSelector} ${block}\\n}\\n`;\n }\n if (invert.length) {\n const invertSelector = selector === \":root\"\n ? \".ui-invert\"\n : `${selector}.ui-invert, ${selector} .ui-invert`;\n css += `${invertSelector} {\\n color-scheme: dark;\\n ${invert.join(\"\\n \")}\\n}\\n`;\n }\n return css;\n}\n\n/** Structural output accepted from `@odla-ai/brand`'s pure token compiler. */\nexport interface CompiledChapterBrandTokens {\n light: Record<string, string>;\n dark: Record<string, string>;\n}\n\n/**\n * Turn a complete compiled token pair into Chapter's brand contract without\n * coupling Chapter's runtime to the brand-book/agent package. Explicit values in\n * `base` win, so a host can make final per-site adjustments after compilation.\n */\nexport function chapterBrandFromTokens(\n compiled: CompiledChapterBrandTokens,\n base: ChapterBrand = {},\n): ChapterBrand {\n return {\n ...base,\n palette: { ...compiled.light, ...base.palette },\n paletteDark: { ...compiled.dark, ...base.paletteDark },\n paletteInvert: { ...compiled.dark, ...base.paletteInvert },\n };\n}\n","// The Google → chapter half of the bidirectional calendar sync. Booking writes\n// events TO the platform calendar (0.4.0's create/reschedule); this ADOPTS edits\n// FROM it: when the owner moves or cancels the intro call directly in Google,\n// reconcile mirrors that onto our canonical `meetings` row and the `application`\n// projection. Chapter never calls Google — the worker reads live events through\n// @odla-ai/calendar's upcoming() (platform-brokered) and applies the ops this\n// returns. Pure + testable; adoption policy (owner edits win) matches the shipped\n// original production worker.\n\n/** A `meetings` row, as far as reconciliation cares. */\nexport interface MeetingForReconcile {\n id: string;\n applicationId: string;\n googleEventId?: string | null;\n status: string;\n startAt?: number | null;\n endAt?: number | null;\n}\n\n/** One live calendar event (a subset of @odla-ai/calendar's Booking). */\nexport interface LiveEvent {\n eventId: string;\n status?: string;\n startAt?: number;\n endAt?: number;\n}\n\n/** An adopt decision: mirror a Google move/cancel onto our rows. */\nexport interface ReconcileDecision {\n meetingId: string;\n applicationId: string;\n kind: \"cancelled\" | \"moved\";\n /** Attrs to write onto the `meetings` row. */\n meetingPatch: Record<string, unknown>;\n /** Attrs to write onto the `applications` row (the projection). */\n applicationPatch: Record<string, unknown>;\n}\n\n/** Meetings still worth reconciling: a scheduled booking with a Google event that\n * starts in the future (or within the last hour, to catch a just-passed edit). */\nexport function isReconcilable(meeting: MeetingForReconcile, now: number): boolean {\n return meeting.status === \"scheduled\" && Boolean(meeting.googleEventId) && (meeting.startAt ?? 0) > now - 3_600_000;\n}\n\n/**\n * Diff canonical `meetings` against the live calendar events and return the adopt\n * decisions — only for meetings that actually changed (a still-matching meeting\n * is omitted). A meeting whose event vanished or is `cancelled` in Google is\n * adopted as cancelled (application `meetingAt` zeroed — 0 means \"was booked,\n * then cancelled\"); a meeting whose event moved adopts the new window (duration\n * preserved when the event omits `endAt`).\n */\nexport function reconcileMeetings(\n meetings: readonly MeetingForReconcile[],\n events: readonly LiveEvent[],\n now: number,\n): ReconcileDecision[] {\n const byEvent = new Map(events.map((e) => [e.eventId, e]));\n const decisions: ReconcileDecision[] = [];\n for (const m of meetings) {\n if (!isReconcilable(m, now) || !m.googleEventId) continue;\n const g = byEvent.get(m.googleEventId);\n if (!g || g.status === \"cancelled\") {\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"cancelled\",\n meetingPatch: { status: \"cancelled\", drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: 0, meetingLink: \"\" },\n });\n } else if (g.startAt !== undefined && g.startAt !== m.startAt) {\n const duration = (m.endAt ?? 0) - (m.startAt ?? 0);\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"moved\",\n meetingPatch: { startAt: g.startAt, endAt: g.endAt ?? g.startAt + duration, drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: g.startAt },\n });\n }\n }\n return decisions;\n}\n","// Scheduling core — config resolution + the booking invariants, ported from the\n// proven production worker. Everything here is PURE (no @odla-ai/calendar, no\n// db), so the correctness properties are unit-testable and package-enforced; the\n// worker route owns only the I/O (FreeBusy, computeBookableSlots, calendar\n// create/reschedule, the db writes) and calls these.\n//\n// Package-enforced invariants:\n// - the `meetings` row is canonical; applications.meetingAt and the calendar\n// event are projections written from it.\n// - one intro event per application, forever: a rebooking RESCHEDULES the\n// existing event (preserving its Meet link + invite thread), never creates a\n// second — see {@link bookingDecision} + {@link introIdempotencyKey}.\n// - status never moves backward on booking; you can only book from a pipeline\n// stage in `bookableFrom` — see `canBook` in ./pipeline + applicationBookingUpdate.\n// - endAt is always derived server-side, never client-supplied — see\n// {@link endForSlot}.\nimport type { ChapterScheduling } from \"./types\";\n\n/** A fully-resolved scheduling config (every field present). */\nexport interface ResolvedScheduling {\n slotMinutes: number;\n days: readonly number[];\n startHour: number;\n endHour: number;\n timezone: string;\n minNoticeHours: number;\n windowDays: number;\n summaryTemplate: string;\n}\n\n/** Proven defaults: 45-minute weekday slots, 9–5 Pacific, 24h notice,\n * a 14-day window. The summary is generic (a chapter's group seed supplies a\n * name-branded one). */\nexport const SCHEDULING_DEFAULTS: ResolvedScheduling = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n summaryTemplate: \"Introduction call with {{firstName}} {{lastName}}\",\n};\n\nfunction isValidTimeZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a group's scheduling config against the defaults, validating every\n * bound at config-write time (throws on a bad config, so a\n * misconfiguration surfaces immediately rather than yielding empty slots).\n * `windowDays` is capped at 62 because Google FreeBusy is.\n */\nexport function resolveScheduling(config?: ChapterScheduling): ResolvedScheduling {\n const result = validateScheduling(config);\n if (result.ok) return result.value;\n const detail = Object.entries(result.errors)\n .map(([field, message]) => `${field}: ${message}`)\n .join(\" \");\n throw new Error(`scheduling: ${detail}`);\n}\n\n/** Validation messages keyed by form field. */\nexport type SchedulingErrors = Record<string, string>;\n\n/**\n * Validate a scheduling config field by field, collecting owner-readable messages\n * rather than throwing on the first problem. An admin settings form needs to say\n * *which* field is wrong and why — \"pick at least one day\" beats a stack trace —\n * so the admin route returns these directly. {@link resolveScheduling} is the\n * throwing wrapper for internal/config-time use.\n */\nexport function validateScheduling(\n config?: ChapterScheduling,\n): { ok: true; value: ResolvedScheduling } | { ok: false; errors: SchedulingErrors } {\n const d = config ?? {};\n const c: ResolvedScheduling = {\n slotMinutes: d.slotMinutes ?? SCHEDULING_DEFAULTS.slotMinutes,\n days: d.days ?? SCHEDULING_DEFAULTS.days,\n startHour: d.startHour ?? SCHEDULING_DEFAULTS.startHour,\n endHour: d.endHour ?? SCHEDULING_DEFAULTS.endHour,\n timezone: d.timezone ?? SCHEDULING_DEFAULTS.timezone,\n minNoticeHours: d.minNoticeHours ?? SCHEDULING_DEFAULTS.minNoticeHours,\n windowDays: d.windowDays ?? SCHEDULING_DEFAULTS.windowDays,\n summaryTemplate: d.summaryTemplate ?? SCHEDULING_DEFAULTS.summaryTemplate,\n };\n const errors: SchedulingErrors = {};\n if (!(c.slotMinutes >= 15 && c.slotMinutes <= 240)) {\n errors.slotMinutes = \"Slot length must be between 15 and 240 minutes.\";\n }\n if (!(c.windowDays >= 1 && c.windowDays <= 62)) {\n errors.windowDays = \"Booking window must be between 1 and 62 days (the calendar caps look-ahead at 62).\";\n }\n if (!(c.minNoticeHours >= 0 && c.minNoticeHours <= 336)) {\n errors.minNoticeHours = \"Minimum notice must be between 0 and 336 hours.\";\n }\n if (!(c.startHour >= 0 && c.startHour < c.endHour && c.endHour <= 24)) {\n errors.hours = \"Hours must satisfy 0 ≤ start < end ≤ 24.\";\n }\n const days = [...c.days];\n if (!days.length) errors.days = \"Pick at least one day.\";\n else if (!days.every((n) => Number.isInteger(n) && n >= 0 && n <= 6)) {\n errors.days = \"Days must be weekday numbers, 0 (Sunday) through 6 (Saturday).\";\n }\n if (typeof c.timezone !== \"string\" || !isValidTimeZone(c.timezone)) {\n errors.timezone = `\"${String(c.timezone)}\" is not a valid IANA timezone (for example \"America/Los_Angeles\").`;\n }\n if (typeof c.summaryTemplate !== \"string\") errors.summaryTemplate = \"Calendar summary template must be text.\";\n return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, value: { ...c, days } };\n}\n\n/** Statuses a member may book/reschedule from (early pipeline only). */\n// Booking eligibility is answered by the configured pipeline — canBook(status,\n// pipeline) in ./pipeline — not a hardcoded status list, so a chapter that\n// customizes its stages gets one consistent answer.\n\n/** The availability window: `[now, now + windowDays]` in epoch ms. */\nexport function slotWindow(now: number, windowDays: number): { from: number; to: number } {\n return { from: now, to: now + windowDays * 86_400_000 };\n}\n\n/** The slot's end instant, always derived from its start (never client-supplied). */\nexport function endForSlot(startAt: number, slotMinutes: number): number {\n return startAt + slotMinutes * 60_000;\n}\n\n/** Double-book pre-check: the requested start must land exactly on a currently\n * bookable slot boundary. */\nexport function isSlotAvailable(slots: readonly { startAt: number }[], startAt: number): boolean {\n return slots.some((s) => s.startAt === startAt);\n}\n\n/** Render a meeting summary from its template (`{{firstName}}`/`{{lastName}}`). */\nexport function renderSummary(template: string, app: { firstName?: string | null; lastName?: string | null }): string {\n return template.replace(\"{{firstName}}\", app.firstName ?? \"\").replace(\"{{lastName}}\", app.lastName ?? \"\");\n}\n\n/** The prior scheduled meeting for an application, as far as booking cares. */\nexport interface ExistingMeeting {\n id: string;\n googleEventId?: string | null;\n meetUrl?: string | null;\n htmlLink?: string | null;\n}\n\n/** Decide reschedule-vs-create: reschedule iff there's an existing event to move,\n * so the Meet link + invite thread survive and no second event is minted. */\nexport function bookingDecision(existing: ExistingMeeting | null | undefined): { reschedule: boolean; eventId: string | null } {\n const eventId = existing?.googleEventId ?? null;\n return { reschedule: Boolean(eventId), eventId };\n}\n\n/** The create idempotency key — one intro event per application, forever, so a\n * retried create returns the same booking rather than a duplicate. */\nexport function introIdempotencyKey(applicationId: string): string {\n return `application:${applicationId}:intro`;\n}\n\n/** The canonical `meetings` row for a first booking. A `type` (not `interface`)\n * so it stays assignable to a db op's `attrs` (Record<string, unknown>). */\nexport type NewMeetingRow = {\n id: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n status: \"scheduled\";\n googleEventId: string;\n meetUrl?: string;\n htmlLink?: string;\n drift: \"none\";\n createdAt: number;\n};\n\n/** Build the new `meetings` row after the calendar created the event. Optional\n * scalars are omitted (never null), per the odla-db porting rule. */\nexport function meetingCreateRow(i: {\n meetingId: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n googleEventId: string;\n meetUrl?: string | null;\n htmlLink?: string | null;\n createdAt: number;\n}): NewMeetingRow {\n return {\n id: i.meetingId,\n applicationId: i.applicationId,\n groupId: i.groupId,\n startAt: i.startAt,\n endAt: i.endAt,\n timezone: i.timezone,\n status: \"scheduled\",\n googleEventId: i.googleEventId,\n ...(i.meetUrl ? { meetUrl: i.meetUrl } : {}),\n ...(i.htmlLink ? { htmlLink: i.htmlLink } : {}),\n drift: \"none\",\n createdAt: i.createdAt,\n };\n}\n\n/** The `meetings`-row patch for a reschedule (same row id, moved in place). */\nexport type MeetingReschedulePatch = {\n startAt: number;\n endAt: number;\n drift: \"none\";\n};\n\n/** Patch to move an existing meeting to a new window. */\nexport function meetingRescheduleUpdate(startAt: number, endAt: number): MeetingReschedulePatch {\n return { startAt, endAt, drift: \"none\" };\n}\n\n/** The `applications`-row patch after a booking. */\nexport type ApplicationBookingPatch = {\n meetingAt: number;\n meetingLink?: string;\n status?: \"call_scheduled\";\n};\n\n/** Project the booking onto the application row: cache the time, adopt the\n * calendar link if any, and advance the status to `call_scheduled` unless it is\n * already there (never backward). */\nexport function applicationBookingUpdate(\n currentStatus: string,\n startAt: number,\n htmlLink?: string | null,\n): ApplicationBookingPatch {\n return {\n meetingAt: startAt,\n ...(htmlLink ? { meetingLink: htmlLink } : {}),\n ...(currentStatus !== \"call_scheduled\" ? { status: \"call_scheduled\" as const } : {}),\n };\n}\n","// Reading tiers out of the database. Kept apart from tiers.ts so the decision\n// logic there stays pure and directly testable, and apart from the route\n// modules so both the join config and the checkout resolve tiers identically —\n// a page that offers a tier the checkout would refuse is the bug this prevents.\nimport type { ChapterDb } from \"./types\";\nimport { offerableTiers, resolveTiers, type ChapterTier, type TierGroup } from \"./tiers\";\n\n/** A `groups` row as the tier loader needs it. */\nexport type TierGroupRow = TierGroup & { id?: string };\n\nfunction rowToTier(row: Record<string, unknown>, groupId: string): ChapterTier {\n return {\n id: String(row.id ?? \"\"),\n groupId: String(row.groupId ?? groupId),\n name: String(row.name ?? \"\"),\n priceCents: typeof row.priceCents === \"number\" ? row.priceCents : 0,\n ...(typeof row.currency === \"string\" && row.currency ? { currency: row.currency } : {}),\n ...(row.interval === \"year\" || row.interval === \"month\" ? { interval: row.interval } : {}),\n ...(typeof row.stripePriceId === \"string\" && row.stripePriceId\n ? { stripePriceId: row.stripePriceId }\n : {}),\n ...(typeof row.blurb === \"string\" ? { blurb: row.blurb } : {}),\n sortOrder: typeof row.sortOrder === \"number\" ? row.sortOrder : 0,\n // A row that never set `active` is offered; only an explicit false retires\n // a tier, so a half-seeded row cannot silently hide a membership.\n active: row.active !== false,\n };\n}\n\n/**\n * Every tier a group offers, ordered, including the implicit tier synthesized\n * for a chapter that predates tiers. Never throws on a missing namespace: a\n * deployment whose schema has not been pushed yet reads as \"no rows\", which\n * resolves to the legacy single tier.\n */\nexport async function loadTiers(db: ChapterDb, group: TierGroupRow): Promise<ChapterTier[]> {\n const groupId = String(group.id ?? \"\");\n let rows: unknown;\n try {\n rows = (await db.query({\n tiers: { $: { where: { groupId }, order: { sortOrder: \"asc\" }, limit: 100 } },\n }) as Record<string, unknown>).tiers;\n } catch {\n rows = undefined;\n }\n const list = Array.isArray(rows)\n ? rows.map((row) => rowToTier(row as Record<string, unknown>, groupId))\n : [];\n return resolveTiers(group, list);\n}\n\n/** The tiers a join page may show: active, and joinable as configured. */\nexport async function loadOfferableTiers(\n db: ChapterDb,\n group: TierGroupRow,\n hasSecretKey: boolean,\n): Promise<ChapterTier[]> {\n return offerableTiers(await loadTiers(db, group), group, hasSecretKey);\n}\n","import type { FieldConditions } from \"@odla-ai/crm\";\nimport type { MembershipPageDocument } from \"./membership-page\";\nimport type { ChapterScheduling } from \"./types\";\nimport type { GiftOfferCatalog } from \"./gift-offers\";\n\n/** Current wire-format version for complete signup-control documents. */\nexport const SIGNUP_CONTROL_SCHEMA_VERSION = 1 as const;\n/** Package-owned follower endpoint for signed signup-control delivery. */\nexport const SIGNUP_CONTROL_PATH = \"/api/signup-control\" as const;\n\n/** One authoritative membership tier in a signup-control revision. */\nexport interface SignupControlTier {\n id: string;\n name: string;\n available: boolean;\n sortOrder: number;\n priceCents: number;\n /** ISO currency; omitted only by pre-field schema-v1 documents. */\n currency?: string;\n /** Recurring interval; omitted only by pre-field schema-v1 documents. */\n interval?: \"year\" | \"month\";\n stripePriceId?: string;\n blurb?: string;\n}\n\n/** A bounded application contract. Fields must already exist in the follower schema. */\nexport interface SignupControlApplication {\n required: readonly string[];\n optional: readonly string[];\n conditions?: Readonly<Record<string, FieldConditions>>;\n copy?: Readonly<Record<string, string>>;\n}\n\n/** Delegated legal and trust copy used by the packaged join journey. */\nexport interface SignupControlPolicy {\n disclaimerText: string;\n refundPolicyText: string;\n /** Plain-language merchant identity displayed before payment consent. */\n merchantDisclosureText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/** Bounded semantic design tokens delegated to the chapter signup surface. */\nexport interface SignupControlTheme {\n /** Includes color, spacing, and typography tokens such as font families. */\n tokens: Readonly<Record<string, string | number>>;\n}\n\n/** Complete desired state delivered by a controlling hub. */\nexport interface SignupControlDocument {\n schemaVersion: typeof SIGNUP_CONTROL_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: { appId: string };\n target: { chapterId: string; environment: string; stripeMode: \"test\" | \"live\" };\n tiers: readonly SignupControlTier[];\n membershipPage: MembershipPageDocument;\n application?: SignupControlApplication;\n policy?: SignupControlPolicy;\n scheduling?: ChapterScheduling;\n theme?: SignupControlTheme;\n giftOffers?: GiftOfferCatalog;\n}\n\n/** Digest travels beside the document so the exact desired state is attestable. */\nexport interface SignupControlEnvelope {\n digest: string;\n document: SignupControlDocument;\n}\n\n/** Exact follower acknowledgement for one accepted or replayed revision. */\nexport interface SignupControlReceipt {\n ok: true;\n target: { chapterId: string; environment: string };\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable reason codes returned when a follower refuses desired state. */\nexport type SignupControlRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"wrong_stripe_mode\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n\n/** Normalized document result returned by the package validator. */\nexport type SignupControlValidation =\n | { ok: true; value: SignupControlDocument }\n | { ok: false; errors: readonly string[] };\n","/** The first stable, shared Chapter membership-page renderer contract. */\nexport const MEMBERSHIP_PAGE_RENDERER = \"membership-cards-v1\" as const;\n\n/** Fixed visual emphasis choices supported by the versioned card renderer. */\nexport type MembershipTierVariant = \"standard\" | \"featured\" | \"supporting\";\n\n/** A bounded, token-rendered aside within one membership card. */\nexport interface MembershipTierCallout {\n label?: string;\n bodyMarkdown: string;\n}\n\n/** Scarcity copy displayed without changing tier availability or checkout. */\nexport interface MembershipTierCapacity {\n total: number;\n label?: string;\n}\n\n/**\n * Presentation attached to one server-authoritative membership tier.\n *\n * Price, free/paid state, identity, and application targeting deliberately do\n * not live here. They are resolved from the public Chapter join config so\n * authored marketing copy can never change what checkout charges.\n */\nexport interface MembershipTierPresentation {\n tierId: string;\n variant?: MembershipTierVariant;\n badge?: string;\n summaryMarkdown?: string;\n priceEyebrow?: string;\n compareAtPriceCents?: number;\n billingLabel?: string;\n priceNoteMarkdown?: string;\n capacity?: MembershipTierCapacity;\n benefits?: readonly string[];\n callout?: MembershipTierCallout;\n ctaLabel?: string;\n}\n\n/** A bounded document that can be reviewed once and rendered by any Chapter host. */\nexport interface MembershipPageDocument {\n schemaVersion: 1;\n renderer: typeof MEMBERSHIP_PAGE_RENDERER;\n tiers: readonly MembershipTierPresentation[];\n footnoteMarkdown?: string;\n}\n\n/** Minimal server-authoritative tier identity and charged amount used during validation. */\nexport interface MembershipTierAuthority {\n id: string;\n priceCents: number;\n}\n\n/** Live tier authority used to reject missing, unknown, or misleading presentation. */\nexport interface MembershipPageValidationOptions {\n /** When supplied, every live tier must occur exactly once in the document. */\n tiers?: readonly MembershipTierAuthority[];\n}\n\n/** A normalized document or the complete actionable list of validation failures. */\nexport type MembershipPageValidationResult =\n | { ok: true; value: MembershipPageDocument }\n | { ok: false; errors: readonly string[] };\n\nconst TIER_ID = /^[a-z][a-z0-9-]{0,79}$/;\nconst VARIANTS = new Set<MembershipTierVariant>([\"standard\", \"featured\", \"supporting\"]);\nconst ROOT_KEYS = new Set([\"schemaVersion\", \"renderer\", \"tiers\", \"footnoteMarkdown\"]);\nconst TIER_KEYS = new Set([\n \"tierId\", \"variant\", \"badge\", \"summaryMarkdown\", \"priceEyebrow\",\n \"compareAtPriceCents\", \"billingLabel\", \"priceNoteMarkdown\", \"capacity\",\n \"benefits\", \"callout\", \"ctaLabel\",\n]);\nconst CALLOUT_KEYS = new Set([\"label\", \"bodyMarkdown\"]);\nconst CAPACITY_KEYS = new Set([\"total\", \"label\"]);\nconst MAX_TIERS = 20;\nconst MAX_BENEFITS = 24;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_LABEL = 160;\n\nconst objectRecord = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n path: string,\n errors: string[],\n): void {\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n }\n}\n\nfunction boundedString(\n value: unknown,\n path: string,\n errors: string[],\n max: number,\n required = false,\n): string | undefined {\n if (value === undefined) {\n if (required) errors.push(`${path} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") {\n errors.push(`${path} must be a string`);\n return undefined;\n }\n const text = value.trim();\n if (required && !text) errors.push(`${path} is required`);\n if (text.length > max) errors.push(`${path} must be at most ${max.toLocaleString(\"en-US\")} characters`);\n return text;\n}\n\n/**\n * Validate and normalize a membership-page document without evaluating code,\n * accepting HTML, or allowing authored links/styles. Markdown slots are later\n * rendered by @odla-ai/ui's bounded safe Markdown component.\n */\nexport function validateMembershipPageDocument(\n input: unknown,\n options: MembershipPageValidationOptions = {},\n): MembershipPageValidationResult {\n const errors: string[] = [];\n const root = objectRecord(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n rejectUnknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== 1) errors.push(\"document.schemaVersion must be 1\");\n if (root.renderer !== MEMBERSHIP_PAGE_RENDERER) {\n errors.push(`document.renderer must be \\\"${MEMBERSHIP_PAGE_RENDERER}\\\"`);\n }\n if (!Array.isArray(root.tiers)) errors.push(\"document.tiers must be an array\");\n const rawTiers = Array.isArray(root.tiers) ? root.tiers : [];\n if (Array.isArray(root.tiers) && rawTiers.length === 0) errors.push(\"document.tiers must include at least one tier\");\n if (rawTiers.length > MAX_TIERS) errors.push(`document.tiers supports at most ${MAX_TIERS} entries`);\n\n const authority = new Map((options.tiers ?? []).map((tier) => [tier.id, tier]));\n const seen = new Set<string>();\n const tiers: MembershipTierPresentation[] = [];\n for (const [index, raw] of rawTiers.slice(0, MAX_TIERS).entries()) {\n const path = `document.tiers[${index}]`;\n const item = objectRecord(raw);\n if (!item) {\n errors.push(`${path} must be an object`);\n continue;\n }\n rejectUnknownKeys(item, TIER_KEYS, path, errors);\n const tierId = boundedString(item.tierId, `${path}.tierId`, errors, 80, true) ?? \"\";\n if (tierId && !TIER_ID.test(tierId)) errors.push(`${path}.tierId must be a lowercase kebab-case id`);\n if (seen.has(tierId)) errors.push(`${path}.tierId duplicates \\\"${tierId}\\\"`);\n seen.add(tierId);\n if (authority.size && !authority.has(tierId)) errors.push(`${path}.tierId \\\"${tierId}\\\" is not an offered tier`);\n\n const variant = item.variant;\n if (variant !== undefined && (typeof variant !== \"string\" || !VARIANTS.has(variant as MembershipTierVariant))) {\n errors.push(`${path}.variant must be standard, featured, or supporting`);\n }\n const compareAt = item.compareAtPriceCents;\n if (compareAt !== undefined && (!Number.isInteger(compareAt) || Number(compareAt) < 0 || Number(compareAt) > 100_000_000)) {\n errors.push(`${path}.compareAtPriceCents must be an integer from 0 to 100,000,000`);\n }\n const actual = authority.get(tierId)?.priceCents;\n if (Number.isInteger(compareAt) && actual !== undefined && Number(compareAt) <= actual) {\n errors.push(`${path}.compareAtPriceCents must be greater than the authoritative tier price`);\n }\n\n let benefits: string[] | undefined;\n if (item.benefits !== undefined) {\n if (!Array.isArray(item.benefits)) errors.push(`${path}.benefits must be an array`);\n else {\n if (item.benefits.length > MAX_BENEFITS) errors.push(`${path}.benefits supports at most ${MAX_BENEFITS} entries`);\n benefits = item.benefits.slice(0, MAX_BENEFITS).flatMap((benefit, benefitIndex) => {\n const text = boundedString(benefit, `${path}.benefits[${benefitIndex}]`, errors, 2_000, true);\n return text ? [text] : [];\n });\n }\n }\n\n let callout: MembershipTierCallout | undefined;\n if (item.callout !== undefined) {\n const rawCallout = objectRecord(item.callout);\n if (!rawCallout) errors.push(`${path}.callout must be an object`);\n else {\n rejectUnknownKeys(rawCallout, CALLOUT_KEYS, `${path}.callout`, errors);\n const bodyMarkdown = boundedString(rawCallout.bodyMarkdown, `${path}.callout.bodyMarkdown`, errors, MAX_MARKDOWN, true);\n const label = boundedString(rawCallout.label, `${path}.callout.label`, errors, MAX_LABEL);\n if (bodyMarkdown) callout = { ...(label ? { label } : {}), bodyMarkdown };\n }\n }\n\n let capacity: MembershipTierCapacity | undefined;\n if (item.capacity !== undefined) {\n const rawCapacity = objectRecord(item.capacity);\n if (!rawCapacity) errors.push(`${path}.capacity must be an object`);\n else {\n rejectUnknownKeys(rawCapacity, CAPACITY_KEYS, `${path}.capacity`, errors);\n const total = rawCapacity.total;\n if (!Number.isInteger(total) || Number(total) < 1 || Number(total) > 1_000_000) {\n errors.push(`${path}.capacity.total must be an integer from 1 to 1,000,000`);\n }\n const label = boundedString(rawCapacity.label, `${path}.capacity.label`, errors, MAX_LABEL);\n if (Number.isInteger(total) && Number(total) >= 1 && Number(total) <= 1_000_000) {\n capacity = { total: Number(total), ...(label ? { label } : {}) };\n }\n }\n }\n\n const badge = boundedString(item.badge, `${path}.badge`, errors, MAX_LABEL);\n const summaryMarkdown = boundedString(item.summaryMarkdown, `${path}.summaryMarkdown`, errors, MAX_MARKDOWN);\n const priceEyebrow = boundedString(item.priceEyebrow, `${path}.priceEyebrow`, errors, MAX_LABEL);\n const billingLabel = boundedString(item.billingLabel, `${path}.billingLabel`, errors, MAX_LABEL);\n const priceNoteMarkdown = boundedString(item.priceNoteMarkdown, `${path}.priceNoteMarkdown`, errors, MAX_MARKDOWN);\n const ctaLabel = boundedString(item.ctaLabel, `${path}.ctaLabel`, errors, MAX_LABEL);\n tiers.push({\n tierId,\n ...(typeof variant === \"string\" && VARIANTS.has(variant as MembershipTierVariant) ? { variant: variant as MembershipTierVariant } : {}),\n ...(badge ? { badge } : {}),\n ...(summaryMarkdown ? { summaryMarkdown } : {}),\n ...(priceEyebrow ? { priceEyebrow } : {}),\n ...(Number.isInteger(compareAt) ? { compareAtPriceCents: Number(compareAt) } : {}),\n ...(billingLabel ? { billingLabel } : {}),\n ...(priceNoteMarkdown ? { priceNoteMarkdown } : {}),\n ...(capacity ? { capacity } : {}),\n ...(benefits ? { benefits } : {}),\n ...(callout ? { callout } : {}),\n ...(ctaLabel ? { ctaLabel } : {}),\n });\n }\n if (authority.size) {\n for (const tierId of authority.keys()) {\n if (!seen.has(tierId)) errors.push(`document.tiers is missing offered tier \\\"${tierId}\\\"`);\n }\n }\n const footnoteMarkdown = boundedString(root.footnoteMarkdown, \"document.footnoteMarkdown\", errors, MAX_MARKDOWN);\n if (errors.length) return { ok: false, errors };\n return {\n ok: true,\n value: {\n schemaVersion: 1,\n renderer: MEMBERSHIP_PAGE_RENDERER,\n tiers,\n ...(footnoteMarkdown ? { footnoteMarkdown } : {}),\n },\n };\n}\n\n/** Validate a document or fail closed with all actionable validation errors. */\nexport function membershipPageDocument(\n input: unknown,\n options: MembershipPageValidationOptions = {},\n): MembershipPageDocument {\n const result = validateMembershipPageDocument(input, options);\n if (!result.ok) throw new TypeError(`Invalid membership page document: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","import { resolveApplication } from \"./member\";\nimport { validateMembershipPageDocument } from \"./membership-page\";\nimport { validateScheduling } from \"./scheduling\";\nimport { validateGiftOfferCatalog } from \"./gift-offers\";\nimport type {\n SignupControlApplication,\n SignupControlDocument,\n SignupControlPolicy,\n SignupControlTheme,\n SignupControlTier,\n SignupControlValidation,\n} from \"./signup-control-contract\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst ENVIRONMENT = /^[a-z][a-z0-9_-]{0,62}$/;\nconst TIER = /^[a-z][a-z0-9-]{0,79}$/;\nconst PRICE = /^price_[A-Za-z0-9]{12,}$/;\nconst ROOT_KEYS = new Set([\n \"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"tiers\",\n \"membershipPage\", \"application\", \"policy\", \"scheduling\", \"theme\", \"giftOffers\",\n]);\nconst TIER_KEYS = new Set([\"id\", \"name\", \"available\", \"sortOrder\", \"priceCents\", \"currency\", \"interval\", \"stripePriceId\", \"blurb\"]);\n\nconst recordOf = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nfunction unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]): void {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nfunction text(value: unknown, path: string, errors: string[], max = 65_536): string {\n if (typeof value !== \"string\" || !value.trim()) {\n errors.push(`${path} is required`);\n return \"\";\n }\n if (value.length > max) errors.push(`${path} must be at most ${max} characters`);\n return value.trim();\n}\n\nfunction tiersOf(value: unknown, errors: string[]): SignupControlTier[] {\n if (!Array.isArray(value) || !value.length) {\n errors.push(\"document.tiers must be a non-empty array\");\n return [];\n }\n if (value.length > 20) errors.push(\"document.tiers supports at most 20 entries\");\n const seen = new Set<string>();\n return value.slice(0, 20).flatMap((raw, index) => {\n const path = `document.tiers[${index}]`;\n const item = recordOf(raw);\n if (!item) {\n errors.push(`${path} must be an object`);\n return [];\n }\n unknownKeys(item, TIER_KEYS, path, errors);\n const id = text(item.id, `${path}.id`, errors, 80);\n if (id && !TIER.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (seen.has(id)) errors.push(`${path}.id duplicates \"${id}\"`);\n seen.add(id);\n const name = text(item.name, `${path}.name`, errors, 160);\n if (typeof item.available !== \"boolean\") errors.push(`${path}.available must be boolean`);\n if (!Number.isInteger(item.sortOrder) || Number(item.sortOrder) < 0) errors.push(`${path}.sortOrder must be a non-negative integer`);\n if (!Number.isInteger(item.priceCents) || Number(item.priceCents) < 0 || Number(item.priceCents) > 100_000_000) {\n errors.push(`${path}.priceCents must be an integer from 0 to 100,000,000`);\n }\n if (item.stripePriceId !== undefined && (typeof item.stripePriceId !== \"string\" || !PRICE.test(item.stripePriceId))) {\n errors.push(`${path}.stripePriceId must be a real Stripe Price id`);\n }\n if (item.available === true && Number(item.priceCents) > 0 && !item.stripePriceId) {\n errors.push(`${path}.stripePriceId is required for an available paid tier`);\n }\n if (item.currency !== undefined && (typeof item.currency !== \"string\" || !/^[a-z]{3}$/.test(item.currency))) {\n errors.push(`${path}.currency must be a lowercase ISO currency code`);\n }\n if (item.interval !== undefined && item.interval !== \"year\" && item.interval !== \"month\") {\n errors.push(`${path}.interval must be year or month`);\n }\n const blurb = item.blurb === undefined ? undefined : text(item.blurb, `${path}.blurb`, errors, 4_000);\n return [{\n id, name, available: item.available === true,\n sortOrder: Number(item.sortOrder) || 0,\n priceCents: Number(item.priceCents) || 0,\n ...(typeof item.currency === \"string\" ? { currency: item.currency } : {}),\n ...(item.interval === \"year\" || item.interval === \"month\" ? { interval: item.interval } : {}),\n ...(typeof item.stripePriceId === \"string\" ? { stripePriceId: item.stripePriceId } : {}),\n ...(blurb ? { blurb } : {}),\n }];\n });\n}\n\nfunction applicationOf(value: unknown, errors: string[]): SignupControlApplication | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n if (!input) {\n errors.push(\"document.application must be an object\");\n return undefined;\n }\n unknownKeys(input, new Set([\"required\", \"optional\", \"conditions\", \"copy\"]), \"document.application\", errors);\n try {\n const resolved = resolveApplication(input);\n const copy = recordOf(input.copy);\n if (input.copy !== undefined && (!copy || Object.values(copy).some((item) => typeof item !== \"string\"))) {\n errors.push(\"document.application.copy must contain only string values\");\n }\n return {\n required: resolved.required,\n optional: resolved.optional,\n ...(Object.keys(resolved.conditions).length ? { conditions: resolved.conditions } : {}),\n ...(copy ? { copy: copy as Record<string, string> } : {}),\n };\n } catch (error) {\n errors.push(error instanceof Error ? error.message : \"document.application is invalid\");\n return undefined;\n }\n}\n\nfunction policyOf(value: unknown, errors: string[]): SignupControlPolicy | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n if (!input) {\n errors.push(\"document.policy must be an object\");\n return undefined;\n }\n const allowed = new Set([\n \"disclaimerText\",\n \"refundPolicyText\",\n \"merchantDisclosureText\",\n \"trustCopy\",\n \"commitmentText\",\n \"normsText\",\n ]);\n unknownKeys(input, allowed, \"document.policy\", errors);\n const result = {} as Record<string, string>;\n for (const key of allowed) {\n if (input[key] === undefined && key !== \"disclaimerText\" && key !== \"refundPolicyText\") continue;\n result[key] = text(input[key], `document.policy.${key}`, errors);\n }\n return result as unknown as SignupControlPolicy;\n}\n\nfunction themeOf(value: unknown, errors: string[]): SignupControlTheme | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n const tokens = recordOf(input?.tokens);\n if (!input || !tokens) {\n errors.push(\"document.theme.tokens must be an object\");\n return undefined;\n }\n unknownKeys(input, new Set([\"tokens\"]), \"document.theme\", errors);\n if (Object.keys(tokens).length > 256) errors.push(\"document.theme.tokens supports at most 256 entries\");\n let serializedLength = 0;\n for (const [key, token] of Object.entries(tokens)) {\n if (!/^--ui-[a-z0-9][a-z0-9-]{0,94}$/.test(key)) {\n errors.push(`document.theme.tokens.${key} must be an allowlisted --ui-* custom property`);\n }\n const rendered = String(token).trim();\n serializedLength += key.length + rendered.length + 4;\n if ((typeof token !== \"string\" && typeof token !== \"number\") ||\n (typeof token === \"number\" && !Number.isFinite(token)) ||\n !rendered || rendered.length > 1_000 ||\n /[\\u0000-\\u001f\\u007f\\\\<>{};]|\\/\\*|\\*\\/|(?:^|[^a-z])(?:url|expression)\\s*\\(|@import/i.test(rendered)) {\n errors.push(`document.theme.tokens.${key} must be a bounded breakout-safe CSS value`);\n }\n }\n if (serializedLength > 65_536) errors.push(\"document.theme.tokens exceeds the serialized size bound\");\n return { tokens: tokens as Record<string, string | number> };\n}\n\n/** Validate and normalize one complete desired signup state. */\nexport function validateSignupControlDocument(input: unknown): SignupControlValidation {\n const errors: string[] = [];\n const root = recordOf(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== 1) errors.push(\"document.schemaVersion must be 1\");\n if (!Number.isSafeInteger(root.revision) || Number(root.revision) < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isSafeInteger(root.generatedAt) || Number(root.generatedAt) < 1) errors.push(\"document.generatedAt must be epoch milliseconds\");\n const source = recordOf(root.source);\n const target = recordOf(root.target);\n const appId = text(source?.appId, \"document.source.appId\", errors, 63);\n const chapterId = text(target?.chapterId, \"document.target.chapterId\", errors, 63);\n const environment = text(target?.environment, \"document.target.environment\", errors, 63);\n if (appId && !SLUG.test(appId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (chapterId && !SLUG.test(chapterId)) errors.push(\"document.target.chapterId must be a lowercase app slug\");\n if (environment && !ENVIRONMENT.test(environment)) errors.push(\"document.target.environment is invalid\");\n if (target?.stripeMode !== \"test\" && target?.stripeMode !== \"live\") errors.push(\"document.target.stripeMode must be test or live\");\n const tiers = tiersOf(root.tiers, errors);\n const available = tiers.filter((tier) => tier.available).sort((a, b) => a.sortOrder - b.sortOrder);\n const page = validateMembershipPageDocument(root.membershipPage, { tiers: available });\n if (!page.ok) errors.push(...page.errors);\n else if (page.value.tiers.some((tier, index) => tier.tierId !== available[index]?.id)) {\n errors.push(\"document.membershipPage.tiers must follow the available tier display order\");\n }\n const application = applicationOf(root.application, errors);\n const policy = policyOf(root.policy, errors);\n let scheduling;\n if (root.scheduling !== undefined) {\n const checked = validateScheduling(root.scheduling as never);\n if (!checked.ok) errors.push(...Object.entries(checked.errors).map(([key, value]) => `document.scheduling.${key}: ${value}`));\n else scheduling = root.scheduling;\n }\n const theme = themeOf(root.theme, errors);\n const giftOffers = root.giftOffers === undefined\n ? undefined\n : validateGiftOfferCatalog(root.giftOffers, new Set(tiers.map((tier) => tier.id)));\n if (giftOffers && !giftOffers.ok) errors.push(...giftOffers.errors);\n if (errors.length || !page.ok) return { ok: false, errors };\n return { ok: true, value: {\n schemaVersion: 1,\n revision: Number(root.revision),\n generatedAt: Number(root.generatedAt),\n source: { appId },\n target: { chapterId, environment, stripeMode: target?.stripeMode as \"test\" | \"live\" },\n tiers,\n membershipPage: page.value,\n ...(application ? { application } : {}),\n ...(policy ? { policy } : {}),\n ...(scheduling ? { scheduling } : {}),\n ...(theme ? { theme } : {}),\n ...(giftOffers?.ok ? { giftOffers: giftOffers.value } : {}),\n } };\n}\n","import type { SignupControlTheme } from \"./signup-control-contract\";\n\n/** Stable marker a static document can place where managed signup tokens belong. */\nexport const SIGNUP_CONTROL_THEME_MARKER = \"<!--odla:signup-control-theme-->\" as const;\n/** Stable id shared by the server renderer and browser hydration helper. */\nexport const SIGNUP_CONTROL_THEME_STYLE_ID = \"odla-signup-control-theme\" as const;\n\nconst TOKEN_NAME = /^--ui-[a-z0-9][a-z0-9-]{0,94}$/;\nconst DIGEST = /^sha256:[0-9a-f]{64}$/;\nconst UNSAFE_VALUE = /[\\u0000-\\u001f\\u007f\\\\<>{};]|\\/\\*|\\*\\/|(?:^|[^a-z])(?:url|expression)\\s*\\(|@import/i;\nconst MAX_TOKENS = 256;\nconst MAX_VALUE_LENGTH = 1_000;\nconst MAX_SERIALIZED_LENGTH = 65_536;\n\n/** The active revision shape exposed by `GET /api/join-config`. */\nexport interface SignupControlThemeRevision {\n revision: number;\n digest: string;\n theme?: SignupControlTheme;\n}\n\n/** Identity shared by initial HTML, response caching, and client hydration. */\nexport interface SignupControlThemeMetadata {\n source: \"active\" | \"bootstrap\";\n revision: number | null;\n digest: string | null;\n /** Include this value in any host-owned cache key for transformed HTML. */\n cacheKey: string;\n}\n\n/** A validated style block ready to place in an HTML head. */\nexport interface SignupControlThemeHead {\n css: string;\n head: string;\n metadata: SignupControlThemeMetadata;\n}\n\n/** Minimal DOM surface required by {@link hydrateSignupControlTheme}. */\nexport interface SignupControlThemeStyleTarget {\n textContent: string | null;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n removeAttribute(name: string): void;\n}\n\n/** Host-owned fallback inputs shared by server rendering and hydration. */\nexport interface SignupControlThemeOptions {\n /** Local site-owned tokens used only when no active managed revision exists. */\n bootstrapTokens?: Readonly<Record<string, string | number>>;\n}\n\nfunction validatedTokens(\n input: Readonly<Record<string, string | number>> | undefined,\n): Readonly<Record<string, string>> {\n const entries = Object.entries(input ?? {});\n if (entries.length > MAX_TOKENS) {\n throw new TypeError(`signup-control theme supports at most ${MAX_TOKENS} tokens`);\n }\n const tokens: Record<string, string> = {};\n let serializedLength = 0;\n for (const [name, raw] of entries.sort(([left], [right]) => left.localeCompare(right))) {\n if (!TOKEN_NAME.test(name)) {\n throw new TypeError(`signup-control theme token \"${name}\" must be an allowlisted --ui-* property`);\n }\n if ((typeof raw !== \"string\" && typeof raw !== \"number\") ||\n (typeof raw === \"number\" && !Number.isFinite(raw))) {\n throw new TypeError(`signup-control theme token \"${name}\" must be a finite string or number`);\n }\n const value = String(raw).trim();\n if (!value || value.length > MAX_VALUE_LENGTH || UNSAFE_VALUE.test(value)) {\n throw new TypeError(`signup-control theme token \"${name}\" has an unsafe or oversized value`);\n }\n serializedLength += name.length + value.length + 4;\n if (serializedLength > MAX_SERIALIZED_LENGTH) {\n throw new TypeError(\"signup-control theme exceeds the serialized size bound\");\n }\n tokens[name] = value;\n }\n return tokens;\n}\n\nfunction cssFor(tokens: Readonly<Record<string, string>>): string {\n const declarations = Object.entries(tokens).map(([name, value]) => ` ${name}: ${value};`);\n return declarations.length ? `:root {\\n${declarations.join(\"\\n\")}\\n}` : \"\";\n}\n\nfunction stateFor(\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions,\n): { css: string; metadata: SignupControlThemeMetadata } {\n if (!revision) {\n return {\n css: cssFor(validatedTokens(options.bootstrapTokens)),\n metadata: { source: \"bootstrap\", revision: null, digest: null, cacheKey: \"signup-control:bootstrap\" },\n };\n }\n if (!Number.isSafeInteger(revision.revision) || revision.revision < 1 || !DIGEST.test(revision.digest)) {\n throw new TypeError(\"signup-control theme revision metadata is invalid\");\n }\n return {\n css: cssFor(validatedTokens(revision.theme?.tokens)),\n metadata: {\n source: \"active\",\n revision: revision.revision,\n digest: revision.digest,\n cacheKey: `signup-control:${revision.digest}`,\n },\n };\n}\n\nfunction attributes(metadata: SignupControlThemeMetadata): string {\n return [\n `id=\"${SIGNUP_CONTROL_THEME_STYLE_ID}\"`,\n `data-signup-control-source=\"${metadata.source}\"`,\n `data-signup-control-cache-key=\"${metadata.cacheKey}\"`,\n ...(metadata.revision === null ? [] : [`data-signup-control-revision=\"${metadata.revision}\"`]),\n ...(metadata.digest === null ? [] : [`data-signup-control-digest=\"${metadata.digest}\"`]),\n ].join(\" \");\n}\n\n/**\n * Render validated signup-control tokens for the initial HTML head. Passing\n * `null` emits the deterministic local bootstrap state; it never performs I/O.\n */\nexport function renderSignupControlThemeHead(\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions = {},\n): SignupControlThemeHead {\n const { css, metadata } = stateFor(revision, options);\n return { css, metadata, head: `<style ${attributes(metadata)}>${css}</style>` };\n}\n\n/**\n * Replace the stable marker (preferred), an earlier Chapter style block, or the\n * closing head tag. The returned HTML always contains exactly one managed block.\n */\nexport function injectSignupControlThemeHead(\n html: string,\n rendered: SignupControlThemeHead,\n marker: string = SIGNUP_CONTROL_THEME_MARKER,\n): string {\n const existing = /<style\\b(?=[^>]*\\bid\\s*=\\s*[\"']odla-signup-control-theme[\"'])[^>]*>[\\s\\S]*?<\\/style>/gi;\n const existingBlocks = html.match(existing) ?? [];\n if (existingBlocks.length > 1) {\n throw new TypeError(\"signup-control theme style block must appear at most once\");\n }\n if (existingBlocks.length === 1) return html.replace(existing, rendered.head);\n const markerIndex = html.indexOf(marker);\n if (markerIndex >= 0) {\n if (html.indexOf(marker, markerIndex + marker.length) >= 0) {\n throw new TypeError(\"signup-control theme marker must appear exactly once\");\n }\n return `${html.slice(0, markerIndex)}${rendered.head}${html.slice(markerIndex + marker.length)}`;\n }\n const closingHead = html.search(/<\\/head\\s*>/i);\n if (closingHead < 0) throw new TypeError(\"signup-control theme requires an HTML head\");\n return `${html.slice(0, closingHead)}${rendered.head}${html.slice(closingHead)}`;\n}\n\n/**\n * Apply a newly fetched revision to the server-rendered style element. When the\n * revision and digest already match, this performs no writes and returns false,\n * so hydration cannot cause a visual token change.\n */\nexport function hydrateSignupControlTheme(\n target: SignupControlThemeStyleTarget,\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions = {},\n): boolean {\n const next = stateFor(revision, options);\n const currentSource = target.getAttribute(\"data-signup-control-source\");\n const currentRevision = target.getAttribute(\"data-signup-control-revision\");\n const currentDigest = target.getAttribute(\"data-signup-control-digest\");\n if (currentSource === next.metadata.source &&\n currentRevision === (next.metadata.revision === null ? null : String(next.metadata.revision)) &&\n currentDigest === next.metadata.digest) {\n return false;\n }\n target.textContent = next.css;\n target.setAttribute(\"data-signup-control-source\", next.metadata.source);\n target.setAttribute(\"data-signup-control-cache-key\", next.metadata.cacheKey);\n if (next.metadata.revision === null) target.removeAttribute(\"data-signup-control-revision\");\n else target.setAttribute(\"data-signup-control-revision\", String(next.metadata.revision));\n if (next.metadata.digest === null) target.removeAttribute(\"data-signup-control-digest\");\n else target.setAttribute(\"data-signup-control-digest\", next.metadata.digest);\n return true;\n}\n","import type { MembershipTierPresentation } from \"./membership-page\";\n\n/** A presentation overlay parsed from the constrained membership Markdown convention. */\nexport type MembershipTierMarkdownResult =\n | { ok: true; value: MembershipTierPresentation }\n | { ok: false; errors: readonly string[] };\n\nconst MAX_BENEFITS = 24;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_LABEL = 160;\nconst MARKDOWN_SECTION = /^##\\s+(.+?)\\s*$/;\nconst MARKDOWN_HEADING = /^#{1,6}\\s+/;\nconst MARKDOWN_BENEFIT = /^\\s*[-*+]\\s+(.+?)\\s*$/;\n\ntype MembershipMarkdownSection = \"summary\" | \"benefits\" | \"priceNote\" | \"callout\" | \"action\";\n\nfunction markdownSection(rawHeading: string): { section?: MembershipMarkdownSection; calloutLabel?: string } {\n const heading = rawHeading.trim();\n const normalized = heading.toLowerCase();\n if (normalized === \"summary\") return { section: \"summary\" };\n if (normalized === \"benefits\") return { section: \"benefits\" };\n if (normalized === \"price note\" || normalized === \"rate note\") return { section: \"priceNote\" };\n if (normalized === \"action\" || normalized === \"call to action\") return { section: \"action\" };\n const callout = heading.match(/^callout(?:\\s*[:—-]\\s*(.+))?$/i);\n if (callout) return { section: \"callout\", ...(callout[1]?.trim() ? { calloutLabel: callout[1].trim() } : {}) };\n return {};\n}\n\nfunction markdownBenefits(lines: readonly string[], path: string, errors: string[]): string[] {\n const benefits: string[] = [];\n for (const [index, line] of lines.entries()) {\n if (!line.trim()) continue;\n const match = line.match(MARKDOWN_BENEFIT);\n if (!match) {\n errors.push(`${path} line ${index + 1} must be a Markdown bullet`);\n continue;\n }\n const text = (match[1] ?? \"\").trim();\n if (text.length > 2_000) errors.push(`${path} line ${index + 1} must be at most 2,000 characters`);\n if (text) benefits.push(text);\n }\n if (benefits.length > MAX_BENEFITS) errors.push(`${path} supports at most ${MAX_BENEFITS} entries`);\n return benefits.slice(0, MAX_BENEFITS);\n}\n\n/**\n * Apply authored Markdown to the text slots of an existing tier presentation.\n *\n * The convention is deliberately small and reviewable:\n * - prelude prose -> summary; prelude bullets -> benefits\n * - `## Summary`, `## Benefits`, `## Price note`, `## Callout: Label`,\n * and `## Action` target those exact renderer slots\n *\n * Identity, price, scarcity, variants, badges, links, HTML, and CSS remain in\n * the reviewed presentation/authority contract and cannot be authored here.\n */\nexport function applyMembershipTierMarkdown(\n presentation: MembershipTierPresentation,\n source: string,\n): MembershipTierMarkdownResult {\n if (typeof source !== \"string\") return { ok: false, errors: [\"membership Markdown must be a string\"] };\n if (source.length > MAX_MARKDOWN) {\n return { ok: false, errors: [`membership Markdown must be at most ${MAX_MARKDOWN.toLocaleString(\"en-US\")} characters`] };\n }\n if (!source.trim()) return { ok: true, value: { ...presentation } };\n\n const errors: string[] = [];\n const sections = new Map<MembershipMarkdownSection, { lines: string[]; calloutLabel?: string }>();\n const prelude: string[] = [];\n let current: MembershipMarkdownSection | null = null;\n for (const [index, line] of source.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\").entries()) {\n const heading = line.match(MARKDOWN_SECTION);\n if (heading) {\n const headingText = heading[1] ?? \"\";\n const parsed = markdownSection(headingText);\n if (!parsed.section) {\n errors.push(`membership Markdown heading \"${headingText.trim()}\" is not supported`);\n current = null;\n continue;\n }\n if (sections.has(parsed.section)) {\n errors.push(`membership Markdown repeats the ${parsed.section} section`);\n current = parsed.section;\n continue;\n }\n sections.set(parsed.section, { lines: [], ...(parsed.calloutLabel ? { calloutLabel: parsed.calloutLabel } : {}) });\n current = parsed.section;\n continue;\n }\n if (MARKDOWN_HEADING.test(line)) {\n errors.push(`membership Markdown line ${index + 1} uses an unsupported heading`);\n continue;\n }\n if (current) sections.get(current)?.lines.push(line);\n else prelude.push(line);\n }\n\n const preludeBenefits: string[] = [];\n const preludeSummary: string[] = [];\n for (const line of prelude) {\n const benefit = line.match(MARKDOWN_BENEFIT);\n if (benefit) preludeBenefits.push((benefit[1] ?? \"\").trim());\n else preludeSummary.push(line);\n }\n if (preludeBenefits.length > MAX_BENEFITS) errors.push(`membership Markdown prelude supports at most ${MAX_BENEFITS} benefits`);\n if (preludeBenefits.some((benefit) => benefit.length > 2_000)) errors.push(\"membership Markdown benefits must be at most 2,000 characters\");\n\n const summarySection = sections.get(\"summary\");\n const benefitsSection = sections.get(\"benefits\");\n const priceNoteSection = sections.get(\"priceNote\");\n const calloutSection = sections.get(\"callout\");\n const actionSection = sections.get(\"action\");\n const summaryMarkdown = (summarySection?.lines ?? preludeSummary).join(\"\\n\").trim();\n const benefits = benefitsSection\n ? markdownBenefits(benefitsSection.lines, \"membership Markdown Benefits\", errors)\n : preludeBenefits.filter(Boolean).slice(0, MAX_BENEFITS);\n const priceNoteMarkdown = priceNoteSection?.lines.join(\"\\n\").trim();\n const calloutBody = calloutSection?.lines.join(\"\\n\").trim();\n const actionLines = actionSection?.lines.filter((line) => line.trim());\n const ctaLabel = actionLines?.join(\" \").trim();\n if (actionLines && actionLines.length !== 1) errors.push(\"membership Markdown Action must contain exactly one line\");\n if (ctaLabel && ctaLabel.length > MAX_LABEL) errors.push(`membership Markdown Action must be at most ${MAX_LABEL} characters`);\n if (calloutSection && !calloutBody) errors.push(\"membership Markdown Callout must include body copy\");\n if (calloutSection?.calloutLabel && calloutSection.calloutLabel.length > MAX_LABEL) {\n errors.push(`membership Markdown Callout label must be at most ${MAX_LABEL} characters`);\n }\n if (errors.length) return { ok: false, errors };\n\n return {\n ok: true,\n value: {\n ...presentation,\n ...(summaryMarkdown ? { summaryMarkdown } : {}),\n ...(benefitsSection || preludeBenefits.length ? { benefits } : {}),\n ...(priceNoteSection ? { priceNoteMarkdown: priceNoteMarkdown ?? \"\" } : {}),\n ...(calloutSection ? {\n callout: {\n ...(calloutSection.calloutLabel || presentation.callout?.label\n ? { label: calloutSection.calloutLabel ?? presentation.callout?.label }\n : {}),\n bodyMarkdown: calloutBody ?? \"\",\n },\n } : {}),\n ...(actionSection && ctaLabel ? { ctaLabel } : {}),\n },\n };\n}\n\n/** Apply constrained membership Markdown or fail closed with actionable errors. */\nexport function membershipTierPresentationFromMarkdown(\n presentation: MembershipTierPresentation,\n source: string,\n): MembershipTierPresentation {\n const result = applyMembershipTierMarkdown(presentation, source);\n if (!result.ok) throw new TypeError(`Invalid membership Markdown: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","import {\n canonicalPromotionValue,\n type PromotionAdapterResult,\n type PromotionArtifactInput,\n type PromotionExclusion,\n} from \"@odla-ai/promotion\";\nimport { signupControlDigest } from \"./signup-control-canonical\";\nimport type { SignupControlDocument } from \"./signup-control-contract\";\nimport { validateSignupControlDocument } from \"./signup-control-validate\";\n\n/** Stable adapter identity bound into Chapter artifact provenance. */\nexport const CHAPTER_PROMOTION_ADAPTER = \"@odla-ai/chapter/v1\";\n\n/** One exact, digest-verified signup-control revision to export. */\nexport interface ChapterPromotionInput {\n document: SignupControlDocument;\n digest: string;\n}\n\nconst exclusions = (chapterId: string, paidTierIds: string[]): PromotionExclusion[] => [\n {\n kind: \"chapter.providers\", id: chapterId, reason: \"provider_identity\",\n paths: [\n ...paidTierIds.map((id) => `tiers[${id}].stripePriceId`),\n \"groups.stripePublishableKey\", \"applications.stripeCustomerId\",\n \"applications.stripeSubscriptionId\", \"meetings.googleEventId\",\n ],\n detail: \"Stripe, Clerk, and Google identities are resolved independently in each target environment.\",\n },\n {\n kind: \"chapter.runtime\", id: chapterId, reason: \"runtime_state\",\n paths: [\"applications.*\", \"meetings.*\", \"emailLog.*\", \"crm_*.*\"],\n detail: \"Applicants, meetings, messages, and CRM rows are operational state, not managed signup content.\",\n },\n {\n kind: \"chapter.access\", id: chapterId, reason: \"personal_data\",\n paths: [\"admins.*\", \"superAdmins.*\", \"networkNotes.*\"],\n detail: \"People, access lists, and private network notes remain local to the target environment.\",\n },\n {\n kind: \"chapter.history\", id: chapterId, reason: \"authority_history\",\n paths: [\"signupControls[active=false]\", \"signupControls.*At\", \"signupControls.environment\"],\n detail: \"The source retains immutable delivery history; only selected published content is exported.\",\n },\n];\n\n/** Export the provider-independent pieces of one exact active signup revision. */\nexport async function exportChapterPromotion(input: ChapterPromotionInput): Promise<PromotionAdapterResult> {\n if (!/^sha256:[0-9a-f]{64}$/.test(input.digest)) throw new TypeError(\"chapter promotion digest is invalid\");\n const checked = validateSignupControlDocument(input.document);\n if (!checked.ok) throw new TypeError(checked.errors.join(\"; \"));\n const document = checked.value;\n if (await signupControlDigest(document) !== input.digest) throw new TypeError(\"chapter promotion digest does not match its document\");\n const revision = `chapter:${document.target.chapterId}:${document.revision}`;\n const promotionProvenance = {\n adapter: CHAPTER_PROMOTION_ADAPTER,\n sourceIds: [`signup-control:${document.revision}`, document.source.appId, document.target.chapterId].sort(),\n receiptDigests: [input.digest as `sha256:${string}`],\n };\n const artifact = (kind: string, id: string, content: unknown): PromotionArtifactInput => ({\n kind, id, sourceRevision: revision, provenance: promotionProvenance,\n content: canonicalPromotionValue(content),\n });\n const chapterId = document.target.chapterId;\n const artifacts = [\n artifact(\"chapter.catalog\", chapterId, {\n chapterId,\n tiers: document.tiers.map(({ stripePriceId: _providerId, ...tier }) => tier),\n }),\n artifact(\"chapter.membership-page\", chapterId, document.membershipPage),\n ...(document.application ? [artifact(\"chapter.application\", chapterId, document.application)] : []),\n ...(document.policy ? [artifact(\"chapter.policy\", chapterId, document.policy)] : []),\n ...(document.scheduling ? [artifact(\"chapter.scheduling\", chapterId, document.scheduling)] : []),\n ...(document.theme ? [artifact(\"chapter.theme\", chapterId, document.theme)] : []),\n ];\n return {\n adapter: CHAPTER_PROMOTION_ADAPTER,\n artifacts,\n exclusions: exclusions(chapterId, document.tiers.filter((tier) => tier.stripePriceId).map((tier) => tier.id)),\n preconditions: [\n {\n code: \"chapter.signup-control.schema\", path: \"services.chapter.signupControl.schemaVersion\", expected: document.schemaVersion,\n detail: \"The target must support this Chapter signup-control document version.\",\n },\n {\n code: \"chapter.identity\", path: \"app.appId\", expected: chapterId,\n detail: \"Chapter content can only target the chapter named by the signed source revision.\",\n },\n ],\n };\n}\n","/** Storage boundary for a member-system field. */\nexport type MemberSystemScope = \"network\" | \"chapter\" | \"provider\";\n\n/** Durable authority allowed to write a member-system field. */\nexport type MemberSystemWriter =\n | \"network_person\"\n | \"chapter_journey\"\n | \"network_membership\"\n | \"network_entitlement\"\n | \"network_seat\"\n | \"network_discount_policy\"\n | \"network_referral_ledger\"\n | \"network_investment_ledger\"\n | \"network_commercial_projection\"\n | \"clerk\"\n | \"stripe\";\n\n/** Read model that may receive an allowlisted field. */\nexport type MemberSystemProjection =\n | \"bnf_admin\"\n | \"chapter_admin\"\n | \"chapter_crm\"\n | \"member_self_service\"\n | \"stripe_billing\"\n | \"clerk_identity\";\n\n/** Privacy classification used by projection policy. */\nexport type MemberFieldSensitivity = \"ordinary\" | \"pii\" | \"sensitive\" | \"restricted\";\n/** Access a member has to her own projected field. */\nexport type MemberFieldSelfAccess = \"edit\" | \"read\" | \"none\";\n\n/** One field's scope, writer, projections, sensitivity, and self-service access. */\nexport interface MemberFieldAuthority {\n id: string;\n scope: MemberSystemScope;\n writer: MemberSystemWriter;\n projections: readonly MemberSystemProjection[];\n sensitivity: MemberFieldSensitivity;\n memberAccess: MemberFieldSelfAccess;\n}\n\ninterface AuthorityGroup extends Omit<MemberFieldAuthority, \"id\"> { fields: readonly string[] }\nconst rows = (group: AuthorityGroup): MemberFieldAuthority[] => group.fields.map((id) => ({ ...group, id }));\n\n/** Each field has one durable writer. BNF is an operator projection, never a writer. */\nexport const MEMBER_SYSTEM_AUTHORITY_MATRIX: readonly MemberFieldAuthority[] = [\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"pii\", memberAccess: \"edit\",\n fields: [\n \"person.legalName\", \"person.preferredName\", \"person.namePronunciation\", \"person.pronouns\",\n \"person.displayLegalName\", \"person.primaryEmail\", \"person.secondaryEmails\", \"person.phone\",\n \"person.linkedinUrl\", \"person.photo\", \"person.homeAddress\", \"person.fulfillmentFit\", \"person.fulfillmentSize\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"edit\",\n fields: [\n \"person.title\", \"person.company\", \"person.companyObservedAt\", \"person.region\", \"person.whyText\",\n \"person.whyTokens\", \"person.skillsOffered\", \"person.openToRequests\", \"person.directoryPhotoConsent\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"person.linkedinMemberId\", \"person.identityClaims\", \"person.aliases\", \"person.mergeHistory\",\n \"person.introducedByPersonId\", \"person.introducedAt\", \"person.firstTouch\", \"person.globalSuppression\",\n \"person.deceasedAt\", \"person.archivedAt\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"sensitive\", memberAccess: \"edit\",\n fields: [\"person.accreditationSelfCertification\", \"person.accreditationCategory\", \"person.accreditationExpiresAt\"],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"restricted\", memberAccess: \"read\", fields: [\"person.acknowledgements\"],\n }),\n ...rows({\n scope: \"provider\", writer: \"clerk\", projections: [\"clerk_identity\", \"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\"identity.clerkUserIds\", \"identity.clerkEmailVerification\"],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\", \"bnf_admin\"],\n sensitivity: \"ordinary\", memberAccess: \"none\",\n fields: [\n \"journey.chapterId\", \"journey.stage\", \"journey.stageEnteredAt\", \"journey.stageHistory\",\n \"journey.ending\", \"journey.endingReason\", \"journey.source\", \"journey.entryChapterId\",\n \"journey.route\", \"journey.flags\", \"journey.applicationStartedAt\", \"journey.appliedAt\",\n \"journey.paidAt\", \"journey.callBookedAt\", \"journey.metAt\", \"journey.approvedAt\",\n \"journey.onboardedAt\", \"journey.firstLoginAt\", \"journey.firstDealAt\",\n ],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\"],\n sensitivity: \"sensitive\", memberAccess: \"none\",\n fields: [\n \"journey.relationshipOwnerId\", \"journey.lastContactAt\", \"journey.nextAction\", \"journey.owes\",\n \"journey.asks\", \"journey.preparation\", \"journey.notes\",\n ],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"edit\",\n fields: [\"journey.dealFlowConsent\", \"journey.directoryConsent\", \"journey.emailConsent\", \"journey.smsConsent\"],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"bnf_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\", fields: [\"journey.memberNumber\"],\n }),\n ...rows({\n scope: \"network\", writer: \"network_membership\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"membership.chapterId\", \"membership.journeyId\", \"membership.termStartsAt\", \"membership.termEndsAt\",\n \"membership.tier\", \"membership.status\", \"membership.joinedAt\", \"membership.autoRenews\",\n \"membership.renewalAt\", \"membership.cancelsAt\", \"membership.graceEndsAt\", \"membership.foundingCohort\",\n \"membership.offeringPolicyVersion\", \"membership.discountPolicyVersion\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_commercial_projection\", projections: [\"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"membership.stripeCustomerId\", \"membership.stripeSubscriptionId\", \"membership.stripePriceId\",\n \"membership.lastInvoiceId\", \"membership.paymentOutcome\", \"membership.refundOutcome\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_discount_policy\", projections: [\"bnf_admin\", \"chapter_admin\", \"stripe_billing\"],\n sensitivity: \"ordinary\", memberAccess: \"none\",\n fields: [\n \"discountPolicy.chapterId\", \"discountPolicy.version\", \"discountPolicy.eligibleOfferingIds\",\n \"discountPolicy.percentOff\", \"discountPolicy.amountOff\", \"discountPolicy.activatesOn\",\n \"discountPolicy.invoiceCount\", \"discountPolicy.expiresAt\", \"discountPolicy.stackingOrder\",\n \"discountPolicy.status\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_entitlement\",\n projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\", \"stripe_billing\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"entitlement.membershipId\", \"entitlement.kind\", \"entitlement.priceCents\", \"entitlement.currency\",\n \"entitlement.payerPersonId\", \"entitlement.purchasedAt\", \"entitlement.termEndsAt\",\n \"entitlement.renewsWithMembership\", \"entitlement.status\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_seat\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"pii\", memberAccess: \"read\",\n fields: [\n \"seat.membershipId\", \"seat.entitlementId\", \"seat.personId\", \"seat.recipientName\", \"seat.recipientEmail\",\n \"seat.role\", \"seat.status\", \"seat.acceptanceExpiresAt\", \"seat.acceptedAt\", \"seat.activatedAt\", \"seat.refundedAt\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_referral_ledger\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"referral.referrerPersonId\", \"referral.referredPersonId\", \"referral.qualifiedMembershipId\",\n \"referral.creditCents\", \"referral.status\", \"referral.appliedInvoiceId\", \"referral.carryForwardCents\",\n \"referral.adjustmentOf\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_investment_ledger\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"restricted\", memberAccess: \"read\",\n fields: [\n \"investment.personId\", \"investment.chapterId\", \"investment.season\", \"investment.purpose\",\n \"investment.targetCount\", \"investment.status\", \"investment.amountCents\", \"investment.closedAt\",\n \"investment.sourceReference\",\n ],\n }),\n ...rows({\n scope: \"provider\", writer: \"stripe\", projections: [\"stripe_billing\", \"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"commercial.charge\", \"commercial.invoice\", \"commercial.refund\", \"commercial.providerSubscription\",\n \"commercial.paymentMethod\",\n ],\n }),\n];\n\n/** Fields a member may change through self-service. */\nexport const MEMBER_SELF_EDITABLE_FIELDS = new Set(\n MEMBER_SYSTEM_AUTHORITY_MATRIX.filter((row) => row.memberAccess === \"edit\").map((row) => row.id),\n);\n/** Fields that may appear in a member self-service response. */\nexport const MEMBER_SELF_READABLE_FIELDS = new Set(\n MEMBER_SYSTEM_AUTHORITY_MATRIX.filter((row) => row.memberAccess !== \"none\").map((row) => row.id),\n);\n\n/** Serialize only the explicit member self-service allowlist. */\nexport function projectMemberSelf(record: Readonly<Record<string, unknown>>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(record).filter(([field]) => MEMBER_SELF_READABLE_FIELDS.has(field)));\n}\n\n/** Proposed field mutation with optimistic-revision evidence. */\nexport interface MemberSystemWriteIntent {\n field: string;\n actor: MemberSystemWriter | \"bnf\";\n expectedRevision: number;\n actualRevision: number;\n}\n/** Result of checking a proposed mutation against surface, writer, and revision rules. */\nexport type MemberSystemWriteDisposition =\n | \"apply\" | \"reject_bnf_surface\" | \"reject_unknown_field\" | \"reject_wrong_writer\" | \"reject_stale_revision\";\n\n/** Reject BNF, wrong-writer, unknown-field, and stale-revision mutations. */\nexport function classifyMemberSystemWrite(intent: MemberSystemWriteIntent): MemberSystemWriteDisposition {\n if (intent.actor === \"bnf\") return \"reject_bnf_surface\";\n const authority = MEMBER_SYSTEM_AUTHORITY_MATRIX.find((row) => row.id === intent.field);\n if (!authority) return \"reject_unknown_field\";\n if (authority.writer !== intent.actor) return \"reject_wrong_writer\";\n if (intent.expectedRevision !== intent.actualRevision) return \"reject_stale_revision\";\n return \"apply\";\n}\n\n/** Result of validating an authority matrix. */\nexport interface MemberAuthorityValidation { ok: boolean; errors: string[] }\n/** Validate uniqueness, self-service projection, and aggregate scope invariants. */\nexport function validateMemberSystemAuthority(\n matrix: readonly MemberFieldAuthority[] = MEMBER_SYSTEM_AUTHORITY_MATRIX,\n): MemberAuthorityValidation {\n const errors: string[] = [];\n const ids = new Set<string>();\n for (const row of matrix) {\n if (!row.id || !row.id.includes(\".\")) errors.push(`invalid field id \"${row.id}\"`);\n if (ids.has(row.id)) errors.push(`duplicate field authority \"${row.id}\"`);\n ids.add(row.id);\n if (row.memberAccess !== \"none\" && !row.projections.includes(\"member_self_service\")) {\n errors.push(`${row.id} grants member access without a member_self_service projection`);\n }\n if (row.id.startsWith(\"person.\") && (row.scope !== \"network\" || row.writer !== \"network_person\")) {\n errors.push(`${row.id} must be network_person authority`);\n }\n if (row.id.startsWith(\"journey.\") && (row.scope !== \"chapter\" || row.writer !== \"chapter_journey\")) {\n errors.push(`${row.id} must be chapter_journey authority`);\n }\n }\n return { ok: errors.length === 0, errors };\n}\n","/** Provider-free lifecycle contract for the network member system. */\nexport const MEMBER_SYSTEM_CONTRACT_VERSION = 1 as const;\nexport * from \"./member-system-authority\";\n\n/** Ordered chapter Journey stages from first identification through first deal. */\nexport const JOURNEY_STAGES = [\n \"identified\", \"researched\", \"outreach\", \"in_conversation\", \"invited_or_requested\",\n \"application_started\", \"applied\", \"paid_awaiting_conversation\", \"ready_to_book\", \"booked\",\n \"met\", \"approved\", \"onboarded\", \"active\", \"first_deal\",\n] as const;\n/** A chapter Journey stage. */\nexport type JourneyStage = typeof JOURNEY_STAGES[number];\n\n/** Terminal Journey outcomes; refunds remain commercial events. */\nexport const JOURNEY_ENDINGS = [\"passed\", \"declined\", \"withdrew\", \"lapsed\"] as const;\n/** A terminal chapter Journey outcome. */\nexport type JourneyEnding = typeof JOURNEY_ENDINGS[number];\n\n/** Required notice categories that may bypass discretionary contact suppression. */\nexport const REQUIRED_NOTICE_KINDS = [\n \"payment_receipt\", \"refund_confirmation\", \"security_alert\", \"legal_notice\",\n \"membership_status\", \"renewal_notice\", \"cancellation_confirmation\",\n] as const;\n/** A typed required notice allowed despite discretionary contact suppression. */\nexport type RequiredNoticeKind = typeof REQUIRED_NOTICE_KINDS[number];\n\n/** Availability inputs that distinguish the BNF UI from the odla data plane. */\nexport interface MemberSystemAvailabilityInput {\n odlaReachable: boolean;\n bnfFrontendReachable: boolean;\n}\n/** Capabilities allowed at the current BNF and odla availability state. */\nexport interface MemberSystemAvailability {\n bnfAdministration: boolean;\n chapterWorkflow: boolean;\n memberSelfService: boolean;\n newApplication: boolean;\n newCheckout: boolean;\n providerRenewalsMayContinue: true;\n reason?: \"odla_unavailable\" | \"bnf_frontend_unavailable\";\n}\n\n/** BNF is optional for chapter execution; odla is not. */\nexport function memberSystemAvailability(input: MemberSystemAvailabilityInput): MemberSystemAvailability {\n if (!input.odlaReachable) {\n return {\n bnfAdministration: false,\n chapterWorkflow: false,\n memberSelfService: false,\n newApplication: false,\n newCheckout: false,\n providerRenewalsMayContinue: true,\n reason: \"odla_unavailable\",\n };\n }\n return {\n bnfAdministration: input.bnfFrontendReachable,\n chapterWorkflow: true,\n memberSelfService: true,\n newApplication: true,\n newCheckout: true,\n providerRenewalsMayContinue: true,\n ...(!input.bnfFrontendReachable ? { reason: \"bnf_frontend_unavailable\" as const } : {}),\n };\n}\n\n/** Partition metadata supplied by a verified Stripe event. */\nexport interface MemberStripeIdentity {\n appId?: string;\n environment?: string;\n dataEnvironment?: string;\n runtime?: string;\n chapterId?: string;\n}\n/** Exact app, environment, runtime, and chapter partition expected by a consumer. */\nexport interface MemberStripeTarget {\n appId: string;\n environment: string;\n dataEnvironment: string;\n runtime: string;\n chapterId: string;\n}\n/** Safe handling of a verified Stripe event after partition checks. */\nexport type MemberStripeDisposition = \"apply\" | \"apply_legacy\" | \"ignore_sibling\" | \"quarantine_unmatched\";\n\n/** Partition verified Stripe events before any lookup or write. */\nexport function classifyMemberStripeEvent(\n identity: MemberStripeIdentity,\n target: MemberStripeTarget,\n hasProvenLegacyLocalLink: boolean,\n): MemberStripeDisposition {\n const keys = [\"appId\", \"environment\", \"dataEnvironment\", \"runtime\", \"chapterId\"] as const;\n const supplied = keys.filter((key) => identity[key] !== undefined);\n if (supplied.some((key) => identity[key] !== target[key])) return \"ignore_sibling\";\n if (supplied.length === keys.length) return \"apply\";\n return hasProvenLegacyLocalLink ? \"apply_legacy\" : \"quarantine_unmatched\";\n}\n\n/** Stable provider-event identity and content digest used for replay. */\nexport interface MemberSystemEventReceiptInput { id: string; digest: string }\n/** Accepted, duplicate, and colliding provider-event identifiers. */\nexport interface MemberSystemEventReplayPlan {\n accepted: string[];\n replayed: string[];\n collisions: string[];\n}\n/** Plan provider-event replay by stable identifier and digest. */\nexport function planMemberSystemEventReplay(\n events: readonly MemberSystemEventReceiptInput[],\n): MemberSystemEventReplayPlan {\n const seen = new Map<string, string>();\n const plan: MemberSystemEventReplayPlan = { accepted: [], replayed: [], collisions: [] };\n for (const event of events) {\n const digest = seen.get(event.id);\n if (digest === undefined) {\n seen.set(event.id, event.digest);\n plan.accepted.push(event.id);\n } else if (digest === event.digest) plan.replayed.push(event.id);\n else plan.collisions.push(event.id);\n }\n return plan;\n}\n\n/** Fail-closed and replay targets for restoring the member-system projection. */\nexport interface MemberSystemRecoveryObjectives {\n failClosedWithinMs: 0;\n replayProjectionWithinMinutes: number;\n providerEventsRemainReplayable: true;\n requireHumanReviewForCollision: true;\n}\n/** Accepted recovery objectives for the first rollout. */\nexport const MEMBER_SYSTEM_RECOVERY_OBJECTIVES: MemberSystemRecoveryObjectives = {\n failClosedWithinMs: 0,\n replayProjectionWithinMinutes: 15,\n providerEventsRemainReplayable: true,\n requireHumanReviewForCollision: true,\n};\n\n/** Candidate legacy or external row considered for migration. */\nexport interface MemberSystemMigrationRow {\n id: string;\n source: \"silver_salt_current\" | \"external_reimport\" | \"synthetic_fixture\";\n isRealPerson: boolean;\n provenance?: string;\n}\n/** Import, fixture-only, and rejected row identifiers. */\nexport interface MemberSystemMigrationPlan {\n importIds: string[];\n fixtureIds: string[];\n rejectedIds: string[];\n}\n\n/** Existing Silver & Salt rows never migrate; external real contacts need provenance. */\nexport function planMemberSystemMigration(rows: readonly MemberSystemMigrationRow[]): MemberSystemMigrationPlan {\n const plan: MemberSystemMigrationPlan = { importIds: [], fixtureIds: [], rejectedIds: [] };\n for (const row of rows) {\n if (row.source === \"synthetic_fixture\" && !row.isRealPerson) plan.fixtureIds.push(row.id);\n else if (row.source === \"external_reimport\" && row.isRealPerson && row.provenance) plan.importIds.push(row.id);\n else plan.rejectedIds.push(row.id);\n }\n return plan;\n}\n\n/** Non-destructive actions used to stop and reconcile the rollout. */\nexport interface MemberSystemRollbackPlan {\n stopNetworkWrites: true;\n disableBnfMemberMutations: true;\n keepChapterProductionReads: true;\n keepStripeBillingAuthority: true;\n deleteProviderObjects: false;\n reverseProviderPayments: false;\n reconciliationRequired: true;\n}\n/** Produce the non-destructive rollback contract. */\nexport function memberSystemRollbackPlan(): MemberSystemRollbackPlan {\n return {\n stopNetworkWrites: true,\n disableBnfMemberMutations: true,\n keepChapterProductionReads: true,\n keepStripeBillingAuthority: true,\n deleteProviderObjects: false,\n reverseProviderPayments: false,\n reconciliationRequired: true,\n };\n}\n\n/** Synthetic-only inventory. Counts describe current development rows, not members. */\nexport const SILVER_SALT_P0_FIXTURE = {\n sourceInventory: { applications: 36, meetings: 7, emails: 49, realPeople: 0 },\n application: { id: \"fixture_application_001\", personId: \"fixture_person_001\", migrates: false },\n crm: { recordId: \"fixture_crm_001\", email: \"fixture.member@example.invalid\", migrates: false },\n clerk: { userId: \"user_fixture_001\", verifiedEmail: \"fixture.member@example.invalid\", migrates: false },\n stripe: {\n customerId: \"cus_fixture_001\",\n subscriptionId: \"sub_fixture_001\",\n productId: \"prod_fixture_001\",\n priceId: \"price_fixture_001\",\n eventId: \"evt_fixture_001\",\n migrates: false,\n },\n unmatchedStripeEvent: { id: \"evt_fixture_unmatched\", disposition: \"quarantine_unmatched\" },\n legacyStripeEvent: { id: \"evt_fixture_legacy\", requiresProvenLocalLink: true },\n} as const;\n"],"mappings":";AAEA,SAAS,iBAAiB;;;ACI1B,SAAS,sBAAsB,0BAA0B;;;ACDzD,IAAM,wBAAwB;AAQ9B,eAAsB,2BAA2B,cAAuC;AACtF,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,GAAG,qBAAqB,GAAG,YAAY,EAAE;AAChF,QAAM,QAAQ,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC,EAAE,MAAM,GAAG,EAAE;AACtF,QAAM,CAAC,IAAK,MAAM,CAAC,IAAK,KAAQ;AAChC,QAAM,CAAC,IAAK,MAAM,CAAC,IAAK,KAAQ;AAChC,QAAM,MAAM,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAChF,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAA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A,IACT,SAAS;AAAA,IACT,UAAU;AAAA,EACZ;AAAA,EACA,sBAAsB,EAAE,IAAI,yBAAyB,aAAa,uBAAuB;AAAA,EACzF,mBAAmB,EAAE,IAAI,sBAAsB,yBAAyB,KAAK;AAC/E;","names":["index","allowed","id","paymentsReady","tiers","attr","attr","id","attr","id","string","number","json","id","attr","id","superAdmins","raw","id","text","order","DEFAULT_REQUIRED","DEFAULT_OPTIONAL","index","index","SLUG","id","SLUG","SLUG","SLUG","SECRET_NAME","SLUG","index","SLUG","id","facts","exceptions","keys","rows","rows","groups","id","projection","exceptions","text","encoder","selected","record","exceptions","key","index","rows","tiers","SLUG","allowed","tiers","raw","index","raw","id","SLUG","order","value","tiers","record","ID","MAX_MARKDOWN","MAX_TEXT","ROOT_KEYS","SOURCE_KEYS","TARGET_KEYS","record","unknownKeys","allowed","text","integer","raw","id","index","encoder","canonicalValue","record","text","emailLog","id","str","encoder","canonicalValue","record","ID","EMAIL_RE","index","raw","id","ID","record","text","index","raw","allowed","id","raw","record","createRecord","updateRecord","updateRecord","createRecord","index","verifyStripeSignature","id","body","id","record","meetings","events","rows","ROOT_KEYS","MAX_MARKDOWN","allowed","text","tiers","index","raw","SLUG","PRICE","ROOT_KEYS","TIER_KEYS","unknownKeys","allowed","text","raw","index","id","tiers","DIGEST","raw","MAX_BENEFITS","MAX_MARKDOWN","MAX_LABEL","index","text","id","rows","id","record","events","rows"]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/schema-account-policy.ts","../src/member.ts","../src/application-id.ts","../src/email-identity.ts","../src/schema-applications.ts","../src/schema-named-seats.ts","../src/schema-admission.ts","../src/schema-gifts.ts","../src/schema-stripe.ts","../src/schema-network-person.ts","../src/schema-network-commercial.ts","../src/schema-signup-control.ts","../src/schema.ts","../src/defaults.ts","../src/group.ts","../src/auth.ts","../src/pipeline.ts","../src/copy-defaults-admin.ts","../src/copy-defaults.ts","../src/copy-resolve.ts","../src/flow-fields.ts","../src/formation.ts","../src/network-contract.ts","../src/config-network.ts","../src/config-network-person.ts","../src/config-network-commercial.ts","../src/config-signup-control.ts","../src/config-member-content.ts","../src/config-builder-library.ts","../src/subscription-billing-terms.ts","../src/stripe-runtime.ts","../src/membership-invoice-evidence.ts","../src/network-commercial.ts","../src/network-commercial-reconcile.ts","../src/network-commercial-parity.ts","../src/leader.ts","../src/descriptor.ts","../src/tiers.ts","../src/membership-policy.ts","../src/membership-offer.ts","../src/membership-offer-store.ts","../src/membership-authority-handler.ts","../src/membership-checkout-binding.ts","../src/membership-authority-state.ts","../src/membership-payment-authority.ts","../src/membership-seat-activation.ts","../src/membership-approval-authority.ts","../src/payments-refund.ts","../src/membership-refund-authority.ts","../src/membership-provider-lifecycle.ts","../src/membership-renewal-authority.ts","../src/membership-access-authority.ts","../src/membership-seat-reservation.ts","../src/membership-seat-stripe.ts","../src/subscription-provider-contract.ts","../src/membership-seat-checkout.ts","../src/membership-seat-payment.ts","../src/membership-seat-renewal.ts","../src/membership-seat-recipient.ts","../src/membership-seat-refund-stripe.ts","../src/membership-seat-refund.ts","../src/membership-seat-provider-refund.ts","../src/membership-seat-offer.ts","../src/membership-seat-invitation.ts","../src/membership-chapter-effect.ts","../src/membership-authority-seat-actions.ts","../src/membership-authority-client.ts","../src/bounded-json-response.ts","../src/membership-authority-receipt.ts","../src/membership-seat-cancel.ts","../src/membership-effects.ts","../src/schema-membership-offers.ts","../src/schema-membership-authority.ts","../src/member-content-validation-helpers.ts","../src/member-content-validation.ts","../src/member-content.ts","../src/member-content-canonical.ts","../src/builder-library-validation.ts","../src/builder-library.ts","../src/builder-library-canonical.ts","../src/email.ts","../src/notify.ts","../src/notify-reconciliation.ts","../src/payments.ts","../src/admission-grants-contract.ts","../src/signup-control-canonical.ts","../src/admission-store-read.ts","../src/admission-grants.ts","../src/join-continuation.ts","../src/gift-offers.ts","../src/network.ts","../src/crm-person-projection.ts","../src/applicant-projection.ts","../src/crm-application-fields.ts","../src/crm-sync.ts","../src/crm-account-projection.ts","../src/series.ts","../src/payments-stripe.ts","../src/clerk-signup.ts","../src/clerk.ts","../src/clerk-roles.ts","../src/clerk-role-migration.ts","../src/clerk-integration.ts","../src/session.ts","../src/brand.ts","../src/reconcile.ts","../src/scheduling.ts","../src/tiers-store.ts","../src/signup-control-contract.ts","../src/membership-page.ts","../src/signup-control-validate.ts","../src/signup-control-theme.ts","../src/membership-markdown.ts","../src/promotion.ts","../src/member-system-authority.ts","../src/member-system-contract.ts","../src/membership-authority-storage.ts"],"sourcesContent":["// defineChapter — validate-at-import config, reusing @odla-ai/crm's defineCrm.\n// A bad config throws here (startup), never at request time.\nimport { defineCrm } from \"@odla-ai/crm\";\nimport type { CrmConfig, Crm } from \"@odla-ai/crm\";\nimport type {\n Chapter,\n ChapterConfig,\n ChapterMode,\n ResolvedOperations,\n} from \"./types\";\nimport { chapterDb } from \"./schema\";\nimport { defaultCrm } from \"./defaults\";\nimport { buildGroupSeed } from \"./group\";\nimport { resolveAuth } from \"./auth\";\nimport { resolvePipeline } from \"./pipeline\";\nimport { resolveApplication } from \"./member\";\nimport { resolveChapterCopy } from \"./copy\";\nimport { resolveLeaderFormation } from \"./formation\";\nimport { resolveNetwork } from \"./config-network\";\nimport { resolveNetworkPersonRegistry } from \"./config-network-person\";\nimport { resolveNetworkCommercialReadModel } from \"./config-network-commercial\";\nimport { resolveSignupControl } from \"./config-signup-control\";\nimport { resolveMemberContent } from \"./config-member-content\";\nimport { resolveBuilderLibrary } from \"./config-builder-library\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\nfunction isResolvedCrm(x: CrmConfig | Crm | undefined): x is Crm {\n return (\n !!x &&\n typeof x === \"object\" &&\n \"prepare\" in x &&\n typeof (x as { prepare?: unknown }).prepare === \"function\"\n );\n}\n\n/**\n * Validate a chapter/hub config and resolve its engine — the CRM, the chapter's\n * odla-db schema/rules, and the seed groups row. Throws at import on a bad\n * config (bad slug, wrong mode, missing chapter-mode prices/emails), never at\n * request time.\n */\nexport function defineChapter(config: ChapterConfig): Chapter {\n if (!config || typeof config !== \"object\") throw new Error(\"defineChapter: a config object is required\");\n const { id, name } = config;\n if (typeof id !== \"string\" || !SLUG.test(id)) {\n throw new Error(`defineChapter.id: must be a lowercase slug [a-z0-9-] (2-63 chars) — got ${JSON.stringify(id)}`);\n }\n if (typeof name !== \"string\" || name.trim() === \"\") throw new Error(\"defineChapter.name: a non-empty name is required\");\n\n const mode: ChapterMode = config.mode ?? \"chapter\";\n if (mode !== \"chapter\" && mode !== \"hub\") throw new Error(`defineChapter.mode: must be \"chapter\" or \"hub\" — got ${JSON.stringify(config.mode)}`);\n\n const crm: Crm = isResolvedCrm(config.crm) ? config.crm : defineCrm(config.crm ?? defaultCrm(mode));\n\n if (mode === \"chapter\") {\n if (!config.emails || typeof config.emails.notificationEmail !== \"string\" || config.emails.notificationEmail === \"\") {\n throw new Error(\"defineChapter.emails.notificationEmail: required in chapter mode\");\n }\n if (!config.prices || typeof config.prices.standardCents !== \"number\") {\n throw new Error(\"defineChapter.prices.standardCents: required in chapter mode\");\n }\n if (config.account === undefined) {\n throw new Error('defineChapter.account: required in chapter mode; choose \"none\", \"create\", or \"invite\" explicitly');\n }\n }\n\n const auth = resolveAuth(mode, config.auth);\n const pipeline = resolvePipeline(config.pipeline);\n const application = resolveApplication(config.application);\n const brand = { ...config.brand, wordmark: config.brand?.wordmark ?? name };\n const copy = resolveChapterCopy(config.copy);\n const network = resolveNetwork(config, crm);\n const networkPersonRegistry = resolveNetworkPersonRegistry(\n mode,\n config.networkPersonRegistry,\n network.targets.map((target) => target.id),\n );\n const networkCommercialReadModel = resolveNetworkCommercialReadModel(\n mode,\n config.networkCommercialReadModel,\n network.targets.map((target) => target.id),\n );\n const signupControl = resolveSignupControl(config.signupControl);\n const memberContent = resolveMemberContent(config.memberContent);\n const builderLibrary = resolveBuilderLibrary(mode, config.builderLibrary, network);\n const formation = resolveLeaderFormation(config.formation, crm);\n if (signupControl && mode !== \"chapter\") {\n throw new Error(\"defineChapter.signupControl: only chapter-mode followers can receive signup control\");\n }\n if (memberContent && mode !== \"chapter\") {\n throw new Error(\"defineChapter.memberContent: only chapter-mode sites can serve member content\");\n }\n const { schema, rules } = chapterDb(\n mode,\n auth,\n network.targets.length > 0,\n application,\n Boolean(signupControl),\n Boolean(memberContent),\n Boolean(builderLibrary),\n network.targets.some((target) => target.admissionGrants),\n Boolean(networkPersonRegistry),\n Boolean(networkCommercialReadModel),\n );\n const services = config.services ?? [\"db\", \"calendar\", \"o11y\"];\n // Hub mode has no public application flow, so its inert resolved value remains\n // `none`. Chapter mode was required to make this decision above.\n const account = config.account ?? \"none\";\n if (account !== \"invite\" && account !== \"create\" && account !== \"none\") {\n throw new Error(`defineChapter.account: must be \"invite\", \"create\", or \"none\" — got \"${String(account)}\"`);\n }\n // crmFields not declared on the CRM person type are dropped by the projection at\n // runtime (the base person still lands), so a typo is invisible. Both the\n // resolved crmFields and the resolved crm are in hand here — cross-check the\n // names and fail at resolve time instead.\n if (application.crmFields.length > 0) {\n let personFields: string[] | null = null;\n try {\n personFields = Object.keys(crm.type(\"person\").fields ?? {});\n } catch {\n // No introspectable \"person\" type — leave it to the projection.\n }\n const unknown = personFields ? application.crmFields.filter((f) => !personFields.includes(f)) : [];\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.application.crmFields: ${unknown.map((f) => `\"${f}\"`).join(\", \")} not declared on the CRM \"person\" type ` +\n `(declared: ${personFields?.join(\", \")}). An undeclared field is silently dropped from the CRM projection — ` +\n `add it to your crm config's person fields, or remove it from crmFields.`,\n );\n }\n }\n const adminNotification = config.sends?.adminNotification ?? \"submit\";\n if (adminNotification !== \"submit\" && adminNotification !== \"payment\" && adminNotification !== \"never\") {\n throw new Error(\n `defineChapter.sends.adminNotification: must be \"submit\", \"payment\", or \"never\" — got \"${String(adminNotification)}\"`,\n );\n }\n const sends = { adminNotification };\n\n // Admin-operation policy. The escalation RULES are not here — they are\n // package-enforced in canChangeRole (gated on auth.superAdmins), so a site\n // cannot weaken them. These two are genuine per-site decisions.\n const onApproveCfg = config.operations?.onApprove ?? {};\n // Default promotion target: the rung directly below admin, so a custom ladder\n // gets the right answer instead of a hardcoded \"member\".\n const belowAdmin = auth.ladder[auth.ladder.length - 2] ?? auth.adminRole;\n const promoteTo = onApproveCfg.promoteTo === undefined ? belowAdmin : onApproveCfg.promoteTo;\n if (promoteTo !== false && !auth.ladder.includes(promoteTo)) {\n throw new Error(\n `defineChapter.operations.onApprove.promoteTo: \"${String(promoteTo)}\" is not in the auth ladder (${auth.ladder.join(\", \")})`,\n );\n }\n const refundCfg = config.operations?.refund ?? {};\n if (refundCfg.allowedFrom !== undefined) {\n const unknown = refundCfg.allowedFrom.filter((s) => !pipeline.stages.includes(s));\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.operations.refund.allowedFrom: ${unknown.map((s) => `\"${s}\"`).join(\", \")} not in the pipeline (${pipeline.stages.join(\", \")})`,\n );\n }\n }\n const operations: ResolvedOperations = {\n onApprove: { promoteTo, send: onApproveCfg.send === undefined ? \"onboardingInvite\" : onApproveCfg.send },\n refund: { allowedFrom: refundCfg.allowedFrom ?? null, cancelSubscription: refundCfg.cancelSubscription ?? true },\n };\n\n const chapter: Chapter = {\n config,\n id,\n name,\n mode,\n brand,\n copy,\n network,\n signupControl,\n memberContent,\n builderLibrary,\n networkPersonRegistry,\n networkCommercialReadModel,\n formation,\n crm,\n auth,\n pipeline,\n application,\n schema,\n rules,\n services,\n account,\n sends,\n operations,\n groupSeed: () => (mode === \"chapter\" ? buildGroupSeed(config) : null),\n };\n if (config.url !== undefined) chapter.url = config.url;\n return chapter;\n}\n","import type { Entity } from \"./types\";\n\n/** Provisioned Chapter role policy consumed by Studio's account type editor. */\nexport const chapterAccountPolicy: Entity = { attrs: {\n id: { type: \"string\", unique: true, indexed: true, optional: false },\n metadata: { type: \"string\", unique: false, indexed: false, optional: false },\n roles: { type: \"json\", unique: false, indexed: false, optional: false },\n} };\n","// The public member surface logic: the join config a site's join page reads (B1)\n// and the idempotent application submit (B2 validation + B3 exactly-once). Both\n// take the structural ChapterDb, so they're tested against an in-memory fake and\n// carry no runtime @odla-ai/db import. The worker builds the real db client, does\n// Clerk verification, enforces the body cap, and mounts these on chapter routes.\nimport type { Chapter, ChapterApplication, ChapterDb, ResolvedApplication } from \"./types\";\nimport { assertFieldCondition, resolveFieldStates } from \"@odla-ai/crm\";\nimport type { FieldConditions } from \"@odla-ai/crm\";\nimport { applicationIdForSubmission } from \"./application-id\";\nimport type { JoinConfigTier } from \"./tiers\";\nimport type { AdmissionGrantRow } from \"./admission-grants\";\nimport { normalizeChapterEmail } from \"./email-identity\";\n\n// The reference join form. `focus` (a json field) is always accepted.\nconst DEFAULT_REQUIRED = [\"firstName\", \"lastName\", \"email\", \"referral\", \"whoYouAre\", \"message\"];\nconst DEFAULT_OPTIONAL = [\"referralName\", \"linkedin\", \"phone\", \"state\"];\nconst SCHEMA_FIELD = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\n/** Apply defaults + validate the application config. Throws at import on bad shape. */\nexport function resolveApplication(a: ChapterApplication | undefined): ResolvedApplication {\n const required = a?.required ?? DEFAULT_REQUIRED;\n const optional = a?.optional ?? DEFAULT_OPTIONAL;\n for (const [name, arr] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(arr) || !arr.every((f) => typeof f === \"string\" && f !== \"\")) {\n throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);\n }\n const unsafe = arr.find((field) => !SCHEMA_FIELD.test(field));\n if (unsafe) {\n throw new Error(`defineChapter.application.${name}: field \"${unsafe}\" must match ${SCHEMA_FIELD.source}`);\n }\n }\n const duplicate = [...required, ...optional].find((field, index, fields) => fields.indexOf(field) !== index);\n if (duplicate) {\n throw new Error(`defineChapter.application: duplicate field \"${duplicate}\" across required/optional lists`);\n }\n if (a?.profileFields !== undefined && (!Array.isArray(a.profileFields) || !a.profileFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.profileFields: must be an array of field-name strings\");\n }\n if (a?.crmFields !== undefined && (!Array.isArray(a.crmFields) || !a.crmFields.every((f) => typeof f === \"string\" && f !== \"\"))) {\n throw new Error(\"defineChapter.application.crmFields: must be an array of field-name strings\");\n }\n // Conditions are checked when the chapter is defined, so a typo fails at\n // startup rather than quietly misbehaving on a live join page. Fields that\n // fail open at runtime are the deliberate second line of defence, not this.\n const conditions = a?.conditions ?? {};\n for (const [field, declared] of Object.entries(conditions)) {\n for (const key of [\"visibleWhen\", \"requiredWhen\"] as const) {\n const expression = declared?.[key];\n if (expression === undefined) continue;\n if (typeof expression !== \"string\" || !expression.trim()) {\n throw new Error(`defineChapter.application.conditions.${field}.${key}: must be a non-empty CEL condition`);\n }\n assertFieldCondition(expression, `defineChapter.application.conditions.${field}.${key}`);\n }\n }\n return {\n required,\n optional,\n conditions,\n maxLen: a?.maxLen ?? {},\n defaultMaxLen: a?.defaultMaxLen ?? 2000,\n bodyCap: a?.bodyCap ?? 32768,\n requireDisclaimerAck: a?.requireDisclaimerAck ?? true,\n profileFields: a?.profileFields ?? [],\n crmFields: a?.crmFields ?? [],\n maxArrayLen: a?.maxArrayLen ?? 100,\n validateEmail: a?.validateEmail ?? true,\n };\n}\n\n// A permissive email shape check: one @, a dot-bearing domain, no whitespace.\n// Deliberately not RFC-exhaustive — the goal is to reject \"notanemail\" before it\n// fails the downstream Clerk create, not to adjudicate exotic-but-valid addresses.\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\n/** Whether a string looks like an email address (see {@link EMAIL_RE}). Exported\n * so a site building its own submit path applies the same rule chapter does. */\nexport function isValidEmail(value: unknown): boolean {\n return typeof value === \"string\" && EMAIL_RE.test(value);\n}\n\n/** Bound an array-valued field: drop non-primitive elements and cap the length,\n * so a client cannot post an unbounded array. Non-arrays pass through unchanged. */\nexport function clampArray(value: unknown, max: number): unknown {\n if (!Array.isArray(value)) return value;\n return value.filter((x) => typeof x === \"string\" || typeof x === \"number\" || typeof x === \"boolean\").slice(0, max);\n}\n\n/** Whether a submit body carries a genuine disclaimer acknowledgement. Accepts\n * the boolean an API client sends and the string a plain HTML form posts. */\nexport function hasDisclaimerAck(fields: Record<string, unknown>): boolean {\n return fields.disclaimerAck === true || fields.disclaimerAck === \"true\";\n}\n\n// Clerk carries these as first-class user fields, so repeating them in\n// public_metadata would be duplicated state that can drift.\nconst IDENTITY_FIELDS = new Set([\"email\", \"firstName\", \"lastName\"]);\n\n/**\n * The applicant profile written to the Clerk account's backend-only\n * `private_metadata.profile`. Projects each configured non-identity field, plus\n * `focus` (clamped), but ONLY those in `application.profileFields`. Derived\n * from config, so a site's own field names project without this package knowing\n * them. Pure; returns `undefined` when there is nothing to write.\n */\nexport function applicantProfile(\n chapter: Chapter,\n fields: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const app = chapter.application;\n const allowed = (f: string): boolean => app.profileFields.includes(f);\n const profile: Record<string, unknown> = {};\n for (const f of [...app.required, ...app.optional]) {\n if (IDENTITY_FIELDS.has(f) || !allowed(f)) continue;\n const v = fields[f];\n if (typeof v === \"string\" && v.trim() !== \"\") profile[f] = v.trim();\n }\n if (fields.focus !== undefined && allowed(\"focus\")) profile.focus = clampArray(fields.focus, app.maxArrayLen);\n return Object.keys(profile).length > 0 ? profile : undefined;\n}\n\n/** A validated submission, or a validation/duplicate-email error the route returns.\n * `disclaimerAckAt` reports what THIS request recorded — a number when consent\n * was stamped, `null` when none was supplied. It is always present so a missing\n * consent record is visible in the response rather than silently absent from a\n * row nobody reads until an audit. */\nexport type SubmitResult =\n | { ok: true; id: string; duplicate: boolean; status: string; disclaimerAckAt: number | null }\n | { ok: false; error: string; code?: string; status?: number };\n\n/**\n * Submit a membership application (B2 + B3). Validates the configured required\n * fields + max lengths, writes the `applications` row at the pipeline's initial\n * status, and — when the client supplies a `submissionId` — stamps it as the\n * transaction's mutationId (`join:${submissionId}`) so a double-tap can never\n * create two applications. The application id is derived from that same stable\n * input, so the duplicate response returns the first request's canonical id\n * rather than a fresh, nonexistent one. Idempotency is package-enforced.\n * A unique normalized signup email key prevents concurrent submissions with\n * different ids from creating two applications; a conflict returns status 409.\n * Apply the current Chapter schema before deploying this writer.\n * `now`/`newId` are injected (deterministic in tests).\n */\nexport async function submitApplication(\n db: ChapterDb,\n chapter: Chapter,\n fields: Record<string, unknown>,\n opts: {\n submissionId?: string;\n groupId?: string;\n now: number;\n newId: () => string;\n /** Tier ids this chapter offers. A posted `tierId` outside it is refused;\n * omit to accept any (pre-tier callers). */\n tierIds?: readonly string[];\n /** Effective one-use waiver selected by the server, never by the client. */\n admissionGrant?: AdmissionGrantRow;\n /** Server-validated gift offer selected from active signed control. */\n giftOfferId?: string;\n /** Server-selected deployment partition, including free applications. */\n runtime?: string;\n },\n): Promise<SubmitResult> {\n const app = chapter.application;\n // Requiredness is resolved against the answers, not read off a static list,\n // so a conditionally-hidden field is not demanded and a conditionally-\n // required one cannot be skipped by posting straight to this route. The\n // renderer calls the same resolver, so the form and the validator cannot\n // disagree. With no conditions declared this is exactly the old static loop.\n const fieldStates = resolveFieldStates(app.conditions ?? {}, fields, app.required);\n for (const [f, state] of Object.entries(fieldStates)) {\n if (!state.required) continue;\n const v = fields[f];\n if (typeof v !== \"string\" || v.trim() === \"\") return { ok: false, error: `${f} is required` };\n }\n for (const f of [...app.required, ...app.optional]) {\n const v = fields[f];\n const cap = app.maxLen[f] ?? app.defaultMaxLen;\n if (typeof v === \"string\" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };\n }\n // A malformed email can only fail the downstream Clerk create; reject it here\n // as a clean 400. A valid application always has a valid email, so no genuine\n // submission is newly rejected.\n if (app.validateEmail && typeof fields.email === \"string\" && !isValidEmail(fields.email.trim())) {\n return { ok: false, error: \"email must be a valid email address\" };\n }\n\n const acked = hasDisclaimerAck(fields);\n if (app.requireDisclaimerAck && !acked) {\n return { ok: false, error: \"disclaimerAck is required\" };\n }\n\n const id = opts.submissionId\n ? await applicationIdForSubmission(opts.submissionId)\n : opts.newId();\n const row: Record<string, unknown> = { id, status: chapter.pipeline.initial, createdAt: opts.now };\n for (const f of [...app.required, ...app.optional]) {\n // A field the conditions hid was never asked, so a value for it is stale\n // or forged. Storing it would answer a question on the applicant's behalf.\n if (fieldStates[f]?.visible === false) continue;\n if (typeof fields[f] === \"string\") row[f] = (fields[f] as string).trim();\n }\n if (fields.focus !== undefined) row.focus = clampArray(fields.focus, app.maxArrayLen);\n if (opts.groupId) row.groupId = opts.groupId;\n if (opts.runtime) row.stripeRuntime = opts.runtime;\n if (chapter.account !== \"none\") row.clerkAccountPending = true;\n if (typeof fields.email === \"string\" && isValidEmail(fields.email.trim())) {\n row.emailNormalized = normalizeChapterEmail(fields.email);\n row.signupEmailKey = row.emailNormalized;\n }\n if (opts.admissionGrant?.decision === \"waive_interview\") {\n row.admissionGrantId = opts.admissionGrant.id;\n row.admissionSource = opts.admissionGrant.sourceScope;\n row.interviewWaivedAt = opts.now;\n }\n if (opts.giftOfferId) row.giftOfferId = opts.giftOfferId;\n // A tier decides what this member is charged, so the posted id is checked\n // against what the chapter actually offers rather than trusted. An unknown\n // id is refused instead of silently dropped: dropping it would bill the\n // applicant whatever the fallback tier costs.\n if (typeof fields.tierId === \"string\" && fields.tierId) {\n if (opts.tierIds && !opts.tierIds.includes(fields.tierId)) {\n return { ok: false, error: \"tierId is not an offered tier\" };\n }\n row.tierId = fields.tierId;\n }\n // The disclaimer acknowledgement is a compliance record, so it is stamped from\n // the server clock on a genuine ack and left absent otherwise — a client-supplied\n // timestamp would be forgeable, and a row that always carries one would record\n // consent nobody gave.\n if (acked) row.disclaimerAckAt = opts.now;\n\n const ops: Parameters<ChapterDb[\"transact\"]>[0] = [\n { t: \"update\", ns: \"applications\", id, attrs: row },\n ];\n if (opts.admissionGrant?.decision === \"waive_interview\") {\n ops.push({ t: \"update\", ns: \"admissionGrants\", id: opts.admissionGrant.id, attrs: {\n consumedAt: opts.now,\n consumedApplicationId: id,\n } });\n }\n try {\n const { duplicate } = await db.transact(\n ops,\n opts.submissionId ? { mutationId: `join:${opts.submissionId}` } : undefined,\n );\n return { ok: true, id, duplicate, status: chapter.pipeline.initial, disclaimerAckAt: acked ? opts.now : null };\n } catch (error) {\n if ((error as { code?: string }).code === \"unique_violation\") return {\n ok: false, code: \"account_already_exists\", status: 409,\n error: \"An account or application already exists for this email. Please sign in to continue.\",\n };\n throw error;\n }\n}\n\n/** The `groups`-row fields the join config exposes. */\nexport interface JoinConfigGroup {\n id: string;\n name: string;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n disclaimerText?: string;\n refundPolicyText?: string;\n merchantDisclosureText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n}\n\n/**\n * The public join config (B1) a site's join page reads: copy + prices from the\n * group row plus `paymentsReady`. When payments aren't wired the join flow drops\n * the payment step (C2) — the worker computes `paymentsReady` from the group's\n * Stripe keys + vault secret. Pure.\n *\n * `tiers` carries the offerable membership tiers. It is additive: the legacy\n * `standardPriceCents`/`foundingDiscountCents` fields still describe the first\n * tier, so a join page written before tiers keeps rendering unchanged. A free\n * tier appears here with `free: true` even when Stripe is unconfigured, because\n * nothing needs charging for it.\n */\nexport function joinConfig(\n group: JoinConfigGroup,\n paymentsReady: boolean,\n tiers: readonly JoinConfigTier[] = [],\n conditions: Readonly<Record<string, FieldConditions>> = {},\n): Record<string, unknown> {\n return {\n id: group.id,\n name: group.name,\n standardPriceCents: group.standardPriceCents ?? 0,\n foundingDiscountCents: group.foundingDiscountCents ?? 0,\n currency: group.currency ?? \"usd\",\n interval: group.interval ?? \"year\",\n tiers: [...tiers],\n // The browser evaluates the same conditions the server enforces.\n conditions,\n disclaimerText: group.disclaimerText ?? \"\",\n refundPolicyText: group.refundPolicyText ?? \"\",\n merchantDisclosureText: group.merchantDisclosureText ?? \"\",\n trustCopy: group.trustCopy ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n paymentsReady,\n };\n}\n","// Application creates use a caller-stable submission id as their database\n// mutation id. The entity id must be derived from that same stable input: if a\n// committed request is retried, the database correctly skips the new ops and\n// Chapter must still return the id of the row written by the first request.\n\nconst APPLICATION_ID_DOMAIN = \"odla-ai/chapter/application/v1:\";\n\n/**\n * Derive the UUID-shaped capability for an idempotent application submission.\n * SHA-256 prevents a caller from choosing a submission id that overwrites a\n * known application id; UUIDv8 bits preserve the identifier shape consumers\n * already expect.\n */\nexport async function applicationIdForSubmission(submissionId: string): Promise<string> {\n const input = new TextEncoder().encode(`${APPLICATION_ID_DOMAIN}${submissionId}`);\n const bytes = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", input)).slice(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Normalize an email address for Chapter identity lookups.\n *\n * Chapter treats the address literally: surrounding whitespace and ASCII case\n * are insignificant, but the local part is otherwise preserved. In\n * particular, provider-specific aliases are never collapsed, so\n * `foo+bar@gmail.com` and `foo@gmail.com` remain distinct applicants,\n * admission decisions, purchasers, and beneficiaries.\n */\nexport function normalizeChapterEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n","import type { Attr, AttrType, Entity, ResolvedApplication } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\n\nconst APPLICATION_INPUT_FIELDS = new Set([\n \"firstName\", \"lastName\", \"email\", \"referral\", \"referralName\", \"whoYouAre\",\n \"focus\", \"linkedin\", \"message\", \"phone\", \"state\",\n]);\n\nconst applicationAttrs: Record<string, Attr> = {\n id: attr(\"string\", { unique: true, indexed: true }), firstName: attr(\"string\"), lastName: attr(\"string\"),\n email: attr(\"string\", { indexed: true }), referral: attr(\"string\"), referralName: attr(\"string\", { optional: true }),\n whoYouAre: attr(\"string\"), focus: attr(\"json\"), linkedin: attr(\"string\", { optional: true }), message: attr(\"string\"),\n status: attr(\"string\", { indexed: true }), createdAt: attr(\"number\", { indexed: true }),\n meetingAt: attr(\"number\", { indexed: true, optional: true }), meetingLink: attr(\"string\", { optional: true }),\n clerkUserId: attr(\"string\", { indexed: true, optional: true }), clerkPrivateMetadataSyncedAt: attr(\"number\", { optional: true }),\n approvalEffectsPending: attr(\"boolean\", { indexed: true, optional: true }), approvalEffectsOrigin: attr(\"string\", { optional: true }),\n approvalEffectsLastAttemptAt: attr(\"number\", { indexed: true, optional: true }),\n phone: attr(\"string\", { optional: true }), state: attr(\"string\", { optional: true }),\n groupId: attr(\"string\", { indexed: true, optional: true }), tierId: attr(\"string\", { indexed: true, optional: true }),\n stripeCustomerId: attr(\"string\", { indexed: true, optional: true }),\n stripeSubscriptionId: attr(\"string\", { indexed: true, optional: true }),\n stripeRuntime: attr(\"string\", { indexed: true, optional: true }), renewalAt: attr(\"number\", { optional: true }),\n disclaimerAckAt: attr(\"number\", { optional: true }), refundPolicyAckAt: attr(\"number\", { optional: true }),\n prepEmailSentAt: attr(\"number\", { optional: true }), canceled: attr(\"boolean\", { optional: true }),\n signupEmailKey: attr(\"string\", { unique: true, indexed: true, optional: true }),\n clerkInvitationSentAt: attr(\"number\", { optional: true }),\n clerkAccountPending: attr(\"boolean\", { optional: true }),\n emailNormalized: attr(\"string\", { indexed: true, optional: true }),\n admissionGrantId: attr(\"string\", { unique: true, indexed: true, optional: true }),\n admissionSource: attr(\"string\", { indexed: true, optional: true }), interviewWaivedAt: attr(\"number\", { optional: true }),\n giftOfferId: attr(\"string\", { optional: true, indexed: true }),\n giftIntentId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n giftClaimId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n giftOrderId: attr(\"string\", { optional: true, indexed: true }), giftPaidAt: attr(\"number\", { optional: true, indexed: true }),\n giftRevokedAt: attr(\"number\", { optional: true, indexed: true }),\n giftCheckoutStartedAt: attr(\"number\", { optional: true, indexed: true }),\n namedSeatId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n namedSeatPrimaryApplicationId: attr(\"string\", { optional: true }),\n namedSeatClaimPending: attr(\"boolean\", { optional: true, indexed: true }),\n namedSeatAcceptedAt: attr(\"number\", { optional: true }),\n};\n\n/** Resolve the site-configurable application inputs without exposing operational fields. */\nexport function applicationsFor(application: ResolvedApplication): Entity {\n const attrs: Record<string, Attr> = {};\n for (const [name, spec] of Object.entries(applicationAttrs)) {\n attrs[name] = { ...spec, optional: APPLICATION_INPUT_FIELDS.has(name) ? true : spec.optional };\n }\n const apply = (field: string, optional: boolean): void => {\n const existing = Object.hasOwn(attrs, field) ? attrs[field] : undefined;\n if (existing && !APPLICATION_INPUT_FIELDS.has(field)) throw new Error(`defineChapter.application: field \"${field}\" is reserved by the applications schema`);\n if (existing && existing.type !== \"string\") throw new Error(`defineChapter.application: field \"${field}\" is not a configurable string field`);\n Object.defineProperty(attrs, field, {\n value: existing ? { ...existing, optional } : attr(\"string\", { optional }),\n enumerable: true, configurable: true, writable: true,\n });\n };\n for (const field of application.required) apply(field, false);\n for (const field of application.optional) apply(field, true);\n return { attrs };\n}\n","import type { Attr, AttrType, Entity } from \"./types\";\nconst attr = (type: AttrType, indexed = false): Attr => ({ type, indexed, optional: false, unique: false });\n/** Chapter-local proof of the purchaser's named-seat consent, not membership or payment authority. */\nexport const namedSeatConsentsEntity: Entity = { attrs: {\n id: { ...attr(\"string\", true), unique: true }, applicationId: attr(\"string\", true), chapterId: attr(\"string\", true), runtime: attr(\"string\", true),\n userId: attr(\"string\", true), quoteDigest: attr(\"string\"), recipientName: attr(\"string\"), recipientEmail: attr(\"string\"),\n refundPolicyText: attr(\"string\"), merchantDisclosureText: attr(\"string\"), acceptedAt: attr(\"number\"),\n} };\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n/** Operational Parent and Chapter admission decisions, never publicly readable. */\nexport const admissionGrantsEntity: Entity = {\n attrs: {\n id: id(),\n sourceGrantId: attr(\"string\", { indexed: true }),\n sourceScope: attr(\"string\", { indexed: true }),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n email: attr(\"string\"),\n emailNormalized: attr(\"string\", { indexed: true }),\n decision: attr(\"string\", { indexed: true }),\n note: attr(\"string\", { optional: true }),\n active: attr(\"boolean\", { indexed: true }),\n sourceRevision: attr(\"number\", { optional: true, indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n createdBy: attr(\"string\", { optional: true, indexed: true }),\n updatedAt: attr(\"number\", { optional: true, indexed: true }),\n updatedBy: attr(\"string\", { optional: true, indexed: true }),\n expiresAt: attr(\"number\", { optional: true, indexed: true }),\n revokedAt: attr(\"number\", { optional: true, indexed: true }),\n revokedBy: attr(\"string\", { optional: true, indexed: true }),\n consumedAt: attr(\"number\", { optional: true, indexed: true }),\n consumedApplicationId: attr(\"string\", { optional: true, indexed: true }),\n },\n};\n\n/** Immutable acknowledgements for signed Parent admission documents. */\nexport const admissionGrantRevisionsEntity: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** Leader-owned assignment of an existing CRM person to one Chapter target. */\nexport const leaderAdmissionAssignmentsEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n personId: attr(\"string\", { indexed: true }),\n grantId: attr(\"string\", { indexed: true }),\n decision: attr(\"string\", { indexed: true }),\n note: attr(\"string\", { optional: true }),\n expiresAt: attr(\"number\", { optional: true, indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n lastMutationId: attr(\"string\", { indexed: true }),\n lastRequestDigest: attr(\"string\"),\n createdAt: attr(\"number\", { indexed: true }),\n createdBy: attr(\"string\", { indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { indexed: true }),\n },\n};\n\n/** Durable desired document plus its latest delivery/acknowledgement state. */\nexport const leaderAdmissionDeliveriesEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n envelope: attr(\"json\"),\n status: attr(\"string\", { indexed: true }),\n attempts: attr(\"number\", { indexed: true }),\n lastAttemptAt: attr(\"number\", { optional: true, indexed: true }),\n lastError: attr(\"string\", { optional: true }),\n acknowledgedAt: attr(\"number\", { optional: true, indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** Stable mutation receipts prevent an old retry from becoming a new revision\n * after later assignments changed the target's desired set. */\nexport const leaderAdmissionMutationsEntity: Entity = {\n attrs: {\n id: id(),\n targetId: attr(\"string\", { indexed: true }),\n personId: attr(\"string\", { indexed: true }),\n requestDigest: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n/** Pre-payment gift checkout state. It holds only a code hash, never plaintext. */\nexport const giftPurchaseIntentsEntity: Entity = { attrs: {\n id: id(), chapterId: attr(\"string\", { indexed: true }), environment: attr(\"string\", { indexed: true }),\n runtime: attr(\"string\", { optional: true, indexed: true }),\n purchaserType: attr(\"string\", { indexed: true }), purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }),\n purchaserUserId: attr(\"string\", { optional: true, indexed: true }), purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n offerId: attr(\"string\", { indexed: true }), offerSnapshot: attr(\"json\"), status: attr(\"string\", { indexed: true }),\n codeHash: attr(\"string\", { indexed: true }), codeVersion: attr(\"number\"), codeIssuedAt: attr(\"number\"),\n providerObjectId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n providerCustomerId: attr(\"string\", { optional: true, indexed: true }), checkoutStartedAt: attr(\"number\", { optional: true }),\n paidAt: attr(\"number\", { optional: true, indexed: true }), claimId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n createdAt: attr(\"number\", { indexed: true }), updatedAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Immutable provider-authorized gift purchase evidence. */\nexport const giftOrdersEntity: Entity = { attrs: {\n id: id(), intentId: attr(\"string\", { unique: true, indexed: true }), chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }), offerId: attr(\"string\", { indexed: true }), offerSnapshot: attr(\"json\"),\n purchaserType: attr(\"string\", { indexed: true }), purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }),\n purchaserUserId: attr(\"string\", { optional: true, indexed: true }), purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n providerEventId: attr(\"string\", { unique: true, indexed: true }), providerObjectId: attr(\"string\", { indexed: true }),\n amountCents: attr(\"number\"), currency: attr(\"string\"), billingMode: attr(\"string\"), createdAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Single-use beneficiary bearer claim. Buyer list routes never return its hash. */\nexport const giftClaimsEntity: Entity = { attrs: {\n id: id(), orderId: attr(\"string\", { unique: true, indexed: true }), intentId: attr(\"string\", { unique: true, indexed: true }),\n chapterId: attr(\"string\", { indexed: true }), offerId: attr(\"string\", { indexed: true }), target: attr(\"json\"),\n purchaserApplicationId: attr(\"string\", { optional: true, indexed: true }), purchaserUserId: attr(\"string\", { optional: true, indexed: true }),\n purchaserEmailNormalized: attr(\"string\", { indexed: true }), codeHash: attr(\"string\", { unique: true, indexed: true }),\n codeVersion: attr(\"number\"), rotationCount: attr(\"number\"), codeIssuedAt: attr(\"number\"), codeExpiresAt: attr(\"number\", { indexed: true }),\n attemptCount: attr(\"number\"), attemptWindowStartedAt: attr(\"number\"), status: attr(\"string\", { indexed: true }),\n redeemedAt: attr(\"number\", { optional: true, indexed: true }), beneficiaryEmailNormalized: attr(\"string\", { optional: true, indexed: true }),\n beneficiaryUserId: attr(\"string\", { optional: true, indexed: true }), applicationId: attr(\"string\", { optional: true, unique: true, indexed: true }),\n entitlementId: attr(\"string\", { optional: true, unique: true, indexed: true }), rotatedAt: attr(\"number\", { optional: true }),\n revokedAt: attr(\"number\", { optional: true, indexed: true }), revokedReason: attr(\"string\", { optional: true }), createdAt: attr(\"number\", { indexed: true }),\n} };\n\n/** Non-membership beneficiary entitlements created by redeemed gift claims. */\nexport const giftEntitlementsEntity: Entity = { attrs: {\n id: id(), claimId: attr(\"string\", { unique: true, indexed: true }), orderId: attr(\"string\", { indexed: true }),\n chapterId: attr(\"string\", { indexed: true }), entitlementKey: attr(\"string\", { indexed: true }),\n beneficiaryEmailNormalized: attr(\"string\", { indexed: true }), beneficiaryUserId: attr(\"string\", { optional: true, indexed: true }),\n active: attr(\"boolean\", { indexed: true }), createdAt: attr(\"number\", { indexed: true }), revokedAt: attr(\"number\", { optional: true }),\n} };\n\n/** Coarse requester buckets that bound public redemption attempts. */\nexport const giftRedemptionAttemptsEntity: Entity = { attrs: {\n id: id(), chapterId: attr(\"string\", { indexed: true }), bucket: attr(\"string\", { indexed: true }),\n attemptCount: attr(\"number\"), windowStartedAt: attr(\"number\", { indexed: true }), updatedAt: attr(\"number\"),\n} };\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr => ({\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\n\n// Content-free Stripe ingress evidence. Sibling endpoints never write it.\nexport const stripeEventReceiptsEntity: Entity = {\n attrs: {\n id: attr(\"string\", { unique: true, indexed: true }),\n eventId: attr(\"string\", { unique: true, indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n disposition: attr(\"string\", { indexed: true }),\n kind: attr(\"string\", { indexed: true }),\n matched: attr(\"boolean\", { indexed: true }),\n appId: attr(\"string\", { indexed: true, optional: true }),\n environment: attr(\"string\", { indexed: true, optional: true }),\n dataEnvironment: attr(\"string\", { indexed: true, optional: true }),\n runtime: attr(\"string\", { indexed: true, optional: true }),\n chapterId: attr(\"string\", { indexed: true, optional: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Durable, non-secret checkout intent written before the Chapter calls Stripe.\n// A retry must match this exact commercial/identity snapshot; provider ids are\n// attached only when the checkout and application row can be committed together.\nexport const subscriptionCheckoutIntentsEntity: Entity = {\n attrs: {\n id: attr(\"string\", { unique: true, indexed: true }),\n applicationId: attr(\"string\", { unique: true, indexed: true }),\n appId: attr(\"string\", { indexed: true }),\n chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n runtime: attr(\"string\", { indexed: true, optional: true }),\n groupId: attr(\"string\", { indexed: true }),\n tierId: attr(\"string\", { indexed: true }),\n priceId: attr(\"string\", { indexed: true }),\n priceCents: attr(\"number\"),\n currency: attr(\"string\", { indexed: true }),\n interval: attr(\"string\", { indexed: true }),\n billingTerms: attr(\"json\", { optional: true }),\n paymentQuote: attr(\"json\", { optional: true }),\n membershipOffer: attr(\"json\", { optional: true }),\n purchaserEmailNormalized: attr(\"string\", { indexed: true }),\n requestedCustomerId: attr(\"string\", { indexed: true, optional: true }),\n providerCustomerId: attr(\"string\", { indexed: true, optional: true }),\n providerSubscriptionId: attr(\"string\", { unique: true, indexed: true, optional: true }),\n status: attr(\"string\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n updatedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Non-authoritative copy of a durable network offer and the exact consent display.\nexport const membershipQuoteProjectionsEntity: Entity = {\n attrs: {\n id: attr(\"string\", { unique: true, indexed: true }),\n applicationId: attr(\"string\", { unique: true, indexed: true }),\n appId: attr(\"string\"), chapterId: attr(\"string\"), environment: attr(\"string\"), runtime: attr(\"string\"), skuId: attr(\"string\"),\n requestId: attr(\"string\"), revision: attr(\"number\"), status: attr(\"string\"), updatedAt: attr(\"number\"),\n offer: attr(\"json\", { optional: true }), offerDigest: attr(\"string\", { optional: true }),\n tier: attr(\"json\", { optional: true }), quote: attr(\"json\", { optional: true }),\n },\n};\n","import type { Entity } from \"./types\";\n\nconst string = (flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"string\" as const,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n});\nconst number = (flags: { indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"number\" as const, unique: false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst json = (flags: { optional?: boolean } = {}) => ({\n type: \"json\" as const, unique: false, indexed: false, optional: flags.optional ?? false,\n});\nconst id = () => string({ unique: true, indexed: true });\n\n/** Canonical identity only. Chapter Journey, notes, consent, and billing stay elsewhere. */\nexport const networkPersonsEntity: Entity = { attrs: {\n id: id(), displayName: string({ indexed: true }), state: string({ indexed: true }),\n mergedIntoId: string({ indexed: true, optional: true }), contactPolicy: json(),\n revision: number({ indexed: true }), createdAt: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} };\n\n/** One verified identifier digest may belong to only one preserved Person row. */\nexport const networkIdentityClaimsEntity: Entity = { attrs: {\n id: id(), personId: string({ indexed: true }), kind: string({ indexed: true }),\n value: string(), hint: string({ optional: true }), verifiedAt: number({ indexed: true }), createdAt: number({ indexed: true }),\n} };\n\n/** Immutable source identity plus a reviewable linking decision. */\nexport const networkPersonAliasesEntity: Entity = { attrs: {\n id: id(), sourceSystem: string({ indexed: true }), sourceRecordId: string({ indexed: true }),\n sourceKey: string({ unique: true, indexed: true }), displayName: string({ indexed: true }),\n provenance: string(), consent: json(), status: string({ indexed: true }), personId: string({ indexed: true, optional: true }),\n candidatePersonIds: json({ optional: true }), identityClaims: json(), chapterLinks: json(),\n revision: number({ indexed: true }), createdAt: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} };\n\n/** Chapter-local record identity remains a link, never copied authority. */\nexport const networkChapterPersonLinksEntity: Entity = { attrs: {\n id: id(), personId: string({ indexed: true }), chapterId: string({ indexed: true }),\n chapterPersonId: string({ indexed: true }),\n // Optional for additive compatibility with links written before 0.47.5.\n // New and reactivated links claim this unique one-way source identity so\n // concurrent reviewers cannot attach one chapter row to two Persons.\n sourceKey: string({ unique: true, indexed: true, optional: true }),\n state: string({ indexed: true }), createdAt: number({ indexed: true }),\n} };\n\n/** Append-only, PII-free lifecycle evidence. No route updates or deletes it. */\nexport const networkPersonEventsEntity: Entity = { attrs: {\n id: id(), kind: string({ indexed: true }), personId: string({ indexed: true, optional: true }),\n aliasId: string({ indexed: true, optional: true }), actorId: string({ indexed: true }),\n mutationId: string({ unique: true, indexed: true }), detail: json(), createdAt: number({ indexed: true }),\n} };\n\nexport const networkPersonEntities = {\n networkPersons: networkPersonsEntity,\n networkIdentityClaims: networkIdentityClaimsEntity,\n networkPersonAliases: networkPersonAliasesEntity,\n networkChapterPersonLinks: networkChapterPersonLinksEntity,\n networkPersonEvents: networkPersonEventsEntity,\n};\n","import type { Entity } from \"./types\";\n\nconst string = (flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"string\" as const, unique: flags.unique ?? false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst number = (flags: { indexed?: boolean; optional?: boolean } = {}) => ({\n type: \"number\" as const, unique: false, indexed: flags.indexed ?? false, optional: flags.optional ?? false,\n});\nconst boolean = (flags: { indexed?: boolean } = {}) => ({\n type: \"boolean\" as const, unique: false, indexed: flags.indexed ?? false, optional: false,\n});\nconst json = () => ({ type: \"json\" as const, unique: false, indexed: false, optional: false });\nconst id = () => string({ unique: true, indexed: true });\n\n/** Append-only verified Stripe facts. `fact` is allowlisted and contains no customer PII. */\nconst events: Entity = { attrs: {\n id: id(), eventId: string({ unique: true, indexed: true }), digest: string({ indexed: true }),\n eventType: string({ indexed: true }), eventCreated: number({ indexed: true }), livemode: boolean({ indexed: true }),\n fact: json(), receivedAt: number({ indexed: true }),\n} };\n\nconst projection = (): Entity => ({ attrs: {\n id: id(), providerId: string({ indexed: true }), sourceKey: string({ indexed: true }),\n status: string({ indexed: true }), snapshot: json(), eventCreated: number({ indexed: true }), updatedAt: number({ indexed: true }),\n} });\n\n/** Current, rebuildable projections plus explained reconciliation exceptions. */\nconst exceptions: Entity = { attrs: {\n id: id(), eventId: string({ indexed: true }), kind: string({ indexed: true }),\n sourceKey: string({ indexed: true, optional: true }), status: string({ indexed: true }),\n detail: json(), updatedAt: number({ indexed: true }),\n} };\n\nexport const networkCommercialEntities = {\n networkCommercialEvents: events,\n networkCommercialCustomers: projection(),\n networkCommercialSubscriptions: projection(),\n networkCommercialInvoices: projection(),\n networkCommercialRefunds: projection(),\n networkCommercialExceptions: exceptions,\n};\n","import type { Attr, AttrType, Entity } from \"./types\";\n\nconst attr = (type: AttrType, indexed = false, unique = false): Attr => ({ type, indexed, unique, optional: false });\n\n/** Immutable signup history. One revision is active in each chapter/data environment. */\nexport const signupControls: Entity = {\n attrs: {\n id: attr(\"string\", true, true), sourceId: attr(\"string\", true), targetId: attr(\"string\", true),\n environment: attr(\"string\", true), revision: attr(\"number\", true), digest: attr(\"string\", true),\n document: attr(\"json\"), active: attr(\"boolean\", true), receivedAt: attr(\"number\", true),\n },\n};\n\n/** Atomic publication head shared across developer runtimes; never promoted between environments. */\nexport const signupControlHeads: Entity = {\n attrs: {\n id: attr(\"string\", true, true), targetId: attr(\"string\", true), environment: attr(\"string\", true),\n revision: attr(\"number\"), digest: attr(\"string\"),\n },\n};\n","import { chapterAccountPolicy } from \"./schema-account-policy\";\n// The chapter's own odla-db namespaces: the operational membership tables\n// (applications, groups, meetings, emailLog) plus the auth tables the resolved\n// auth policy selects — the `admins` allowlist (source \"table\") and/or the\n// legacy read-only `superAdmins` tier. All deny-all. The `crm_*` namespaces are\n// contributed separately by @odla-ai/crm's integration and merged by the CLI.\nimport type {\n Attr,\n AttrType,\n DbRules,\n DbSchema,\n Entity,\n ChapterMode,\n ResolvedApplication,\n ResolvedAuth,\n} from \"./types\";\nimport { resolveApplication } from \"./member\";\nimport { applicationsFor } from \"./schema-applications\";\nimport { namedSeatConsentsEntity } from \"./schema-named-seats\";\nimport { admissionGrantRevisionsEntity, admissionGrantsEntity, leaderAdmissionAssignmentsEntity, leaderAdmissionDeliveriesEntity, leaderAdmissionMutationsEntity } from \"./schema-admission\";\nimport {\n giftClaimsEntity, giftEntitlementsEntity, giftOrdersEntity,\n giftPurchaseIntentsEntity, giftRedemptionAttemptsEntity,\n} from \"./schema-gifts\";\nimport { stripeEventReceiptsEntity, subscriptionCheckoutIntentsEntity, membershipQuoteProjectionsEntity } from \"./schema-stripe\";\nimport { networkPersonEntities } from \"./schema-network-person\";\nimport { networkCommercialEntities } from \"./schema-network-commercial\";\nimport { signupControlHeads, signupControls } from \"./schema-signup-control\";\n\nfunction attr(type: AttrType, flags: { unique?: boolean; indexed?: boolean; optional?: boolean } = {}): Attr {\n return {\n type,\n unique: flags.unique ?? false,\n indexed: flags.indexed ?? false,\n optional: flags.optional ?? false,\n };\n}\nconst id = (): Attr => attr(\"string\", { unique: true, indexed: true });\n\n// The allowlist that gates admin access in BOTH modes. Studio-write-only:\n// deny-all, and no worker route ever writes it. Creation time is odla-db's\n// built-in $createdAt. One row per admin, keyed by lowercased email.\nconst admins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n name: attr(\"string\", { optional: true }),\n note: attr(\"string\", { optional: true }),\n },\n};\n\n// The super-admin tier: the ONLY tier that may create or modify admins. A\n// separate, app-READ-ONLY entity — deny-all like every namespace AND no worker\n// route ever writes it, so membership can only be set in the odla Studio data\n// browser, never from the app or an injected page script. One row per\n// super-admin, keyed by lowercased email.\nconst superAdmins: Entity = {\n attrs: {\n id: id(),\n email: attr(\"string\", { unique: true, indexed: true }),\n note: attr(\"string\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Leader-private annotations on records that remain authoritative in a\n// follower CRM. `recordKey` is the stable target/type/id tuple used for bounded\n// reads; notes never cross the federation edge or mutate the follower.\nconst networkNotes: Entity = {\n attrs: {\n id: id(),\n recordKey: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n recordType: attr(\"string\", { indexed: true }),\n recordId: attr(\"string\", { indexed: true }),\n body: attr(\"string\"),\n authorId: attr(\"string\", { indexed: true }),\n authorEmail: attr(\"string\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Immutable Parent member-content revisions. Exactly one row is active per\n// environment; Chapter-owned content lives in a separate singleton below so a\n// replay or replacement from the Parent cannot overwrite local authority.\nconst memberContentControls: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n document: attr(\"json\"),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One complete Chapter-owned authoring layer per environment. Admin writes are\n// revision-guarded and never share a row with inherited Parent content.\nconst memberContentLocal: Entity = {\n attrs: {\n id: id(),\n chapterId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n document: attr(\"json\"),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { optional: true }),\n },\n};\n\n// Immutable signed Builder Library revisions received from Chapters or Built\n// Not Found. Source layers remain separate so sibling material is never joined\n// accidentally and global promotion retains exact provenance.\nconst builderLibraryControls: Entity = {\n attrs: {\n id: id(),\n sourceId: attr(\"string\", { indexed: true }),\n targetId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n digest: attr(\"string\", { indexed: true }),\n document: attr(\"json\"),\n active: attr(\"boolean\", { indexed: true }),\n receivedAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One complete locally authored layer per app/environment. Chapter mode permits\n// only its own Chapter scope; hub mode permits Built Not Found and global scope.\nconst builderLibraryLocal: Entity = {\n attrs: {\n id: id(),\n appId: attr(\"string\", { indexed: true }),\n environment: attr(\"string\", { indexed: true }),\n revision: attr(\"number\", { indexed: true }),\n document: attr(\"json\"),\n updatedAt: attr(\"number\", { indexed: true }),\n updatedBy: attr(\"string\", { optional: true }),\n },\n};\n\n// Per-group settings — prices, policy copy, email templates, scheduling — never\n// in code. Seeded once from the defineChapter config (see group.ts).\nconst groups: Entity = {\n attrs: {\n id: id(),\n name: attr(\"string\"),\n standardPriceCents: attr(\"number\"),\n foundingDiscountCents: attr(\"number\"),\n currency: attr(\"string\", { optional: true }), interval: attr(\"string\", { optional: true }),\n stripePriceId: attr(\"string\", { optional: true }),\n stripePublishableKey: attr(\"string\", { optional: true }),\n notificationEmail: attr(\"string\"),\n replyTo: attr(\"string\"),\n debugEmail: attr(\"string\", { optional: true }),\n calendarLink: attr(\"string\", { optional: true }),\n disclaimerText: attr(\"string\"),\n refundPolicyText: attr(\"string\"),\n merchantDisclosureText: attr(\"string\", { optional: true }),\n trustCopy: attr(\"string\"),\n commitmentText: attr(\"string\", { optional: true }),\n normsText: attr(\"string\", { optional: true }),\n emailTemplates: attr(\"json\"),\n schedulingJson: attr(\"json\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// One row per membership tier a group offers. The price lives here rather than\n// on the group so a chapter can offer several, and so a free tier (priceCents\n// 0, no stripePriceId) is expressible at all. Deny-all like every namespace:\n// tiers are set in Studio or seeded from the chapter config, never written by a\n// join-flow route.\nconst tiers: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n name: attr(\"string\"),\n priceCents: attr(\"number\"),\n currency: attr(\"string\", { optional: true }), interval: attr(\"string\", { optional: true }),\n stripePriceId: attr(\"string\", { optional: true }),\n blurb: attr(\"string\", { optional: true }),\n sortOrder: attr(\"number\", { indexed: true }),\n active: attr(\"boolean\", { indexed: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Intro-call meetings: the source of truth for scheduling; Google Calendar is a\n// projection. Drift fields record when Google disagrees with us.\nconst meetings: Entity = {\n attrs: {\n id: id(),\n applicationId: attr(\"string\", { indexed: true }),\n groupId: attr(\"string\", { indexed: true }),\n startAt: attr(\"number\", { indexed: true }),\n endAt: attr(\"number\"),\n timezone: attr(\"string\"),\n status: attr(\"string\", { indexed: true }),\n googleEventId: attr(\"string\", { indexed: true, optional: true }),\n meetUrl: attr(\"string\", { optional: true }),\n htmlLink: attr(\"string\", { optional: true }),\n drift: attr(\"string\", { indexed: true, optional: true }),\n driftGoogleStartAt: attr(\"number\", { optional: true }),\n driftDetectedAt: attr(\"number\", { optional: true }),\n adoptedFromGoogleAt: attr(\"number\", { optional: true }),\n createdAt: attr(\"number\", { indexed: true }),\n },\n};\n\n// Audit of every transactional send.\nconst emailLog: Entity = {\n attrs: {\n id: id(),\n groupId: attr(\"string\", { indexed: true }),\n applicationId: attr(\"string\", { indexed: true, optional: true }),\n to: attr(\"string\", { indexed: true }),\n template: attr(\"string\", { indexed: true }),\n subject: attr(\"string\"),\n body: attr(\"string\", { optional: true }),\n transport: attr(\"string\"),\n messageId: attr(\"string\", { optional: true }),\n redirected: attr(\"boolean\", { optional: true }),\n dedupeKey: attr(\"string\", { indexed: true, optional: true }),\n error: attr(\"string\", { optional: true }),\n deliveryState: attr(\"string\", { optional: true, indexed: true }),\n deliveryAttempt: attr(\"number\", { optional: true }),\n deliveryResolution: attr(\"json\", { optional: true }),\n sentAt: attr(\"number\", { indexed: true }),\n },\n};\n\n/** The chapter's own schema + deny-all rules for a mode + auth policy.\n *\n * In chapter mode, the optional {@link ResolvedApplication} supplies the exact\n * required/optional application string attrs. Omit it for the reference form.\n * Built-in attrs retain their types/indexes; site-defined fields become string\n * attrs, while package-owned operational attrs cannot be repurposed as inputs.\n *\n * Operational tables (`applications`/`groups`/`meetings`/`emailLog`) are added in\n * `chapter` mode only. The auth tables follow {@link ResolvedAuth}: `source:\n * \"table\"` adds the `admins` allowlist (hub/BNF); `superAdminSource: \"table\"`\n * adds the legacy read-only super-admin tier (the backward-compatible default).\n * `superAdminSource: \"odla\"` uses reserved `$users` and adds no app namespace. A `\"claim\"`\n * chapter therefore emits the reference namespace set — `applications`,\n * `groups`, `meetings`, `emailLog`, `stripeEventReceipts`,\n * `subscriptionCheckoutIntents`, `chapterAccountPolicy`, `superAdmins` — with\n * no `admins` table. */\nexport function chapterDb(\n mode: ChapterMode,\n auth: ResolvedAuth,\n includeNetworkNotes = false,\n application: ResolvedApplication = resolveApplication(undefined),\n includeSignupControl = false,\n includeMemberContent = false,\n includeBuilderLibrary = false,\n includeLeaderAdmissions = false,\n includeNetworkPersonRegistry = false,\n includeNetworkCommercialReadModel = false,\n): { schema: DbSchema; rules: DbRules } {\n const entities: Record<string, Entity> = {};\n if (mode === \"chapter\") {\n entities.applications = applicationsFor(application);\n entities.groups = groups;\n entities.tiers = tiers;\n entities.meetings = meetings;\n entities.emailLog = emailLog;\n entities.stripeEventReceipts = stripeEventReceiptsEntity;\n entities.subscriptionCheckoutIntents = subscriptionCheckoutIntentsEntity;\n entities.membershipQuoteProjections = membershipQuoteProjectionsEntity;\n entities.namedSeatConsents = namedSeatConsentsEntity;\n entities.admissionGrants = admissionGrantsEntity;\n entities.admissionGrantRevisions = admissionGrantRevisionsEntity;\n entities.giftPurchaseIntents = giftPurchaseIntentsEntity;\n entities.giftOrders = giftOrdersEntity;\n entities.giftClaims = giftClaimsEntity;\n entities.giftEntitlements = giftEntitlementsEntity;\n entities.giftRedemptionAttempts = giftRedemptionAttemptsEntity;\n if (includeSignupControl) {\n entities.signupControls = signupControls;\n entities.signupControlHeads = signupControlHeads;\n }\n if (includeMemberContent) {\n entities.memberContentControls = memberContentControls;\n entities.memberContentLocal = memberContentLocal;\n }\n }\n if (auth.source !== \"table\") entities.chapterAccountPolicy = chapterAccountPolicy;\n if (auth.source === \"table\") entities.admins = admins;\n if (auth.superAdminSource === \"table\") entities.superAdmins = superAdmins;\n if (includeNetworkNotes) entities.networkNotes = networkNotes;\n if (includeBuilderLibrary) {\n entities.builderLibraryControls = builderLibraryControls;\n entities.builderLibraryLocal = builderLibraryLocal;\n }\n if (includeLeaderAdmissions) {\n entities.leaderAdmissionAssignments = leaderAdmissionAssignmentsEntity;\n entities.leaderAdmissionDeliveries = leaderAdmissionDeliveriesEntity;\n entities.leaderAdmissionMutations = leaderAdmissionMutationsEntity;\n }\n if (includeNetworkPersonRegistry) {\n Object.assign(entities, networkPersonEntities);\n }\n if (includeNetworkCommercialReadModel) Object.assign(entities, networkCommercialEntities);\n const schema: DbSchema = { entities, links: {} };\n const rules: DbRules = {};\n for (const ns of Object.keys(entities)) {\n rules[ns] = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n }\n return { schema, rules };\n}\n","// Per-mode default CRM configs. Consumers pass their own via defineChapter's\n// `crm`; these are sensible starting points. Both modes share the canonical\n// people + businesses graph, while `chapter` additionally feeds the person\n// pipeline from applications through the operational package routes.\nimport type { CrmConfig } from \"@odla-ai/crm\";\nimport type { ChapterMode } from \"./types\";\n\nconst TEMPLATES: CrmConfig[\"templates\"] = {\n personal: {\n class: \"transactional\",\n vars: [\"firstName\", \"subject\", \"body\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\" },\n },\n announcement: {\n class: \"marketing\",\n vars: [\"firstName\", \"subject\", \"body\", \"unsubscribeUrl\"],\n defaults: { subject: \"{{subject}}\", text: \"{{body}}\\n\\n{{unsubscribeUrl}}\" },\n },\n};\n\nfunction personType(mode: ChapterMode): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Person\",\n labelPlural: \"People\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n email: { type: \"email\", label: \"Email\" },\n firstName: { type: \"string\", label: \"First name\" },\n lastName: { type: \"string\", label: \"Last name\" },\n phone: { type: \"string\", label: \"Phone\" },\n state: { type: \"string\", label: \"State\", slot: \"s1\" },\n whoYouAre: { type: \"string\", label: \"Who they are\", slot: \"s2\" },\n referral: { type: \"string\", label: \"Referral source\", slot: \"s3\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n focus: { type: \"json\", label: \"Focus areas\" },\n message: { type: \"string\", label: \"Intro message\" },\n ...(mode === \"chapter\" ? {\n applicationId: { type: \"string\" as const, label: \"Application id\", search: false },\n tier: { type: \"string\" as const, label: \"Tier\", slot: \"s4\" as const },\n } : {}),\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"paid_pending_vetting\", label: \"Paid, pending vetting\" },\n { id: \"call_scheduled\", label: \"Call scheduled\" },\n { id: \"interviewed\", label: \"Interviewed\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"declined\", label: \"Declined\" },\n { id: \"refunded\", label: \"Refunded\" },\n ],\n },\n facets: { identity: true, email: true, rank: \"manual\" },\n };\n}\n\nfunction companyType(): NonNullable<CrmConfig[\"types\"]>[string] {\n return {\n label: \"Business\",\n labelPlural: \"Businesses\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n domain: { type: \"string\", label: \"Domain / website\", slot: \"s1\" },\n industry: { type: \"string\", label: \"Industry\", slot: \"s2\" },\n location: { type: \"string\", label: \"Location\", slot: \"s3\" },\n chapter: { type: \"string\", label: \"Chapter\", slot: \"s4\" },\n linkedin: { type: \"string\", label: \"LinkedIn\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n facets: { rank: \"manual\" },\n };\n}\n\n/** The default shared CRM graph: people (with the application/member pipeline)\n * plus businesses and the `works_at` relation, in both modes. */\nexport function defaultCrm(mode: ChapterMode): CrmConfig {\n return {\n types: { person: personType(mode), company: companyType() },\n relations: { works_at: { from: \"person\", to: \"company\", label: \"works at\", reverseLabel: \"team\" } },\n templates: TEMPLATES,\n };\n}\n","// Build the seed `groups` row from a defineChapter config. This is the whole\n// per-chapter payload the worker reads at runtime (prices/policy/emails/\n// scheduling), so nothing brand-specific is hardcoded in the worker. createdAt\n// is stamped by the integration/seed layer, not here.\nimport type { ChapterConfig, ChapterScheduling } from \"./types\";\n\nconst DEFAULT_SCHEDULING: Required<Omit<ChapterScheduling, \"summaryTemplate\">> = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n};\n\nfunction defaultEmailTemplates(name: string): Record<string, { subject: string; text: string }> {\n const sign = `\\n\\nWarmly,\\n${name}`;\n return {\n adminNotification: {\n subject: `New application: {{firstName}} {{lastName}}`,\n text: `A new application came in for ${name}.\\n\\nName: {{firstName}} {{lastName}}\\nEmail: {{email}}`,\n },\n paymentConfirmation: {\n subject: `Welcome to ${name}`,\n text: `Hi {{firstName}},\\n\\nYour membership payment{{paymentAmountSummary}} is confirmed. {{paymentNextStep}}${sign}`,\n },\n prepEmail: {\n subject: `Your ${name} intro call`,\n text: `Hi {{firstName}},\\n\\nLooking forward to our call at {{meetingTime}}. {{meetingLink}}${sign}`,\n },\n onboardingInvite: {\n subject: `You're in, ${name}`,\n text: `Hi {{firstName}},\\n\\nWelcome to ${name}. Your member area is here: {{membersUrl}}${sign}`,\n },\n };\n}\n\n/** The `groups` row (attrs) for `chapter` mode. Missing config falls back to\n * empty copy / defaults, so a minimal config still provisions cleanly. */\nexport function buildGroupSeed(config: ChapterConfig): Record<string, unknown> {\n const prices = config.prices;\n const emails = config.emails;\n const policy = config.policy ?? {};\n const scheduling = {\n ...DEFAULT_SCHEDULING,\n ...(config.scheduling ?? {}),\n summaryTemplate:\n config.scheduling?.summaryTemplate ?? `${config.name}: introduction call with {{firstName}} {{lastName}}`,\n };\n const row: Record<string, unknown> = {\n id: config.id,\n name: config.name,\n standardPriceCents: prices?.standardCents ?? 0,\n foundingDiscountCents: prices?.foundingDiscountCents ?? 0,\n currency: prices?.currency ?? \"usd\",\n interval: prices?.interval ?? \"year\",\n notificationEmail: emails?.notificationEmail ?? \"\",\n replyTo: emails?.replyTo ?? emails?.notificationEmail ?? \"\",\n disclaimerText: policy.disclaimerText ?? \"\",\n refundPolicyText: policy.refundPolicyText ?? \"\",\n merchantDisclosureText: policy.merchantDisclosureText ?? \"\",\n trustCopy: policy.trustCopy ?? \"\",\n emailTemplates: emails?.templates ?? defaultEmailTemplates(config.name),\n schedulingJson: scheduling,\n };\n if (emails?.debugEmail) row.debugEmail = emails.debugEmail;\n if (policy.commitmentText) row.commitmentText = policy.commitmentText;\n if (policy.normsText) row.normsText = policy.normsText;\n return row;\n}\n","// Identity + authorization for a chapter/hub site — the pieces every membership\n// site needs and none should re-derive: a resolved role policy, role resolution\n// from a JWT claim, the privilege-escalation guard, and a tenant-vault read.\n// Everything here is pure or structural (no runtime @odla-ai/db import), so it is\n// trivially testable and the worker stays the only thing that talks to odla-db.\nimport type { ChapterAuth, ChapterMode, ResolvedAuth } from \"./types\";\n\n/**\n * Apply defaults + validate the auth config into a {@link ResolvedAuth}. Defaults\n * by mode: `chapter` → the `provisional/member/admin` claim ladder with the\n * `superAdmins` tier; `hub` → the `admins` allowlist table with no super tier.\n * Existing sites retain the legacy `superAdmins` table unless they explicitly\n * select protected odla user roles.\n * Throws at import on a bad policy.\n */\nexport function resolveAuth(mode: ChapterMode, auth: ChapterAuth | undefined): ResolvedAuth {\n const a = auth ?? {};\n const source = a.source ?? (mode === \"hub\" ? \"table\" : \"claim\");\n if (source !== \"claim\" && source !== \"table\" && source !== \"clerk\") {\n throw new Error(`defineChapter.auth.source: must be \"clerk\", \"claim\" or \"table\" — got ${JSON.stringify(a.source)}`);\n }\n const claim = a.claim ?? \"role\";\n if (typeof claim !== \"string\" || claim === \"\") {\n throw new Error(\"defineChapter.auth.claim: must be a non-empty string\");\n }\n const ladder = a.ladder ?? [\"provisional\", \"member\", \"admin\"];\n if (!Array.isArray(ladder) || ladder.length === 0 || !ladder.every((r) => typeof r === \"string\" && r !== \"\")) {\n throw new Error(\"defineChapter.auth.ladder: must be a non-empty array of role strings\");\n }\n const adminRole = ladder[ladder.length - 1] as string;\n const superAdmins = a.superAdmins ?? source !== \"table\";\n const configuredSuperSource = a.superAdminSource ?? (source === \"clerk\" ? \"odla\" : \"table\");\n if (configuredSuperSource !== \"table\" && configuredSuperSource !== \"odla\") {\n throw new Error(`defineChapter.auth.superAdminSource: must be \"table\" or \"odla\" — got ${JSON.stringify(a.superAdminSource)}`);\n }\n const superAdminSource = superAdmins ? configuredSuperSource : \"none\";\n return { source, claim, ladder, adminRole, superAdmins, superAdminSource };\n}\n\n/** The role from a verified JWT payload, per the resolved policy. An unknown or\n * missing claim falls back to the lowest ladder rung (fail safe, never admin). */\nexport function roleFromClaim(payload: Record<string, unknown>, auth: ResolvedAuth): string {\n const raw = payload[auth.claim];\n return typeof raw === \"string\" && auth.ladder.includes(raw) ? raw : (auth.ladder[0] as string);\n}\n\n/** Does a role meet the admin bar (the highest ladder rung)? */\nexport function isAdminRole(role: string, auth: ResolvedAuth): boolean {\n return role === auth.adminRole;\n}\n\n/** Inputs to the role-change guard — resolved by the caller (route) from the\n * identity provider + the configured Studio-managed super-admin authority. */\nexport interface RoleChangeContext {\n actorId: string;\n actorIsSuper: boolean;\n targetId: string;\n targetCurrentRole: string;\n targetIsSuper: boolean;\n newRole: string;\n auth: ResolvedAuth;\n}\n\n/** The result of {@link canChangeRole}: allow, or deny with the HTTP status +\n * message the route should return. */\nexport type GuardResult = { ok: true } | { ok: false; status: number; error: string };\n\n/**\n * The privilege-escalation guard — package-enforced so every site gets it and\n * none re-derives it. Denies: an out-of-ladder role; changing your own role;\n * touching a super-admin unless you are one; and (when a `superAdmins` tier\n * exists) creating or altering an admin unless you are a super-admin. Note the\n * super-admin tier itself is never writable here — it is set only in odla\n * Studio, either as a protected `$users.role` or in the legacy allowlist.\n */\nexport function canChangeRole(ctx: RoleChangeContext): GuardResult {\n const { auth } = ctx;\n if (!auth.ladder.includes(ctx.newRole)) {\n return { ok: false, status: 400, error: `role must be one of: ${auth.ladder.join(\", \")}` };\n }\n if (ctx.actorId === ctx.targetId) {\n return { ok: false, status: 400, error: \"you cannot change your own role\" };\n }\n if (ctx.targetIsSuper && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: \"this person is a super-admin; their access is managed in odla Studio\" };\n }\n const touchesAdmin = ctx.newRole === auth.adminRole || ctx.targetCurrentRole === auth.adminRole;\n if (auth.superAdmins && touchesAdmin && !ctx.actorIsSuper) {\n return { ok: false, status: 403, error: `only super-admins can create or change an ${auth.adminRole}` };\n }\n return { ok: true };\n}\n\n/** Structural view of odla-db's tenant-vault read, so chapter takes no runtime\n * dependency on @odla-ai/db. The worker's admin client satisfies this. */\nexport interface SecretStore {\n secrets: { get(name: string): Promise<string> };\n}\n\n/**\n * Read a tenant-vault secret by name; `undefined` when it is absent or the vault\n * errors, so callers degrade gracefully (e.g. `paymentsReady: false`) rather than\n * throwing. Never logs the value.\n */\nexport async function getVaultSecret(db: SecretStore, name: string): Promise<string | undefined> {\n try {\n const value = await db.secrets.get(name);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","// The application status pipeline — config, not code. Which statuses exist, which\n// a member can book an intro call from, and which an admin can approve from\n// differ per site; the one invariant every site wants is that status never moves\n// backwards. All of this is pure + tested here; the worker enforces it on every\n// status write, and the CRM record.stage mirrors application.status (never the\n// reverse). Defaults reproduce the proven membership pipeline exactly.\nimport type { ChapterPipeline, ResolvedPipeline } from \"./types\";\n\nconst DEFAULT_STAGES = [\n \"submitted\",\n \"paid_pending_vetting\",\n \"call_scheduled\",\n \"interviewed\",\n \"approved\",\n \"declined\",\n \"refunded\",\n] as const;\nconst DEFAULT_BOOKABLE = [\"submitted\", \"paid_pending_vetting\", \"call_scheduled\"] as const;\nconst DEFAULT_APPROVABLE = [\"paid_pending_vetting\", \"call_scheduled\", \"interviewed\"] as const;\n\n/**\n * Apply defaults + validate the pipeline config. With no config, the complete\n * reference pipeline. With `stages` given but the subsets omitted, the subsets\n * default to empty (a site opts in to bookable/approvable states explicitly).\n * Throws at import on a bad pipeline (empty/duplicate stages, an initial or a\n * subset entry not on the ladder).\n */\nexport function resolvePipeline(p: ChapterPipeline | undefined): ResolvedPipeline {\n const usingDefaults = !p?.stages;\n const stages = p?.stages ?? [...DEFAULT_STAGES];\n if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => typeof s === \"string\" && s !== \"\")) {\n throw new Error(\"defineChapter.pipeline.stages: must be a non-empty array of status strings\");\n }\n if (new Set(stages).size !== stages.length) {\n throw new Error(\"defineChapter.pipeline.stages: statuses must be unique\");\n }\n const initial = p?.initial ?? (stages[0] as string);\n if (!stages.includes(initial)) {\n throw new Error(`defineChapter.pipeline.initial: \"${initial}\" is not one of the stages`);\n }\n const bookableFrom = p?.bookableFrom ?? (usingDefaults ? [...DEFAULT_BOOKABLE] : []);\n const approvableFrom = p?.approvableFrom ?? (usingDefaults ? [...DEFAULT_APPROVABLE] : []);\n for (const [name, subset] of [\n [\"bookableFrom\", bookableFrom],\n [\"approvableFrom\", approvableFrom],\n ] as const) {\n for (const s of subset) {\n if (!stages.includes(s)) throw new Error(`defineChapter.pipeline.${name}: \"${s}\" is not one of the stages`);\n }\n }\n return { stages, bookableFrom, approvableFrom, initial };\n}\n\n/** The ordinal of a status in the ladder, or -1 if unknown. */\nexport function stageIndex(status: string, p: ResolvedPipeline): number {\n return p.stages.indexOf(status);\n}\n\n/**\n * The status-never-moves-backwards invariant: a transition is allowed only when\n * both statuses are on the ladder and `to` is at or ahead of `from`. The worker\n * calls this before every status write; a violation is a 409, never a silent\n * downgrade.\n */\nexport function canTransition(from: string, to: string, p: ResolvedPipeline): boolean {\n const fi = p.stages.indexOf(from);\n const ti = p.stages.indexOf(to);\n return fi >= 0 && ti >= 0 && ti >= fi;\n}\n\n/** May an intro call be booked from this status? */\nexport function canBook(status: string, p: ResolvedPipeline): boolean {\n return p.bookableFrom.includes(status);\n}\n\n/** May an application be approved (→ member) from this status? */\nexport function canApprove(status: string, p: ResolvedPipeline): boolean {\n return p.approvableFrom.includes(status);\n}\n","import type { ChapterCopy } from \"./copy.js\";\n\nexport const DEFAULT_ADMIN_COPY: ChapterCopy[\"admin\"] = {\n auth: {\n checking: \"Checking access…\",\n notAuthorized: \"Not authorized\",\n accountNotAuthorized: \"{account} isn't on the admin list.\",\n thisAccount: \"This account\",\n signOut: \"Sign out\",\n loading: \"Loading…\",\n signInNotConfigured: \"Sign-in not configured\",\n missingPublishableKey: \"No Clerk publishable key is set for this environment yet.\",\n noWorkspaces: \"No admin workspaces are configured.\",\n signInTagline: \"Admin sign-in, invite only\",\n },\n shell: {\n adminRole: \"admin\",\n adminConsole: \"Admin Console\",\n adminName: \"Admin\",\n navigationLabel: \"Admin navigation\",\n },\n workspaces: {\n dashboard: \"Dashboard\",\n overview: \"Overview\",\n billing: \"Billing\",\n people: \"People\",\n admission: \"Admission\",\n network: \"Network\",\n portfolio: \"Portfolio\",\n settings: \"Settings\",\n calendar: \"Calendar\",\n email: \"Email\",\n chapters: \"Chapters\",\n formations: \"Formation applications\",\n dealFlow: \"Deal flow\",\n dashboardViewsLabel: \"Dashboard views\",\n settingsViewsLabel: \"Settings views\",\n collectionsLabel: \"CRM collections\",\n portfolioViewsLabel: \"Portfolio views\",\n },\n dashboard: {\n loading: \"Loading dashboard…\",\n loadFailed: \"Couldn't load the dashboard\",\n upcomingCalls: \"Upcoming calls\",\n callsNeedAttention: \"{count} need attention\",\n noUpcomingCalls: \"No upcoming calls.\",\n drift: \"drift\",\n open: \"Open\",\n meet: \"Meet\",\n applications: \"Applications\",\n newMembers: \"New members\",\n newMembersUnavailable: \"Appears once billing is connected.\",\n revenueAdded: \"Revenue · annual run rate added\",\n revenue: \"Revenue\",\n revenueUnavailable: \"Appears once billing is connected.\",\n pipeline: \"Pipeline\",\n pipelineLabel: \"Membership pipeline\",\n thisWeek: \"+{count} this week\",\n noChange: \"no change\",\n activeMemberships: \"Active memberships\",\n annualRunRate: \"Annual run rate\",\n testMode: \"test mode\",\n },\n billing: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load billing\",\n notConfigured: \"Billing isn't configured. No Stripe key is vaulted for this group.\",\n active: \"Active\",\n annualized: \"Annualized\",\n renewingSoon: \"Renewing within 60 days\",\n pastDue: \"Past due\",\n subscriptions: \"Subscriptions\",\n testMode: \"Stripe test mode\",\n truncated: \"Showing the first 100 subscriptions. The list is truncated.\",\n name: \"Name\",\n email: \"Email\",\n application: \"Application\",\n subscription: \"Subscription\",\n cancelling: \"cancelling\",\n amount: \"Amount\",\n renews: \"Renews\",\n },\n availability: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load availability\",\n saved: \"Saved.\",\n title: \"Booking availability\",\n days: \"Days\",\n startHour: \"Start hour (0–24)\",\n endHour: \"End hour (0–24)\",\n slotMinutes: \"Slot length (minutes)\",\n minNoticeHours: \"Minimum notice (hours)\",\n windowDays: \"Booking window (days)\",\n timezone: \"Timezone\",\n summaryTemplate: \"Event summary template\",\n save: \"Save availability\",\n dayLabels: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n },\n email: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load email config\",\n saved: \"Saved.\",\n sent: \"Sent {template} to {address}{redirected}.\",\n testFailed: \"Test send did not deliver.\",\n delivery: \"Delivery\",\n notificationAddress: \"Notification address\",\n replyTo: \"Reply-to\",\n debugInbox: \"Debug inbox\",\n debugInboxHint: \"Non-production sends redirect here.\",\n sendTest: \"Send test\",\n enabled: \"Enabled\",\n subject: \"Subject\",\n body: \"Body\",\n save: \"Save changes\",\n sendLog: \"Send log\",\n sentColumn: \"Sent\",\n templateColumn: \"Template\",\n statusColumn: \"Status\",\n toColumn: \"To\",\n failed: \"failed\",\n redirected: \"redirected\",\n delivered: \"delivered\",\n },\n meetings: {\n loading: \"Loading…\",\n loadFailed: \"Couldn't load meetings\",\n cancelConfirm: \"Cancel this call? The calendar provider notifies the attendee.\",\n newStartPrompt: \"New start time (for example, 2026-08-01 14:00):\",\n parseFailed: \"Couldn't parse that time.\",\n agenda: \"Agenda\",\n empty: \"No meetings.\",\n unknown: \"(unknown)\",\n drift: \"drift\",\n meet: \"Meet\",\n reschedule: \"Reschedule\",\n cancel: \"Cancel\",\n },\n admission: {\n title: \"Interview decisions\",\n description: \"Local decisions override Parent decisions. Requiring an interview locally suppresses a Parent waiver for the same email.\",\n email: \"Email\",\n decision: \"Decision\",\n expires: \"Expires\",\n note: \"Internal note\",\n waive: \"Waive interview\",\n require: \"Require interview\",\n add: \"Add decision\",\n ledger: \"Effective grant ledger\",\n loading: \"Loading…\",\n consumed: \"consumed\",\n revoked: \"revoked\",\n expired: \"expired\",\n active: \"active\",\n local: \"local\",\n parent: \"Parent\",\n revoke: \"Revoke\",\n },\n network: {\n title: \"Share to a follower\",\n allowlistDescription: \"Sends the target's allowlisted fields. Its pipeline and account state remain local.\",\n sharing: \"Sharing…\",\n shareWith: \"Share with {target}\",\n shared: \"Shared with {target}.\",\n shareFailed: \"Could not share with {target}.\",\n deliveryFailed: \"Delivery failed.\",\n loadingRollup: \"Loading network overview…\",\n loadRollupFailed: \"Couldn't load the network overview\",\n overview: \"Network overview\",\n configuredFollowers: \"Configured followers\",\n reachableFollowers: \"Reachable followers\",\n recordsAcrossFollowers: \"Records across followers\",\n noFollowers: \"No follower sites are configured.\",\n followers: \"Followers\",\n available: \"available\",\n unavailable: \"unavailable\",\n transportReachable: \"transport reachable\",\n transportUnavailable: \"transport unavailable\",\n transportNotChecked: \"transport not checked\",\n bindingTransport: \"service binding {binding}\",\n urlTransport: \"public URL transport\",\n activeConfiguration: \"active configuration r{revision}\",\n noActiveConfiguration: \"no active managed configuration\",\n publicSiteAvailable: \"public site reachable\",\n publicSiteUnavailable: \"public site unavailable\",\n publicSiteNotChecked: \"public site not probed\",\n recordTotals: \"Portfolio records\",\n noRecordTotals: \"No aggregate records are available yet.\",\n },\n records: {\n workflowMissing: \"This record is not linked to an application workflow.\",\n comms: \"Comms\",\n commsHistory: \"Comms history\",\n scheduling: \"Scheduling\",\n billing: \"Billing\",\n notes: \"Notes\",\n access: \"Access\",\n sharing: \"Sharing\",\n lifecycle: \"Access & lifecycle\",\n role: \"Role\",\n superAdminHint: \"Super-admin, managed in odla Studio.\",\n noAccount: \"No linked account yet. The role is set once they sign in.\",\n approve: \"Approve\",\n refund: \"Refund\",\n approved: \"Approved.\",\n refunded: \"Refund issued.\",\n roleSet: \"Role set to {role}.\",\n messageSent: \"Message sent.\",\n messageNotSent: \"Message was not sent.\",\n loadingTemplates: \"Loading templates…\",\n template: \"Template\",\n chooseTemplate: \"Choose a template…\",\n sending: \"Sending…\",\n send: \"Send\",\n noMessages: \"No messages recorded.\",\n message: \"Message\",\n newStartPrompt: \"New start time:\",\n parseFailed: \"Couldn't parse that time.\",\n cancelConfirm: \"Cancel this call?\",\n callCancelled: \"Call cancelled.\",\n callRescheduled: \"Call rescheduled.\",\n noApplication: \"No application is linked to this record.\",\n loadingMeetings: \"Loading meetings…\",\n noMeetings: \"No meetings recorded.\",\n joinMeeting: \"Join meeting\",\n openCalendar: \"Open calendar\",\n reschedule: \"Reschedule\",\n cancel: \"Cancel\",\n },\n};\n","import type { ChapterCopy } from \"./copy.js\";\n\nexport const DEFAULT_COMMON_COPY: ChapterCopy[\"common\"] = {\n loading: \"Loading…\",\n saved: \"Saved.\",\n unknown: \"(unknown)\",\n};\n\nexport const DEFAULT_JOIN_COPY: ChapterCopy[\"join\"] = {\n form: {\n submit: \"Submit application\",\n submitting: \"Submitting…\",\n submitFailed: \"Your application could not be submitted.\",\n unexpectedFailure: \"Something went wrong. Please try again.\",\n },\n booking: {\n unavailable: \"Scheduling is briefly unavailable. We'll reach out by email to arrange your call.\",\n loadFailed: \"Times are briefly unavailable. Please try again.\",\n slotTaken: \"That time was just taken. Here are the current openings.\",\n failed: \"The booking could not be completed.\",\n loading: \"Loading available times…\",\n book: \"Book this time\",\n booking: \"Booking…\",\n },\n payment: {\n setupFailed: \"Payment could not be set up. Please try again.\",\n preparing: \"Preparing secure payment…\",\n pending: \"Confirming your payment…\",\n processing: \"Processing…\",\n payAndContinue: \"Pay and continue\",\n incomplete: \"The payment did not complete. Please try again.\",\n consent: \"I have read and agree to the pricing and refund policy above.\",\n },\n done: {\n label: \"You're booked\",\n calendarInvite: \"A calendar invitation with the video call link is on its way to your email.\",\n memberArea: \"Go to your member area\",\n },\n accepted: {\n label: \"You're approved\",\n body: \"Your membership is approved. No introduction call is required.\",\n },\n gift: {\n chooseSelf: \"Buy membership for myself\",\n optionsLabel: \"Or give access to someone else\",\n label: \"Your gift code\",\n body: \"Share this one-time code with the recipient. It becomes active after payment is confirmed.\",\n save: \"Save it now. For security, this code is shown only once.\",\n rotate: \"Generate a new code\",\n rotateFailed: \"A new code could not be generated.\",\n claimTitle: \"Have a gift code?\",\n claimBody: \"Use it here instead of paying by card.\",\n code: \"One-time code\",\n redeem: \"Use gift code\",\n redeemed: \"Gift code applied.\",\n redeemFailed: \"The code is invalid, unavailable, or does not match this membership.\",\n },\n};\n\nexport const DEFAULT_MEMBERS_COPY: ChapterCopy[\"members\"] = {\n loadFailed: \"Sign in is briefly unavailable. Please refresh.\",\n account: {\n signOut: \"Sign out\",\n adminConsole: \"Admin console\",\n },\n provisional: {\n cardLabel: \"Your Application\",\n applicationNeeded: \"One step remains\",\n applicationNeededBody: \"Your account is ready, and the application that completes it takes a few minutes.\",\n apply: \"Apply for membership\",\n refunded: \"Membership refunded\",\n refundedBody: \"Your fee has been refunded in full and your membership is canceled.\",\n active: \"Your membership is active.\",\n renews: \"Your membership is active and renews {date}.\",\n introductionCall: \"Your introduction call\",\n calendarInvite: \"A calendar invitation with the video call link is in your email.\",\n joinCall: \"Join the video call\",\n bookCall: \"Book your introduction call\",\n bookCallBody: \"Your application is in. Choose a time below, and a calendar invitation will reach your email.\",\n chooseTime: \"Choose a time\",\n },\n full: {\n welcome: \"Welcome back.\",\n },\n gifts: {\n title: \"Give access\",\n body: \"Purchase access for someone else and share the one-time claim code.\",\n noneAvailable: \"No gift options are available right now.\",\n paid: \"Payment submitted. Save the code below while it is visible.\",\n saveCode: \"This code is shown once. Save it before leaving this page.\",\n purchases: \"Your gifts\",\n noPurchases: \"No gift purchases yet.\",\n pending: \"Pending\",\n redeemed: \"Redeemed\",\n expired: \"Expired\",\n revoked: \"Revoked\",\n rotate: \"Rotate code\",\n rotated: \"A new code was generated. Save it now.\",\n rotateFailed: \"The code could not be rotated.\",\n redeemTitle: \"Redeem a gift\",\n code: \"One-time code\",\n redeem: \"Redeem\",\n redeemFailed: \"The code is invalid or unavailable.\",\n },\n reschedule: {\n changeTime: \"Change your time\",\n unavailable: \"Scheduling is briefly unavailable. We'll reach out by email to arrange your call.\",\n loadFailed: \"Times are briefly unavailable. Please try again.\",\n slotGone: \"That time is no longer available. Please pick another.\",\n loading: \"Loading available times…\",\n noTimes: \"No open times right now. Please check back soon.\",\n rescheduling: \"Rescheduling…\",\n keepTime: \"Keep my current time\",\n },\n};\n","import { DEFAULT_ADMIN_COPY } from \"./copy-defaults-admin.js\";\nimport {\n DEFAULT_COMMON_COPY,\n DEFAULT_JOIN_COPY,\n DEFAULT_MEMBERS_COPY,\n} from \"./copy-defaults.js\";\nimport type { ChapterCopy, ChapterCopyInput } from \"./copy.js\";\n\n/** Complete default language resolved beneath partial Chapter copy overrides. */\nexport const DEFAULT_CHAPTER_COPY: ChapterCopy = {\n common: DEFAULT_COMMON_COPY,\n join: DEFAULT_JOIN_COPY,\n members: DEFAULT_MEMBERS_COPY,\n admin: DEFAULT_ADMIN_COPY,\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n\nfunction mergeCopy<T>(base: T, input: unknown, path: string): T {\n if (typeof base === \"string\") {\n if (input === undefined) return base;\n if (typeof input !== \"string\") throw new Error(`${path}: must be a string`);\n return input as T;\n }\n if (Array.isArray(base)) {\n if (input === undefined) return [...base] as T;\n if (!Array.isArray(input) || !input.every((item) => typeof item === \"string\")) {\n throw new Error(`${path}: must be an array of strings`);\n }\n return [...input] as T;\n }\n if (!isObject(base)) return base;\n if (input !== undefined && !isObject(input)) throw new Error(`${path}: must be an object`);\n const overrides = input as Record<string, unknown> | undefined;\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(base)) {\n result[key] = mergeCopy(value, overrides?.[key], `${path}.${key}`);\n }\n return result as T;\n}\n\n/** Resolve a partial copy contract and validate every supplied leaf. */\nexport function resolveChapterCopy(input?: ChapterCopyInput): ChapterCopy {\n return mergeCopy(DEFAULT_CHAPTER_COPY, input, \"defineChapter.copy\");\n}\n\n/** Replace `{name}` placeholders without interpreting the resulting text as HTML. */\nexport function formatChapterCopy(\n template: string,\n values: Readonly<Record<string, string | number>>,\n): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, key: string) =>\n Object.prototype.hasOwnProperty.call(values, key) ? String(values[key]) : match,\n );\n}\n","import type { Crm, FieldConditions, FieldDef, FieldType } from \"@odla-ai/crm\";\nimport type { Chapter, ResolvedApplication, ResolvedLeaderFormation } from \"./types\";\n\n/** Current public schema version for Chapter flow-field contracts. */\nexport const CHAPTER_FLOW_FIELDS_SCHEMA_VERSION = 1 as const;\n\n/** Configurable Chapter intake journeys that publish field contracts. */\nexport type ChapterFieldFlow = \"join\" | \"formation\";\n\n/** Email comparison policy advertised by an email field. */\nexport type ChapterEmailIdentity = \"literal\";\n\n/**\n * One effective field in a Chapter intake journey.\n *\n * IDs, value types, and options come from the follower-declared schema. A hub\n * or CMS may select, order, and configure only those declared fields; it cannot\n * use this presentation document to add storage or widen follower authority.\n */\nexport interface ChapterFlowField {\n id: string;\n label: string;\n type: FieldType;\n required: boolean;\n order: number;\n maxLength?: number;\n options?: readonly string[];\n conditions?: FieldConditions;\n /** Present only for an email identity field. Aliases such as `+tag` remain significant. */\n emailIdentity?: ChapterEmailIdentity;\n}\n\n/** Ordered, versioned effective field state for one Chapter journey. */\nexport interface ChapterFlowFieldContract {\n schemaVersion: typeof CHAPTER_FLOW_FIELDS_SCHEMA_VERSION;\n flow: ChapterFieldFlow;\n fields: readonly ChapterFlowField[];\n}\n\nconst APPLICATION_LABELS: Readonly<Record<string, string>> = {\n firstName: \"First name\",\n lastName: \"Last name\",\n email: \"Email\",\n referral: \"Referral source\",\n referralName: \"Referral name\",\n whoYouAre: \"Who you are\",\n linkedin: \"LinkedIn\",\n message: \"Intro message\",\n phone: \"Phone\",\n state: \"State\",\n};\n\nfunction humanize(id: string): string {\n const text = id.replace(/([a-z0-9])([A-Z])/g, \"$1 $2\").replace(/[_-]+/g, \" \").trim();\n return text ? `${text[0]!.toUpperCase()}${text.slice(1)}` : id;\n}\n\nfunction applicationDefs(chapter: Chapter): Record<string, FieldDef> {\n try {\n return chapter.crm.type(\"person\").fields;\n } catch {\n return {};\n }\n}\n\nfunction applicationType(id: string, def: FieldDef | undefined): FieldType {\n // Application rows accept configurable strings. Preserve the richer\n // string-like CRM hints without claiming that a numeric/date/json CRM field\n // changes the application storage contract.\n if (def && [\"string\", \"email\", \"url\", \"enum\"].includes(def.type)) return def.type;\n return id === \"email\" ? \"email\" : id === \"linkedin\" ? \"url\" : \"string\";\n}\n\n/** Resolve the exact ordered fields accepted by the membership application flow. */\nexport function applicationFlowFields(\n chapter: Chapter,\n application: ResolvedApplication = chapter.application,\n): ChapterFlowField[] {\n const defs = applicationDefs(chapter);\n return [...application.required, ...application.optional].map((id, order) => {\n const def = defs[id];\n const conditions = application.conditions[id];\n const type = applicationType(id, def);\n return {\n id,\n label: def?.label ?? APPLICATION_LABELS[id] ?? humanize(id),\n type,\n required: application.required.includes(id),\n order,\n maxLength: application.maxLen[id] ?? application.defaultMaxLen,\n ...(type === \"enum\" && def?.options ? { options: [...def.options] } : {}),\n ...(conditions ? { conditions: { ...conditions } } : {}),\n ...(type === \"email\" ? { emailIdentity: \"literal\" as const } : {}),\n };\n });\n}\n\n/** Common resolver retained separately so the legacy formationFields helper cannot drift. */\nexport function resolveFormationFlowFields(\n crm: Crm,\n formation: ResolvedLeaderFormation,\n): ChapterFlowField[] {\n if (!formation.enabled) return [];\n const def = crm.type(formation.type);\n return [...formation.required, ...formation.optional].map((id, order) => {\n const field = def.fields[id]!;\n return {\n id,\n label: field.label ?? humanize(id),\n type: field.type,\n required: formation.required.includes(id),\n order,\n maxLength: formation.maxLen[id] ?? formation.defaultMaxLen,\n ...(field.options ? { options: [...field.options] } : {}),\n ...(id === def.emailField || field.type === \"email\" ? { emailIdentity: \"literal\" as const } : {}),\n };\n });\n}\n\n/** Resolve the exact ordered fields accepted by the chapter-formation flow. */\nexport function formationFlowFields(\n chapter: Chapter,\n formation: ResolvedLeaderFormation = chapter.formation,\n): ChapterFlowField[] {\n return resolveFormationFlowFields(chapter.crm, formation);\n}\n\n/**\n * Build the public field contract consumed by follower forms and CMS previews.\n * The optional application is the already-authorized effective selection from\n * signup control; it never expands the follower's declared application schema.\n */\nexport function chapterFlowFieldContract(\n chapter: Chapter,\n flow: ChapterFieldFlow,\n application: ResolvedApplication = chapter.application,\n): ChapterFlowFieldContract {\n return {\n schemaVersion: CHAPTER_FLOW_FIELDS_SCHEMA_VERSION,\n flow,\n fields: flow === \"join\"\n ? applicationFlowFields(chapter, application)\n : formationFlowFields(chapter),\n };\n}\n","import type { Crm } from \"@odla-ai/crm\";\nimport type { LeaderFormationConfig, ResolvedLeaderFormation } from \"./types\";\nimport { resolveFormationFlowFields } from \"./flow-fields\";\n\nconst DEFAULT_REQUIRED = [\"name\", \"email\", \"location\", \"thesis\"];\nconst DEFAULT_OPTIONAL = [\"proposedChapter\", \"experience\", \"collaborators\"];\n\n/** Resolve and validate the public chapter-formation intake contract. */\nexport function resolveLeaderFormation(\n input: LeaderFormationConfig | undefined,\n crm: Crm,\n): ResolvedLeaderFormation {\n const type = input?.type ?? \"chapter_application\";\n if (!input) {\n return {\n enabled: false,\n type,\n required: [],\n optional: [],\n maxLen: {},\n defaultMaxLen: 4000,\n bodyCap: 32768,\n };\n }\n const def = crm.config.types[type];\n if (!def) throw new Error(`defineChapter.formation.type: unknown CRM type \"${type}\"`);\n const required = input.required ?? (type === \"chapter_application\" ? DEFAULT_REQUIRED : []);\n const optional = input.optional ?? (type === \"chapter_application\" ? DEFAULT_OPTIONAL : []);\n for (const [name, values] of [[\"required\", required], [\"optional\", optional]] as const) {\n if (!Array.isArray(values) || !values.every((field) => typeof field === \"string\" && field !== \"\")) {\n throw new Error(`defineChapter.formation.${name}: must be an array of field-name strings`);\n }\n }\n const duplicates = [...required, ...optional].filter((field, index, fields) => fields.indexOf(field) !== index);\n if (duplicates.length) throw new Error(`defineChapter.formation: duplicate public field \"${duplicates[0]}\"`);\n const unknown = [...required, ...optional].filter((field) => !def.fields[field]);\n if (unknown.length) throw new Error(`defineChapter.formation: field \"${unknown[0]}\" is not declared on CRM type \"${type}\"`);\n const missingRequired = Object.entries(def.fields)\n .filter(([, field]) => field.required)\n .map(([field]) => field)\n .filter((field) => !required.includes(field));\n if (missingRequired.length) {\n throw new Error(`defineChapter.formation.required: must include required CRM field \"${missingRequired[0]}\"`);\n }\n const unsupportedRequired = required.find((field) =>\n ![\"string\", \"email\", \"url\", \"enum\"].includes(def.fields[field]!.type));\n if (unsupportedRequired) {\n throw new Error(`defineChapter.formation.required: field \"${unsupportedRequired}\" must be string-like`);\n }\n if (required.length === 0) throw new Error(\"defineChapter.formation.required: must not be empty\");\n const defaultMaxLen = input.defaultMaxLen ?? 4000;\n const bodyCap = input.bodyCap ?? 32768;\n if (!Number.isSafeInteger(defaultMaxLen) || defaultMaxLen < 1 || defaultMaxLen > 32768) {\n throw new Error(\"defineChapter.formation.defaultMaxLen: must be an integer from 1 to 32768\");\n }\n if (!Number.isSafeInteger(bodyCap) || bodyCap < 1024 || bodyCap > 131072) {\n throw new Error(\"defineChapter.formation.bodyCap: must be an integer from 1024 to 131072\");\n }\n for (const [field, cap] of Object.entries(input.maxLen ?? {})) {\n if (![...required, ...optional].includes(field) || !Number.isSafeInteger(cap) || cap < 1 || cap > 32768) {\n throw new Error(`defineChapter.formation.maxLen.${field}: must name a public field and be an integer from 1 to 32768`);\n }\n }\n return {\n enabled: true,\n type,\n required,\n optional,\n maxLen: input.maxLen ?? {},\n defaultMaxLen,\n bodyCap,\n };\n}\n\n/** Public, presentational field metadata for a host-owned intake form. */\nexport function formationFields(\n crm: Crm,\n formation: ResolvedLeaderFormation,\n): import(\"./flow-fields\").ChapterFlowField[] {\n return resolveFormationFlowFields(crm, formation);\n}\n","import type { Crm, FieldType, TypeSummary } from \"@odla-ai/crm\";\nimport type { ChapterDb } from \"./types\";\n\n/** The contact data the hub shares for a prospect. `hubRecordId` is the stable\n * idempotency key (the hub's crm_record id). */\nexport interface SharedPerson {\n email: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n hubRecordId: string;\n}\n\n/** Convenience wire shape for sharing the default `company` CRM type. */\nexport interface SharedBusiness {\n type: \"company\";\n name: string;\n domain?: string;\n industry?: string;\n location?: string;\n linkedin?: string;\n notes?: string;\n hubRecordId: string;\n}\n\n/** Versioned generic wire shape. `input` is validated against the follower's\n * own CRM type before any write, so a leader cannot smuggle undeclared fields. */\nexport interface SharedRecordV1 {\n version: 1;\n type: string;\n hubRecordId: string;\n input: Record<string, unknown>;\n}\n\n/** Current wire envelope. `source.siteId` prevents records from two leaders\n * with the same local id from colliding in a follower CRM. */\nexport interface SharedRecordV2 {\n version: 2;\n source: { siteId: string; recordId: string };\n type: string;\n input: Record<string, unknown>;\n}\n\n/** Accepted generic share envelopes. Version 1 remains readable for migration. */\nexport type SharedRecord = SharedRecordV1 | SharedRecordV2;\n\n/** Privacy-bounded follower status returned to an authenticated leader. */\nexport interface NetworkSnapshot {\n version: 1;\n site: { id: string; name: string; mode: string };\n generatedAt: number;\n /** Active follower-owned receipt for the managed signup configuration.\n * Optional on the wire so a newer leader can still inspect an older follower. */\n configuration?: { activeRevision: number | null; digest?: string };\n types: TypeSummary[];\n}\n\n/** Server-side route used for the signed follower snapshot. `reachable: null`\n * means the request could not be attempted (for example, a missing edge secret). */\nexport interface NetworkTargetTransportStatus {\n kind: \"binding\" | \"url\";\n binding?: string;\n reachable: boolean | null;\n error?: {\n code: \"binding_unavailable\" | \"binding_request_failed\" | \"url_request_failed\" | \"edge_secret_missing\";\n message: string;\n };\n}\n\n/** One configured target's latest live result in a leader rollup. */\nexport interface NetworkRollupTarget {\n id: string;\n name: string;\n url: string;\n available: boolean;\n /** Signed snapshot transport; independent of public-origin availability. */\n transport: NetworkTargetTransportStatus;\n /** Last active managed configuration reported by the authenticated follower. */\n configuration: { activeRevision: number | null; digest?: string };\n /** `null` when a service binding was authoritative and the public origin was\n * deliberately not probed. */\n publicSite: { available: boolean | null };\n generatedAt?: number;\n types?: TypeSummary[];\n error?: string;\n}\n\n/** Cross-target totals returned to the local leader admin. */\nexport interface NetworkRollup {\n configured: number;\n available: number;\n totalRecords: number;\n types: Array<{ type: string; total: number; stages: Record<string, number> }>;\n targets: NetworkRollupTarget[];\n}\n\n/** Privacy-bounded CRM record returned by a follower to one configured,\n * authenticated reader. */\nexport interface NetworkRecord {\n id: string;\n type: string;\n name: string;\n stage?: string;\n fields: Record<string, unknown>;\n createdAt: number;\n updatedAt: number;\n /** Optimistic concurrency token authored by the follower. */\n revision: number;\n /** Follower-authored edit contract. Omitted when this edge is read-only. */\n edit?: NetworkRecordEdit;\n}\n\n/** One follower CRM field a leader may patch. */\nexport interface NetworkEditableField {\n id: string;\n label: string;\n type: FieldType;\n required: boolean;\n options?: readonly string[];\n}\n\n/** One follower-authoritative lifecycle destination currently allowed. */\nexport interface NetworkStageTransition {\n id: string;\n label: string;\n}\n\n/** Edit metadata computed from the follower schema, pipeline, and record. */\nexport interface NetworkRecordEdit {\n fields: NetworkEditableField[];\n allowedStages: NetworkStageTransition[];\n /** Durable application operation awaiting reconciliation by its original operator. */\n pendingAction?: { mutationId: string; stage: string; expectedStage: string; expectedRevision: number; actorId: string; actorEmail?: string };\n}\n\n/** Signed follower mutation dispatched by a leader admin. Exactly one of\n * `fields` or `stage` is present. */\nexport interface NetworkRecordMutation {\n type: string;\n expectedRevision: number;\n expectedStage?: string | null;\n mutationId: string;\n fields?: Record<string, unknown>;\n stage?: string;\n actor: { id: string; email?: string };\n}\n\n/** Successful follower mutation response. */\nexport interface NetworkRecordMutationResult {\n version: 1;\n site: { id: string; name: string };\n record: NetworkRecord;\n duplicate: boolean;\n}\n\n/** One bounded, offset-paged follower record window. */\nexport interface NetworkRecordPage {\n version: 1;\n site: { id: string; name: string };\n type: string;\n records: NetworkRecord[];\n total: number;\n limit: number;\n offset: number;\n /** Follower-authored options that may safely be used for this type. Older\n * followers omit this, so leaders must not offer source-side filters unless\n * the capability is present. */\n filters?: {\n stages: Array<{ id: string; label: string }>;\n sorts: Array<{ id: NetworkRecordSort; label: string }>;\n };\n /** Normalized query the follower actually applied. A leader checks this\n * echo before presenting filtered results, preventing an older follower\n * from silently ignoring newer query parameters. */\n appliedQuery?: {\n stage?: string;\n sort: NetworkRecordSort;\n };\n}\n\n/** Bounded source-side ordering supported by the federated record route. */\nexport type NetworkRecordSort = \"updated_desc\" | \"updated_asc\" | \"name_asc\" | \"name_desc\";\n\n/** Leader-private note attached to a stable remote record identity. */\nexport interface NetworkRecordNote {\n id: string;\n targetId: string;\n recordType: string;\n recordId: string;\n body: string;\n authorId: string;\n authorEmail?: string;\n createdAt: number;\n}\n\n/** A note deliberately shared across the federation edge and stored in the\n * follower CRM activity feed. Unlike NetworkRecordNote, this is visible to\n * the follower's own CRM admins. */\nexport interface NetworkSharedNote {\n id: string;\n sourceId: string;\n recordType: string;\n recordId: string;\n body: string;\n createdAt: number;\n}\n\nexport interface NormalizedSharedRecord {\n version: 1 | 2;\n sourceId: string;\n sourceRecordId: string;\n type: string;\n input: Record<string, unknown>;\n}\n\n/** Dependencies for applying a shared projection. */\nexport interface ProjectionDeps {\n crm: Crm;\n db: ChapterDb;\n now: () => number;\n newId: () => string;\n}\n\n/** Safe defaults when a target does not declare an explicit field allowlist. */\nexport const DEFAULT_SHARE_FIELDS: Readonly<Record<string, readonly string[]>> = {\n person: [\"name\", \"email\", \"firstName\", \"lastName\", \"phone\", \"linkedin\"],\n company: [\"name\", \"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"],\n};\n","import type { Crm } from \"@odla-ai/crm\";\nimport type {\n ChapterConfig,\n ResolvedNetwork,\n ResolvedNetworkReader,\n ResolvedNetworkTarget,\n} from \"./types\";\nimport { DEFAULT_SHARE_FIELDS } from \"./network-contract\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst FIELD = /^[a-z][a-zA-Z0-9_]*$/;\nconst BINDING = /^[A-Z][A-Z0-9_]{0,127}$/;\n\nfunction validateSharedNotes(opts: {\n path: string;\n values: readonly string[];\n crm: Crm;\n fields?: Record<string, readonly string[]>;\n}) {\n const duplicate = opts.values.some((type, index) => opts.values.indexOf(type) !== index);\n const invalid = opts.values.some((type) =>\n !FIELD.test(type) || !opts.crm.config.types[type] || (opts.fields ? !opts.fields[type] : false));\n if (duplicate || invalid) {\n throw new Error(`${opts.path}: must contain unique CRM types allowed by fields`);\n }\n}\n\nfunction validateEditableFields(opts: {\n path: string;\n values: Record<string, readonly string[]>;\n crm: Crm;\n readable?: Record<string, readonly string[]>;\n}) {\n for (const [type, names] of Object.entries(opts.values)) {\n const readable = opts.readable?.[type];\n const def = opts.crm.config.types[type];\n const duplicate = names.some((name, index) => names.indexOf(name) !== index);\n const unknown = names.some((name) => !FIELD.test(name) || !def?.fields[name]);\n const hidden = opts.readable\n ? !readable || names.some((name) => !readable.includes(name))\n : false;\n if (!FIELD.test(type) || names.length === 0 || duplicate || !def || unknown || hidden) {\n throw new Error(\n `${opts.path}.${type}: must contain unique, readable fields declared on CRM type \"${type}\"`,\n );\n }\n }\n}\n\nfunction validateStageTransitions(opts: {\n path: string;\n values: readonly string[];\n crm: Crm;\n readable?: Record<string, readonly string[]>;\n}) {\n const duplicate = opts.values.some((type, index) => opts.values.indexOf(type) !== index);\n const invalid = opts.values.some((type) =>\n !FIELD.test(type) || !opts.crm.config.types[type]?.pipeline || (opts.readable ? !opts.readable[type] : false));\n if (duplicate || invalid) {\n throw new Error(`${opts.path}: must contain unique, readable CRM types with pipelines`);\n }\n}\n\nfunction validateAdmissionCapability(path: string, enabled: boolean | undefined, crm: Crm) {\n if (!enabled) return;\n const person = crm.config.types.person;\n if (!person?.emailField || person.fields[person.emailField]?.type !== \"email\") {\n throw new Error(`${path}: requires a CRM person type with an emailField`);\n }\n}\n\n/** Resolve the two-sided federation contract. Targets are leader-owned\n * outbound policy; readers are follower-owned disclosure/write policy. */\nexport function resolveNetwork(config: ChapterConfig, crm: Crm): ResolvedNetwork {\n const seen = new Set<string>();\n const targets: ResolvedNetworkTarget[] = [];\n for (const target of config.network?.targets ?? []) {\n if (!SLUG.test(target.id)) {\n throw new Error(`defineChapter.network.targets.id: must be a lowercase slug — got ${JSON.stringify(target.id)}`);\n }\n if (seen.has(target.id)) throw new Error(`defineChapter.network.targets: duplicate target \"${target.id}\"`);\n seen.add(target.id);\n let url: URL;\n try {\n url = new URL(target.url);\n } catch {\n throw new Error(`defineChapter.network.targets.${target.id}.url: must be an absolute URL`);\n }\n const local = url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"::1\";\n if (url.protocol !== \"https:\" && !(local && url.protocol === \"http:\")) {\n throw new Error(`defineChapter.network.targets.${target.id}.url: must use https (http is allowed only for localhost)`);\n }\n const fields = target.fields;\n for (const [type, names] of Object.entries(fields ?? {})) {\n if (!FIELD.test(type) || names.length === 0 || names.some((name) => !FIELD.test(name))) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: type and field names must be non-empty CRM identifiers`,\n );\n }\n const def = crm.config.types[type];\n if (!def) throw new Error(`defineChapter.network.targets.${target.id}.fields: unknown leader CRM type \"${type}\"`);\n const unknown = names.filter((field) => !def.fields[field]);\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: ${unknown.map((field) => `\"${field}\"`).join(\", \")} ` +\n \"not declared on the leader CRM type\",\n );\n }\n const nameField = def.nameField ?? \"name\";\n if (!names.includes(nameField)) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.fields.${type}: must include required name field \"${nameField}\"`,\n );\n }\n }\n const secretName = target.secretName?.trim() || `network_share_${target.id.replaceAll(\"-\", \"_\")}`;\n if (!/^[a-zA-Z][a-zA-Z0-9_-]{1,127}$/.test(secretName)) {\n throw new Error(`defineChapter.network.targets.${target.id}.secretName: must be a vault-key identifier`);\n }\n const binding = target.binding?.trim();\n if (binding && !BINDING.test(binding)) {\n throw new Error(\n `defineChapter.network.targets.${target.id}.binding: must be an uppercase Worker binding identifier`,\n );\n }\n const sharedNotes = target.sharedNotes ?? [];\n validateSharedNotes({\n path: `defineChapter.network.targets.${target.id}.sharedNotes`,\n values: sharedNotes,\n crm,\n fields,\n });\n const readableFields = fields ?? DEFAULT_SHARE_FIELDS;\n const editableFields = target.editableFields ?? {};\n validateEditableFields({\n path: `defineChapter.network.targets.${target.id}.editableFields`,\n values: editableFields,\n crm,\n readable: readableFields,\n });\n const stageTransitions = target.stageTransitions ?? [];\n validateStageTransitions({\n path: `defineChapter.network.targets.${target.id}.stageTransitions`,\n values: stageTransitions,\n crm,\n readable: readableFields,\n });\n validateAdmissionCapability(\n `defineChapter.network.targets.${target.id}.admissionGrants`,\n target.admissionGrants,\n crm,\n );\n targets.push({\n id: target.id,\n name: target.name?.trim() || target.id,\n url: url.origin,\n ...(binding ? { binding } : {}),\n secretName,\n ...(fields ? { fields } : {}),\n sharedNotes,\n editableFields,\n stageTransitions,\n ...(target.admissionGrants === true ? { admissionGrants: true } : {}),\n ...(target.commercialParity === true ? { commercialParity: true } : {}),\n });\n }\n const readerIds = new Set<string>();\n const readers: ResolvedNetworkReader[] = [];\n for (const reader of config.network?.readers ?? []) {\n if (!SLUG.test(reader.id)) {\n throw new Error(`defineChapter.network.readers.id: must be a lowercase slug — got ${JSON.stringify(reader.id)}`);\n }\n if (readerIds.has(reader.id)) {\n throw new Error(`defineChapter.network.readers: duplicate reader \"${reader.id}\"`);\n }\n readerIds.add(reader.id);\n const readerFields = reader.fields ?? {};\n const entries = Object.entries(readerFields);\n if (entries.length === 0 && !reader.admissionGrants && !reader.commercialParity) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields: at least one CRM type is required unless this is an admission-only or commercial-parity reader`,\n );\n }\n for (const [type, names] of entries) {\n if (!FIELD.test(type) || names.length === 0 || names.some((name) => !FIELD.test(name))) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: type and field names must be non-empty CRM identifiers`,\n );\n }\n const def = crm.config.types[type];\n if (!def) {\n throw new Error(`defineChapter.network.readers.${reader.id}.fields: unknown local CRM type \"${type}\"`);\n }\n const unknown = names.filter((field) => !def.fields[field]);\n if (unknown.length > 0) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: ` +\n `${unknown.map((field) => `\"${field}\"`).join(\", \")} not declared on the local CRM type`,\n );\n }\n const nameField = def.nameField ?? \"name\";\n if (!names.includes(nameField)) {\n throw new Error(\n `defineChapter.network.readers.${reader.id}.fields.${type}: must include required name field \"${nameField}\"`,\n );\n }\n }\n const sharedNotes = reader.sharedNotes ?? [];\n validateSharedNotes({\n path: `defineChapter.network.readers.${reader.id}.sharedNotes`,\n values: sharedNotes,\n crm,\n fields: readerFields,\n });\n const editableFields = reader.editableFields ?? {};\n validateEditableFields({\n path: `defineChapter.network.readers.${reader.id}.editableFields`,\n values: editableFields,\n crm,\n readable: readerFields,\n });\n const stageTransitions = reader.stageTransitions ?? [];\n validateStageTransitions({\n path: `defineChapter.network.readers.${reader.id}.stageTransitions`,\n values: stageTransitions,\n crm,\n readable: readerFields,\n });\n validateAdmissionCapability(\n `defineChapter.network.readers.${reader.id}.admissionGrants`,\n reader.admissionGrants,\n crm,\n );\n readers.push({\n id: reader.id,\n fields: readerFields,\n sharedNotes,\n editableFields,\n stageTransitions,\n ...(reader.admissionGrants === true ? { admissionGrants: true } : {}),\n ...(reader.commercialParity === true ? { commercialParity: true } : {}),\n });\n }\n return { targets, readers, ...(config.network?.requireSuperAdminWrites ? { requireSuperAdminWrites: true } : {}) };\n}\n","import type { ChapterMode } from \"./types\";\nimport type { ChapterNetworkPersonRegistry, ResolvedNetworkPersonRegistry } from \"./types-network-person\";\n\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/** Validate the opt-in, hub-only shadow Person registry. */\nexport function resolveNetworkPersonRegistry(\n mode: ChapterMode,\n input: ChapterNetworkPersonRegistry | undefined,\n targetIds: readonly string[],\n): ResolvedNetworkPersonRegistry | null {\n if (!input) return null;\n if (mode !== \"hub\") throw new Error(\"defineChapter.networkPersonRegistry: only hub mode may own network Person authority\");\n if (input.mode !== \"shadow\") throw new Error('defineChapter.networkPersonRegistry.mode: must be \"shadow\"');\n const chapterIds = input.chapterIds ? [...input.chapterIds] : [...targetIds];\n if (chapterIds.length === 0) throw new Error(\"defineChapter.networkPersonRegistry.chapterIds: at least one chapter is required\");\n if (new Set(chapterIds).size !== chapterIds.length || chapterIds.some((id) => !SLUG.test(id))) {\n throw new Error(\"defineChapter.networkPersonRegistry.chapterIds: expected distinct lowercase slugs\");\n }\n const unknown = chapterIds.filter((id) => !targetIds.includes(id));\n if (unknown.length) {\n throw new Error(`defineChapter.networkPersonRegistry.chapterIds: ${unknown.map((id) => `\"${id}\"`).join(\", \")} are not configured network targets`);\n }\n return { mode: \"shadow\", chapterIds };\n}\n","import type { ChapterMode } from \"./types\";\nimport type {\n ChapterNetworkCommercialReadModel,\n NetworkCommercialSource,\n ResolvedNetworkCommercialReadModel,\n} from \"./types-network-commercial\";\n\nconst SLUG = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\nconst TOKEN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\n/** Stable, PII-free identity for one accepted Stripe partition. */\nexport function networkCommercialSourceKey(source: NetworkCommercialSource): string {\n return [source.stripeMode, source.appId, source.environment, source.dataEnvironment, source.runtime, source.chapterId].join(\":\");\n}\n\n/** Validate the opt-in hub-only commercial shadow. */\nexport function resolveNetworkCommercialReadModel(\n mode: ChapterMode,\n input: ChapterNetworkCommercialReadModel | undefined,\n targetIds: readonly string[],\n): ResolvedNetworkCommercialReadModel | null {\n if (!input) return null;\n if (mode !== \"hub\") throw new Error(\"defineChapter.networkCommercialReadModel: only hub mode may own the network commercial projection\");\n if (input.mode !== \"shadow\") throw new Error('defineChapter.networkCommercialReadModel.mode: must be \"shadow\"');\n if (!Array.isArray(input.sources) || input.sources.length === 0) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: at least one exact source is required\");\n }\n const sources = input.sources.map((source) => ({ ...source }));\n for (const source of sources) {\n if (!SLUG.test(source.appId) || !SLUG.test(source.chapterId) ||\n !TOKEN.test(source.environment) || !TOKEN.test(source.dataEnvironment) || !TOKEN.test(source.runtime) ||\n (source.stripeMode !== \"test\" && source.stripeMode !== \"live\")) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: every source requires valid app, chapter, environment, data-environment, runtime, and Stripe mode values\");\n }\n if (!targetIds.includes(source.chapterId)) {\n throw new Error(`defineChapter.networkCommercialReadModel.sources: chapter \"${source.chapterId}\" is not a configured network target`);\n }\n }\n if (new Set(sources.map(networkCommercialSourceKey)).size !== sources.length) {\n throw new Error(\"defineChapter.networkCommercialReadModel.sources: exact source partitions must be distinct\");\n }\n return { mode: \"shadow\", sources };\n}\n","import type { ChapterSignupControl, ResolvedSignupControl } from \"./types-signup-control\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst SECRET_NAME = /^[a-z][a-z0-9_]{1,127}$/;\n\n/** Validate one deliberately separate signup-control edge. */\nexport function resolveSignupControl(\n input: ChapterSignupControl | undefined,\n): ResolvedSignupControl | null {\n if (!input) return null;\n if (!SLUG.test(input.sourceId)) {\n throw new Error(\"defineChapter.signupControl.sourceId: must be a lowercase app slug\");\n }\n if (input.stripeMode !== \"test\" && input.stripeMode !== \"live\") {\n throw new Error('defineChapter.signupControl.stripeMode: must be \"test\" or \"live\"');\n }\n const secretName = input.secretName?.trim() || \"signup_control_secret\";\n if (!SECRET_NAME.test(secretName)) {\n throw new Error(\"defineChapter.signupControl.secretName: must be a vault-key identifier\");\n }\n if (input.runtimeSecrets !== undefined && (\n !input.runtimeSecrets || typeof input.runtimeSecrets !== \"object\" || Array.isArray(input.runtimeSecrets) ||\n !Object.keys(input.runtimeSecrets).length || Object.keys(input.runtimeSecrets).length > 32 ||\n Object.entries(input.runtimeSecrets).some(([runtime, name]) => !SLUG.test(runtime) || typeof name !== \"string\" || !SECRET_NAME.test(name)) ||\n new Set(Object.values(input.runtimeSecrets)).size !== Object.keys(input.runtimeSecrets).length\n )) throw new Error(\"defineChapter.signupControl.runtimeSecrets: requires unique vault keys for a bounded runtime allowlist\");\n return { sourceId: input.sourceId, secretName, stripeMode: input.stripeMode,\n ...(input.runtimeSecrets ? { runtimeSecrets: { ...input.runtimeSecrets } } : {}),\n };\n}\n","import type { ChapterMemberContent, ResolvedMemberContent } from \"./types-member-content\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst SECRET_NAME = /^[a-z][a-z0-9_]{1,127}$/;\n\n/** Validate the deliberately separate member-content authoring boundary. */\nexport function resolveMemberContent(input: ChapterMemberContent | undefined): ResolvedMemberContent | null {\n if (!input) return null;\n const parent = input.parent;\n if (parent && !SLUG.test(parent.sourceId)) {\n throw new Error(\"defineChapter.memberContent.parent.sourceId: must be a lowercase app slug\");\n }\n const secretName = parent?.secretName?.trim() || \"member_content_control_secret\";\n if (parent && !SECRET_NAME.test(secretName)) {\n throw new Error(\"defineChapter.memberContent.parent.secretName: must be a vault-key identifier\");\n }\n return {\n enabled: true,\n localAuthoring: input.localAuthoring !== false,\n parent: parent ? { sourceId: parent.sourceId, secretName } : null,\n };\n}\n","import type { ChapterMode, ResolvedNetwork } from \"./types\";\nimport type { ChapterBuilderLibrary, ResolvedBuilderLibrary } from \"./types-builder-library\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\n\n/** Validate the private Builder Library boundary against Chapter's existing\n * network peers. Builder Library never introduces a second edge credential. */\nexport function resolveBuilderLibrary(\n mode: ChapterMode,\n input: ChapterBuilderLibrary | undefined,\n network: ResolvedNetwork = { targets: [], readers: [] },\n): ResolvedBuilderLibrary | null {\n if (!input) return null;\n if (input.sources !== undefined && !Array.isArray(input.sources)) {\n throw new Error(\"defineChapter.builderLibrary.sources: must be an array\");\n }\n const seen = new Set<string>();\n const sources = (input.sources ?? []).map((source, index) => {\n if (!source || typeof source !== \"object\" || !SLUG.test(source.sourceId)) {\n throw new Error(`defineChapter.builderLibrary.sources[${index}].sourceId: must be a lowercase app slug`);\n }\n if (source.sourceId === \"built-not-found\" && mode === \"hub\") {\n throw new Error(`defineChapter.builderLibrary.sources[${index}]: a hub accepts Chapter sources, not itself`);\n }\n if (mode === \"chapter\" && source.sourceId !== \"built-not-found\") {\n throw new Error(`defineChapter.builderLibrary.sources[${index}]: Chapters may accept only the built-not-found source`);\n }\n if (seen.has(source.sourceId)) {\n throw new Error(`defineChapter.builderLibrary.sources: duplicate source \"${source.sourceId}\"`);\n }\n seen.add(source.sourceId);\n if (\"secretName\" in source) {\n throw new Error(\n `defineChapter.builderLibrary.sources[${index}].secretName: remove this field; Builder Library reuses the Chapter network edge`,\n );\n }\n const networkPeer = mode === \"hub\"\n ? network.targets.some((target) => target.id === source.sourceId)\n : network.readers.some((reader) => reader.id === source.sourceId);\n if (!networkPeer) {\n const side = mode === \"hub\" ? \"targets\" : \"readers\";\n throw new Error(\n `defineChapter.builderLibrary.sources[${index}]: \"${source.sourceId}\" must already be configured in network.${side}`,\n );\n }\n return { sourceId: source.sourceId };\n });\n return { enabled: true, localAuthoring: input.localAuthoring !== false, sources };\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\n\n/** Frozen commercial terms supplied by the issuing membership authority, never the browser. */\nexport interface SubscriptionBillingTerms {\n /** Immutable offering version whose base Price is subscribed. */\n offeringVersionId: string;\n /** Immutable discount policy, independent of the base SKU and permanent cohort. */\n discount?: {\n policyVersionId: string;\n couponId: string;\n percentOffBps: number;\n duration: \"once\" | \"forever\";\n };\n /** Extended initial paid service end, epoch milliseconds. Renewal starts here. */\n initialTermEndsAt?: number;\n}\n\ntype Contract = {\n appId: string; chapterId: string; environment: string; runtime?: string;\n priceCents: number; currency: string; billingTerms?: SubscriptionBillingTerms;\n /** Product obtained from the verified base Price; limits the benefit to this SKU. */\n discountProductId?: string;\n};\nconst fail = (): never => {\n throw Object.assign(new Error(\"Stripe billing terms do not match the issued offer\"), { code: \"stripe_contract_mismatch\" });\n};\nconst boundedId = (value: unknown): value is string => typeof value === \"string\" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/.test(value);\n\n/** Validate the frozen terms before database or provider writes, normalizing their key order for replay. */\nexport function subscriptionBillingTerms(value: SubscriptionBillingTerms): SubscriptionBillingTerms {\n if (!value || typeof value !== \"object\" || Array.isArray(value) || !boundedId(value.offeringVersionId) ||\n Object.keys(value).some((key) => ![\"offeringVersionId\", \"discount\", \"initialTermEndsAt\"].includes(key))) fail();\n const discount = value.discount;\n if (discount !== undefined && (!discount || typeof discount !== \"object\" || Array.isArray(discount) ||\n !boundedId(discount.policyVersionId) || !boundedId(discount.couponId) ||\n !Number.isSafeInteger(discount.percentOffBps) || discount.percentOffBps <= 0 || discount.percentOffBps >= 10000 ||\n ![\"once\", \"forever\"].includes(discount.duration) ||\n Object.keys(discount).some((key) => ![\"policyVersionId\", \"couponId\", \"percentOffBps\", \"duration\"].includes(key)))) fail();\n if (value.initialTermEndsAt !== undefined && (!Number.isSafeInteger(value.initialTermEndsAt) ||\n value.initialTermEndsAt <= 0 || value.initialTermEndsAt % 1000 !== 0)) fail();\n return {\n offeringVersionId: value.offeringVersionId,\n ...(discount ? { discount: { policyVersionId: discount.policyVersionId, couponId: discount.couponId,\n percentOffBps: discount.percentOffBps, duration: discount.duration } } : {}),\n ...(value.initialTermEndsAt !== undefined ? { initialTermEndsAt: value.initialTermEndsAt } : {}),\n };\n}\n\n/** Amount due today; the Stripe recurring Price remains the undiscounted base amount. */\nexport function subscriptionAmountDue(input: Pick<Contract, \"priceCents\" | \"billingTerms\">): number {\n if (!Number.isSafeInteger(input.priceCents) || input.priceCents <= 0) fail();\n const terms = input.billingTerms ? subscriptionBillingTerms(input.billingTerms) : undefined;\n return Math.round(input.priceCents * (10000 - (terms?.discount?.percentOffBps ?? 0)) / 10000);\n}\n\n/** Verify a separately managed Stripe coupon before creating any customer or subscription. */\nexport async function verifySubscriptionBillingTerms(secretKey: string, input: Contract, resume: boolean, now = Date.now()): Promise<void> {\n return checkBillingTerms(secretKey, input, resume, now, false);\n}\n\n/** Provision only a missing immutable coupon for a server-issued policy.\n * This does not issue eligibility or alter an existing coupon or base Price.\n * Replays of existing subscriptions never create a replacement benefit.\n */\nexport async function prepareSubscriptionBillingTerms(secretKey: string, input: Contract, resume: boolean, now = Date.now()): Promise<void> {\n return checkBillingTerms(secretKey, input, resume, now, !resume);\n}\n\nasync function checkBillingTerms(secretKey: string, input: Contract, resume: boolean, now: number, createMissing: boolean): Promise<void> {\n if (!input.billingTerms) return;\n const terms = subscriptionBillingTerms(input.billingTerms);\n // Stripe's trial mechanism anchors the next recurring invoice. The initial\n // service is NOT free: a full, non-prorated invoice item is charged today.\n if (!resume && terms.initialTermEndsAt !== undefined &&\n (terms.initialTermEndsAt <= now || terms.initialTermEndsAt - now > 730 * 86400000)) fail();\n if (!terms.discount) return;\n const { couponId, percentOffBps, duration, policyVersionId } = terms.discount;\n const productId = input.discountProductId;\n if (productId !== undefined && !/^prod_[A-Za-z0-9_]+$/.test(productId)) fail();\n const metadata = { ...stripePartitionMetadata(input), discountPolicyVersionId: policyVersionId };\n // Stripe omits this expandable field by default, including on creation.\n // Missing evidence must still fail closed, but request the evidence first.\n const expansion = { \"expand[0]\": \"applies_to\" };\n let result = await stripeRequest<Record<string, any>>({ secretKey }, \"GET\", `/v1/coupons/${encodeURIComponent(couponId)}`, expansion);\n if (createMissing && result.status === 404 && result.body?.error?.code === \"resource_missing\") {\n result = await stripeRequest<Record<string, any>>({ secretKey }, \"POST\", \"/v1/coupons\",\n { id: couponId, percent_off: percentOffBps / 100, duration, metadata, ...expansion,\n ...(productId ? { \"applies_to[products][0]\": productId } : {}) }, { idempotencyKey: `chapter-policy-coupon:${couponId}` });\n }\n const coupon = result.body;\n if (!result.ok || !coupon || coupon.id !== couponId || (!resume && coupon.valid !== true) ||\n coupon.livemode !== (input.environment === \"prod\") || coupon.percent_off !== percentOffBps / 100 ||\n coupon.duration !== duration || coupon.amount_off != null ||\n (productId ? !Array.isArray(coupon.applies_to?.products) || coupon.applies_to.products.length !== 1 ||\n coupon.applies_to.products[0] !== productId : coupon.applies_to != null) ||\n !Object.entries(metadata).every(([key, value]) => coupon.metadata?.[key] === value)) fail();\n}\n\n/** Stripe parameters for charging the full initial term while deferring the next annual/monthly invoice. */\nexport function subscriptionBillingParams(input: Contract, productId?: string): Record<string, unknown> {\n if (!input.billingTerms) return {};\n const terms = subscriptionBillingTerms(input.billingTerms);\n if (terms.initialTermEndsAt !== undefined && (!productId || !/^prod_[A-Za-z0-9]+$/.test(productId))) fail();\n return {\n ...(terms.discount ? { \"discounts[0][coupon]\": terms.discount.couponId, \"expand[2]\": \"discounts\" } : {}),\n ...(terms.initialTermEndsAt !== undefined ? {\n trial_end: terms.initialTermEndsAt / 1000,\n \"trial_settings[end_behavior][missing_payment_method]\": \"cancel\",\n \"add_invoice_items[0][price_data][product]\": productId,\n \"add_invoice_items[0][price_data][currency]\": input.currency,\n \"add_invoice_items[0][price_data][unit_amount]\": input.priceCents,\n \"add_invoice_items[0][quantity]\": 1,\n \"add_invoice_items[0][discountable]\": true,\n } : {}),\n };\n}\n\n/** Reject substituted discounts or renewal dates before a client secret is returned. */\nexport function verifySubscriptionBillingResult(sub: Record<string, any>, input: Pick<Contract, \"billingTerms\" | \"priceCents\">): void {\n const terms = input.billingTerms;\n if (terms?.initialTermEndsAt !== undefined) {\n if (sub.trial_end !== terms.initialTermEndsAt / 1000 || sub.billing_cycle_anchor !== terms.initialTermEndsAt / 1000) fail();\n } else if (sub.trial_end != null) fail();\n const discounts = sub.discounts ?? (sub.discount ? [sub.discount] : []);\n if (!Array.isArray(discounts)) fail();\n if (!terms?.discount) { if (discounts.length) fail(); return; }\n if (terms.discount.duration === \"once\" && discounts.length === 0) {\n // Stripe removes a consumed once-only discount from future subscription\n // discounts. Require exact evidence on the initial invoice, not merely a\n // coincidentally correct invoice total or a coupon referenced in metadata.\n const invoice = sub.latest_invoice;\n const applied = invoice?.discounts;\n const amounts = invoice?.total_discount_amounts;\n if (invoice?.billing_reason !== \"subscription_create\" || !Array.isArray(applied) || applied.length !== 1 ||\n !Array.isArray(amounts) || amounts.length !== 1) fail();\n const discount = applied[0];\n const coupon = discount?.source?.coupon ?? discount?.coupon;\n if (typeof discount?.id !== \"string\" || !/^di_[A-Za-z0-9]+$/.test(discount.id) ||\n discount.customer !== sub.customer || discount.subscription !== sub.id ||\n (typeof coupon === \"string\" ? coupon : coupon?.id) !== terms.discount.couponId ||\n amounts[0]?.discount !== discount.id || amounts[0]?.amount !== input.priceCents - subscriptionAmountDue(input)) fail();\n return;\n }\n if (discounts.length !== 1) fail();\n const coupon = discounts[0]?.source?.coupon ?? discounts[0]?.coupon;\n if ((typeof coupon === \"string\" ? coupon : coupon?.id) !== terms.discount.couponId) fail();\n}\n","/** Name this Worker's preferred runtime-scoped webhook secret. Legacy Workers\n * without ODLA_RUNTIME retain the historical fixed slot. */\nexport function stripeWebhookSecretName(runtime?: string): string {\n if (!runtime) return \"stripe_webhook_secret\";\n if (!/^[a-z0-9]{2,12}$/.test(runtime) || runtime === \"prod\" || runtime === \"production\") {\n throw new Error(\"ODLA_RUNTIME is invalid\");\n }\n return `stripe_webhook_secret__${runtime}`;\n}\n\n/** Stable provider partition for deployments that predate ODLA_RUNTIME. */\nexport function stripeRuntimeIdentity(runtime?: string): string {\n return runtime || \"default\";\n}\n\n/** Non-PII metadata attached to every Chapter-owned Stripe object. */\nexport function stripePartitionMetadata(input: {\n appId: string;\n chapterId: string;\n environment: string;\n runtime?: string;\n}): Record<string, string> {\n return {\n odlaAppId: input.appId,\n odlaEnvironment: input.environment,\n odlaDataEnvironment: input.environment,\n odlaRuntime: stripeRuntimeIdentity(input.runtime),\n chapterId: input.chapterId,\n };\n}\n","import { subscriptionAmountDue, subscriptionBillingTerms, type SubscriptionBillingTerms } from \"./subscription-billing-terms\";\n\ntype Row = Record<string, unknown>;\n\n/** Bounded recurring-price evidence for renewals. Unknown, one-off, or prorated lines fail closed. */\nexport function membershipRecurringInvoiceLines(invoice: Row): Array<{ priceId: string; quantity: number; startsAt: number; endsAt: number }> | undefined {\n const lines = invoice.lines as Row | undefined, data = lines?.data;\n if (!Array.isArray(data) || lines?.has_more === true || data.length < 1 || data.length > 2) return undefined;\n const result: Array<{ priceId: string; quantity: number; startsAt: number; endsAt: number }> = [];\n for (const value of data) {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const line = value as Row, parent = line.parent as Row | undefined;\n const details = parent?.subscription_item_details as Row | undefined;\n if ((line.type !== \"subscription\" && parent?.type !== \"subscription_item_details\") ||\n line.proration === true || details?.proration === true) return undefined;\n const price = typeof line.price === \"string\" ? line.price : (line.price as Row | undefined)?.id ??\n ((line.pricing as Row | undefined)?.price_details as Row | undefined)?.price;\n const period = line.period as Row | undefined;\n if (typeof price !== \"string\" || !/^price_[A-Za-z0-9_]+$/.test(price) || line.quantity !== 1 ||\n !Number.isSafeInteger(period?.start) || !Number.isSafeInteger(period?.end) ||\n Number(period?.start) <= 0 || Number(period?.end) <= Number(period?.start)) return undefined;\n result.push({ priceId: price, quantity: 1, startsAt: Number(period!.start) * 1000, endsAt: Number(period!.end) * 1000 });\n }\n if (!result.every(line => line.startsAt === result[0]!.startsAt && line.endsAt === result[0]!.endsAt) ||\n new Set(result.map(line => line.priceId)).size !== result.length) return undefined;\n return result;\n}\n\n/** Provider evidence retained from a signed initial invoice, not browser success. */\nexport interface MembershipInvoiceEvidence {\n invoiceId?: string;\n subscriptionId?: string;\n customerId?: string;\n currency?: string;\n total?: number;\n amountPaid?: number;\n status?: string;\n}\n\n/** Ignore one-time invoice items and ambiguous/prorated subscription periods. */\nexport function membershipInvoicePeriodEnd(invoice: Row): number | undefined {\n const raw = (invoice.lines as Row | undefined)?.data;\n if (!Array.isArray(raw) || (invoice.lines as Row).has_more === true ||\n raw.some((line) => !line || typeof line !== \"object\" || Array.isArray(line))) return undefined;\n const recurring = raw.filter((line: Row) => line.type === \"subscription\" ||\n (line.parent as Row | undefined)?.type === \"subscription_item_details\");\n // Old API fixtures can omit line type. Only an untyped single line is safe\n // to interpret; a known invoice item must never become a renewal date.\n const candidates = recurring.length ? recurring : raw.length === 1 && !raw[0].type && !raw[0].parent ? raw : [];\n if (!candidates.length) return undefined;\n const ends = candidates.map((line: Row) => {\n const details = (line.parent as Row | undefined)?.subscription_item_details as Row | undefined;\n if (line.proration === true || details?.proration === true) return undefined;\n const end = (line.period as Row | undefined)?.end;\n return Number.isSafeInteger(end) && Number(end) > 0 ? Number(end) * 1000 : undefined;\n });\n // A primary plus named seat is unambiguous only when every recurring item co-terminates.\n return ends.every(end => end !== undefined && end === ends[0]) ? ends[0] : undefined;\n}\n\n/** Extract legacy and current Stripe invoice ownership shapes. */\nexport function membershipInvoiceEvidence(invoice: Row): MembershipInvoiceEvidence {\n const details = (invoice.parent as Row | undefined)?.subscription_details as Row | undefined;\n const subscription = invoice.subscription ?? details?.subscription;\n return {\n ...(typeof invoice.id === \"string\" ? { invoiceId: invoice.id } : {}),\n ...(typeof subscription === \"string\" ? { subscriptionId: subscription } : {}),\n ...(typeof invoice.customer === \"string\" ? { customerId: invoice.customer } : {}),\n ...(typeof invoice.currency === \"string\" ? { currency: invoice.currency } : {}),\n ...(typeof invoice.total === \"number\" ? { total: invoice.total } : {}),\n ...(typeof invoice.amount_paid === \"number\" ? { amountPaid: invoice.amount_paid } : {}),\n ...(typeof invoice.status === \"string\" ? { status: invoice.status } : {}),\n };\n}\n\n/** Reconcile a signed first invoice with the already persisted checkout. */\nexport function verifyInitialMembershipInvoice(intent: Row, evidence?: MembershipInvoiceEvidence):\n { status: \"verified\"; renewalAt?: number } | { status: \"retry\" } | { status: \"mismatch\" } {\n // Provider success can race the ready transaction. Ask Stripe to retry;\n // never permanently quarantine this recoverable ordering.\n if (!intent.providerSubscriptionId || !intent.providerCustomerId) return { status: \"retry\" };\n try {\n const terms = intent.billingTerms ? subscriptionBillingTerms(intent.billingTerms as SubscriptionBillingTerms) : undefined;\n const due = subscriptionAmountDue({ priceCents: Number(intent.priceCents), billingTerms: terms });\n if (!evidence || !/^in_[A-Za-z0-9]+$/.test(evidence.invoiceId ?? \"\") ||\n evidence.subscriptionId !== intent.providerSubscriptionId || evidence.customerId !== intent.providerCustomerId ||\n evidence.currency !== intent.currency || evidence.total !== due || evidence.amountPaid !== due ||\n due <= 0 || evidence.status !== \"paid\") return { status: \"mismatch\" };\n return { status: \"verified\", ...(terms?.initialTermEndsAt ? { renewalAt: terms.initialTermEndsAt } : {}) };\n } catch { return { status: \"mismatch\" }; }\n}\n","import { networkCommercialSourceKey } from \"./config-network-commercial\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\nimport { membershipInvoicePeriodEnd, membershipRecurringInvoiceLines } from \"./membership-invoice-evidence\";\nimport type { CommercialIdentity, NetworkCommercialException, NetworkCommercialFact, NetworkCommercialProjectedRow, NetworkCommercialProjection } from \"./types-network-commercial-projection\";\n\ntype Raw = Record<string, unknown>;\nconst raw = (value: unknown): Raw => value && typeof value === \"object\" && !Array.isArray(value) ? value as Raw : {};\nconst text = (value: unknown): string | undefined => typeof value === \"string\" && value.length > 0 && value.length <= 255 ? value : undefined;\nconst integer = (value: unknown): number | undefined => typeof value === \"number\" && Number.isSafeInteger(value) ? value : undefined;\nconst bool = (value: unknown): boolean | undefined => typeof value === \"boolean\" ? value : undefined;\nconst providerId = (value: unknown, prefix?: string): string | undefined => {\n const valueText = text(value);\n return valueText && (!prefix || valueText.startsWith(prefix)) ? valueText : undefined;\n};\n\nfunction metadataCandidates(object: Raw): Raw[] {\n const parent = raw(object.parent);\n const subscriptionDetails = raw(object.subscription_details);\n const parentSubscription = raw(parent.subscription_details);\n return [raw(object.metadata), raw(subscriptionDetails.metadata), raw(parentSubscription.metadata)];\n}\n\nfunction metadataValue(candidates: Raw[], key: string): string | undefined {\n return candidates.map((candidate) => text(candidate[key])).find(Boolean);\n}\n\nfunction refId(value: unknown, prefix: string): string | undefined {\n if (typeof value === \"string\") return providerId(value, prefix);\n return providerId(raw(value).id, prefix);\n}\n\nfunction subscriptionRef(object: Raw): string | undefined {\n return refId(object.subscription, \"sub_\")\n ?? refId(raw(object.subscription_details).subscription, \"sub_\")\n ?? refId(raw(raw(object.parent).subscription_details).subscription, \"sub_\");\n}\n\nfunction firstPrice(object: Raw): { priceId?: string; quantity?: number } {\n const data = raw(object.items).data;\n const item = Array.isArray(data) ? raw(data[0]) : {};\n const priceId = refId(item.price, \"price_\");\n const quantity = integer(item.quantity);\n return { ...(priceId ? { priceId } : {}), ...(quantity !== undefined ? { quantity } : {}) };\n}\n\n/** Reduce a verified Stripe event to a bounded, PII-free fact. */\nexport function normalizeNetworkCommercialStripeEvent(input: unknown, digest: string): NetworkCommercialFact {\n const event = raw(input);\n const eventId = providerId(event.id, \"evt_\") ?? \"\";\n const eventType = text(event.type) ?? \"\";\n const object = raw(raw(event.data).object);\n const objectId = providerId(object.id) ?? \"\";\n const candidates = metadataCandidates(object);\n const identity: CommercialIdentity = {};\n const identityKeys = {\n appId: \"odlaAppId\", chapterId: \"chapterId\", environment: \"odlaEnvironment\",\n dataEnvironment: \"odlaDataEnvironment\", runtime: \"odlaRuntime\",\n } as const;\n for (const [target, source] of Object.entries(identityKeys)) {\n const value = metadataValue(candidates, source);\n if (value) identity[target as keyof CommercialIdentity] = value;\n }\n let objectKind: NetworkCommercialFact[\"objectKind\"] = \"ignored\";\n if (eventType.startsWith(\"customer.subscription.\")) objectKind = \"subscription\";\n else if (eventType.startsWith(\"customer.\")) objectKind = \"customer\";\n else if (eventType.startsWith(\"invoice.\")) objectKind = \"invoice\";\n else if (eventType.startsWith(\"refund.\")) objectKind = \"refund\";\n else if (eventType === \"charge.refunded\") objectKind = \"refund\";\n else if (eventType.startsWith(\"payment_intent.\")) objectKind = \"payment_intent\";\n\n const customerId = refId(object.customer, \"cus_\");\n const subscriptionId = objectKind === \"subscription\" ? providerId(objectId, \"sub_\") : subscriptionRef(object);\n const invoiceId = objectKind === \"invoice\" ? providerId(objectId, \"in_\") : refId(object.invoice, \"in_\");\n const chargeId = eventType === \"charge.refunded\" ? providerId(objectId, \"ch_\") : refId(object.charge, \"ch_\");\n const paymentIntentId = objectKind === \"payment_intent\" ? providerId(objectId, \"pi_\") : refId(object.payment_intent, \"pi_\");\n const price = firstPrice(object);\n const amountCents = integer(eventType === \"charge.refunded\" ? object.amount_refunded : object.amount);\n const currency = text(object.currency)?.toLowerCase();\n const status = text(object.status);\n return {\n eventId, digest, eventType, eventCreated: integer(event.created) ?? 0,\n livemode: event.livemode === true, objectKind, objectId, identity,\n ...(metadataValue(candidates, \"applicationId\") ? { applicationId: metadataValue(candidates, \"applicationId\") } : {}),\n ...(metadataValue(candidates, \"personId\") ? { personId: metadataValue(candidates, \"personId\") } : {}),\n ...(metadataValue(candidates, \"membershipId\") ? { membershipId: metadataValue(candidates, \"membershipId\") } : {}),\n ...(metadataValue(candidates, \"seatId\") ? { seatId: metadataValue(candidates, \"seatId\") } : {}),\n ...(customerId ? { customerId } : {}), ...(subscriptionId ? { subscriptionId } : {}),\n ...(invoiceId ? { invoiceId } : {}), ...(chargeId ? { chargeId } : {}),\n ...(paymentIntentId ? { paymentIntentId } : {}), ...price,\n ...(status ? { status } : {}), ...(currency ? { currency } : {}),\n ...(amountCents !== undefined ? { amountCents } : {}),\n ...(integer(object.amount_paid) !== undefined ? { amountPaidCents: integer(object.amount_paid) } : {}),\n ...(integer(object.amount_received) !== undefined ? { amountReceivedCents: integer(object.amount_received) } : {}),\n ...(objectKind === \"invoice\" ? {\n ...(integer(object.total) !== undefined ? { invoiceTotalCents: integer(object.total) } : {}),\n ...(text(object.billing_reason) ? { billingReason: text(object.billing_reason) } : {}),\n ...(integer(raw(object.status_transitions).paid_at) !== undefined ? { invoicePaidAt: Number(raw(object.status_transitions).paid_at) * 1000 } : {}),\n ...(membershipInvoicePeriodEnd(object) !== undefined ? { invoicePeriodEndsAt: membershipInvoicePeriodEnd(object) } : {}),\n ...(membershipRecurringInvoiceLines(object) ? { recurringInvoiceLines: membershipRecurringInvoiceLines(object) } : {}),\n } : {}),\n ...(integer(object.amount_remaining) !== undefined ? { amountRemainingCents: integer(object.amount_remaining) } : {}),\n ...(integer(object.current_period_start) !== undefined ? { currentPeriodStart: integer(object.current_period_start) } : {}),\n ...(integer(object.current_period_end) !== undefined ? { currentPeriodEnd: integer(object.current_period_end) } : {}),\n ...(bool(object.cancel_at_period_end) !== undefined ? { cancelAtPeriodEnd: bool(object.cancel_at_period_end) } : {}),\n };\n}\n\nconst identityFields = [\"appId\", \"chapterId\", \"environment\", \"dataEnvironment\", \"runtime\"] as const;\nfunction directSource(fact: NetworkCommercialFact, sources: readonly NetworkCommercialSource[]): NetworkCommercialSource | null | \"wrong\" {\n const mode = fact.livemode ? \"live\" : \"test\";\n const supplied = identityFields.filter((field) => fact.identity[field] !== undefined);\n const candidates = sources.filter((source) => source.stripeMode === mode && supplied.every((field) => source[field] === fact.identity[field]));\n if (supplied.length === identityFields.length) return candidates.length === 1 ? candidates[0]! : \"wrong\";\n if (supplied.length > 0 && candidates.length === 0) return \"wrong\";\n return null;\n}\n\nconst objectRefs = (fact: NetworkCommercialFact): string[] => [\n fact.customerId && `customer:${fact.customerId}`, fact.subscriptionId && `subscription:${fact.subscriptionId}`,\n fact.invoiceId && `invoice:${fact.invoiceId}`, fact.chargeId && `charge:${fact.chargeId}`,\n fact.paymentIntentId && `payment_intent:${fact.paymentIntentId}`,\n].filter((value): value is string => Boolean(value));\n\nfunction ownRef(fact: NetworkCommercialFact): string | null {\n if (!fact.objectId) return null;\n if (fact.objectKind === \"customer\") return `customer:${fact.objectId}`;\n if (fact.objectKind === \"subscription\") return `subscription:${fact.objectId}`;\n if (fact.objectKind === \"invoice\") return `invoice:${fact.objectId}`;\n if (fact.objectKind === \"payment_intent\") return `payment_intent:${fact.objectId}`;\n if (fact.eventType.startsWith(\"refund.\")) return `refund:${fact.objectId}`;\n return fact.eventType === \"charge.refunded\" ? `charge:${fact.objectId}` : null;\n}\n\nconst order = (left: NetworkCommercialFact, right: NetworkCommercialFact) =>\n left.eventCreated - right.eventCreated || left.eventId.localeCompare(right.eventId);\n\n/** Deterministically rebuild the network commercial projection from its event log. */\nexport function projectNetworkCommercialEvents(\n input: readonly NetworkCommercialFact[], sources: readonly NetworkCommercialSource[],\n): NetworkCommercialProjection {\n const facts = [...input].sort(order);\n const exceptions: NetworkCommercialException[] = [];\n const unique: NetworkCommercialFact[] = [];\n const digests = new Map<string, string>();\n for (const fact of facts) {\n const prior = digests.get(fact.eventId);\n if (prior === undefined) { digests.set(fact.eventId, fact.digest); unique.push(fact); }\n else if (prior !== fact.digest) exceptions.push({ eventId: fact.eventId, kind: \"collision\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n }\n const assignments = new Map<string, NetworkCommercialSource>();\n const refs = new Map<string, Set<string>>();\n for (const fact of unique) {\n const direct = directSource(fact, sources);\n if (direct && direct !== \"wrong\") assignments.set(fact.eventId, direct);\n }\n let changed = true;\n while (changed) {\n changed = false;\n for (const fact of unique) {\n const assigned = assignments.get(fact.eventId);\n if (assigned) {\n const key = networkCommercialSourceKey(assigned);\n for (const ref of [...objectRefs(fact), ownRef(fact)].filter((value): value is string => Boolean(value))) {\n const keys = refs.get(ref) ?? new Set<string>();\n const before = keys.size;\n keys.add(key); refs.set(ref, keys);\n if (keys.size !== before) changed = true;\n }\n continue;\n }\n if (directSource(fact, sources) === \"wrong\") continue;\n const keys = new Set(objectRefs(fact).flatMap((ref) => [...(refs.get(ref) ?? [])]));\n if (keys.size !== 1) continue;\n const candidate = sources.find((source) => networkCommercialSourceKey(source) === [...keys][0]);\n if (candidate && directSource({ ...fact, identity: fact.identity }, [candidate]) !== \"wrong\") {\n assignments.set(fact.eventId, candidate); changed = true;\n }\n }\n }\n const latest = new Map<string, NetworkCommercialProjectedRow>();\n for (const fact of unique) {\n if (fact.objectKind === \"ignored\" || !fact.eventId || !fact.objectId) {\n exceptions.push({ eventId: fact.eventId, kind: \"unsupported\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n continue;\n }\n const source = assignments.get(fact.eventId);\n if (!source) {\n const direct = directSource(fact, sources);\n const keys = new Set(objectRefs(fact).flatMap((ref) => [...(refs.get(ref) ?? [])]));\n exceptions.push({ eventId: fact.eventId, kind: direct === \"wrong\" ? \"wrong_partition\" : keys.size > 1 ? \"ambiguous_partition\" : \"unmatched_partition\", detail: { eventType: fact.eventType, objectId: fact.objectId } });\n continue;\n }\n const row = { ...fact, sourceKey: networkCommercialSourceKey(source) };\n const key = `${fact.objectKind}:${fact.objectId}`;\n const prior = latest.get(key);\n if (!prior || order(prior, fact) <= 0) latest.set(key, row);\n }\n const rows = [...latest.values()];\n const customers = rows.filter((row) => row.objectKind === \"customer\");\n const subscriptions = rows.filter((row) => row.objectKind === \"subscription\");\n const invoices = rows.filter((row) => row.objectKind === \"invoice\");\n const seatPayments = rows.filter(row => row.objectKind === \"payment_intent\" && row.seatId && row.membershipId && !row.invoiceId);\n const refunds = rows.filter((row) => row.objectKind === \"refund\" && row.eventType.startsWith(\"refund.\"));\n for (const charge of rows.filter((row) => row.eventType === \"charge.refunded\")) {\n if (!refunds.some((refund) => refund.chargeId === charge.objectId)) {\n exceptions.push({ eventId: charge.eventId, kind: \"charge_refund_without_refund_object\", sourceKey: charge.sourceKey, detail: { eventType: charge.eventType, objectId: charge.objectId } });\n }\n }\n const totalsMap = new Map<string, { sourceKey: string; currency: string; paidCents: number; refundedCents: number; netCents: number }>();\n const add = (row: NetworkCommercialProjectedRow, field: \"paidCents\" | \"refundedCents\", amount: number) => {\n if (!row.currency) return;\n const key = `${row.sourceKey}:${row.currency}`;\n const total = totalsMap.get(key) ?? { sourceKey: row.sourceKey, currency: row.currency, paidCents: 0, refundedCents: 0, netCents: 0 };\n total[field] += amount; total.netCents = total.paidCents - total.refundedCents; totalsMap.set(key, total);\n };\n for (const row of invoices) add(row, \"paidCents\", row.amountPaidCents ?? 0);\n for (const row of seatPayments) add(row, \"paidCents\", row.amountReceivedCents ?? 0);\n for (const row of refunds) add(row, \"refundedCents\", row.amountCents ?? 0);\n return { ...(seatPayments.length ? { seatPayments } : {}), customers, subscriptions, invoices, refunds, exceptions,\n totals: [...totalsMap.values()].sort((a, b) => `${a.sourceKey}:${a.currency}`.localeCompare(`${b.sourceKey}:${b.currency}`)) };\n}\n","import type { StripeClient } from \"@odla-ai/stripe\";\nimport { normalizeNetworkCommercialStripeEvent, projectNetworkCommercialEvents } from \"./network-commercial\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\nimport type { NetworkCommercialProjectedRow, NetworkCommercialProjection } from \"./types-network-commercial-projection\";\n\ntype Raw = Record<string, unknown>;\n\ninterface ProviderPage { data?: unknown; has_more?: unknown }\n\nexport interface StripeObjectSnapshot {\n objects: Raw[];\n complete: boolean;\n}\n\nexport interface StripeCommercialReconciliation {\n ok: boolean;\n complete: boolean;\n ignoredObjects: number;\n exceptions: Array<{\n kind: \"missing_from_stripe\" | \"missing_from_shadow\" | \"object_mismatch\" | \"totals_mismatch\" | \"stripe_snapshot_truncated\";\n sourceKey?: string;\n objectKind?: string;\n providerId?: string;\n detail: Record<string, unknown>;\n }>;\n stripeTotals: NetworkCommercialProjection[\"totals\"];\n}\n\nconst asRaw = (value: unknown): Raw | null =>\n value && typeof value === \"object\" && !Array.isArray(value) ? value as Raw : null;\n\n/** Read a bounded current-object snapshot through the typed Stripe client. */\nexport async function listStripeObjects(\n client: StripeClient,\n path: string,\n params: Record<string, unknown> = {},\n maxPages = 20,\n): Promise<StripeObjectSnapshot> {\n const objects: Raw[] = [];\n let startingAfter: string | undefined;\n for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {\n const page = await client.request<ProviderPage>(\"GET\", path, {\n ...params, limit: 100, ...(startingAfter ? { starting_after: startingAfter } : {}),\n });\n if (!Array.isArray(page.data) || typeof page.has_more !== \"boolean\") {\n throw new Error(\"Stripe returned an invalid commercial list response\");\n }\n const rows = page.data.map(asRaw).filter((row): row is Raw => row !== null);\n if (rows.length !== page.data.length) throw new Error(\"Stripe returned a malformed commercial object\");\n objects.push(...rows);\n if (!page.has_more) return { objects, complete: true };\n const cursor = rows.at(-1)?.id;\n if (typeof cursor !== \"string\" || !cursor) throw new Error(\"Stripe pagination did not provide a cursor\");\n startingAfter = cursor;\n }\n return { objects, complete: false };\n}\n\nfunction facts(\n snapshots: { customers: StripeObjectSnapshot; subscriptions: StripeObjectSnapshot; invoices: StripeObjectSnapshot; refunds: StripeObjectSnapshot; payments?: StripeObjectSnapshot },\n) {\n const groups = [\n [\"customer.updated\", snapshots.customers.objects],\n [\"customer.subscription.updated\", snapshots.subscriptions.objects],\n [\"invoice.updated\", snapshots.invoices.objects],\n [\"refund.updated\", snapshots.refunds.objects],\n [\"payment_intent.updated\", snapshots.payments?.objects ?? []],\n ] as const;\n return groups.flatMap(([eventType, objects]) => objects.map((object) => {\n const id = typeof object.id === \"string\" ? object.id : \"invalid\";\n return normalizeNetworkCommercialStripeEvent({\n id: `evt_snapshot_${eventType.replaceAll(\".\", \"_\")}_${id}`,\n type: eventType,\n created: typeof object.created === \"number\" ? object.created : 0,\n livemode: object.livemode === true,\n data: { object },\n }, `stripe-snapshot:${eventType}:${id}`);\n }));\n}\n\nconst selected = (row: NetworkCommercialProjectedRow) => ({\n status: row.status ?? null,\n currency: row.currency ?? null,\n amountCents: row.amountCents ?? null,\n amountPaidCents: row.amountPaidCents ?? null,\n amountReceivedCents: row.amountReceivedCents ?? null,\n seatId: row.seatId ?? null,\n amountRemainingCents: row.amountRemainingCents ?? null,\n customerId: row.customerId ?? null,\n subscriptionId: row.subscriptionId ?? null,\n invoiceId: row.invoiceId ?? null,\n priceId: row.priceId ?? null,\n quantity: row.quantity ?? null,\n applicationId: row.applicationId ?? null,\n personId: row.personId ?? null,\n membershipId: row.membershipId ?? null,\n currentPeriodStart: row.currentPeriodStart ?? null,\n currentPeriodEnd: row.currentPeriodEnd ?? null,\n cancelAtPeriodEnd: row.cancelAtPeriodEnd ?? null,\n});\n\nconst index = (projection: NetworkCommercialProjection) => new Map(\n ([...projection.customers, ...projection.subscriptions, ...projection.invoices, ...projection.refunds, ...(projection.seatPayments ?? [])])\n .map((row) => [`${row.sourceKey}:${row.objectKind}:${row.objectId}`, row]),\n);\n\n/** Compare the event shadow with an independent current-object Stripe read. */\nexport function reconcileStripeSnapshot(\n shadow: NetworkCommercialProjection,\n snapshots: { customers: StripeObjectSnapshot; subscriptions: StripeObjectSnapshot; invoices: StripeObjectSnapshot; refunds: StripeObjectSnapshot; payments?: StripeObjectSnapshot },\n sources: readonly NetworkCommercialSource[],\n): StripeCommercialReconciliation {\n const stripe = projectNetworkCommercialEvents(facts(snapshots), sources);\n const shadowRows = index(shadow);\n const stripeRows = index(stripe);\n const exceptions: StripeCommercialReconciliation[\"exceptions\"] = [];\n const complete = Object.values(snapshots).every((snapshot) => snapshot.complete);\n if (!complete) exceptions.push({ kind: \"stripe_snapshot_truncated\", detail: {} });\n for (const [key, row] of shadowRows) {\n const other = stripeRows.get(key);\n if (!other) {\n exceptions.push({ kind: \"missing_from_stripe\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: {} });\n } else if (JSON.stringify(selected(row)) !== JSON.stringify(selected(other))) {\n exceptions.push({ kind: \"object_mismatch\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: { shadow: selected(row), stripe: selected(other) } });\n }\n }\n for (const [key, row] of stripeRows) {\n if (!shadowRows.has(key)) exceptions.push({ kind: \"missing_from_shadow\", sourceKey: row.sourceKey, objectKind: row.objectKind, providerId: row.objectId, detail: {} });\n }\n if (JSON.stringify(shadow.totals) !== JSON.stringify(stripe.totals)) {\n exceptions.push({ kind: \"totals_mismatch\", detail: { shadow: shadow.totals, stripe: stripe.totals } });\n }\n return {\n ok: exceptions.length === 0,\n complete,\n ignoredObjects: stripe.exceptions.filter((item) => item.kind === \"wrong_partition\" || item.kind === \"unmatched_partition\").length,\n exceptions,\n stripeTotals: stripe.totals,\n };\n}\n","import { networkCommercialSourceKey } from \"./config-network-commercial\";\nimport type { NetworkCommercialProjection } from \"./types-network-commercial-projection\";\nimport type { NetworkCommercialSource } from \"./types-network-commercial\";\n\ntype Row = Record<string, unknown>;\n\n/** Exact chapter/runtime partition that binds every parity digest. */\nexport interface CommercialParityPartition {\n appId: string;\n chapterId: string;\n environment: string;\n dataEnvironment: string;\n runtime: string;\n}\n\n/** PII-free chapter membership identity and lifecycle disclosure. */\nexport interface ChapterCommercialParityRecord {\n applicationDigest: string;\n customerDigest: string | null;\n subscriptionDigest: string | null;\n status: string | null;\n canceled: boolean;\n}\n\n/** Bounded, signed-response payload produced by an opted-in chapter. */\nexport interface ChapterCommercialParitySnapshot {\n version: 1;\n site: { id: string };\n partition: CommercialParityPartition;\n generatedAt: number;\n complete: boolean;\n truncated: boolean;\n counts: { scanned: number; eligible: number; returned: number };\n records: ChapterCommercialParityRecord[];\n}\n\n/** Reconciliation exception categories that never expose raw identifiers. */\nexport type CommercialParityExceptionKind =\n | \"chapter_only\"\n | \"shadow_only\"\n | \"cancellation_mismatch\"\n | \"chapter_truncated\"\n | \"count_mismatch\";\n\n/** One privacy-preserving mismatch between a chapter and its Stripe shadow. */\nexport interface CommercialParityException {\n kind: CommercialParityExceptionKind;\n applicationDigest?: string;\n detail: Record<string, string | number | boolean | null>;\n}\n\n/** Read-only result of comparing one chapter snapshot with one exact shadow partition. */\nexport interface CommercialParityResult {\n ok: boolean;\n complete: boolean;\n counts: { chapter: number; shadow: number; matched: number };\n records: Array<ChapterCommercialParityRecord & {\n stripeStatus: string | null;\n stripeCanceled: boolean;\n }>;\n exceptions: CommercialParityException[];\n}\n\nconst DIGEST = /^[0-9a-f]{64}$/;\nconst MAX_RECORDS = 500;\nconst text = (value: unknown, max = 255): string | null =>\n typeof value === \"string\" && value.length > 0 && value.length <= max ? value : null;\n\nfunction parityMessage(partition: CommercialParityPartition, kind: string, value: string): string {\n return [\n \"chapter-commercial-parity\", \"v1\", partition.appId, partition.chapterId,\n partition.environment, partition.dataEnvironment, partition.runtime, kind, value,\n ].join(\"\\u001f\");\n}\n\n/** Import the edge secret once so a bounded snapshot does not repeat key setup. */\nasync function parityKey(secret: string): Promise<CryptoKey> {\n const encoder = new TextEncoder();\n return crypto.subtle.importKey(\n \"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"],\n );\n}\n\nasync function digestWithKey(\n key: CryptoKey,\n partition: CommercialParityPartition,\n kind: \"application\" | \"customer\" | \"subscription\",\n value: string,\n): Promise<string> {\n const encoder = new TextEncoder();\n const signed = await crypto.subtle.sign(\"HMAC\", key, encoder.encode(parityMessage(partition, kind, value)));\n return [...new Uint8Array(signed)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/** Edge-keyed, domain-separated digest. Raw identifiers never enter a response. */\nexport async function commercialParityDigest(\n secret: string,\n partition: CommercialParityPartition,\n kind: \"application\" | \"customer\" | \"subscription\",\n value: string,\n): Promise<string> {\n return digestWithKey(await parityKey(secret), partition, kind, value);\n}\n\n/** Build the bounded disclosure from already-bounded local application rows. */\nexport async function buildChapterCommercialParitySnapshot(input: {\n rows: readonly Row[];\n secret: string;\n partition: CommercialParityPartition;\n siteId: string;\n scanned: number;\n scanTruncated: boolean;\n maxRecords?: number;\n now?: number;\n}): Promise<ChapterCommercialParitySnapshot> {\n const requestedMax = input.maxRecords ?? MAX_RECORDS;\n const maxRecords = Number.isSafeInteger(requestedMax)\n ? Math.max(0, Math.min(requestedMax, MAX_RECORDS))\n : MAX_RECORDS;\n const eligible = input.rows.filter((row) =>\n text(row.id) && (text(row.stripeCustomerId) || text(row.stripeSubscriptionId)));\n const selected = eligible.slice(0, maxRecords);\n const key = await parityKey(input.secret);\n const records = await Promise.all(selected.map(async (row): Promise<ChapterCommercialParityRecord> => {\n const applicationId = text(row.id)!;\n const customerId = text(row.stripeCustomerId);\n const subscriptionId = text(row.stripeSubscriptionId);\n return {\n applicationDigest: await digestWithKey(key, input.partition, \"application\", applicationId),\n customerDigest: customerId\n ? await digestWithKey(key, input.partition, \"customer\", customerId)\n : null,\n subscriptionDigest: subscriptionId\n ? await digestWithKey(key, input.partition, \"subscription\", subscriptionId)\n : null,\n status: text(row.status, 64),\n canceled: row.canceled === true,\n };\n }));\n records.sort((left, right) => left.applicationDigest.localeCompare(right.applicationDigest));\n const truncated = input.scanTruncated || eligible.length > maxRecords;\n return {\n version: 1,\n site: { id: input.siteId },\n partition: input.partition,\n generatedAt: input.now ?? Date.now(),\n complete: !truncated,\n truncated,\n counts: { scanned: input.scanned, eligible: eligible.length, returned: records.length },\n records,\n };\n}\n\nfunction recordKey(record: Pick<ChapterCommercialParityRecord, \"applicationDigest\" | \"customerDigest\" | \"subscriptionDigest\">): string {\n return `${record.applicationDigest}:${record.customerDigest ?? \"-\"}:${record.subscriptionDigest ?? \"-\"}`;\n}\n\nfunction validSnapshot(snapshot: ChapterCommercialParitySnapshot, source: NetworkCommercialSource): boolean {\n const partition = snapshot?.partition;\n const records = snapshot?.records;\n if (\n snapshot?.version !== 1 || snapshot.site?.id !== source.chapterId || !partition || !Array.isArray(records) ||\n records.length > MAX_RECORDS ||\n partition.appId !== source.appId || partition.chapterId !== source.chapterId ||\n partition.environment !== source.environment || partition.dataEnvironment !== source.dataEnvironment ||\n partition.runtime !== source.runtime || typeof snapshot.complete !== \"boolean\" ||\n typeof snapshot.truncated !== \"boolean\" || !snapshot.counts\n ) return false;\n const seen = new Set<string>();\n for (const record of records) {\n if (\n !DIGEST.test(record.applicationDigest) ||\n (record.customerDigest !== null && !DIGEST.test(record.customerDigest)) ||\n (record.subscriptionDigest !== null && !DIGEST.test(record.subscriptionDigest)) ||\n (record.status !== null && text(record.status, 64) === null) ||\n typeof record.canceled !== \"boolean\"\n ) return false;\n const key = recordKey(record);\n if (seen.has(key)) return false;\n seen.add(key);\n }\n return Number.isSafeInteger(snapshot.counts.scanned) && Number.isSafeInteger(snapshot.counts.eligible) &&\n Number.isSafeInteger(snapshot.counts.returned) && snapshot.counts.returned === records.length &&\n snapshot.counts.scanned >= snapshot.counts.eligible && snapshot.counts.eligible >= snapshot.counts.returned;\n}\n\n/** Compare one follower disclosure to the matching Stripe shadow partition. */\nexport async function reconcileCommercialParitySnapshot(input: {\n projection: NetworkCommercialProjection;\n source: NetworkCommercialSource;\n snapshot: ChapterCommercialParitySnapshot;\n secret: string;\n}): Promise<CommercialParityResult> {\n if (!validSnapshot(input.snapshot, input.source)) throw new Error(\"invalid chapter commercial parity snapshot\");\n const sourceKey = networkCommercialSourceKey(input.source);\n const key = await parityKey(input.secret);\n const shadow = await Promise.all(input.projection.subscriptions\n .filter((row) => row.sourceKey === sourceKey && text(row.applicationId) && text(row.objectId))\n .map(async (row): Promise<ChapterCommercialParityRecord & { stripeStatus: string | null; stripeCanceled: boolean }> => {\n const customerId = text(row.customerId);\n const subscriptionId = text(row.subscriptionId) ?? text(row.objectId);\n return {\n applicationDigest: await digestWithKey(key, input.snapshot.partition, \"application\", row.applicationId!),\n customerDigest: customerId\n ? await digestWithKey(key, input.snapshot.partition, \"customer\", customerId)\n : null,\n subscriptionDigest: subscriptionId\n ? await digestWithKey(key, input.snapshot.partition, \"subscription\", subscriptionId)\n : null,\n status: null,\n canceled: false,\n stripeStatus: text(row.status, 64),\n stripeCanceled: row.status === \"canceled\",\n };\n }));\n const chapterByKey = new Map(input.snapshot.records.map((record) => [recordKey(record), record]));\n const shadowByKey = new Map(shadow.map((record) => [recordKey(record), record]));\n const exceptions: CommercialParityException[] = [];\n const records: CommercialParityResult[\"records\"] = [];\n for (const [key, chapter] of chapterByKey) {\n const stripe = shadowByKey.get(key);\n if (!stripe) {\n exceptions.push({ kind: \"chapter_only\", applicationDigest: chapter.applicationDigest, detail: { chapterStatus: chapter.status } });\n continue;\n }\n const compared = { ...chapter, stripeStatus: stripe.stripeStatus, stripeCanceled: stripe.stripeCanceled };\n records.push(compared);\n if (chapter.canceled !== stripe.stripeCanceled) {\n exceptions.push({\n kind: \"cancellation_mismatch\",\n applicationDigest: chapter.applicationDigest,\n detail: { chapterCanceled: chapter.canceled, stripeCanceled: stripe.stripeCanceled },\n });\n }\n }\n for (const [key, stripe] of shadowByKey) {\n if (!chapterByKey.has(key)) {\n exceptions.push({ kind: \"shadow_only\", applicationDigest: stripe.applicationDigest, detail: { stripeStatus: stripe.stripeStatus } });\n }\n }\n if (!input.snapshot.complete || input.snapshot.truncated) {\n exceptions.push({\n kind: \"chapter_truncated\",\n detail: { scanned: input.snapshot.counts.scanned, eligible: input.snapshot.counts.eligible, returned: input.snapshot.counts.returned },\n });\n }\n if (chapterByKey.size !== shadowByKey.size) {\n exceptions.push({ kind: \"count_mismatch\", detail: { chapter: chapterByKey.size, shadow: shadowByKey.size } });\n }\n records.sort((left, right) => left.applicationDigest.localeCompare(right.applicationDigest));\n return {\n ok: input.snapshot.complete && exceptions.length === 0,\n complete: input.snapshot.complete,\n counts: { chapter: chapterByKey.size, shadow: shadowByKey.size, matched: records.length },\n records,\n exceptions,\n };\n}\n","// Reusable CRM records for a leader that forms and operates a portfolio of\n// chapters. This is configuration, not a second data engine: every record still\n// uses @odla-ai/crm's normal CRUD, pipelines, activities, views, and relations.\nimport { composeCrmConfigs, type CrmConfig, type TypeDef } from \"@odla-ai/crm\";\nimport { defaultCrm } from \"./defaults\";\n\n/** Options for {@link leaderCrmConfig}. */\nexport interface LeaderCrmOptions {\n /** Existing host CRM config to preserve. Defaults to Chapter's people +\n * businesses graph for hub mode. */\n base?: CrmConfig;\n /** Host-owned additions or replacements for the durable chapter record.\n * Fields and facets merge with the preset; a supplied pipeline replaces the\n * generic proposed/forming/active lifecycle. The final composed CRM still\n * goes through defineCrm's normal validation. */\n chapter?: Partial<TypeDef>;\n}\n\n/**\n * Add generic chapter-formation, portfolio, and deal-flow records to an\n * existing CRM. Collisions fail through `composeCrmConfigs`, so this preset\n * never silently replaces a host's people pipeline or templates.\n */\nexport function leaderCrmConfig(options: LeaderCrmOptions = {}): CrmConfig {\n const base = options.base ?? defaultCrm(\"hub\");\n const defaultChapter: TypeDef = {\n label: \"Chapter\",\n labelPlural: \"Chapters\",\n workspace: \"portfolio\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Name\", required: true },\n slug: { type: \"string\", label: \"Slug\", slot: \"s1\" },\n region: { type: \"string\", label: \"Region\", slot: \"s2\" },\n url: { type: \"url\", label: \"Website\" },\n thesis: { type: \"string\", label: \"Investment thesis\" },\n launchedAt: { type: \"date\", label: \"Launch date\", slot: \"d1\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n pipeline: {\n stages: [\n { id: \"proposed\", label: \"Proposed\" },\n { id: \"forming\", label: \"Forming\" },\n { id: \"active\", label: \"Active\" },\n { id: \"paused\", label: \"Paused\" },\n { id: \"closed\", label: \"Closed\", terminal: true },\n ],\n transitions: {\n proposed: [\"forming\", \"closed\"],\n forming: [\"active\", \"paused\", \"closed\"],\n active: [\"paused\", \"closed\"],\n paused: [\"forming\", \"active\", \"closed\"],\n },\n },\n facets: { rank: \"manual\" },\n };\n const chapterOverride = options.chapter ?? {};\n const chapterType: TypeDef = {\n ...defaultChapter,\n ...chapterOverride,\n fields: {\n ...defaultChapter.fields,\n ...(chapterOverride.fields ?? {}),\n // The preset's natural identity is not optional even when the host adds\n // its own fields or relabels the name input.\n name: {\n ...defaultChapter.fields.name,\n ...(chapterOverride.fields?.name ?? {}),\n type: \"string\",\n required: true,\n },\n },\n facets: {\n ...defaultChapter.facets,\n ...(chapterOverride.facets ?? {}),\n },\n };\n const portfolio: CrmConfig = {\n types: {\n chapter: chapterType,\n chapter_application: {\n label: \"Chapter application\",\n labelPlural: \"Formation applications\",\n workspace: \"portfolio\",\n nameField: \"name\",\n emailField: \"email\",\n fields: {\n name: { type: \"string\", label: \"Applicant name\", required: true },\n email: { type: \"email\", label: \"Email\", required: true },\n location: { type: \"string\", label: \"Location\", required: true, slot: \"s1\" },\n proposedChapter: { type: \"string\", label: \"Proposed chapter\", slot: \"s2\" },\n thesis: { type: \"string\", label: \"Proposed thesis\", required: true },\n experience: { type: \"string\", label: \"Relevant experience\" },\n collaborators: { type: \"json\", label: \"Collaborators\" },\n notes: { type: \"string\", label: \"Internal notes\" },\n },\n pipeline: {\n stages: [\n { id: \"submitted\", label: \"Submitted\" },\n { id: \"reviewing\", label: \"Reviewing\" },\n { id: \"interviewing\", label: \"Interviewing\" },\n { id: \"approved\", label: \"Approved\" },\n { id: \"forming\", label: \"Forming\" },\n { id: \"declined\", label: \"Declined\", terminal: true },\n ],\n transitions: {\n submitted: [\"reviewing\", \"declined\"],\n reviewing: [\"interviewing\", \"approved\", \"declined\"],\n interviewing: [\"approved\", \"declined\"],\n approved: [\"forming\", \"declined\"],\n },\n },\n facets: { email: true, rank: \"manual\" },\n },\n deal: {\n label: \"Deal\",\n labelPlural: \"Deal flow\",\n workspace: \"portfolio\",\n nameField: \"name\",\n fields: {\n name: { type: \"string\", label: \"Company or deal\", required: true },\n chapter: { type: \"string\", label: \"Source chapter\", slot: \"s1\" },\n sector: { type: \"string\", label: \"Sector\", slot: \"s2\" },\n source: { type: \"string\", label: \"Source\", slot: \"s3\" },\n website: { type: \"url\", label: \"Website\" },\n amount: { type: \"number\", label: \"Target amount\", slot: \"n1\" },\n notes: { type: \"string\", label: \"Notes\" },\n },\n pipeline: {\n stages: [\n { id: \"sourced\", label: \"Sourced\" },\n { id: \"screening\", label: \"Screening\" },\n { id: \"diligence\", label: \"Diligence\" },\n { id: \"committee\", label: \"Committee\" },\n { id: \"offered\", label: \"Offered\" },\n { id: \"invested\", label: \"Invested\", terminal: true },\n { id: \"passed\", label: \"Passed\", terminal: true },\n ],\n transitions: {\n sourced: [\"screening\", \"passed\"],\n screening: [\"diligence\", \"committee\", \"passed\"],\n diligence: [\"committee\", \"offered\", \"passed\"],\n committee: [\"offered\", \"passed\"],\n offered: [\"invested\", \"passed\"],\n passed: [\"sourced\"],\n },\n },\n facets: { rank: \"manual\" },\n },\n },\n relations: {\n formation_result: {\n from: \"chapter_application\",\n to: \"chapter\",\n label: \"formed as\",\n reverseLabel: \"formation application\",\n },\n chapter_deal: {\n from: \"deal\",\n to: \"chapter\",\n label: \"sourced by\",\n reverseLabel: \"deal flow\",\n },\n },\n };\n if (base.types.company) {\n portfolio.relations!.deal_company = {\n from: \"deal\",\n to: \"company\",\n label: \"concerns\",\n reverseLabel: \"deals\",\n };\n }\n if (base.types.person) {\n portfolio.relations!.application_contact = {\n from: \"person\",\n to: \"chapter_application\",\n label: \"submitted\",\n reverseLabel: \"applicant\",\n };\n }\n return composeCrmConfigs(base, portfolio);\n}\n","// The CLI-consumable provisioning descriptor. It composes @odla-ai/crm's\n// integration (crm_* namespaces + crm_config seed + route probe) with the\n// chapter's own namespaces and a guarded `groups`-row seed, so a site's\n// odla.config.mjs lists ONE integration. The CLI reads it structurally\n// (matching OdlaIntegration) and merges schema/rules by namespace.\nimport { createCrmIntegration } from \"@odla-ai/crm\";\nimport { buildTierSeeds } from \"./tiers\";\nimport type { Chapter } from \"./types\";\n\n/** Options for {@link createChapterIntegration}. */\nexport interface ChapterIntegrationOptions {\n /** CRM route mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\ninterface IntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\ninterface IntegrationSecret {\n name: string;\n description: string;\n required: boolean;\n}\n\n/** Structural match for the CLI's `OdlaIntegration`. */\nexport interface ChapterIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n schema: { entities: Record<string, unknown>; links: Record<string, unknown> };\n rules: Record<string, unknown>;\n seeds: IntegrationSeed[];\n probes: Array<{ path: string; expectedStatus: number }>;\n /** Tenant-vault secret names read by configured Chapter capabilities. */\n secrets: IntegrationSecret[];\n /** Runbooks that bear on THIS chapter's role, so tooling can point at the\n * right procedure without the operator knowing it exists. A chapter declaring\n * `network.targets` is a leader hub; one with no targets is a follower site\n * (and may declare `network.readers` for bounded CRM browsing). */\n runbooks: ChapterRunbookHints;\n}\n\n/** Which runbooks apply, and why. */\nexport interface ChapterRunbookHints {\n role: \"leader\" | \"follower\";\n /** Platform runbook slugs, most relevant first. */\n slugs: string[];\n /** One line a human or agent can act on. */\n guidance: string;\n}\n\n/**\n * Build the one CLI-consumable integration for a chapter/hub: the crm_*\n * namespaces + crm_config seed + route probe, merged with the chapter's own\n * namespaces and a guarded `groups`-row seed. Drop it in odla.config.mjs's\n * `integrations` array. Claim/private-Clerk policies also seed the exact role\n * ladder and metadata source for Studio. Seeds are insert-only: when changing\n * auth policy, reconcile that stored policy explicitly before enabling editing.\n */\nexport function createChapterIntegration(\n chapter: Chapter,\n options: ChapterIntegrationOptions = {},\n): ChapterIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n const now = options.now ?? Date.now();\n const emails = chapter.config.emails;\n\n const crmDesc = createCrmIntegration(chapter.crm, {\n basePath,\n now,\n ...(emails?.notificationEmail ? { notificationEmail: emails.notificationEmail } : {}),\n ...(emails?.replyTo ? { replyTo: emails.replyTo } : {}),\n ...(emails?.debugEmail ? { debugEmail: emails.debugEmail } : {}),\n });\n\n const seeds: IntegrationSeed[] = [...(crmDesc.seeds ?? [])];\n if (chapter.auth.source !== \"table\") seeds.push({\n id: \"account-policy\", ns: \"chapterAccountPolicy\", key: { attr: \"id\", value: chapter.id },\n attrs: { metadata: chapter.auth.source === \"clerk\" ? \"private\" : \"public\", roles: [...chapter.auth.ladder] },\n });\n const group = chapter.groupSeed();\n if (group) {\n seeds.push({ id: \"group\", ns: \"groups\", key: { attr: \"id\", value: chapter.id }, attrs: { ...group, createdAt: now } });\n // One insert-only seed per declared tier, keyed by its own id so re-running\n // provisioning never duplicates a tier or overwrites a price an owner has\n // since changed in Studio.\n for (const tier of buildTierSeeds(chapter.id, chapter.config.tiers, now)) {\n seeds.push({\n id: `tier:${String(tier.id)}`,\n ns: \"tiers\",\n key: { attr: \"id\", value: String(tier.id) },\n attrs: tier,\n });\n }\n }\n\n // A leader declares where it pushes records. A follower declares no targets;\n // it may still declare readers for bounded record browsing.\n const isLeader = (chapter.config.network?.targets?.length ?? 0) > 0;\n const runbooks: ChapterRunbookHints = isLeader\n ? {\n role: \"leader\",\n slugs: [\"chapter-leader\", \"chapter-network\", \"crm\", ...(chapter.networkCommercialReadModel ? [\"stripe-network-shadow\"] : [])],\n guidance:\n `${chapter.name} is a LEADER hub: it holds the CRM and shares records with its chapters. ` +\n `Read it with \\`odla-ai runbook get chapter-leader\\`.`,\n }\n : {\n role: \"follower\",\n slugs: [\"chapter-follower\", \"chapter-network\"],\n guidance:\n `${chapter.name} is a FOLLOWER site: it receives people and records from a leader hub. ` +\n `Read it with \\`odla-ai runbook get chapter-follower\\`.`,\n };\n const secrets: IntegrationSecret[] = [];\n if (chapter.account !== \"none\") secrets.push({\n // Released Chapter workers request this effective name. odla-db maps it to\n // the canonical reserved `$clerk_secret` value written by the CLI.\n name: \"clerk_secret_key\",\n description: \"Clerk backend key (set with odla-ai secrets set-clerk-key) required by the configured Chapter account model.\",\n required: true,\n });\n if (chapter.networkCommercialReadModel) secrets.push({\n name: \"network_commercial_stripe_webhook_secret\",\n description: \"Signing secret for the read-only network commercial Stripe webhook endpoint.\",\n required: true,\n });\n\n return {\n id: \"chapter\",\n title: `Chapter: ${chapter.name}`,\n npm: \"@odla-ai/chapter\",\n schema: {\n entities: { ...crmDesc.schema.entities, ...chapter.schema.entities },\n links: { ...crmDesc.schema.links, ...chapter.schema.links },\n },\n rules: { ...crmDesc.rules, ...chapter.rules },\n seeds,\n secrets,\n probes: [\n ...(crmDesc.probes ?? []),\n // The snapshot route is deliberately private. A credential-free smoke\n // request must prove that the route is mounted and closed.\n { path: \"/api/network/snapshot\", expectedStatus: 401 },\n ...(chapter.network.readers.length > 0\n ? [{ path: \"/api/network/records\", expectedStatus: 401 }]\n : []),\n ...(chapter.network.readers.some((reader) => reader.sharedNotes.length > 0)\n ? [{\n path: \"/api/network/shared-notes\",\n expectedStatus: 401,\n }]\n : []),\n ...(chapter.network.readers.some((reader) => reader.commercialParity)\n ? [{ path: \"/api/network/commercial-parity\", expectedStatus: 401 }]\n : []),\n // Formation metadata is public only when the host explicitly enables\n // the bounded intake contract.\n ...(chapter.formation.enabled\n ? [{ path: \"/api/formation/config\", expectedStatus: 200 }]\n : []),\n ...(chapter.memberContent\n ? [\n { path: \"/api/member-content\", expectedStatus: 401 },\n { path: \"/api/admin/member-content\", expectedStatus: 401 },\n ]\n : []),\n ...(chapter.builderLibrary\n ? [\n { path: \"/api/builder-library-control\", expectedStatus: 401 },\n { path: \"/api/admin/builder-library\", expectedStatus: 401 },\n { path: \"/api/admin/builder-library/manifest\", expectedStatus: 401 },\n ]\n : []),\n ...(chapter.networkPersonRegistry\n ? [{ path: \"/api/admin/network-person-registry\", expectedStatus: 401 }]\n : []),\n ...(chapter.networkCommercialReadModel\n ? [\n { path: \"/api/network-commercial/stripe-webhook\", expectedStatus: 405 },\n { path: \"/api/admin/network-commercial-read-model\", expectedStatus: 401 },\n ]\n : []),\n ],\n runbooks,\n };\n}\n","// Membership tiers. A chapter offers one or more tiers, and a tier — not the\n// group — decides what a member pays. Keeping the price on the tier is what\n// makes a free tier expressible: `paymentsReady` used to gate the whole join\n// flow on the group holding a Stripe price, so a £0 membership was unjoinable.\n//\n// Everything here is pure so the join page, the checkout route and the seeder\n// agree about which tiers exist and which of them can actually be bought.\n\n/** One membership tier a chapter offers. `priceCents: 0` means free. */\nexport interface ChapterTier {\n /** Stable slug, referenced by `applications.tierId`. Never renumbered. */\n id: string;\n /** The group this tier belongs to. */\n groupId: string;\n /** Display name, e.g. \"Founding\". */\n name: string;\n /** Price in minor units. `0` is free and needs no Stripe price. */\n priceCents: number;\n /** ISO currency inherited from the group for legacy rows. */\n currency?: string;\n /** Recurring interval inherited from the group for legacy rows. */\n interval?: \"year\" | \"month\";\n /** Stripe price to subscribe. Required only when `priceCents > 0`. */\n stripePriceId?: string | null;\n /** Short description shown beside the tier on the join page. */\n blurb?: string;\n /** Ascending display order; ties fall back to `id` for a stable sort. */\n sortOrder: number;\n /** An inactive tier is retained for existing members but never offered. */\n active: boolean;\n}\n\n/**\n * A tier as declared in `defineChapter`, before it becomes a row.\n *\n * `groupId` is absent here because the chapter owns exactly one group at seed\n * time; the seeder fills it in.\n */\nexport interface ChapterTierConfig {\n id: string;\n name: string;\n priceCents: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n stripePriceId?: string;\n blurb?: string;\n /** Defaults to declaration order when omitted. */\n sortOrder?: number;\n /** Defaults to true; set false to retire a tier without deleting it. */\n active?: boolean;\n}\n\n/** Build the seed rows for a chapter's declared tiers. */\nexport function buildTierSeeds(\n groupId: string,\n configured: readonly ChapterTierConfig[] = [],\n now = 0,\n): Array<Record<string, unknown>> {\n return configured.map((tier, index) => ({\n id: tier.id,\n groupId,\n name: tier.name,\n priceCents: tier.priceCents,\n ...(tier.currency ? { currency: tier.currency } : {}),\n ...(tier.interval ? { interval: tier.interval } : {}),\n ...(tier.stripePriceId ? { stripePriceId: tier.stripePriceId } : {}),\n ...(tier.blurb ? { blurb: tier.blurb } : {}),\n sortOrder: tier.sortOrder ?? index,\n active: tier.active !== false,\n createdAt: now,\n }));\n}\n\n/** The `groups`-row fields tier payability depends on. */\nexport interface TierGroup {\n id?: string;\n stripePublishableKey?: string | null;\n /** Legacy single price, used only to synthesize an implicit tier. */\n stripePriceId?: string | null;\n standardPriceCents?: number;\n foundingDiscountCents?: number;\n currency?: string;\n interval?: \"year\" | \"month\";\n}\n\n/**\n * Whether this tier costs nothing. A free tier never touches Stripe.\n *\n * Free means both no price AND no Stripe price to charge against. The second\n * half matters for chapters that predate tiers: a group can carry a real\n * `stripePriceId` while `standardPriceCents` is 0, because the cents field is\n * display copy and the amount actually lives in Stripe. Reading such a group as\n * free would silently stop charging an existing paying chapter.\n */\nexport function tierIsFree(\n tier: Pick<ChapterTier, \"priceCents\"> & { stripePriceId?: string | null },\n): boolean {\n return !(tier.priceCents > 0) && !tier.stripePriceId;\n}\n\n/**\n * Whether a tier can actually be joined right now.\n *\n * A free tier is always joinable — there is nothing to charge, so Stripe being\n * unconfigured is irrelevant to it. A paid tier needs the group's publishable\n * key, its own Stripe price, and the vault secret; missing any of those drops\n * the tier rather than half-charging for it.\n */\nexport function tierPayable(\n tier: Pick<ChapterTier, \"priceCents\" | \"stripePriceId\">,\n group: TierGroup,\n hasSecretKey: boolean,\n): boolean {\n if (tierIsFree(tier)) return true;\n return Boolean(group.stripePublishableKey && tier.stripePriceId && hasSecretKey);\n}\n\n/** Sort by `sortOrder`, then `id`, so a page never reorders between reads. */\nfunction byOrder(a: ChapterTier, b: ChapterTier): number {\n return a.sortOrder - b.sortOrder || a.id.localeCompare(b.id);\n}\n\n/**\n * The tiers a chapter offers, given the stored rows.\n *\n * A chapter that predates tiers has no rows, and must keep working untouched:\n * one implicit `\"standard\"` tier is synthesized from the group's legacy\n * `standardPriceCents`/`stripePriceId` columns. That is why there is no\n * migration — an existing chapter reads exactly as it did before, and writing\n * its first real tier row takes over.\n */\nexport function resolveTiers(group: TierGroup, rows: readonly ChapterTier[] = []): ChapterTier[] {\n const stored = rows.filter((tier) => tier.active);\n if (rows.length) return [...stored].sort(byOrder);\n return [{\n id: \"standard\",\n groupId: String(group.id ?? \"\"),\n name: \"Membership\",\n priceCents: group.standardPriceCents ?? 0,\n currency: group.currency ?? \"usd\",\n interval: group.interval ?? \"year\",\n ...(group.stripePriceId ? { stripePriceId: group.stripePriceId } : {}),\n sortOrder: 0,\n active: true,\n }];\n}\n\n/** The tiers to show on the join page: active, and joinable as configured. */\nexport function offerableTiers(\n tiers: readonly ChapterTier[],\n group: TierGroup,\n hasSecretKey: boolean,\n): ChapterTier[] {\n return tiers.filter((tier) => tier.active && tierPayable(tier, group, hasSecretKey));\n}\n\n/**\n * Resolve the tier an application chose.\n *\n * An absent `tierId` is the pre-tier case and selects the only offered tier\n * when exactly one exists; with several it is genuinely ambiguous and returns\n * `null`, because guessing would charge someone the wrong price.\n */\nexport function findTier(\n tiers: readonly ChapterTier[],\n tierId: string | null | undefined,\n): ChapterTier | null {\n if (!tierId) return tiers.length === 1 ? tiers[0]! : null;\n return tiers.find((tier) => tier.id === tierId) ?? null;\n}\n\n/** The public shape of a tier on the join config. Never exposes Stripe ids. */\nexport interface JoinConfigTier {\n id: string;\n name: string;\n priceCents: number;\n currency: string;\n interval: \"year\" | \"month\";\n blurb: string;\n free: boolean;\n}\n\n/** Project tiers for the public join config, dropping provider identifiers. */\nexport function joinConfigTiers(\n tiers: readonly ChapterTier[],\n defaults: { currency?: string; interval?: \"year\" | \"month\" } = {},\n): JoinConfigTier[] {\n return tiers.map((tier) => ({\n id: tier.id,\n name: tier.name,\n priceCents: tier.priceCents,\n currency: tier.currency ?? defaults.currency ?? \"usd\",\n interval: tier.interval ?? defaults.interval ?? \"year\",\n blurb: tier.blurb ?? \"\",\n free: tierIsFree(tier),\n }));\n}\n","/** Immutable commercial policy, separate from the recurring base SKU. */\nexport interface MembershipOfferingVersion {\n id: string;\n chapterId: string;\n baseSkuId: string;\n version: number;\n status: \"draft\" | \"published\" | \"retired\";\n effectiveFrom: number;\n effectiveUntil?: number;\n basePriceCents: number;\n currency: string;\n interval: \"month\" | \"year\";\n term: { kind: \"fixed_end\"; endsAt: number } | { kind: \"rolling_months\"; months: number };\n autoRenew: true;\n paymentGraceDays: number;\n seatPriceCents: number;\n seatPurchaseWindowCalendarMonths: number;\n requiredDisclosures: string[];\n}\n\n/** Cohort qualification survives the expiration of its monetary benefit. */\nexport interface MembershipDiscountPolicyVersion {\n id: string;\n chapterId: string;\n version: number;\n status: \"draft\" | \"published\" | \"retired\";\n cohortLabel: string;\n cohortEligibleSkuIds: string[];\n discountEligibleSkuIds: string[];\n softTarget: number;\n percentOffBps: number;\n qualifyingStartsAt: number;\n qualifyingEndsAt: number;\n benefitDuration: { kind: \"first_term\" | \"while_active\" } | { kind: \"fixed_end\"; endsAt: number };\n}\n\nconst fail = (field: string): never => { throw new TypeError(`invalid membership policy: ${field}`); };\nconst object = (value: unknown): Record<string, unknown> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return fail(\"object\");\n return value as Record<string, unknown>;\n};\nconst id = (value: unknown): string => typeof value === \"string\" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{2,159}$/.test(value) ? value : fail(\"id\");\nconst integer = (value: unknown, min: number, max: number): number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= min && value <= max ? value : fail(\"integer\");\nconst time = (value: unknown): number => {\n const at = typeof value === \"number\" ? value : typeof value === \"string\" ? Date.parse(value) : NaN;\n return integer(at, 0, 8_640_000_000_000_000);\n};\nconst ids = (value: unknown, allowEmpty = false): string[] => {\n if (!Array.isArray(value) || value.length > 100 || (!allowEmpty && value.length === 0)) return fail(\"ids\");\n const values = value.map(id);\n if (new Set(values).size !== values.length) return fail(\"duplicate ids\");\n return values;\n};\nconst status = (value: unknown): MembershipOfferingVersion[\"status\"] =>\n value === \"draft\" || value === \"published\" || value === \"retired\" ? value : fail(\"status\");\n\n/** Add UTC calendar months, clamping month-end dates while preserving the time. */\nexport function addMembershipCalendarMonths(input: number | string, months: number): number {\n const source = new Date(time(input));\n integer(months, 1, 120);\n const result = new Date(source);\n result.setUTCDate(1);\n result.setUTCMonth(result.getUTCMonth() + months);\n const lastDay = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();\n result.setUTCDate(Math.min(source.getUTCDate(), lastDay));\n return time(result.getTime());\n}\n\n/** Normalize one version before publishing or issuing it; never retain caller-owned nested objects. */\nexport function membershipOfferingVersion(value: unknown): MembershipOfferingVersion {\n const input = object(value);\n const effectiveFrom = time(input.effectiveFrom);\n const effectiveUntil = input.effectiveUntil === undefined ? undefined : time(input.effectiveUntil);\n if (effectiveUntil !== undefined && effectiveUntil <= effectiveFrom) return fail(\"effective window\");\n const term = object(input.term);\n const normalizedTerm: MembershipOfferingVersion[\"term\"] = term.kind === \"fixed_end\"\n ? { kind: \"fixed_end\", endsAt: time(term.endsAt) }\n : term.kind === \"rolling_months\" ? { kind: \"rolling_months\", months: integer(term.months, 1, 120) } : fail(\"term\");\n if (normalizedTerm.kind === \"fixed_end\" && normalizedTerm.endsAt <= effectiveFrom) return fail(\"term end\");\n if (input.autoRenew !== true) return fail(\"autoRenew\");\n if (typeof input.currency !== \"string\" || !/^[a-z]{3}$/.test(input.currency)) return fail(\"currency\");\n if (input.interval !== \"month\" && input.interval !== \"year\") return fail(\"interval\");\n return {\n id: id(input.id), chapterId: id(input.chapterId), baseSkuId: id(input.baseSkuId),\n version: integer(input.version, 1, Number.MAX_SAFE_INTEGER), status: status(input.status),\n effectiveFrom, ...(effectiveUntil !== undefined ? { effectiveUntil } : {}),\n basePriceCents: integer(input.basePriceCents, 0, Number.MAX_SAFE_INTEGER), currency: input.currency, interval: input.interval,\n term: normalizedTerm, autoRenew: true, paymentGraceDays: integer(input.paymentGraceDays, 0, 60),\n seatPriceCents: integer(input.seatPriceCents, 1, Number.MAX_SAFE_INTEGER),\n seatPurchaseWindowCalendarMonths: integer(input.seatPurchaseWindowCalendarMonths, 1, 120),\n requiredDisclosures: ids(input.requiredDisclosures),\n };\n}\n\n/** Normalize cohort and discount eligibility independently; zero discount can still confer founding status. */\nexport function membershipDiscountPolicyVersion(value: unknown): MembershipDiscountPolicyVersion {\n const input = object(value);\n const qualifyingStartsAt = time(input.qualifyingStartsAt);\n const qualifyingEndsAt = time(input.qualifyingEndsAt);\n if (qualifyingEndsAt <= qualifyingStartsAt) return fail(\"qualification window\");\n const eligible = ids(input.cohortEligibleSkuIds);\n const discounted = ids(input.discountEligibleSkuIds ?? [], true);\n if (discounted.some(sku => !eligible.includes(sku))) return fail(\"discount eligibility\");\n const duration = object(input.benefitDuration);\n const benefitDuration: MembershipDiscountPolicyVersion[\"benefitDuration\"] = duration.kind === \"fixed_end\"\n ? { kind: \"fixed_end\", endsAt: time(duration.endsAt) }\n : duration.kind === \"first_term\" || duration.kind === \"while_active\" ? { kind: duration.kind } : fail(\"benefit duration\");\n return {\n id: id(input.id), chapterId: id(input.chapterId), version: integer(input.version, 1, Number.MAX_SAFE_INTEGER),\n status: status(input.status), cohortLabel: id(input.cohortLabel),\n cohortEligibleSkuIds: eligible, discountEligibleSkuIds: discounted,\n softTarget: integer(input.softTarget, 1, Number.MAX_SAFE_INTEGER),\n percentOffBps: integer(input.percentOffBps, 0, 10000), qualifyingStartsAt, qualifyingEndsAt, benefitDuration,\n };\n}\n","import {\n addMembershipCalendarMonths, membershipDiscountPolicyVersion, membershipOfferingVersion,\n type MembershipDiscountPolicyVersion, type MembershipOfferingVersion,\n} from \"./membership-policy\";\nimport { subscriptionBillingTerms, type SubscriptionBillingTerms } from \"./subscription-billing-terms\";\n\n/** Money and service promise frozen at offer issuance, not recomputed from later policy edits. */\nexport interface MembershipCommercialOffer {\n offering: MembershipOfferingVersion;\n discountPolicy: MembershipDiscountPolicyVersion | null;\n issuedAt: number;\n founding: boolean;\n dueTodayCents: number;\n /** Fixed service end only; rolling service starts at the provider-confirmed payment. */\n initialTermEndsAt?: number;\n renewalCents: number;\n billingTerms: SubscriptionBillingTerms;\n}\n\n/** Calculate a new offer from authority-owned policy and its approved, dues-paying cohort count.\n * This pure function does not reserve a position or make a shadow ledger authoritative.\n * Persist the returned promise before accepting consent or performing provider I/O.\n */\nexport function createMembershipCommercialOffer(input: {\n offering: unknown;\n discountPolicy?: unknown;\n approvedFoundingCount: number;\n now: number;\n /** Coupon identity must be partitioned by app, environment, runtime and immutable policy. */\n couponId?: string;\n}): MembershipCommercialOffer {\n const offering = membershipOfferingVersion(input.offering);\n const policy = input.discountPolicy === undefined || input.discountPolicy === null\n ? null : membershipDiscountPolicyVersion(input.discountPolicy);\n const now = input.now;\n if (!Number.isSafeInteger(now) || now < 0 || !Number.isSafeInteger(input.approvedFoundingCount) || input.approvedFoundingCount < 0) {\n throw new TypeError(\"invalid offer clock or founding count\");\n }\n if (offering.status !== \"published\" || now < offering.effectiveFrom ||\n (offering.effectiveUntil !== undefined && now >= offering.effectiveUntil)) throw new TypeError(\"offering is unavailable\");\n if (policy && policy.chapterId !== offering.chapterId) throw new TypeError(\"policy belongs to another chapter\");\n const founding = Boolean(policy && policy.status === \"published\" && offering.basePriceCents > 0 &&\n policy.cohortEligibleSkuIds.includes(offering.baseSkuId) && now >= policy.qualifyingStartsAt && now < policy.qualifyingEndsAt &&\n input.approvedFoundingCount < policy.softTarget);\n const earned = founding ? policy : null;\n const initialTermEndsAt = offering.term.kind === \"fixed_end\" ? offering.term.endsAt : addMembershipCalendarMonths(now, offering.term.months);\n if (initialTermEndsAt <= now) throw new TypeError(\"membership service term has ended\");\n if (offering.term.kind === \"rolling_months\" && offering.term.months !== (offering.interval === \"year\" ? 12 : 1)) {\n throw Object.assign(new Error(\"custom initial term requires a provider schedule\"), { code: \"term_schedule_required\" });\n }\n const applies = earned && earned.discountEligibleSkuIds.includes(offering.baseSkuId) && earned.percentOffBps > 0 &&\n (earned.benefitDuration.kind !== \"fixed_end\" || now < earned.benefitDuration.endsAt);\n const bps = applies ? earned.percentOffBps : 0;\n const dueTodayCents = Math.round(offering.basePriceCents * (10000 - bps) / 10000);\n let duration: \"once\" | \"forever\" = \"once\";\n if (applies) {\n if (earned.benefitDuration.kind === \"while_active\") duration = \"forever\";\n else if (earned.benefitDuration.kind === \"fixed_end\" &&\n (offering.term.kind !== \"fixed_end\" || earned.benefitDuration.endsAt !== initialTermEndsAt)) {\n // An arbitrary expiry needs a provider schedule. Never silently convert\n // it to a once/forever coupon with a different financial promise.\n throw Object.assign(new Error(\"discount expiry requires a provider schedule\"), { code: \"discount_schedule_required\" });\n }\n if (!input.couponId) throw new TypeError(\"a policy-partitioned coupon id is required\");\n }\n const billingTerms = subscriptionBillingTerms({\n offeringVersionId: offering.id,\n ...(offering.term.kind === \"fixed_end\" ? { initialTermEndsAt } : {}),\n ...(applies ? { discount: { policyVersionId: earned.id, couponId: input.couponId!, percentOffBps: bps, duration } } : {}),\n });\n return {\n offering, discountPolicy: earned, issuedAt: now, founding, dueTodayCents,\n ...(offering.term.kind === \"fixed_end\" ? { initialTermEndsAt } : {}),\n renewalCents: applies && duration === \"forever\" ? dueTodayCents : offering.basePriceCents,\n billingTerms,\n };\n}\n","import type { ChapterDb } from \"./types\";\nimport { createMembershipCommercialOffer, type MembershipCommercialOffer } from \"./membership-offer\";\nimport { membershipDiscountPolicyVersion, membershipOfferingVersion } from \"./membership-policy\";\n\ntype Row = Record<string, unknown>;\n/** Verified source identity supplied by the server adapter, never by a browser's price payload. */\nexport interface MembershipOfferRequest {\n offerId: string;\n applicationId: string;\n appId: string;\n chapterId: string;\n environment: string;\n runtime: string;\n skuId: string;\n now: number;\n lifetimeMs: number;\n}\n/** Durable pre-payment promise. The opaque digest is what the member acknowledges. */\nexport interface IssuedMembershipOffer {\n id: string;\n applicationId: string;\n appId: string;\n chapterId: string;\n environment: string;\n runtime: string;\n skuId: string;\n issuedAt: number;\n expiresAt: number;\n digest: string;\n contract: MembershipCommercialOffer;\n}\nconst identityKeys = [\"applicationId\", \"appId\", \"chapterId\", \"environment\", \"runtime\", \"skuId\"] as const;\nconst reject = (code: string): never => { throw Object.assign(new Error(code), { code }); };\nasync function hash(value: unknown): Promise<string> {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(JSON.stringify(value)));\n return [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\nasync function couponId(input: Pick<MembershipOfferRequest, \"appId\" | \"chapterId\" | \"environment\" | \"runtime\" | \"skuId\">, policyId?: string) {\n return policyId ? `odla_m_${await hash([input.appId, input.chapterId, input.environment, input.runtime, input.skuId, policyId])}` : undefined;\n}\nasync function load(db: ChapterDb, ns: string, id: string): Promise<Row | undefined> {\n return (await db.query({ [ns]: { $: { where: { id }, limit: 1 } } }))[ns]?.[0];\n}\n/** Stable request identity shared by the issuer and a verifying follower. */\nexport async function membershipOfferIdForRequest(input: Pick<MembershipOfferRequest, \"appId\" | \"chapterId\" | \"environment\" | \"runtime\" | \"applicationId\"> & { requestId: string }): Promise<string> {\n return `offer_${await hash([input.appId, input.chapterId, input.environment, input.runtime, input.applicationId, input.requestId])}`;\n}\nfunction validate(input: MembershipOfferRequest): void {\n for (const key of [\"offerId\", ...identityKeys] as const) {\n if (typeof input[key] !== \"string\" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{1,159}$/.test(input[key])) reject(\"invalid_offer_identity\");\n }\n if (!Number.isSafeInteger(input.now) || input.now < 0 || !Number.isSafeInteger(input.lifetimeMs) ||\n input.lifetimeMs < 60_000 || input.lifetimeMs > 23 * 3600000 || !Number.isSafeInteger(input.now + input.lifetimeMs)) {\n reject(\"invalid_offer_window\");\n }\n}\nasync function restore(row: Row, input: MembershipOfferRequest): Promise<IssuedMembershipOffer> {\n if (row.id !== input.offerId || identityKeys.some(key => row[key] !== input[key])) reject(\"offer_identity_conflict\");\n const contract = row.contract as MembershipCommercialOffer;\n if (!contract || !Number.isSafeInteger(row.issuedAt) || !Number.isSafeInteger(row.expiresAt) ||\n Number(row.expiresAt) <= Number(row.issuedAt) || Number(row.expiresAt) - Number(row.issuedAt) > 23 * 3600000) reject(\"invalid_offer_snapshot\");\n const expected = createMembershipCommercialOffer({\n offering: contract.offering, discountPolicy: contract.discountPolicy,\n approvedFoundingCount: Number(row.approvedFoundingCount), now: Number(row.issuedAt),\n couponId: await couponId(input, contract.discountPolicy?.id),\n });\n if (expected.offering.chapterId !== input.chapterId || expected.offering.baseSkuId !== input.skuId) reject(\"invalid_offer_snapshot\");\n const result = { id: input.offerId, ...Object.fromEntries(identityKeys.map(key => [key, input[key]])),\n issuedAt: Number(row.issuedAt), expiresAt: Number(row.expiresAt), contract: expected } as Omit<IssuedMembershipOffer, \"digest\">;\n if (await hash(result) !== row.digest || JSON.stringify(expected) !== JSON.stringify(contract)) reject(\"invalid_offer_snapshot\");\n return { ...result, digest: String(row.digest) };\n}\n\n/** Validate and copy a trusted authority response before saving it as a chapter projection.\n * This verifies the complete target, normalized money promise and digest; it does not\n * authenticate its transport or make caller-supplied offers authoritative.\n */\nexport async function verifyIssuedMembershipOffer(value: unknown, expected: MembershipOfferRequest): Promise<IssuedMembershipOffer> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return reject(\"invalid_offer_snapshot\");\n // The wire contract contains only an earned policy, so replay qualification\n // uses zero here. The private authority count is not disclosed to followers.\n return restore({ ...(value as Row), approvedFoundingCount: 0 }, expected);\n}\n\n/** Issue in the network data scope with a revision fence against policy/cohort changes.\n * The authority state must be explicitly initialized and every policy/count mutation\n * must increment its revision in the same transaction. Shadow data never qualifies.\n * This function neither calls Stripe nor grants access. Its caller authenticates the\n * source deployment before invoking it and must enforce expiry before checkout starts.\n */\nexport async function issueMembershipCommercialOffer(db: ChapterDb, input: MembershipOfferRequest): Promise<IssuedMembershipOffer> {\n validate(input);\n const stateId = `${input.chapterId}:${input.environment}`;\n const state = await load(db, \"membershipAuthorityState\", stateId);\n if (!state || state.mode !== \"authoritative\" || state.chapterId !== input.chapterId || state.environment !== input.environment ||\n !Number.isSafeInteger(state.revision) || Number(state.revision) < 1 || !state.cohortCounts || typeof state.cohortCounts !== \"object\" ||\n Array.isArray(state.cohortCounts)) return reject(\"membership_authority_unavailable\");\n const existing = await load(db, \"membershipCheckoutOffer\", input.offerId);\n if (existing) return restore(existing, input);\n const rows = await db.query({\n membershipOfferingVersion: { $: { where: { chapterId: input.chapterId }, limit: 200 } },\n discountPolicyVersion: { $: { where: { chapterId: input.chapterId }, limit: 200 } },\n });\n if (!Array.isArray(rows.membershipOfferingVersion) || !Array.isArray(rows.discountPolicyVersion) ||\n rows.membershipOfferingVersion.length >= 200 || rows.discountPolicyVersion.length >= 200) return reject(\"policy_history_incomplete\");\n const offerings = rows.membershipOfferingVersion.map(row => membershipOfferingVersion(row.snapshot))\n .filter(offer => offer.chapterId === input.chapterId && offer.baseSkuId === input.skuId && offer.status === \"published\" &&\n input.now >= offer.effectiveFrom && (offer.effectiveUntil === undefined || input.now < offer.effectiveUntil));\n const policies = rows.discountPolicyVersion.map(row => membershipDiscountPolicyVersion(row.snapshot))\n .filter(policy => policy.chapterId === input.chapterId && policy.status === \"published\" && policy.cohortEligibleSkuIds.includes(input.skuId) &&\n input.now >= policy.qualifyingStartsAt && input.now < policy.qualifyingEndsAt);\n const offering = offerings.sort((a, b) => b.version - a.version)[0];\n const policy = policies.sort((a, b) => b.version - a.version)[0];\n if (!offering || offerings.filter(item => item.version === offering.version).length !== 1 ||\n (policy && policies.filter(item => item.version === policy.version).length !== 1)) reject(\"ambiguous_membership_policy\");\n const approvedFoundingCount = policy ? (state.cohortCounts as Record<string, unknown>)[policy.cohortLabel] ?? 0 : 0;\n if (!Number.isSafeInteger(approvedFoundingCount) || Number(approvedFoundingCount) < 0) reject(\"invalid_cohort_count\");\n const contract = createMembershipCommercialOffer({ offering, discountPolicy: policy,\n approvedFoundingCount: Number(approvedFoundingCount), now: input.now, couponId: await couponId(input, policy?.id) });\n const value = { id: input.offerId, ...Object.fromEntries(identityKeys.map(key => [key, input[key]])),\n issuedAt: input.now, expiresAt: input.now + input.lifetimeMs, contract } as Omit<IssuedMembershipOffer, \"digest\">;\n const row = { ...value, digest: await hash(value), approvedFoundingCount, authorityRevision: state.revision };\n try {\n await db.transact([{ t: \"update\", ns: \"membershipCheckoutOffer\", id: input.offerId, attrs: row }], {\n mutationId: `membership-offer:${input.offerId}`,\n guards: [{ ns: \"membershipCheckoutOffer\", id: input.offerId, exists: false },\n { ns: \"membershipAuthorityState\", id: stateId, exists: true, equals: { mode: \"authoritative\", revision: state.revision } }],\n });\n } catch (error) {\n if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error;\n // An identical racing issuer may have won. A changed policy/count retries\n // from canonical state instead of issuing a stale discount.\n const winner = await load(db, \"membershipCheckoutOffer\", input.offerId);\n if (winner) return restore(winner, input);\n return reject(\"membership_authority_changed\");\n }\n const stored = await load(db, \"membershipCheckoutOffer\", input.offerId);\n if (!stored) return reject(\"offer_persistence_unconfirmed\");\n return restore(stored, input);\n}\n","import { FEDERATION_HEADERS, verifyFederatedRequest } from \"@odla-ai/db\";\nimport { getVaultSecret } from \"./auth\";\nimport { issueMembershipCommercialOffer, membershipOfferIdForRequest } from \"./membership-offer-store\";\nimport { bindMembershipCheckout } from \"./membership-checkout-binding\";\nimport { confirmMembershipPayment } from \"./membership-payment-authority\";\nimport { approveNetworkMembership } from \"./membership-approval-authority\";\nimport { refundNetworkMembership } from \"./membership-refund-authority\";\nimport { reconcileMembershipBilling } from \"./membership-provider-lifecycle\";\nimport { readMembershipAccess } from \"./membership-access-authority\";\nimport { handleMembershipSeatAction, MEMBERSHIP_SEAT_ACTION_FIELDS } from \"./membership-authority-seat-actions\";\nimport type { ChapterDb } from \"./types\";\n\n/** A dedicated two-sided edge: no chapter receives the network database credential. */\nexport interface MembershipAuthorityPeer {\n appId: string;\n chapterId: string;\n environment: string;\n runtime: string;\n secretName: string;\n /** Authority-configured, product-separated recurring named-seat Price. Omit to disable seat commands. */\n seatPriceId?: string;\n}\n/** Business API configuration, independent of the browser UI. May be mounted in\n * the existing BNF backend using its existing odla database; no extra app required.\n */\nexport interface MembershipAuthorityHandlerOptions {\n peers: readonly MembershipAuthorityPeer[];\n /** Connect to the network owner's database (BNF), never a chapter projection. */\n makeDb: () => ChapterDb;\n now?: () => number;\n offerLifetimeMs: number;\n /** Network vault slot; never supplied by a caller. Defaults to stripe_secret_key. */\n stripeSecretName?: string;\n}\n/** Signed server-to-server route; the runtime is included in the signed request target. */\nexport const MEMBERSHIP_AUTHORITY_PATH = \"/api/membership-authority\";\nconst respond = (body: unknown, status = 200) => new Response(JSON.stringify(body), {\n status, headers: { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" },\n});\nconst SAFE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{2,159}$/;\nconst SAFE_ERROR = new Set([\"offer_identity_conflict\", \"membership_authority_unavailable\", \"policy_history_incomplete\",\n \"ambiguous_membership_policy\", \"invalid_cohort_count\", \"membership_authority_changed\", \"offer_persistence_unconfirmed\",\n \"invalid_offer_snapshot\", \"discount_schedule_required\", \"term_schedule_required\"]);\n\nasync function boundedBody(req: Request): Promise<string | null> {\n if (!req.body) return \"\";\n const reader = req.body.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n try {\n while (true) {\n const part = await reader.read();\n if (part.done) break;\n length += part.value.byteLength;\n if (length > 4096) { await reader.cancel(); return null; }\n parts.push(part.value);\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.byteLength; }\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } finally { reader.releaseLock(); }\n}\n\n/** Create the narrow signed offer issuer. Authentication maps each dedicated edge\n * to an exact app/chapter/environment/runtime; callers cannot select another scope,\n * provide prices, grant roles, or run arbitrary network database operations.\n * Replayed signed requests are safe because issuance is durably idempotent.\n */\nexport function createMembershipAuthorityHandler(options: MembershipAuthorityHandlerOptions): (req: Request) => Promise<Response> {\n if (!Number.isSafeInteger(options.offerLifetimeMs) || options.offerLifetimeMs < 60000 || options.offerLifetimeMs > 23 * 3600000) {\n throw new TypeError(\"invalid authority offer lifetime\");\n }\n const peers = options.peers.map(peer => ({ ...peer }));\n if (options.stripeSecretName !== undefined && !/^[A-Za-z][A-Za-z0-9_-]{1,127}$/.test(options.stripeSecretName)) throw new TypeError(\"invalid Stripe secret slot\");\n const identities = new Set<string>();\n for (const peer of peers) {\n if (!/^[a-z0-9][a-z0-9-]{1,62}$/.test(peer.appId) || !SAFE.test(peer.chapterId) ||\n !/^[a-z0-9][a-z0-9-]{1,31}$/.test(peer.environment) || !/^[a-z0-9]{2,12}$/.test(peer.runtime) ||\n !/^[A-Za-z][A-Za-z0-9_-]{1,127}$/.test(peer.secretName)) throw new TypeError(\"invalid authority peer\");\n const identity = `${peer.appId}:${peer.runtime}`;\n if (identities.has(identity)) throw new TypeError(\"ambiguous authority peer\");\n identities.add(identity);\n if (peer.seatPriceId !== undefined && !/^price_[A-Za-z0-9]+$/.test(peer.seatPriceId)) throw new TypeError(\"invalid seat Price\");\n }\n return async req => {\n const url = new URL(req.url);\n if (req.method !== \"POST\") return respond({ error: \"method_not_allowed\" }, 405);\n const sender = req.headers.get(FEDERATION_HEADERS.sender);\n const action = url.pathname.split(\"/\").at(-1);\n if (![\"offers\", \"checkouts\", \"payments\", \"approvals\", \"refunds\", \"renewals\", \"access\", ...Object.keys(MEMBERSHIP_SEAT_ACTION_FIELDS)].includes(action ?? \"\")) return respond({ error: \"unauthorized\" }, 401);\n const peer = peers.find(candidate => candidate.appId === sender &&\n url.pathname === `${MEMBERSHIP_AUTHORITY_PATH}/${candidate.runtime}/${action}` && !url.search);\n if (!peer) return respond({ error: \"unauthorized\" }, 401);\n let body: string | null;\n try { body = await boundedBody(req); } catch { return respond({ error: \"invalid_body\" }, 400); }\n if (body === null) return respond({ error: \"body_too_large\" }, 413);\n try {\n const db = options.makeDb();\n const secret = await getVaultSecret(db, peer.secretName);\n if (!secret) return respond({ error: \"authority_edge_unavailable\" }, 503);\n const verified = await verifyFederatedRequest(new Request(req.url, { method: \"POST\", headers: req.headers, body }),\n { secret, senders: [peer.appId], now: options.now });\n if (!verified.ok) return respond({ error: \"unauthorized\" }, 401);\n let input: Record<string, unknown>;\n try {\n input = JSON.parse(verified.body);\n const fields = action === \"seat-invitation\" ? MEMBERSHIP_SEAT_ACTION_FIELDS[action]! : [\"applicationId\", \"skuId\", ...(action === \"offers\" ? [\"requestId\"] : action === \"checkouts\" ?\n [\"offerId\", \"offerDigest\", \"quoteDigest\", \"priceId\"] : action === \"payments\" ?\n [\"eventId\", \"providerSubscriptionId\", \"providerCustomerId\"] : action === \"renewals\" ? [\"eventId\"] : MEMBERSHIP_SEAT_ACTION_FIELDS[action!] ?? [])];\n if (!input || typeof input !== \"object\" || Array.isArray(input) ||\n Object.keys(input).some(key => !fields.includes(key)) ||\n !fields.every(key => typeof input[key] === \"string\" &&\n ([\"recipientName\", \"recipientEmail\", \"purchaserEmail\", \"verifiedRecipientEmail\"].includes(key)\n ? input[key].length > 0 && input[key].length <= 254 && !/[\\u0000-\\u001f\\u007f]/.test(input[key]) : SAFE.test(input[key])))) {\n throw new TypeError(\"invalid request\");\n }\n } catch { return respond({ error: \"invalid_offer_request\" }, 400); }\n if (Object.hasOwn(MEMBERSHIP_SEAT_ACTION_FIELDS, action!)) {\n return respond({ ok: true, seat: await handleMembershipSeatAction(action!, db, peer, input,\n options.now?.() ?? Date.now(), options.stripeSecretName ?? \"stripe_secret_key\") });\n }\n const target = { appId: peer.appId, chapterId: peer.chapterId, environment: peer.environment, runtime: peer.runtime,\n applicationId: String(input.applicationId), skuId: String(input.skuId) };\n if (action === \"access\") return respond({ ok: true, access: await readMembershipAccess(db, target, options.now?.() ?? Date.now()) });\n if (action === \"renewals\") return respond({ ok: true, renewal: await reconcileMembershipBilling(db,\n { ...target, eventId: String(input.eventId) }, options.now?.() ?? Date.now(), options.stripeSecretName) });\n if (action === \"refunds\") {\n const stripeSecret = await getVaultSecret(db, options.stripeSecretName ?? \"stripe_secret_key\");\n if (!stripeSecret) return respond({ error: \"membership_authority_unavailable\" }, 503);\n return respond({ ok: true, refund: await refundNetworkMembership(db, target, stripeSecret, options.now?.() ?? Date.now()) });\n }\n if (action === \"payments\" || action === \"approvals\") {\n const membership = action === \"payments\" ? await confirmMembershipPayment(db, { ...target,\n eventId: String(input.eventId), providerSubscriptionId: String(input.providerSubscriptionId), providerCustomerId: String(input.providerCustomerId),\n }, options.now?.() ?? Date.now()) : await approveNetworkMembership(db, target, options.now?.() ?? Date.now());\n return respond({ ok: true, membership });\n }\n if (action === \"checkouts\") {\n const binding = await bindMembershipCheckout(db, { appId: peer.appId, chapterId: peer.chapterId,\n environment: peer.environment, runtime: peer.runtime, applicationId: String(input.applicationId), skuId: String(input.skuId),\n offerId: String(input.offerId), offerDigest: String(input.offerDigest), quoteDigest: String(input.quoteDigest), priceId: String(input.priceId),\n }, options.now?.() ?? Date.now());\n return respond({ ok: true, binding });\n }\n const offerId = await membershipOfferIdForRequest({ ...peer, applicationId: String(input.applicationId), requestId: String(input.requestId) });\n const offer = await issueMembershipCommercialOffer(db, { offerId, appId: peer.appId, chapterId: peer.chapterId,\n environment: peer.environment, runtime: peer.runtime, applicationId: String(input.applicationId), skuId: String(input.skuId),\n now: options.now?.() ?? Date.now(), lifetimeMs: options.offerLifetimeMs });\n return respond({ ok: true, offer });\n } catch (error) {\n const code = (error as { code?: string })?.code;\n return respond({ error: code && SAFE_ERROR.has(code) ? code : \"membership_authority_unavailable\" },\n code === \"offer_identity_conflict\" ? 409 : 503);\n }\n };\n}\n","import type { ChapterDb } from \"./types\";\nimport { membershipOfferIdForRequest, verifyIssuedMembershipOffer } from \"./membership-offer-store\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\n\n/** A consented offer, bound once to the follower's immutable provider Price and quote. */\nexport interface MembershipCheckoutBindingInput extends MembershipQuoteTarget {\n offerId: string; offerDigest: string; quoteDigest: string; priceId: string;\n}\n/** Content-free authority receipt. It does not mean paid, approved, or entitled. */\nexport interface MembershipCheckoutBinding extends MembershipCheckoutBindingInput { id: string; boundAt: number }\nconst keys = [\"appId\", \"chapterId\", \"environment\", \"runtime\", \"applicationId\", \"skuId\", \"offerId\", \"offerDigest\", \"quoteDigest\", \"priceId\"] as const;\nconst reject = (code: string): never => { throw Object.assign(new Error(code), { code }); };\nconst load = async (db: ChapterDb, ns: string, id: string) => (await db.query({ [ns]: { $: { where: { id }, limit: 1 } } }))[ns]?.[0];\n\n/** Stable per-application binding identity, separate from an individual offer generation. */\nexport async function membershipCheckoutBindingId(input: MembershipQuoteTarget): Promise<string> {\n return (await membershipOfferIdForRequest({ ...input, requestId: \"checkout_binding\" })).replace(/^offer_/, \"checkout_\");\n}\n/** Validate an authenticated transport's receipt and discard all undeclared fields. */\nexport async function verifyMembershipCheckoutBinding(value: unknown, input: MembershipCheckoutBindingInput): Promise<MembershipCheckoutBinding> {\n const row = value as MembershipCheckoutBinding | undefined;\n if (!row || typeof row !== \"object\" || row.id !== await membershipCheckoutBindingId(input) ||\n keys.some(key => row[key] !== input[key]) || !Number.isSafeInteger(row.boundAt) || row.boundAt < 0) return reject(\"membership_checkout_conflict\");\n return { id: row.id, ...Object.fromEntries(keys.map(key => [key, input[key]])), boundAt: row.boundAt } as MembershipCheckoutBinding;\n}\n\n/** Bind accepted terms in the network transaction before any provider creation.\n * Replays preserve an already-bound offer after its issuance window ends.\n * A different offer/Price/consent for the same application is never a second purchase.\n */\nexport async function bindMembershipCheckout(db: ChapterDb, input: MembershipCheckoutBindingInput, now: number): Promise<MembershipCheckoutBinding> {\n if (!Number.isSafeInteger(now) || now < 0 || !/^[a-f0-9]{64}$/.test(input.offerDigest) ||\n !/^[a-f0-9]{64}$/.test(input.quoteDigest) || !/^price_[A-Za-z0-9_]+$/.test(input.priceId)) return reject(\"invalid_membership_checkout\");\n const stateId = `${input.chapterId}:${input.environment}`;\n const state = await load(db, \"membershipAuthorityState\", stateId);\n if (!state || state.mode !== \"authoritative\" || state.chapterId !== input.chapterId || state.environment !== input.environment ||\n !Number.isSafeInteger(state.revision) || Number(state.revision) < 1) return reject(\"membership_authority_unavailable\");\n const id = await membershipCheckoutBindingId(input);\n const existing = await load(db, \"membershipOfferCheckout\", id);\n if (existing) return verifyMembershipCheckoutBinding(existing, input);\n const row = await load(db, \"membershipCheckoutOffer\", input.offerId);\n const offer = await verifyIssuedMembershipOffer(row, { ...input, now, lifetimeMs: 60000 });\n if (offer.digest !== input.offerDigest || offer.expiresAt <= now || offer.issuedAt > now) return reject(\"membership_offer_expired\");\n const receipt = { id, ...Object.fromEntries(keys.map(key => [key, input[key]])), boundAt: now };\n try {\n await db.transact([{ t: \"update\", ns: \"membershipOfferCheckout\", id, attrs: receipt }], {\n mutationId: `membership-checkout:${id}`,\n guards: [{ ns: \"membershipOfferCheckout\", id, exists: false },\n { ns: \"membershipCheckoutOffer\", id: input.offerId, exists: true, equals: { digest: input.offerDigest } },\n { ns: \"membershipAuthorityState\", id: stateId, exists: true, equals: { mode: \"authoritative\", revision: state.revision } }],\n });\n } catch (error) {\n if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error;\n }\n const saved = await load(db, \"membershipOfferCheckout\", id);\n if (!saved) return reject(\"membership_binding_unconfirmed\");\n return verifyMembershipCheckoutBinding(saved, input);\n}\n","import type { ChapterDb, DbOp } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\n\nexport type MembershipRow = Record<string, unknown>;\nexport const membershipFail = (code: string): never => { throw Object.assign(new Error(code), { code }); };\nexport const membershipLoad = async (db: ChapterDb, ns: string, id: string): Promise<MembershipRow | undefined> =>\n (await db.query({ [ns]: { $: { where: { id }, limit: 1 } } }))[ns]?.[0];\nexport const membershipScopeKeys = [\"appId\", \"chapterId\", \"environment\", \"runtime\", \"applicationId\", \"skuId\"] as const;\nexport const membershipScope = (input: MembershipQuoteTarget) => Object.fromEntries(membershipScopeKeys.map(key => [key, input[key]]));\nexport function requireMembershipScope(row: MembershipRow | undefined, input: MembershipQuoteTarget): asserts row is MembershipRow {\n if (!row || membershipScopeKeys.some(key => row[key] !== input[key])) membershipFail(\"membership_scope_mismatch\");\n}\nexport async function loadMembershipAuthorityState(db: ChapterDb, input: Pick<MembershipQuoteTarget, \"chapterId\" | \"environment\">) {\n const row = await membershipLoad(db, \"membershipAuthorityState\", `${input.chapterId}:${input.environment}`);\n if (!row || row.mode !== \"authoritative\" || row.chapterId !== input.chapterId || row.environment !== input.environment ||\n !Number.isSafeInteger(row.revision) || Number(row.revision) < 1) return membershipFail(\"membership_authority_unavailable\");\n return row;\n}\nexport const membershipUpdate = (ns: string, id: string, attrs: MembershipRow): DbOp => ({ t: \"update\", ns, id, attrs });\nexport const membershipClock = (now: number) => {\n if (!Number.isSafeInteger(now) || now < 0) membershipFail(\"invalid_membership_clock\");\n};\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NetworkCommercialFact } from \"./types-network-commercial-projection\";\nimport { membershipCheckoutBindingId } from \"./membership-checkout-binding\";\nimport { verifyIssuedMembershipOffer } from \"./membership-offer-store\";\nimport { addMembershipCalendarMonths } from \"./membership-policy\";\nimport { membershipClock, membershipFail, membershipLoad, membershipScope, membershipUpdate, requireMembershipScope,\n loadMembershipAuthorityState } from \"./membership-authority-state\";\n\n/** References only. Money facts must already exist in the verified network Stripe event log. */\nexport interface ConfirmMembershipPaymentInput extends MembershipQuoteTarget {\n eventId: string; providerSubscriptionId: string; providerCustomerId: string;\n}\n/** The network identity remains source-linked until an explicit canonical Person link exists. */\nexport interface MembershipPaymentReceipt {\n membershipId: string; status: string; initialTermStartedAt: number; initialTermEndsAt: number;\n cohort: string; memberNumber?: number;\n}\n\n/** Stable network membership identity for the exact chapter application and runtime. */\nexport async function networkMembershipId(input: MembershipQuoteTarget): Promise<string> {\n return (await membershipCheckoutBindingId(input)).replace(/^checkout_/, \"membership_\");\n}\n/** Commit payment and the pending primary entitlement together, before chapter access can advance.\n * An authenticated Chapter supplies references, never a paid amount or a synthetic Person id.\n * A missing independently verified Stripe fact is retryable; browser success is not evidence.\n */\nexport async function confirmMembershipPayment(db: ChapterDb, input: ConfirmMembershipPaymentInput, now: number): Promise<MembershipPaymentReceipt> {\n membershipClock(now);\n if (!/^evt_[A-Za-z0-9_]+$/.test(input.eventId)) membershipFail(\"invalid_membership_payment\");\n const state = await loadMembershipAuthorityState(db, input);\n const binding = await membershipLoad(db, \"membershipOfferCheckout\", await membershipCheckoutBindingId(input));\n requireMembershipScope(binding, input);\n const offer = await verifyIssuedMembershipOffer(await membershipLoad(db, \"membershipCheckoutOffer\", String(binding.offerId)),\n { ...input, offerId: String(binding.offerId), now, lifetimeMs: 60000 });\n if (binding.offerDigest !== offer.digest) membershipFail(\"membership_checkout_conflict\");\n const eventRow = await membershipLoad(db, \"networkCommercialEvents\", `network-commercial-event:${input.eventId}`);\n if (!eventRow) membershipFail(\"membership_payment_evidence_pending\");\n if (await membershipLoad(db, \"networkCommercialExceptions\", `network-commercial-exception:${input.eventId}:collision`)) {\n membershipFail(\"membership_payment_evidence_quarantined\");\n }\n const fact = eventRow!.fact as NetworkCommercialFact;\n if (!fact || !fact.identity || !/^[a-f0-9]{64}$/.test(String(eventRow!.digest)) || fact.digest !== eventRow!.digest || fact.eventId !== input.eventId ||\n fact.eventType !== \"invoice.payment_succeeded\" || fact.objectKind !== \"invoice\" || fact.billingReason !== \"subscription_create\" ||\n fact.livemode !== (input.environment === \"prod\") || fact.status !== \"paid\" || fact.applicationId !== input.applicationId ||\n fact.subscriptionId !== input.providerSubscriptionId || fact.customerId !== input.providerCustomerId ||\n !/^in_[A-Za-z0-9_]+$/.test(fact.invoiceId ?? \"\") || fact.currency !== offer.contract.offering.currency ||\n fact.invoiceTotalCents !== offer.contract.dueTodayCents || fact.amountPaidCents !== offer.contract.dueTodayCents ||\n Object.entries({ appId: input.appId, chapterId: input.chapterId, environment: input.environment,\n dataEnvironment: input.environment, runtime: input.runtime }).some(([key, value]) => fact.identity[key as keyof typeof fact.identity] !== value)) {\n membershipFail(\"membership_payment_evidence_mismatch\");\n }\n const paidAt = fact.invoicePaidAt;\n const endsAt = offer.contract.initialTermEndsAt ?? fact.invoicePeriodEndsAt;\n // Stripe timestamps have second precision; binding timestamps have millisecond precision.\n if (!Number.isSafeInteger(paidAt) || Number(paidAt) < Math.floor(Number(binding.boundAt) / 1000) * 1000 || Number(paidAt) > now + 30000 ||\n !Number.isSafeInteger(endsAt) || Number(endsAt) <= Number(paidAt)) membershipFail(\"membership_payment_period_mismatch\");\n const id = await networkMembershipId(input), entitlementId = `${id}:primary`;\n let member = await membershipLoad(db, \"networkMembership\", id);\n if (!member) {\n const offering = offer.contract.offering;\n const attrs = { id, membershipId: id, ...membershipScope(input), baseSkuId: input.skuId, status: \"paid_pending_approval\",\n purchaseOfferId: offer.id, purchaseOfferDigest: offer.digest, providerInitialInvoiceId: fact.invoiceId,\n providerSubscriptionId: fact.subscriptionId, providerCustomerId: fact.customerId,\n providerPriceId: binding.priceId,\n offeringVersionId: offering.id, offeringSnapshot: offering,\n ...(offer.contract.discountPolicy ? { discountPolicyVersionId: offer.contract.discountPolicy.id, discountSnapshot: offer.contract.discountPolicy } : {}),\n founding: offer.contract.founding, cohort: offer.contract.founding ? offer.contract.discountPolicy!.cohortLabel : \"standard\",\n baseAmountCents: offering.basePriceCents, amountCents: offer.contract.dueTodayCents, renewalAmountCents: offer.contract.renewalCents,\n currency: offering.currency, interval: offering.interval,\n initialTermStartedAt: paidAt, initialTermEndsAt: endsAt, termStartedAt: paidAt, termEndsAt: endsAt,\n seatPurchaseEndsAt: addMembershipCalendarMonths(Number(paidAt), offering.seatPurchaseWindowCalendarMonths),\n autoRenew: true, refundedCents: 0, revision: 1, createdAt: now, updatedAt: now };\n try { await db.transact([\n membershipUpdate(\"networkMembership\", id, attrs),\n membershipUpdate(\"networkEntitlement\", entitlementId, { id: entitlementId, ...membershipScope(input), membershipId: id,\n kind: \"primary\", status: \"pending_approval\", termStartedAt: paidAt, termEndsAt: endsAt,\n offeringSnapshot: offering, sourceEventId: input.eventId, revision: 1, createdAt: now, updatedAt: now }),\n ], { mutationId: `membership-paid:${id}`, guards: [\n { ns: \"networkMembership\", id, exists: false },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n { ns: \"membershipOfferCheckout\", id: String(binding.id), exists: true, equals: { offerDigest: offer.digest } },\n { ns: \"networkCommercialEvents\", id: String(eventRow!.id), exists: true, equals: { digest: eventRow!.digest } },\n { ns: \"networkCommercialExceptions\", id: `network-commercial-exception:${input.eventId}:collision`, exists: false },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n member = await membershipLoad(db, \"networkMembership\", id);\n }\n requireMembershipScope(member, input);\n if (member.purchaseOfferDigest !== offer.digest || member.providerInitialInvoiceId !== fact.invoiceId ||\n member.providerSubscriptionId !== fact.subscriptionId || member.providerCustomerId !== fact.customerId) membershipFail(\"membership_purchase_conflict\");\n return { membershipId: id, status: String(member.status), cohort: String(member.cohort),\n initialTermStartedAt: Number(member.initialTermStartedAt), initialTermEndsAt: Number(member.initialTermEndsAt),\n ...(typeof member.memberNumber === \"number\" ? { memberNumber: member.memberNumber } : {}) };\n}\n","import type { ChapterDb, DbOp } from \"./types\";\nimport { membershipLoad, membershipUpdate, membershipFail, type MembershipRow } from \"./membership-authority-state\";\ntype Guard = NonNullable<NonNullable<Parameters<ChapterDb[\"transact\"]>[1]>[\"guards\"]>[number];\n\n/** Include these guards even when no seat is eligible yet, so recipient approval cannot race primary approval. */\nexport async function namedSeatPrimaryActivation(db: ChapterDb, member: MembershipRow, now: number): Promise<{ ops: DbOp[]; guards: Guard[] }> {\n if (!member.namedSeatId) return { ops: [], guards: [] };\n const seat = await membershipLoad(db, \"networkSeat\", String(member.namedSeatId));\n if (!seat || seat.primaryMembershipId !== member.id) return membershipFail(\"named_seat_primary_conflict\");\n const guards: Guard[] = [{ ns: \"networkSeat\", id: String(seat.id), exists: true, equals: { revision: seat.revision } }];\n if (seat.status !== \"pending_primary\") return { ops: [], guards };\n if (!seat.acceptedAt || !seat.journeyApprovedAt || !seat.recipientApplicationId || !seat.recipientUserId ||\n !seat.providerSubscriptionItemId || Number(seat.termEndsAt) <= now) return membershipFail(\"named_seat_primary_conflict\");\n const entitlement = await membershipLoad(db, \"networkEntitlement\", String(seat.entitlementId));\n if (!entitlement || entitlement.seatId !== seat.id || entitlement.status !== \"pending_primary\") return membershipFail(\"named_seat_primary_conflict\");\n guards.push({ ns: \"networkEntitlement\", id: String(entitlement.id), exists: true, equals: { revision: entitlement.revision } });\n return { guards, ops: [\n membershipUpdate(\"networkSeat\", String(seat.id), { status: \"active\", revision: Number(seat.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", String(entitlement.id), { status: \"active\", revision: Number(entitlement.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", `${seat.id}:grant`, { id: `${seat.id}:grant`, chapterId: member.chapterId,\n environment: member.environment, runtime: member.runtime, membershipId: member.id, seatId: seat.id,\n kind: \"grant_named_recipient_access\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now }),\n ] };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { networkMembershipId, type MembershipPaymentReceipt } from \"./membership-payment-authority\";\nimport { namedSeatPrimaryActivation } from \"./membership-seat-activation\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate,\n requireMembershipScope } from \"./membership-authority-state\";\n\n/** The signed chapter adapter attests that its own Journey approval is durable.\n * Payment, cohort and order come exclusively from network authority records.\n * An issued paid founding promise is honored even after the soft target is reached.\n */\nexport async function approveNetworkMembership(db: ChapterDb, input: MembershipQuoteTarget, now: number): Promise<MembershipPaymentReceipt> {\n membershipClock(now);\n const id = await networkMembershipId(input), entitlementId = `${id}:primary`;\n for (let attempt = 0; attempt < 8; attempt++) {\n const state = await loadMembershipAuthorityState(db, input);\n const member = await membershipLoad(db, \"networkMembership\", id);\n requireMembershipScope(member, input);\n const entitlement = await membershipLoad(db, \"networkEntitlement\", entitlementId);\n requireMembershipScope(entitlement, input);\n if (entitlement.membershipId !== id || entitlement.kind !== \"primary\") membershipFail(\"membership_entitlement_conflict\");\n if ([\"active\", \"cancel_at_term_end\"].includes(String(member.status)) && entitlement.status === \"active\" &&\n Number(member.refundedCents) === 0 &&\n Number.isSafeInteger(member.memberNumber) && Number(member.memberNumber) > 0 && Number(member.termEndsAt) > now) {\n return { membershipId: id, status: String(member.status), cohort: String(member.cohort), memberNumber: Number(member.memberNumber),\n initialTermStartedAt: Number(member.initialTermStartedAt), initialTermEndsAt: Number(member.initialTermEndsAt) };\n }\n if (member.status !== \"paid_pending_approval\" || entitlement.status !== \"pending_approval\" ||\n Number(member.amountCents) <= 0 || Number(member.refundedCents) !== 0 || Number(member.termEndsAt) <= now ||\n !/^in_/.test(String(member.providerInitialInvoiceId)) || !Number.isSafeInteger(member.revision) ||\n !Number.isSafeInteger(entitlement.revision) || member.memberNumber !== undefined) membershipFail(\"membership_not_approvable\");\n const memberNumber = state.nextMemberNumber;\n const counts = state.cohortCounts as Record<string, unknown>;\n if (!Number.isSafeInteger(memberNumber) || Number(memberNumber) < 1 || Number(memberNumber) >= Number.MAX_SAFE_INTEGER ||\n !counts || typeof counts !== \"object\" || Array.isArray(counts)) membershipFail(\"membership_numbering_unavailable\");\n const cohort = String(member.cohort), previousCount = counts[cohort] ?? 0;\n if (!Number.isSafeInteger(previousCount) || Number(previousCount) < 0 || Number(previousCount) >= Number.MAX_SAFE_INTEGER) {\n membershipFail(\"invalid_cohort_count\");\n }\n const cohortCounts = { ...counts, ...(member.founding === true ? { [cohort]: Number(previousCount) + 1 } : {}) };\n const seatActivation = await namedSeatPrimaryActivation(db, member, now);\n try {\n await db.transact([\n membershipUpdate(\"networkMembership\", id, { status: member.autoRenew ? \"active\" : \"cancel_at_term_end\", memberNumber, journeyApprovedAt: now,\n revision: Number(member.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", entitlementId, { status: \"active\", revision: Number(entitlement.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipAuthorityState\", String(state.id), { nextMemberNumber: Number(memberNumber) + 1,\n cohortCounts, revision: Number(state.revision) + 1, updatedAt: now }),\n ...seatActivation.ops,\n ], { mutationId: `membership-approve:${id}`, guards: [\n { ns: \"networkMembership\", id, exists: true, equals: { revision: member.revision, status: \"paid_pending_approval\" }, absent: [\"memberNumber\"] },\n { ns: \"networkEntitlement\", id: entitlementId, exists: true, equals: { revision: entitlement.revision, status: \"pending_approval\" } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { revision: state.revision, mode: \"authoritative\" } },\n ...seatActivation.guards,\n ] });\n } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n // Read canonical state even after a successful/duplicate acknowledgement.\n }\n return membershipFail(\"membership_approval_retry_required\");\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\n\ntype Row = Record<string, unknown>;\nconst row = (value: unknown): Row => value && typeof value === \"object\" && !Array.isArray(value) ? value as Row : {};\nconst id = (value: unknown): string => typeof value === \"string\" ? value : String(row(value).id ?? \"\");\nconst providerId = (value: string, prefix: string) => new RegExp(`^${prefix}_[A-Za-z0-9]+$`).test(value);\nfunction fail(code = \"refund_target_mismatch\"): never { throw Object.assign(new Error(code), { code }); }\n\n/** Full initial-payment refund, bound to a subscription rather than a customer charge list. */\nexport interface SubscriptionRefundInput {\n customerId: string;\n subscriptionId: string;\n /** Exact expected subscription partition metadata; supplied by the admin route. */\n metadata?: Record<string, string>;\n /** Defaults to true. Failed cancellation is an error and can be retried after refund. */\n cancelSubscription?: boolean;\n /** Frozen network purchase evidence, when authority has already identified the initial invoice. */\n expectedInvoiceId?: string;\n expectedAmountCents?: number;\n /** Reconcile a provider-initiated full refund: verify this exact charge is already fully refunded before any write. */\n alreadyRefundedChargeId?: string;\n}\n\n/** Refund the same first paid invoice on every retry, then finish cancellation.\n * Already fully refunded charges never cause selection of a later renewal.\n * Ambiguous/multi-payment invoices fail closed for explicit reconciliation.\n */\nexport async function refundSubscriptionPayment(secretKey: string, input: SubscriptionRefundInput): Promise<{\n refundedCents: number; subscriptionCanceled: boolean;\n}> {\n if (!providerId(input.customerId, \"cus\") || !providerId(input.subscriptionId, \"sub\")) fail();\n const call = async (method: \"GET\" | \"POST\" | \"DELETE\", path: string, params?: Row, key?: string): Promise<Row> => {\n const result = await stripeRequest({ secretKey }, method, path, params, key ? { idempotencyKey: key } : {});\n if (!result.ok) fail(\"stripe_error\");\n if (!result.body || typeof result.body !== \"object\" || Array.isArray(result.body)) fail(\"stripe_invalid_response\");\n return result.body;\n };\n const sub = await call(\"GET\", `/v1/subscriptions/${input.subscriptionId}`);\n if (id(sub) !== input.subscriptionId || id(sub.customer) !== input.customerId) fail();\n for (const [key, value] of Object.entries(input.metadata ?? {})) {\n if (row(sub.metadata)[key] !== value) fail();\n }\n let cursor: string | undefined;\n let earliest: Row | undefined;\n const seen = new Set<string>();\n for (let page = 0; page < 10; page++) {\n const list = await call(\"GET\", \"/v1/invoices\", { subscription: input.subscriptionId, customer: input.customerId,\n status: \"paid\", limit: 100, ...(cursor ? { starting_after: cursor } : {}) });\n if (!Array.isArray(list.data) || typeof list.has_more !== \"boolean\") fail(\"stripe_invalid_response\");\n for (const value of list.data) {\n const invoice = row(value);\n const subscription = invoice.subscription ?? row(row(invoice.parent).subscription_details).subscription;\n if (!providerId(id(invoice), \"in\") || seen.has(id(invoice)) || id(subscription) !== input.subscriptionId ||\n id(invoice.customer) !== input.customerId || invoice.status !== \"paid\" ||\n !Number.isSafeInteger(invoice.created) || !Number.isSafeInteger(invoice.amount_paid) || Number(invoice.amount_paid) < 0) fail();\n seen.add(id(invoice));\n if (Number(invoice.amount_paid) > 0 && (!earliest || Number(invoice.created) < Number(earliest.created))) earliest = invoice;\n }\n if (!list.has_more) break;\n if (!list.data.length || page === 9) fail(\"refund_history_incomplete\");\n cursor = id(list.data[list.data.length - 1]);\n }\n if (!earliest) fail(\"no_charge\");\n const invoice = earliest!;\n if ((input.expectedInvoiceId !== undefined && id(invoice) !== input.expectedInvoiceId) ||\n (input.expectedAmountCents !== undefined && invoice.amount_paid !== input.expectedAmountCents)) fail();\n let chargeId = id(invoice.charge);\n let paymentIntentId = id(invoice.payment_intent);\n if (!chargeId && !paymentIntentId) {\n const payments = await call(\"GET\", \"/v1/invoice_payments\", { invoice: id(invoice), status: \"paid\", limit: 100 });\n if (payments.has_more !== false || !Array.isArray(payments.data) || payments.data.length !== 1) fail(\"refund_payment_ambiguous\");\n const payment = row(payments.data[0]);\n if (id(payment.invoice) !== id(invoice) || payment.status !== \"paid\" || row(payment.payment).type !== \"payment_intent\") fail();\n paymentIntentId = id(row(payment.payment).payment_intent);\n }\n if (!chargeId) {\n if (!providerId(paymentIntentId, \"pi\")) fail();\n const payment = await call(\"GET\", `/v1/payment_intents/${paymentIntentId}`);\n if (id(payment) !== paymentIntentId || id(payment.customer) !== input.customerId || payment.status !== \"succeeded\") fail();\n chargeId = id(payment.latest_charge);\n }\n if (!providerId(chargeId, \"ch\")) fail();\n const charge = await call(\"GET\", `/v1/charges/${chargeId}`);\n if (id(charge) !== chargeId || id(charge.customer) !== input.customerId || charge.status !== \"succeeded\" ||\n (charge.invoice != null && id(charge.invoice) !== id(invoice)) ||\n (paymentIntentId && id(charge.payment_intent) !== paymentIntentId) ||\n !Number.isSafeInteger(charge.amount) || Number(charge.amount) <= 0 ||\n !Number.isSafeInteger(charge.amount_refunded) || Number(charge.amount_refunded) < 0 ||\n Number(charge.amount_refunded) > Number(charge.amount) || charge.currency !== invoice.currency ||\n Number(charge.amount) !== Number(invoice.amount_paid)) fail();\n if (input.alreadyRefundedChargeId !== undefined && (chargeId !== input.alreadyRefundedChargeId ||\n charge.amount_refunded !== charge.amount || charge.refunded !== true)) fail();\n if (charge.amount_refunded !== charge.amount) {\n const refund = await call(\"POST\", \"/v1/refunds\", { charge: chargeId,\n ...(input.metadata ? { metadata: input.metadata } : {}) }, `chapter-initial-refund:${input.subscriptionId}:${chargeId}`);\n if (id(refund.charge) !== chargeId || ![\"succeeded\", \"pending\"].includes(String(refund.status)) ||\n !Number.isSafeInteger(refund.amount) || Number(refund.amount) !== Number(charge.amount) - Number(charge.amount_refunded)) fail(\"refund_not_confirmed\");\n }\n let subscriptionCanceled = sub.status === \"canceled\";\n if (input.cancelSubscription !== false && !subscriptionCanceled) {\n const canceled = await call(\"DELETE\", `/v1/subscriptions/${input.subscriptionId}`);\n if (id(canceled) !== input.subscriptionId || canceled.status !== \"canceled\") fail(\"refund_cancel_incomplete\");\n subscriptionCanceled = true;\n }\n // A pending refund is not a completed refund. Re-read the exact charge on\n // every attempt, including recovery after a lost response or missing webhook.\n const confirmed = await call(\"GET\", `/v1/charges/${chargeId}`);\n if (id(confirmed) !== chargeId || id(confirmed.customer) !== input.customerId ||\n confirmed.amount !== charge.amount || confirmed.currency !== charge.currency ||\n confirmed.amount_refunded !== charge.amount || confirmed.refunded !== true) fail(\"refund_not_confirmed\");\n return { refundedCents: Number(charge.amount), subscriptionCanceled };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { refundSubscriptionPayment } from \"./payments-refund\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Verified full initial refund and subscription cancellation, not a browser assertion. */\nexport interface MembershipRefundReceipt { membershipId: string; status: \"refunded\"; refundedCents: number; subscriptionCanceled: true }\n/** Refund the frozen initial membership purchase; retain cohort and member order permanently.\n * The adapter authenticates the operator. Pending state prevents new access while provider effects retry.\n */\nexport async function refundNetworkMembership(db: ChapterDb, input: MembershipQuoteTarget, secretKey: string, now: number): Promise<MembershipRefundReceipt> {\n membershipClock(now);\n const id = await networkMembershipId(input), entitlementId = `${id}:primary`;\n let state = await loadMembershipAuthorityState(db, input), member = await membershipLoad(db, \"networkMembership\", id);\n requireMembershipScope(member, input);\n if (member.status === \"refunded\") return { membershipId: id, status: \"refunded\", refundedCents: Number(member.refundedCents), subscriptionCanceled: true };\n if (![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\", \"payment_grace\", \"lapsed\", \"refund_pending\"].includes(String(member.status))) membershipFail(\"membership_refund_not_eligible\");\n if (member.status !== \"refund_pending\") {\n const entitlement = await membershipLoad(db, \"networkEntitlement\", entitlementId); requireMembershipScope(entitlement, input);\n await db.transact([\n membershipUpdate(\"networkMembership\", id, { status: \"refund_pending\", refundRequestedAt: now,\n revision: Number(member.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", entitlementId, { status: \"closed\", revision: Number(entitlement.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", `${id}:refund`, { id: `${id}:refund`, chapterId: input.chapterId, environment: input.environment,\n runtime: input.runtime, membershipId: id, kind: \"refund_membership\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now }),\n ], { mutationId: `membership-refund-request:${id}`, guards: [\n { ns: \"networkMembership\", id, exists: true, equals: { revision: member.revision } },\n { ns: \"networkEntitlement\", id: entitlementId, exists: true, equals: { revision: entitlement.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { revision: state.revision, mode: \"authoritative\" } },\n ] });\n }\n member = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(member, input);\n if (member.status !== \"refund_pending\") membershipFail(\"membership_refund_retry_required\");\n const result = await refundSubscriptionPayment(secretKey, { customerId: String(member.providerCustomerId), subscriptionId: String(member.providerSubscriptionId),\n expectedInvoiceId: String(member.providerInitialInvoiceId), expectedAmountCents: Number(member.amountCents), cancelSubscription: true,\n metadata: { ...stripePartitionMetadata(input), applicationId: input.applicationId },\n });\n if (!result.subscriptionCanceled || result.refundedCents !== member.amountCents) membershipFail(\"membership_refund_unconfirmed\");\n for (let attempt = 0; attempt < 8; attempt++) {\n state = await loadMembershipAuthorityState(db, input);\n member = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(member, input);\n if (member.status === \"refunded\") return { membershipId: id, status: \"refunded\", refundedCents: Number(member.refundedCents), subscriptionCanceled: true };\n if (member.status !== \"refund_pending\") membershipFail(\"membership_refund_retry_required\");\n const counted = member.founding === true && member.memberNumber !== undefined;\n const counts = state.cohortCounts as Record<string, number>;\n if (!counts || (counted && (!Number.isSafeInteger(counts[String(member.cohort)]) || counts[String(member.cohort)]! < 1))) membershipFail(\"invalid_cohort_count\");\n try { await db.transact([\n membershipUpdate(\"networkMembership\", id, { status: \"refunded\", refundedCents: result.refundedCents, autoRenew: false,\n revision: Number(member.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", `${id}:refund`, { status: \"complete\", updatedAt: now }),\n ...(counted ? [membershipUpdate(\"membershipAuthorityState\", String(state.id), { cohortCounts: { ...counts, [String(member.cohort)]: counts[String(member.cohort)]! - 1 },\n revision: Number(state.revision) + 1, updatedAt: now })] : []),\n ...(member.namedSeatId ? [membershipUpdate(\"membershipEffect\", `${member.namedSeatId}:primary-refund`, {\n id: `${member.namedSeatId}:primary-refund`, chapterId: input.chapterId, environment: input.environment, runtime: input.runtime,\n membershipId: id, seatId: member.namedSeatId, kind: \"refund_seat_with_primary\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now })] : []),\n ], { mutationId: `membership-refunded:${id}`, guards: [\n { ns: \"networkMembership\", id, exists: true, equals: { status: \"refund_pending\", revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n }\n return membershipFail(\"membership_refund_retry_required\");\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\nimport type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NetworkCommercialFact } from \"./types-network-commercial-projection\";\nimport type { MembershipRenewalReceipt } from \"./membership-renewal-authority\";\nimport { getVaultSecret } from \"./auth\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { reconcileMembershipRenewal } from \"./membership-renewal-authority\";\nimport { refundNetworkMembership } from \"./membership-refund-authority\";\nimport { refundSubscriptionPayment } from \"./payments-refund\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Reconcile invoices, cancellation settings and provider-initiated full initial refunds from independent evidence.\n * Current Stripe reads arbitrate out-of-order subscription events. Only paid invoices extend a membership term.\n */\nexport async function reconcileMembershipBilling(db: ChapterDb, input: MembershipQuoteTarget & { eventId: string }, now: number,\n stripeSecretName = \"stripe_secret_key\"): Promise<MembershipRenewalReceipt> {\n membershipClock(now);\n const row = await membershipLoad(db, \"networkCommercialEvents\", `network-commercial-event:${input.eventId}`);\n const fact = row?.fact as NetworkCommercialFact | undefined;\n if (fact?.objectKind === \"invoice\") return reconcileMembershipRenewal(db, input, now);\n const collisionId = `network-commercial-exception:${input.eventId}:collision`;\n if (!fact || fact.eventId !== input.eventId || fact.digest !== row!.digest || !/^[a-f0-9]{64}$/.test(fact.digest) ||\n ![\"customer.subscription.updated\", \"customer.subscription.deleted\", \"charge.refunded\"].includes(fact.eventType) ||\n fact.livemode !== (input.environment === \"prod\") || fact.applicationId !== input.applicationId || !fact.identity ||\n Object.entries({ appId: input.appId, chapterId: input.chapterId, environment: input.environment, dataEnvironment: input.environment,\n runtime: input.runtime }).some(([key, value]) => fact.identity[key as keyof typeof fact.identity] !== value) ||\n await membershipLoad(db, \"networkCommercialExceptions\", collisionId)) membershipFail(\"membership_billing_evidence_pending\");\n const sk = await getVaultSecret(db, stripeSecretName);\n if (!sk) membershipFail(\"membership_billing_provider_unavailable\");\n const id = await networkMembershipId(input);\n for (let attempt = 0; attempt < 8; attempt++) {\n const state = await loadMembershipAuthorityState(db, input), member = await membershipLoad(db, \"networkMembership\", id);\n requireMembershipScope(member, input);\n const receipt = (value = member): MembershipRenewalReceipt => ({ membershipId: id, status: String(value.status),\n termEndsAt: Number(value.termEndsAt), graceEndsAt: Number(value.graceEndsAt ?? 0), autoRenew: value.autoRenew === true });\n if (fact!.customerId !== member.providerCustomerId) membershipFail(\"membership_billing_scope_mismatch\");\n if (fact!.eventType === \"charge.refunded\") {\n if (!fact!.chargeId || fact!.seatId || fact!.amountCents !== member.amountCents || fact!.currency !== member.currency) membershipFail(\"membership_refund_evidence_mismatch\");\n // Read-only proof resolves modern invoice_payments before closing access. A renewal charge cannot refund the initial membership.\n await refundSubscriptionPayment(sk!, { customerId: String(member.providerCustomerId), subscriptionId: String(member.providerSubscriptionId),\n metadata: { ...stripePartitionMetadata(input), applicationId: input.applicationId }, expectedInvoiceId: String(member.providerInitialInvoiceId),\n expectedAmountCents: Number(member.amountCents), alreadyRefundedChargeId: fact!.chargeId, cancelSubscription: false });\n if (await membershipLoad(db, \"networkCommercialExceptions\", collisionId)) membershipFail(\"membership_billing_evidence_pending\");\n await refundNetworkMembership(db, input, sk!, now);\n const saved = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(saved, input); return receipt(saved);\n }\n if (fact!.subscriptionId !== member.providerSubscriptionId || fact!.objectKind !== \"subscription\") membershipFail(\"membership_billing_scope_mismatch\");\n if ([\"refund_pending\", \"refunded\", \"declined\", \"canceled\"].includes(String(member.status))) return receipt();\n const result = await stripeRequest<Record<string, any>>({ secretKey: sk! }, \"GET\", `/v1/subscriptions/${encodeURIComponent(String(member.providerSubscriptionId))}`);\n const sub = result.body;\n if (!result.ok || sub.id !== member.providerSubscriptionId || sub.customer !== member.providerCustomerId ||\n sub.livemode !== (input.environment === \"prod\") || typeof sub.cancel_at_period_end !== \"boolean\" ||\n ![\"active\", \"trialing\", \"past_due\", \"unpaid\", \"canceled\"].includes(sub.status) ||\n !Object.entries({ ...stripePartitionMetadata(input), applicationId: input.applicationId }).every(([key, value]) => sub.metadata?.[key] === value)) {\n membershipFail(\"membership_billing_provider_mismatch\");\n }\n const autoRenew = sub.status !== \"canceled\" && sub.cancel_at_period_end !== true;\n // Canceling billing never removes the already-paid term. Grace ends if collection is explicitly canceled.\n const status = autoRenew ? (member.status === \"cancel_at_term_end\" ? \"active\" : String(member.status)) :\n now >= Number(member.termEndsAt) ? \"lapsed\" : member.journeyApprovedAt ? \"cancel_at_term_end\" : \"paid_pending_approval\";\n const graceEndsAt = autoRenew ? Number(member.graceEndsAt ?? 0) : 0;\n if (member.autoRenew === autoRenew && member.status === status && Number(member.graceEndsAt ?? 0) === graceEndsAt) return receipt();\n const entitlement = await membershipLoad(db, \"networkEntitlement\", `${id}:primary`); requireMembershipScope(entitlement, input);\n try { await db.transact([\n membershipUpdate(\"networkMembership\", id, { status, autoRenew, graceEndsAt, revision: Number(member.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", String(entitlement.id), { status: status === \"lapsed\" ? \"closed\" : entitlement.status,\n revision: Number(entitlement.revision) + 1, updatedAt: now }),\n ], { guards: [\n { ns: \"networkMembership\", id, exists: true, equals: { revision: member.revision } },\n { ns: \"networkEntitlement\", id: String(entitlement.id), exists: true, equals: { revision: entitlement.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n { ns: \"networkCommercialEvents\", id: String(row!.id), exists: true, equals: { digest: fact!.digest } },\n { ns: \"networkCommercialExceptions\", id: collisionId, exists: false },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; continue; }\n const saved = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(saved, input); return receipt(saved);\n }\n return membershipFail(\"membership_billing_retry_required\");\n}\n","import type { ChapterDb, DbOp } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NetworkCommercialFact } from \"./types-network-commercial-projection\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { addMembershipCalendarMonths } from \"./membership-policy\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate,\n requireMembershipScope } from \"./membership-authority-state\";\n\n/** Current authoritative billing state; a chapter projection must not derive it from arrival order. */\nexport interface MembershipRenewalReceipt { membershipId: string; status: string; termEndsAt: number; graceEndsAt: number; autoRenew: boolean }\n/** Apply independently verified renewal success/failure, including co-terminating named seats.\n * The period and immutable Price set, not webhook delivery order, fence progression.\n */\nexport async function reconcileMembershipRenewal(db: ChapterDb, input: MembershipQuoteTarget & { eventId: string }, now: number): Promise<MembershipRenewalReceipt> {\n membershipClock(now);\n const id = await networkMembershipId(input), eventRow = await membershipLoad(db, \"networkCommercialEvents\", `network-commercial-event:${input.eventId}`);\n const fact = eventRow?.fact as NetworkCommercialFact | undefined;\n if (!fact || !/^evt_[A-Za-z0-9_]+$/.test(input.eventId) || !/^[a-f0-9]{64}$/.test(String(eventRow!.digest)) ||\n fact.digest !== eventRow!.digest || fact.eventId !== input.eventId || fact.objectKind !== \"invoice\" ||\n ![\"invoice.payment_succeeded\", \"invoice.payment_failed\"].includes(fact.eventType) || fact.billingReason !== \"subscription_cycle\" ||\n fact.livemode !== (input.environment === \"prod\") || fact.applicationId !== input.applicationId ||\n Object.entries({ appId: input.appId, chapterId: input.chapterId, environment: input.environment,\n dataEnvironment: input.environment, runtime: input.runtime }).some(([key, value]) => fact.identity[key as keyof typeof fact.identity] !== value) ||\n await membershipLoad(db, \"networkCommercialExceptions\", `network-commercial-exception:${input.eventId}:collision`)) {\n return membershipFail(\"membership_renewal_evidence_pending\");\n }\n for (let attempt = 0; attempt < 8; attempt++) {\n const state = await loadMembershipAuthorityState(db, input), member = await membershipLoad(db, \"networkMembership\", id);\n requireMembershipScope(member, input);\n const receipt = (): MembershipRenewalReceipt => ({ membershipId: id, status: String(member.status), termEndsAt: Number(member.termEndsAt),\n graceEndsAt: Number(member.graceEndsAt ?? 0), autoRenew: member.autoRenew === true });\n if (fact.subscriptionId !== member.providerSubscriptionId || fact.customerId !== member.providerCustomerId ||\n fact.currency !== member.currency) membershipFail(\"membership_renewal_scope_mismatch\");\n // Terminal purchases cannot be revived by a late paid event.\n if ([\"refunded\", \"refund_pending\", \"canceled\", \"declined\"].includes(String(member.status))) return receipt();\n const lines = fact.recurringInvoiceLines;\n if (!lines?.length || lines.length > 2) membershipFail(\"membership_renewal_lines_missing\");\n const start = lines![0]!.startsAt, end = lines![0]!.endsAt;\n if (!lines!.every(line => line.startsAt === start && line.endsAt === end && line.quantity === 1) ||\n end !== addMembershipCalendarMonths(start, member.interval === \"year\" ? 12 : 1)) membershipFail(\"membership_renewal_period_mismatch\");\n // Older periods, including failed attempts delivered after their successful payment, are no-ops.\n if (end <= Number(member.termEndsAt)) return receipt();\n if (start !== member.termEndsAt || start > now + 30000) membershipFail(\"membership_renewal_period_gap\");\n const seat = member.namedSeatId ? await membershipLoad(db, \"networkSeat\", String(member.namedSeatId)) : undefined;\n if (seat) requireMembershipScope(seat, input);\n const billedSeat = seat && seat.providerSubscriptionItemId && ![\"refunded\", \"refund_pending\"].includes(String(seat.status)) ? seat : undefined;\n const prices = [String(member.providerPriceId), ...(billedSeat ? [String(billedSeat.priceId)] : [])].sort();\n const amount = Number(member.renewalAmountCents) + Number(billedSeat?.amountCents ?? 0);\n if (!Number.isSafeInteger(amount) || amount <= 0 || fact.invoiceTotalCents !== amount ||\n JSON.stringify(lines!.map(line => line.priceId).sort()) !== JSON.stringify(prices)) membershipFail(\"membership_renewal_amount_mismatch\");\n const paid = fact.eventType === \"invoice.payment_succeeded\";\n if (!paid && (fact.status !== \"open\" || !Number.isSafeInteger(fact.amountPaidCents) ||\n Number(fact.amountPaidCents) < 0 || Number(fact.amountPaidCents) >= amount)) membershipFail(\"membership_renewal_failure_mismatch\");\n if (paid && (fact.status !== \"paid\" || fact.amountPaidCents !== amount || !Number.isSafeInteger(fact.invoicePaidAt) ||\n Number(fact.invoicePaidAt) < start || Number(fact.invoicePaidAt) > now + 30000)) membershipFail(\"membership_renewal_unpaid\");\n const entitlement = await membershipLoad(db, \"networkEntitlement\", `${id}:primary`); requireMembershipScope(entitlement, input);\n const graceEndsAt = paid ? 0 : start + 14 * 86400000;\n const status = paid ? (member.journeyApprovedAt ? (member.autoRenew ? \"active\" : \"cancel_at_term_end\") : \"paid_pending_approval\") :\n now < graceEndsAt ? \"payment_grace\" : \"lapsed\";\n const entitlementStatus = member.journeyApprovedAt && (paid || now < graceEndsAt) ? \"active\" :\n member.journeyApprovedAt ? \"closed\" : \"pending_approval\";\n const ops: DbOp[] = [\n membershipUpdate(\"networkMembership\", id, { status, graceEndsAt, ...(paid ? { termStartedAt: start, termEndsAt: end } : {}),\n revision: Number(member.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", `${id}:primary`, { status: entitlementStatus,\n ...(paid ? { termStartedAt: start, termEndsAt: end } : {}), sourceEventId: input.eventId,\n revision: Number(entitlement.revision) + 1, updatedAt: now }),\n ];\n const guards = [\n { ns: \"networkMembership\", id, exists: true, equals: { revision: member.revision } },\n { ns: \"networkEntitlement\", id: `${id}:primary`, exists: true, equals: { revision: entitlement.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { revision: state.revision, mode: \"authoritative\" } },\n { ns: \"networkCommercialEvents\", id: String(eventRow!.id), exists: true, equals: { digest: eventRow!.digest } },\n { ns: \"networkCommercialExceptions\", id: `network-commercial-exception:${input.eventId}:collision`, exists: false },\n ];\n if (seat) guards.push({ ns: \"networkSeat\", id: String(seat.id), exists: true, equals: { revision: seat.revision } });\n if (billedSeat?.entitlementId) {\n const seatEntitlement = await membershipLoad(db, \"networkEntitlement\", String(billedSeat.entitlementId)); requireMembershipScope(seatEntitlement, input);\n guards.push({ ns: \"networkEntitlement\", id: String(seatEntitlement.id), exists: true, equals: { revision: seatEntitlement.revision } });\n ops.push(membershipUpdate(\"networkSeat\", String(billedSeat.id), { ...(paid ? { termStartedAt: start, termEndsAt: end } : {}),\n revision: Number(billedSeat.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", String(seatEntitlement.id), { ...(paid ? { termStartedAt: start, termEndsAt: end } : {}),\n status: billedSeat.journeyApprovedAt ? entitlementStatus : seatEntitlement.status,\n revision: Number(seatEntitlement.revision) + 1, updatedAt: now }));\n }\n try { await db.transact(ops, { mutationId: `membership-renewal:${id}:${input.eventId}`, guards }); }\n catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; continue; }\n const saved = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(saved, input);\n return { membershipId: id, status: String(saved.status), termEndsAt: Number(saved.termEndsAt),\n graceEndsAt: Number(saved.graceEndsAt ?? 0), autoRenew: saved.autoRenew === true };\n }\n return membershipFail(\"membership_renewal_retry_required\");\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { loadMembershipAuthorityState, membershipClock, membershipLoad, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Short-lived decision from current network state; never a durable bearer capability. */\nexport interface MembershipAccessReceipt { membershipId: string; allowed: boolean; status: string; accessEndsAt: number; revision: number }\n/** Enforce term/grace expiry even when a webhook, cron, or Clerk role update is delayed. */\nexport async function readMembershipAccess(db: ChapterDb, input: MembershipQuoteTarget, now: number): Promise<MembershipAccessReceipt> {\n membershipClock(now); await loadMembershipAuthorityState(db, input);\n const id = await networkMembershipId(input), member = await membershipLoad(db, \"networkMembership\", id);\n if (!member) return { membershipId: id, allowed: false, status: \"unpaid\", accessEndsAt: 0, revision: 0 };\n requireMembershipScope(member, input);\n const entitlement = await membershipLoad(db, \"networkEntitlement\", `${id}:primary`); requireMembershipScope(entitlement, input);\n const endsAt = member.status === \"payment_grace\" ? Number(member.graceEndsAt) : Number(member.termEndsAt);\n const allowed = [\"active\", \"cancel_at_term_end\", \"payment_grace\"].includes(String(member.status)) &&\n member.journeyApprovedAt !== undefined && Number.isSafeInteger(member.memberNumber) && Number(member.memberNumber) > 0 &&\n member.refundedCents === 0 && entitlement.status === \"active\" && entitlement.membershipId === id &&\n entitlement.kind === \"primary\" && Number.isSafeInteger(endsAt) && endsAt > now && Number(member.termStartedAt) <= now;\n return { membershipId: id, allowed, status: String(member.status), accessEndsAt: Number.isSafeInteger(endsAt) ? endsAt : 0,\n revision: Number(member.revision) };\n}\n\n/** Reject an invalid network receipt before a chapter grants private-content access. */\nexport async function verifyMembershipAccessReceipt(value: unknown, input: MembershipQuoteTarget, now: number): Promise<MembershipAccessReceipt> {\n const row = value as MembershipAccessReceipt;\n if (!row || row.membershipId !== await networkMembershipId(input) || typeof row.allowed !== \"boolean\" || typeof row.status !== \"string\" ||\n !Number.isSafeInteger(row.revision) || row.revision < 0 || !Number.isSafeInteger(row.accessEndsAt) || row.accessEndsAt < 0 ||\n (row.allowed && (!['active', 'cancel_at_term_end', 'payment_grace'].includes(row.status) || row.accessEndsAt <= now || row.revision < 1))) {\n throw new Error(\"invalid network access receipt\");\n }\n return { membershipId: row.membershipId, allowed: row.allowed, status: row.status, accessEndsAt: row.accessEndsAt, revision: row.revision };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { normalizeChapterEmail } from \"./email-identity\";\nimport { membershipOfferingVersion } from \"./membership-policy\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { membershipOfferIdForRequest } from \"./membership-offer-store\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipScope,\n membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** The adapter verifies the purchaser session and supplies its canonical email and the configured seat Price. */\nexport interface ReserveNamedMembershipSeatInput extends MembershipQuoteTarget {\n recipientName: string; recipientEmail: string; purchaserEmail: string; purchaserUserId: string; priceId: string;\n}\n/** A named, immutable purchase intent. No entitlement exists before provider payment and recipient approval. */\nexport interface NamedMembershipSeatReservation extends MembershipQuoteTarget {\n id: string; primaryMembershipId: string; recipientName: string; recipientEmailNormalized: string;\n recipientClaimId: string; priceId: string; primaryPriceId: string; amountCents: number; currency: string; interval: \"month\" | \"year\";\n providerCustomerId: string; providerSubscriptionId: string; providerPaymentIntentId?: string;\n status: string; preparedAt: number; termEndsAt: number; seatPurchaseEndsAt: number;\n}\nasync function recipientKey(input: ReserveNamedMembershipSeatInput, email: string) {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(JSON.stringify([input.appId, input.chapterId, input.environment, input.runtime, email])));\n return `seat-recipient:${[...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n/** Reserve the only additional seat and its named recipient atomically before any provider I/O.\n * Concurrent purchases cannot allocate two seats or assign the same recipient twice in a chapter.\n * Calendar eligibility is tied to the original membership, never reset by renewal.\n */\nexport async function reserveNamedMembershipSeat(db: ChapterDb, input: ReserveNamedMembershipSeatInput, now: number): Promise<NamedMembershipSeatReservation> {\n membershipClock(now);\n const name = typeof input.recipientName === \"string\" ? input.recipientName.trim().replace(/\\s+/g, \" \") : \"\";\n const email = normalizeChapterEmail(typeof input.recipientEmail === \"string\" ? input.recipientEmail : \"\");\n const purchaser = normalizeChapterEmail(typeof input.purchaserEmail === \"string\" ? input.purchaserEmail : \"\");\n if (name.length < 2 || name.length > 160 || /[\\u0000-\\u001f\\u007f]/.test(input.recipientName) ||\n email.length > 254 || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) || !purchaser || email === purchaser ||\n !/^price_[A-Za-z0-9_]+$/.test(input.priceId) || !/^user_[A-Za-z0-9_]+$/.test(input.purchaserUserId)) membershipFail(\"invalid_named_seat_recipient\");\n const state = await loadMembershipAuthorityState(db, input);\n const memberId = await networkMembershipId(input), member = await membershipLoad(db, \"networkMembership\", memberId);\n requireMembershipScope(member, input);\n if (!Number.isSafeInteger(member.revision) || !/^price_[A-Za-z0-9_]+$/.test(String(member.providerPriceId)) ||\n member.providerPriceId === input.priceId) membershipFail(\"named_seat_purchase_unavailable\");\n const id = (await membershipOfferIdForRequest({ ...input, requestId: \"named_seat\" })).replace(/^offer_/, \"seat_\");\n let seat = await membershipLoad(db, \"networkSeat\", id);\n if (!seat) {\n if (![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) ||\n Number(member.refundedCents) !== 0 || now < Number(member.initialTermStartedAt) || now >= Number(member.termEndsAt) ||\n now > Number(member.seatPurchaseEndsAt) || !Number.isSafeInteger(member.seatPurchaseEndsAt) || member.namedSeatId !== undefined) {\n membershipFail(\"named_seat_purchase_unavailable\");\n }\n const offering = membershipOfferingVersion(member.offeringSnapshot), claimId = await recipientKey(input, email);\n const attrs = { id, ...membershipScope(input), primaryMembershipId: memberId, recipientName: name,\n recipientEmailNormalized: email, purchaserUserId: input.purchaserUserId, recipientClaimId: claimId, priceId: input.priceId, primaryPriceId: member.providerPriceId,\n amountCents: offering.seatPriceCents, currency: offering.currency, interval: offering.interval,\n providerCustomerId: member.providerCustomerId, providerSubscriptionId: member.providerSubscriptionId,\n status: \"payment_pending\", preparedAt: now, termEndsAt: member.termEndsAt, seatPurchaseEndsAt: member.seatPurchaseEndsAt,\n offeringSnapshot: offering, revision: 1, createdAt: now, updatedAt: now };\n try { await db.transact([\n membershipUpdate(\"networkSeat\", id, attrs),\n membershipUpdate(\"networkSeatRecipient\", claimId, { id: claimId, appId: input.appId, chapterId: input.chapterId, environment: input.environment, runtime: input.runtime,\n seatId: id, recipientEmailNormalized: email, createdAt: now }),\n membershipUpdate(\"networkMembership\", memberId, { namedSeatId: id, revision: Number(member.revision) + 1, updatedAt: now }),\n ], { mutationId: `named-seat-reserve:${id}`, guards: [\n { ns: \"networkSeat\", id, exists: false }, { ns: \"networkSeatRecipient\", id: claimId, exists: false },\n { ns: \"networkMembership\", id: memberId, exists: true, equals: { revision: member.revision }, absent: [\"namedSeatId\"] },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n seat = await membershipLoad(db, \"networkSeat\", id);\n if (!seat && await membershipLoad(db, \"networkSeatRecipient\", claimId)) membershipFail(\"named_seat_recipient_unavailable\");\n }\n requireMembershipScope(seat, input);\n if (seat.primaryMembershipId !== memberId || seat.recipientName !== name || seat.recipientEmailNormalized !== email ||\n seat.priceId !== input.priceId || seat.purchaserUserId !== input.purchaserUserId) membershipFail(\"named_seat_purchase_conflict\");\n return seat as unknown as NamedMembershipSeatReservation;\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\nimport type { NamedMembershipSeatReservation } from \"./membership-seat-reservation\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport { verifySubscriptionPrice } from \"./subscription-provider-contract\";\n\ntype Row = Record<string, any>;\nconst reject = (): never => { throw Object.assign(new Error(\"named seat provider contract mismatch\"), { code: \"named_seat_provider_mismatch\" }); };\nconst metadataFor = (seat: NamedMembershipSeatReservation) => ({ ...stripePartitionMetadata(seat),\n applicationId: seat.applicationId, membershipId: seat.primaryMembershipId, seatId: seat.id });\nconst matches = (value: Row | undefined, expected: Record<string, string>) => value && Object.entries(expected).every(([key, item]) => value[key] === item);\nasync function read(sk: string, path: string, params?: Record<string, unknown>): Promise<Row> {\n const response = await stripeRequest<Row>({ secretKey: sk }, \"GET\", path, params);\n if (!response.ok) return reject();\n return response.body;\n}\n\n/** Read and verify the co-terminating subscription and immutable seat Price before any provider write. */\nasync function subscriptionForSeat(sk: string, seat: NamedMembershipSeatReservation): Promise<Row> {\n const productId = await verifySubscriptionPrice(sk, { priceId: seat.priceId, priceCents: seat.amountCents,\n currency: seat.currency, interval: seat.interval, environment: seat.environment }, Boolean(seat.providerPaymentIntentId));\n if (!productId) reject();\n const sub = await read(sk, `/v1/subscriptions/${encodeURIComponent(seat.providerSubscriptionId)}?expand[]=discounts`);\n const items = sub.items?.data;\n if (sub.id !== seat.providerSubscriptionId || sub.customer !== seat.providerCustomerId ||\n sub.livemode !== (seat.environment === \"prod\") || ![\"active\", \"trialing\"].includes(sub.status) ||\n !matches(sub.metadata, { ...stripePartitionMetadata(seat), applicationId: seat.applicationId }) ||\n sub.items?.has_more !== false || !Array.isArray(items) || items.length < 1 || items.length > 2) reject();\n const primary = items.find((item: Row) => item.price?.id === seat.primaryPriceId);\n const other = items.filter((item: Row) => item !== primary);\n if (!primary || primary.quantity !== 1 || primary.price?.product === productId || !primary.price?.product ||\n (sub.trial_end ?? primary.current_period_end ?? sub.current_period_end) * 1000 !== seat.termEndsAt ||\n other.some((item: Row) => item.price?.id !== seat.priceId || item.quantity !== 1 || item.metadata?.seatId !== seat.id)) reject();\n const discounts = sub.discounts ?? [];\n if (!Array.isArray(discounts) || discounts.length > 5) reject();\n for (const discount of discounts) {\n const couponRef = discount.source?.coupon ?? discount.coupon;\n const couponId = typeof couponRef === \"string\" ? couponRef : couponRef?.id;\n if (!couponId || typeof couponId !== \"string\") reject();\n const coupon = await read(sk, `/v1/coupons/${encodeURIComponent(couponId)}`, { \"expand[0]\": \"applies_to\" });\n if (coupon.livemode !== (seat.environment === \"prod\") || !Array.isArray(coupon.applies_to?.products) ||\n coupon.applies_to.products.length !== 1 || coupon.applies_to.products[0] !== primary.price.product) reject();\n }\n return sub;\n}\n\n/** Full up-front payment for the named recipient, never a prorated charge.\n * The caller must durably reserve the seat before invoking this function.\n * An ambiguous create is replayed only inside Stripe's idempotency retention window.\n */\nexport async function createNamedSeatStripePayment(sk: string, seat: NamedMembershipSeatReservation, now: number): Promise<{\n paymentIntentId: string; clientSecret: string; status: string;\n}> {\n if (!Number.isSafeInteger(now) || now < seat.preparedAt ||\n ![\"payment_pending\", \"payment_processing\", \"renewal_pending\", \"pending_acceptance\", \"pending_approval\", \"active\"].includes(seat.status)) reject();\n if (!seat.providerPaymentIntentId && (now - seat.preparedAt >= 23 * 3600000 || now > seat.seatPurchaseEndsAt || now >= seat.termEndsAt)) {\n throw Object.assign(new Error(\"named seat payment requires reconciliation\"), { code: \"named_seat_reconciliation_required\" });\n }\n await subscriptionForSeat(sk, seat);\n const metadata = metadataFor(seat);\n const result = seat.providerPaymentIntentId ? await stripeRequest<Row>({ secretKey: sk }, \"GET\",\n `/v1/payment_intents/${encodeURIComponent(seat.providerPaymentIntentId)}`) : await stripeRequest<Row>({ secretKey: sk }, \"POST\", \"/v1/payment_intents\", {\n amount: seat.amountCents, currency: seat.currency, customer: seat.providerCustomerId,\n \"payment_method_types[0]\": \"card\", setup_future_usage: \"off_session\", metadata,\n description: \"Named additional membership seat; full initial fee, renews with primary membership\",\n }, { idempotencyKey: `named-seat-payment:${seat.id}` });\n const pi = result.body;\n if (!result.ok || !/^pi_[A-Za-z0-9_]+$/.test(pi?.id) || (seat.providerPaymentIntentId && pi.id !== seat.providerPaymentIntentId) ||\n pi.customer !== seat.providerCustomerId || pi.livemode !== (seat.environment === \"prod\") || pi.amount !== seat.amountCents ||\n pi.currency !== seat.currency || !matches(pi.metadata, metadata) || typeof pi.client_secret !== \"string\" ||\n ![\"requires_payment_method\", \"requires_confirmation\", \"requires_action\", \"processing\", \"succeeded\"].includes(pi.status)) reject();\n return { paymentIntentId: pi.id, clientSecret: pi.client_secret, status: pi.status };\n}\n\n/** After paid evidence, add the recurring seat to the primary subscription with no immediate proration.\n * A lost response is recovered by its immutable seat metadata before another create.\n */\nexport async function attachNamedSeatStripeRenewal(sk: string, seat: NamedMembershipSeatReservation): Promise<string> {\n if (!seat.providerPaymentIntentId || ![\"renewal_pending\", \"pending_acceptance\", \"pending_approval\", \"active\"].includes(seat.status)) reject();\n const sub = await subscriptionForSeat(sk, seat);\n const existing = sub.items.data.find((item: Row) => item.metadata?.seatId === seat.id);\n if (existing) return String(existing.id);\n const result = await stripeRequest<Row>({ secretKey: sk }, \"POST\", \"/v1/subscription_items\", {\n subscription: seat.providerSubscriptionId, price: seat.priceId, quantity: 1, proration_behavior: \"none\", metadata: metadataFor(seat),\n }, { idempotencyKey: `named-seat-renewal:${seat.id}` });\n const item = result.body;\n if (!result.ok || !/^si_[A-Za-z0-9_]+$/.test(item?.id) || item.subscription !== seat.providerSubscriptionId ||\n item.price?.id !== seat.priceId || item.quantity !== 1 || !matches(item.metadata, metadataFor(seat))) reject();\n return item.id;\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\nimport { subscriptionAmountDue, verifySubscriptionBillingResult, type SubscriptionBillingTerms } from \"./subscription-billing-terms\";\n\ntype Row = Record<string, any>;\nexport interface SubscriptionPriceContract {\n priceId: string;\n priceCents: number;\n currency: string;\n interval: \"month\" | \"year\";\n environment: string;\n billingTerms?: SubscriptionBillingTerms;\n}\n\nexport function subscriptionContractMismatch(): never {\n throw Object.assign(new Error(\"Stripe subscription does not match the checkout contract\"), { code: \"stripe_contract_mismatch\" });\n}\n\n/** Verify the immutable price before creating any customer or money object. */\nexport async function verifySubscriptionPrice(secretKey: string, input: SubscriptionPriceContract, resume = false): Promise<string | undefined> {\n if (!/^price_[A-Za-z0-9]+$/.test(input.priceId) || !Number.isSafeInteger(input.priceCents) || input.priceCents <= 0 ||\n !/^[a-z]{3}$/.test(input.currency) || ![\"month\", \"year\"].includes(input.interval)) subscriptionContractMismatch();\n const result = await stripeRequest<Row>({ secretKey }, \"GET\", `/v1/prices/${encodeURIComponent(input.priceId)}`);\n const price = result.body;\n if (!result.ok || !price || price.id !== input.priceId || (!resume && price.active !== true) ||\n price.unit_amount !== input.priceCents || price.currency !== input.currency ||\n price.type !== \"recurring\" || price.billing_scheme !== \"per_unit\" || price.custom_unit_amount || price.transform_quantity ||\n price.recurring?.interval !== input.interval || price.recurring?.interval_count !== 1 ||\n price.recurring?.usage_type !== \"licensed\" || price.livemode !== (input.environment === \"prod\")) subscriptionContractMismatch();\n return typeof price.product === \"string\" ? price.product : undefined;\n}\n\n/** No provider identifier or client secret escapes until ownership and price agree. */\nexport function verifySubscriptionResult(sub: Row, input: SubscriptionPriceContract & { existingSubscriptionId?: string },\n customerId: string, metadata: Record<string, string>): void {\n const items = sub?.items;\n if (!sub || !/^sub_[A-Za-z0-9]+$/.test(sub.id) || sub.customer !== customerId ||\n (input.existingSubscriptionId && sub.id !== input.existingSubscriptionId) ||\n !(input.billingTerms?.initialTermEndsAt ? [\"incomplete\", \"active\", \"trialing\"] : [\"incomplete\", \"active\"]).includes(sub.status) || sub.livemode !== (input.environment === \"prod\") ||\n !Object.entries(metadata).every(([key, value]) => sub.metadata?.[key] === value) ||\n !Array.isArray(items?.data) || items.has_more !== false || items.data.length !== 1 ||\n items.data[0]?.price?.id !== input.priceId || items.data[0]?.quantity !== 1) subscriptionContractMismatch();\n const invoice = sub.latest_invoice;\n if (!invoice || typeof invoice !== \"object\" || invoice.customer !== customerId ||\n invoice.currency !== input.currency || invoice.total !== subscriptionAmountDue(input) ||\n invoice.billing_reason !== \"subscription_create\") subscriptionContractMismatch();\n verifySubscriptionBillingResult(sub, input);\n}\n","import type { ChapterDb } from \"./types\";\nimport { reserveNamedMembershipSeat, type ReserveNamedMembershipSeatInput, type NamedMembershipSeatReservation } from \"./membership-seat-reservation\";\nimport { createNamedSeatStripePayment } from \"./membership-seat-stripe\";\nimport { loadMembershipAuthorityState, membershipLoad, membershipUpdate, membershipFail, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Reserve, fence, create/retrieve, then persist provider identity before returning a client secret.\n * The authenticated adapter supplies the network's Stripe credential; the browser cannot select a scope or amount.\n */\nexport async function prepareNamedMembershipSeatPayment(db: ChapterDb, input: ReserveNamedMembershipSeatInput, secretKey: string, now: number) {\n let seat = await reserveNamedMembershipSeat(db, input, now);\n const state = await loadMembershipAuthorityState(db, input);\n const member = await membershipLoad(db, \"networkMembership\", seat.primaryMembershipId);\n requireMembershipScope(member, input);\n if (![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) ||\n Number(member.refundedCents) !== 0 || member.namedSeatId !== seat.id || now >= Number(member.termEndsAt)) {\n membershipFail(\"named_seat_purchase_unavailable\");\n }\n if (seat.status === \"payment_pending\") {\n try { await db.transact([membershipUpdate(\"networkSeat\", seat.id, { status: \"payment_processing\", updatedAt: now })], {\n mutationId: `named-seat-start:${seat.id}`, guards: [\n { ns: \"networkSeat\", id: seat.id, exists: true, equals: { status: \"payment_pending\", primaryMembershipId: member.id } },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision, namedSeatId: seat.id } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ],\n }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n }\n const saved = await membershipLoad(db, \"networkSeat\", seat.id); requireMembershipScope(saved, input);\n seat = saved as unknown as NamedMembershipSeatReservation;\n if (![\"payment_processing\", \"renewal_pending\", \"pending_acceptance\", \"pending_approval\", \"active\"].includes(seat.status)) membershipFail(\"named_seat_purchase_unavailable\");\n const provider = await createNamedSeatStripePayment(secretKey, seat, now);\n if (!seat.providerPaymentIntentId) {\n try { await db.transact([membershipUpdate(\"networkSeat\", seat.id, { providerPaymentIntentId: provider.paymentIntentId, updatedAt: now })], {\n mutationId: `named-seat-provider:${seat.id}`, guards: [\n { ns: \"networkSeat\", id: seat.id, exists: true, equals: { status: \"payment_processing\" }, absent: [\"providerPaymentIntentId\"] },\n ],\n }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n }\n const current = await membershipLoad(db, \"networkSeat\", seat.id); requireMembershipScope(current, input);\n if (current.providerPaymentIntentId !== provider.paymentIntentId ||\n ![\"payment_processing\", \"renewal_pending\", \"pending_acceptance\", \"pending_approval\", \"active\"].includes(String(current.status))) {\n membershipFail(\"named_seat_payment_reconciliation_required\");\n }\n return { seatId: seat.id, paymentIntentId: provider.paymentIntentId, clientSecret: provider.clientSecret,\n amountCents: seat.amountCents, currency: seat.currency, termEndsAt: seat.termEndsAt, status: String(current.status) };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NetworkCommercialFact } from \"./types-network-commercial-projection\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** References from an authenticated peer; the independent network Stripe log supplies all payment facts. */\nexport async function confirmNamedMembershipSeatPayment(db: ChapterDb, input: MembershipQuoteTarget & { seatId: string; eventId: string }, now: number) {\n membershipClock(now);\n const state = await loadMembershipAuthorityState(db, input);\n let seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n const member = await membershipLoad(db, \"networkMembership\", String(seat.primaryMembershipId)); requireMembershipScope(member, input);\n const row = await membershipLoad(db, \"networkCommercialEvents\", `network-commercial-event:${input.eventId}`);\n if (!row || !seat.providerPaymentIntentId) membershipFail(\"named_seat_payment_evidence_pending\");\n const collisionId = `network-commercial-exception:${input.eventId}:collision`;\n if (await membershipLoad(db, \"networkCommercialExceptions\", collisionId)) membershipFail(\"named_seat_payment_evidence_quarantined\");\n const fact = row!.fact as NetworkCommercialFact;\n if (!fact || fact.eventId !== input.eventId || fact.digest !== row!.digest || !/^[a-f0-9]{64}$/.test(fact.digest) ||\n fact.eventType !== \"payment_intent.succeeded\" || fact.objectKind !== \"payment_intent\" || fact.status !== \"succeeded\" ||\n fact.livemode !== (input.environment === \"prod\") || fact.paymentIntentId !== seat.providerPaymentIntentId ||\n fact.seatId !== seat.id || fact.membershipId !== member.id || fact.customerId !== seat.providerCustomerId ||\n fact.applicationId !== input.applicationId || fact.amountCents !== seat.amountCents || fact.amountReceivedCents !== seat.amountCents ||\n fact.currency !== seat.currency || !fact.identity || Object.entries({ appId: input.appId, chapterId: input.chapterId,\n environment: input.environment, dataEnvironment: input.environment, runtime: input.runtime })\n .some(([key, value]) => fact.identity[key as keyof typeof fact.identity] !== value)) membershipFail(\"named_seat_payment_evidence_mismatch\");\n const paidAt = fact.eventCreated * 1000;\n if (!Number.isSafeInteger(paidAt) || paidAt < Math.floor(Number(seat.preparedAt) / 1000) * 1000 || paidAt > now + 30000) {\n membershipFail(\"named_seat_payment_evidence_mismatch\");\n }\n if (seat.purchasedAt === undefined) {\n if (![\"payment_processing\", \"payment_canceling\"].includes(String(seat.status))) membershipFail(\"named_seat_payment_not_expected\");\n const eligible = seat.status !== \"payment_canceling\" && [\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) &&\n Number(member.refundedCents) === 0 && paidAt <= Number(member.seatPurchaseEndsAt) && now < Number(member.termEndsAt);\n const status = eligible ? \"renewal_pending\" : \"refund_pending\", effectId = `${seat.id}:${eligible ? \"attach-renewal\" : \"refund\"}`;\n try { await db.transact([\n membershipUpdate(\"networkSeat\", input.seatId, { status, purchasedAt: paidAt, acceptanceEndsAt: Math.min(paidAt + 30 * 86400000, Number(member.termEndsAt)),\n termStartedAt: paidAt, termEndsAt: member.termEndsAt, paymentEventId: input.eventId, revision: Number(seat.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", effectId, { id: effectId, chapterId: input.chapterId, environment: input.environment,\n runtime: input.runtime, membershipId: member.id, seatId: seat.id, kind: eligible ? \"attach_seat_renewal\" : \"refund_seat\",\n status: \"pending\", attempts: 0, createdAt: now, updatedAt: now }),\n ], { mutationId: `named-seat-paid:${seat.id}`, guards: [\n { ns: \"networkSeat\", id: input.seatId, exists: true, equals: { status: seat.status, providerPaymentIntentId: seat.providerPaymentIntentId }, absent: [\"purchasedAt\"] },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n { ns: \"networkCommercialEvents\", id: String(row!.id), exists: true, equals: { digest: fact.digest } },\n { ns: \"networkCommercialExceptions\", id: collisionId, exists: false },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n }\n if (seat.purchasedAt === undefined || seat.providerPaymentIntentId !== fact.paymentIntentId) membershipFail(\"named_seat_payment_retry_required\");\n return { seatId: seat.id, status: seat.status, purchasedAt: seat.purchasedAt, acceptanceEndsAt: seat.acceptanceEndsAt };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { NamedMembershipSeatReservation } from \"./membership-seat-reservation\";\nimport { attachNamedSeatStripeRenewal } from \"./membership-seat-stripe\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipScope,\n membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Drain the durable paid-seat renewal effect. Safe to invoke from a webhook retry or a scheduled worker.\n * Provider attachment is idempotent and no recipient entitlement is active at this stage.\n */\nexport async function completeNamedSeatRenewal(db: ChapterDb, seatId: string, secretKey: string, now: number): Promise<void> {\n membershipClock(now);\n const seat = await membershipLoad(db, \"networkSeat\", seatId);\n if (!seat) membershipFail(\"named_seat_not_found\");\n const target = seat as unknown as NamedMembershipSeatReservation;\n const state = await loadMembershipAuthorityState(db, target);\n if ([\"pending_acceptance\", \"pending_approval\", \"pending_primary\", \"active\", \"refunded\"].includes(String(seat!.status))) return;\n if (seat!.status !== \"renewal_pending\" || !seat!.purchasedAt) membershipFail(\"named_seat_renewal_not_ready\");\n const member = await membershipLoad(db, \"networkMembership\", target.primaryMembershipId); requireMembershipScope(member, target);\n if (now >= Number(seat!.acceptanceEndsAt) || now >= Number(member.termEndsAt) || Number(member.refundedCents) !== 0 ||\n ![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status))) membershipFail(\"named_seat_refund_required\");\n const itemId = await attachNamedSeatStripeRenewal(secretKey, target);\n const entitlementId = `${seatId}:entitlement`, effectId = `${seatId}:attach-renewal`;\n try { await db.transact([\n membershipUpdate(\"networkSeat\", seatId, { status: \"pending_acceptance\", entitlementId, providerSubscriptionItemId: itemId,\n revision: Number(seat!.revision) + 1, updatedAt: now }),\n membershipUpdate(\"networkEntitlement\", entitlementId, { id: entitlementId, ...membershipScope(target), membershipId: member.id,\n seatId, kind: \"named_seat\", status: \"pending_acceptance\", termStartedAt: seat!.purchasedAt, termEndsAt: member.termEndsAt,\n offeringSnapshot: member.offeringSnapshot, sourceEventId: seat!.paymentEventId, revision: 1, createdAt: now, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", effectId, { status: \"complete\", providerObjectId: itemId, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", `${seatId}:invite`, { id: `${seatId}:invite`, chapterId: target.chapterId,\n environment: target.environment, runtime: target.runtime, membershipId: member.id, seatId, kind: \"invite_named_recipient\",\n status: \"pending\", attempts: 0, createdAt: now, updatedAt: now }),\n ], { mutationId: `named-seat-renewal-ready:${seatId}`, guards: [\n { ns: \"networkSeat\", id: seatId, exists: true, equals: { status: \"renewal_pending\", revision: seat!.revision } },\n { ns: \"networkEntitlement\", id: entitlementId, exists: false },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n const current = await membershipLoad(db, \"networkSeat\", seatId);\n if (!current || current.providerSubscriptionItemId !== itemId || current.status === \"renewal_pending\") membershipFail(\"named_seat_renewal_retry_required\");\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { normalizeChapterEmail } from \"./email-identity\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate,\n requireMembershipScope } from \"./membership-authority-state\";\n\n/** Session identity attested by the signed chapter adapter, never a browser's email_verified flag. */\nexport interface NamedSeatRecipientInput extends MembershipQuoteTarget {\n seatId: string; recipientApplicationId: string; recipientUserId: string; verifiedRecipientEmail: string;\n}\n/** Bind a paid invitation to its verified named recipient, once. Acceptance alone never grants access. */\nexport async function acceptNamedSeatRecipient(db: ChapterDb, input: NamedSeatRecipientInput, now: number) {\n return recordRecipient(db, input, now, false);\n}\n/** Attest the recipient's own completed chapter Journey, independently of the purchaser's waiver or approval. */\nexport async function approveNamedSeatRecipient(db: ChapterDb, input: NamedSeatRecipientInput, now: number) {\n return recordRecipient(db, input, now, true);\n}\nasync function recordRecipient(db: ChapterDb, input: NamedSeatRecipientInput, now: number, approve: boolean) {\n membershipClock(now);\n if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{2,159}$/.test(input.recipientApplicationId) ||\n !/^user_[A-Za-z0-9]+$/.test(input.recipientUserId) || input.recipientApplicationId === input.applicationId) membershipFail(\"invalid_named_seat_recipient_identity\");\n for (let attempt = 0; attempt < 6; attempt++) {\n const state = await loadMembershipAuthorityState(db, input);\n const seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n if (!seat.purchaserUserId || seat.purchaserUserId === input.recipientUserId) membershipFail(\"named_seat_recipient_must_differ_from_purchaser\");\n const member = await membershipLoad(db, \"networkMembership\", String(seat.primaryMembershipId)); requireMembershipScope(member, input);\n const entitlement = await membershipLoad(db, \"networkEntitlement\", String(seat.entitlementId)); requireMembershipScope(entitlement, input);\n if (![\"pending_acceptance\", \"pending_approval\", \"pending_primary\", \"active\"].includes(String(seat.status)) ||\n ![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) || Number(member.refundedCents) !== 0 ||\n now >= Number(member.termEndsAt) || !seat.providerPaymentIntentId || !seat.providerSubscriptionItemId) membershipFail(\"named_seat_acceptance_unavailable\");\n if (seat.acceptedAt === undefined) {\n if (approve || now >= Number(seat.acceptanceEndsAt) || normalizeChapterEmail(input.verifiedRecipientEmail) !== seat.recipientEmailNormalized) {\n membershipFail(\"named_seat_recipient_verification_required\");\n }\n } else if (seat.recipientUserId !== input.recipientUserId || seat.recipientApplicationId !== input.recipientApplicationId) {\n membershipFail(\"named_seat_recipient_identity_conflict\");\n }\n const acceptedAt = seat.acceptedAt ?? now, journeyApprovedAt = seat.journeyApprovedAt ?? (approve ? now : undefined);\n const active = journeyApprovedAt !== undefined && [\"active\", \"cancel_at_term_end\"].includes(String(member.status));\n const status = active ? \"active\" : journeyApprovedAt !== undefined ? \"pending_primary\" : \"pending_approval\";\n if (seat.acceptedAt !== undefined && seat.journeyApprovedAt === journeyApprovedAt && seat.status === status) {\n return { seatId: input.seatId, status, recipientApplicationId: input.recipientApplicationId };\n }\n const attrs = { acceptedAt, ...(journeyApprovedAt !== undefined ? { journeyApprovedAt } : {}),\n recipientUserId: input.recipientUserId, recipientApplicationId: input.recipientApplicationId, status, updatedAt: now };\n try { await db.transact([\n membershipUpdate(\"networkSeat\", input.seatId, { ...attrs, revision: Number(seat.revision) + 1 }),\n membershipUpdate(\"networkEntitlement\", String(entitlement.id), { ...attrs, revision: Number(entitlement.revision) + 1 }),\n ...(active ? [membershipUpdate(\"membershipEffect\", `${seat.id}:grant`, { id: `${seat.id}:grant`, chapterId: input.chapterId,\n environment: input.environment, runtime: input.runtime, membershipId: member.id, seatId: seat.id,\n kind: \"grant_named_recipient_access\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now })] : []),\n ], { mutationId: `named-seat-${approve ? \"approve\" : \"accept\"}:${seat.id}`, guards: [\n { ns: \"networkSeat\", id: input.seatId, exists: true, equals: { revision: seat.revision } },\n { ns: \"networkEntitlement\", id: String(entitlement.id), exists: true, equals: { revision: entitlement.revision } },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ] }); } catch (error) { if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error; }\n }\n return membershipFail(\"named_seat_recipient_retry_required\");\n}\n","import { stripeRequest } from \"@odla-ai/stripe\";\nimport type { NamedMembershipSeatReservation } from \"./membership-seat-reservation\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\n\ntype Row = Record<string, any>;\nconst fail = (code = \"named_seat_refund_mismatch\"): never => { throw Object.assign(new Error(code), { code }); };\n/** Remove only this named seat's renewal item, then fully refund its exact original PaymentIntent.\n * Customer-wide charge selection is never used. Partial existing refunds and lost responses converge.\n */\nexport async function refundNamedSeatStripePayment(secretKey: string, seat: NamedMembershipSeatReservation): Promise<{ refundedCents: number; refundIds: string[] }> {\n if (!seat.providerPaymentIntentId || seat.status !== \"refund_pending\") fail();\n const call = async (method: \"GET\" | \"POST\" | \"DELETE\", path: string, params?: Row, idempotencyKey?: string): Promise<Row> => {\n const result = await stripeRequest<Row>({ secretKey }, method, path, params, idempotencyKey ? { idempotencyKey } : {});\n if (!result.ok || !result.body) return fail(\"named_seat_refund_provider_unavailable\");\n return result.body;\n };\n const metadata = { ...stripePartitionMetadata(seat), applicationId: seat.applicationId, membershipId: seat.primaryMembershipId, seatId: seat.id };\n const payment = await call(\"GET\", `/v1/payment_intents/${encodeURIComponent(seat.providerPaymentIntentId!)}`);\n if (payment.id !== seat.providerPaymentIntentId || payment.customer !== seat.providerCustomerId || payment.amount !== seat.amountCents ||\n payment.amount_received !== seat.amountCents || payment.currency !== seat.currency || payment.livemode !== (seat.environment === \"prod\") ||\n payment.status !== \"succeeded\" || !Object.entries(metadata).every(([key, value]) => payment.metadata?.[key] === value)) fail();\n const sub = await call(\"GET\", `/v1/subscriptions/${encodeURIComponent(seat.providerSubscriptionId)}`);\n if (sub.id !== seat.providerSubscriptionId || sub.customer !== seat.providerCustomerId || sub.livemode !== (seat.environment === \"prod\") ||\n !Object.entries({ ...stripePartitionMetadata(seat), applicationId: seat.applicationId }).every(([key, value]) => sub.metadata?.[key] === value) ||\n sub.items?.has_more !== false || !Array.isArray(sub.items?.data)) fail();\n const items = sub.items.data.filter((item: Row) => item.metadata?.seatId === seat.id);\n if (items.length > 1) fail();\n if (items.length && sub.status !== \"canceled\") {\n const item = items[0];\n if (!/^si_[A-Za-z0-9_]+$/.test(item.id) || item.price?.id !== seat.priceId || item.quantity !== 1) fail();\n const removed = await call(\"DELETE\", `/v1/subscription_items/${encodeURIComponent(item.id)}`, { proration_behavior: \"none\" });\n if (removed.id !== item.id || removed.deleted !== true) fail(\"named_seat_renewal_removal_unconfirmed\");\n }\n const list = await call(\"GET\", \"/v1/refunds\", { payment_intent: seat.providerPaymentIntentId, limit: 100 });\n if (!Array.isArray(list.data) || list.has_more !== false || list.data.length >= 100) fail(\"named_seat_refund_history_incomplete\");\n let refundedCents = 0, pendingCents = 0; const refundIds: string[] = [];\n for (const refund of list.data) {\n if (!/^re_[A-Za-z0-9_]+$/.test(refund.id) || refund.payment_intent !== seat.providerPaymentIntentId ||\n refund.currency !== seat.currency || !Number.isSafeInteger(refund.amount) || refund.amount <= 0 ||\n ![\"succeeded\", \"pending\", \"requires_action\", \"failed\", \"canceled\"].includes(refund.status)) fail();\n if (refund.status === \"succeeded\") { refundedCents += refund.amount; refundIds.push(refund.id); }\n else if (refund.status === \"pending\" || refund.status === \"requires_action\") pendingCents += refund.amount;\n }\n if (refundedCents + pendingCents > seat.amountCents) fail();\n if (pendingCents) fail(\"named_seat_refund_pending\");\n if (refundedCents < seat.amountCents) {\n const remaining = seat.amountCents - refundedCents;\n const refund = await call(\"POST\", \"/v1/refunds\", { payment_intent: seat.providerPaymentIntentId,\n amount: remaining, reason: \"requested_by_customer\", metadata }, `named-seat-refund:${seat.id}:${remaining}`);\n if (refund.payment_intent !== seat.providerPaymentIntentId || refund.amount !== remaining || refund.currency !== seat.currency ||\n !/^re_[A-Za-z0-9_]+$/.test(refund.id)) fail();\n if (refund.status !== \"succeeded\") fail(\"named_seat_refund_pending\");\n refundedCents += remaining; refundIds.push(refund.id);\n }\n return { refundedCents, refundIds };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NamedMembershipSeatReservation } from \"./membership-seat-reservation\";\nimport { refundNamedSeatStripePayment } from \"./membership-seat-refund-stripe\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\n\n/** The signed adapter verifies who declined. Expiry is independently checked here against the frozen 30-day deadline. */\nexport async function requestNamedSeatRefund(db: ChapterDb, input: MembershipQuoteTarget & { seatId: string; reason: \"declined\" | \"expired\" | \"primary_closed\" | \"provider_refund\" }, now: number) {\n membershipClock(now);\n const state = await loadMembershipAuthorityState(db, input);\n const seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n const member = await membershipLoad(db, \"networkMembership\", String(seat.primaryMembershipId)); requireMembershipScope(member, input);\n if (seat.status === \"refunded\" || seat.status === \"refund_pending\") return;\n if (!seat.purchasedAt || !seat.providerPaymentIntentId ||\n (input.reason === \"declined\" && seat.journeyApprovedAt !== undefined) ||\n (input.reason === \"expired\" && (seat.acceptedAt !== undefined || !Number.isSafeInteger(seat.acceptanceEndsAt) || now < Number(seat.acceptanceEndsAt))) ||\n (input.reason === \"primary_closed\" && ![\"refunded\", \"declined\"].includes(String(member.status)))) membershipFail(\"named_seat_refund_not_eligible\");\n const entitlement = seat.entitlementId ? await membershipLoad(db, \"networkEntitlement\", String(seat.entitlementId)) : undefined;\n await db.transact([\n membershipUpdate(\"networkSeat\", input.seatId, { status: \"refund_pending\", refundReason: input.reason, revision: Number(seat.revision) + 1, updatedAt: now }),\n ...(entitlement ? [membershipUpdate(\"networkEntitlement\", String(entitlement.id), { status: \"closed\", revision: Number(entitlement.revision) + 1, updatedAt: now })] : []),\n membershipUpdate(\"membershipEffect\", `${seat.id}:refund`, { id: `${seat.id}:refund`, chapterId: input.chapterId,\n environment: input.environment, runtime: input.runtime, membershipId: member.id, seatId: seat.id,\n kind: \"refund_seat\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now }),\n ...(seat.recipientUserId ? [membershipUpdate(\"membershipEffect\", `${seat.id}:revoke`, { id: `${seat.id}:revoke`, chapterId: input.chapterId,\n environment: input.environment, runtime: input.runtime, membershipId: member.id, seatId: seat.id,\n kind: \"revoke_named_recipient_access\", status: \"pending\", attempts: 0, createdAt: now, updatedAt: now })] : []),\n ], { mutationId: `named-seat-refund-request:${seat.id}`, guards: [\n { ns: \"networkSeat\", id: input.seatId, exists: true, equals: { revision: seat.revision } },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ...(entitlement ? [{ ns: \"networkEntitlement\", id: String(entitlement.id), exists: true, equals: { revision: entitlement.revision } }] : []),\n ] });\n}\n\n/** Drain a pending refund effect without ever switching to another payment or another member's seat. */\nexport async function completeNamedSeatRefund(db: ChapterDb, seatId: string, secretKey: string, now: number): Promise<void> {\n membershipClock(now);\n const seat = await membershipLoad(db, \"networkSeat\", seatId);\n if (!seat) return membershipFail(\"named_seat_not_found\");\n await loadMembershipAuthorityState(db, seat as unknown as MembershipQuoteTarget);\n if (seat.status === \"refunded\") return;\n if (seat.status !== \"refund_pending\") membershipFail(\"named_seat_refund_not_ready\");\n const result = await refundNamedSeatStripePayment(secretKey, seat as unknown as NamedMembershipSeatReservation);\n await db.transact([\n membershipUpdate(\"networkSeat\", seatId, { status: \"refunded\", refundedCents: result.refundedCents, providerRefundIds: result.refundIds,\n revision: Number(seat.revision) + 1, updatedAt: now }),\n membershipUpdate(\"membershipEffect\", `${seatId}:refund`, { status: \"complete\", updatedAt: now }),\n ], { mutationId: `named-seat-refunded:${seatId}`, guards: [\n { ns: \"networkSeat\", id: seatId, exists: true, equals: { status: \"refund_pending\", revision: seat.revision } },\n ] });\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport type { NetworkCommercialFact } from \"./types-network-commercial-projection\";\nimport { membershipLoad, membershipFail, requireMembershipScope } from \"./membership-authority-state\";\nimport { requestNamedSeatRefund } from \"./membership-seat-refund\";\n\n/** Independently verified complete provider refunds revoke only the exact named seat, never its purchaser. */\nexport async function confirmNamedSeatProviderRefund(db: ChapterDb, input: MembershipQuoteTarget & { seatId: string; eventId: string }, now: number) {\n const seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n const row = await membershipLoad(db, \"networkCommercialEvents\", `network-commercial-event:${input.eventId}`);\n if (!row) return membershipFail(\"named_seat_refund_evidence_pending\");\n const fact = row.fact as NetworkCommercialFact;\n if (await membershipLoad(db, \"networkCommercialExceptions\", `network-commercial-exception:${input.eventId}:collision`)) membershipFail(\"named_seat_refund_evidence_quarantined\");\n if (!fact || fact.eventId !== input.eventId || fact.digest !== row.digest || !/^[a-f0-9]{64}$/.test(fact.digest) ||\n fact.eventType !== \"charge.refunded\" || fact.seatId !== seat.id || fact.membershipId !== seat.primaryMembershipId ||\n fact.paymentIntentId !== seat.providerPaymentIntentId || fact.amountCents !== seat.amountCents || fact.currency !== seat.currency ||\n fact.customerId !== seat.providerCustomerId || fact.applicationId !== input.applicationId ||\n fact.livemode !== (input.environment === \"prod\") || !fact.identity ||\n Object.entries({ appId: input.appId, chapterId: input.chapterId, environment: input.environment, dataEnvironment: input.environment, runtime: input.runtime })\n .some(([key, value]) => fact.identity[key as keyof typeof fact.identity] !== value)) membershipFail(\"named_seat_refund_evidence_mismatch\");\n await requestNamedSeatRefund(db, { ...input, reason: \"provider_refund\" }, now);\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport { membershipOfferingVersion } from \"./membership-policy\";\nimport { loadMembershipAuthorityState, membershipClock, membershipLoad, requireMembershipScope } from \"./membership-authority-state\";\n\n/** Named-seat offer for the authenticated purchaser, not a transferable gift or arbitrary quantity. */\nexport interface NamedSeatOffer {\n membershipId: string; amountCents: number; currency: string; interval: \"year\" | \"month\";\n termEndsAt: number; purchaseEndsAt: number; autoRenew: boolean; eligible: boolean; digest: string;\n seat?: { seatId: string; status: string; recipientName: string; recipientEmail: string };\n}\n/** Stable commercial consent fingerprint; eligibility is always checked again at checkout. */\nexport async function namedSeatOfferDigest(offer: Omit<NamedSeatOffer, \"digest\">): Promise<string> {\n const bytes = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(JSON.stringify([\n offer.membershipId, offer.amountCents, offer.currency, offer.interval, offer.termEndsAt, offer.purchaseEndsAt,\n \"named-only\", \"full-upfront\", \"auto-renew-coterm\", \"30-day-unaccepted-full-refund\",\n ])));\n return [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n/** Read the frozen offering and any existing seat without reserving or charging anything. */\nexport async function readNamedSeatOffer(db: ChapterDb, input: MembershipQuoteTarget, now: number): Promise<NamedSeatOffer> {\n membershipClock(now); await loadMembershipAuthorityState(db, input);\n const id = await networkMembershipId(input), member = await membershipLoad(db, \"networkMembership\", id); requireMembershipScope(member, input);\n const offering = membershipOfferingVersion(member.offeringSnapshot);\n const seat = member.namedSeatId ? await membershipLoad(db, \"networkSeat\", String(member.namedSeatId)) : undefined;\n if (seat) requireMembershipScope(seat, input);\n const offer = { membershipId: id, amountCents: offering.seatPriceCents, currency: offering.currency, interval: offering.interval,\n termEndsAt: Number(member.termEndsAt), purchaseEndsAt: Number(member.seatPurchaseEndsAt), autoRenew: member.autoRenew === true,\n eligible: [\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) &&\n member.refundedCents === 0 && now >= Number(member.initialTermStartedAt) && now < Number(member.termEndsAt) &&\n now <= Number(member.seatPurchaseEndsAt) && (!seat || [\"payment_pending\", \"payment_processing\"].includes(String(seat.status))),\n ...(seat ? { seat: { seatId: String(seat.id), status: String(seat.status), recipientName: String(seat.recipientName),\n recipientEmail: String(seat.recipientEmailNormalized) } } : {}),\n };\n return { ...offer, digest: await namedSeatOfferDigest(offer) };\n}\n","import type { ChapterDb } from \"./types\";\nimport { normalizeChapterEmail } from \"./email-identity\";\nimport { loadMembershipAuthorityState, membershipClock, membershipFail, membershipLoad, requireMembershipScope } from \"./membership-authority-state\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { readMembershipAccess, type MembershipAccessReceipt } from \"./membership-access-authority\";\n\n/** Identity attested by the recipient's chapter after checking Clerk's verified primary email. */\nexport interface NamedSeatInvitationRequest {\n appId: string; chapterId: string; environment: string; runtime: string;\n seatId: string; recipientUserId: string; verifiedRecipientEmail: string;\n}\n/** Recipient-visible invitation; no purchaser contact information or provider credentials. */\nexport interface NamedSeatInvitation {\n seatId: string; primaryApplicationId: string; skuId: string; recipientName: string; status: string; acceptanceEndsAt: number; termEndsAt: number;\n}\n/** Resolve the invitation only for its named, verified person (or already bound user ID). */\nexport async function readNamedSeatInvitation(db: ChapterDb, input: NamedSeatInvitationRequest, now: number): Promise<NamedSeatInvitation> {\n membershipClock(now);\n const seat = await membershipLoad(db, \"networkSeat\", input.seatId);\n if (!seat || [\"appId\", \"chapterId\", \"environment\", \"runtime\"].some(key => seat[key] !== input[key as keyof typeof input]) ||\n !/^user_[A-Za-z0-9_]+$/.test(input.recipientUserId) || seat.purchaserUserId === input.recipientUserId ||\n (seat.recipientUserId ? seat.recipientUserId !== input.recipientUserId :\n seat.recipientEmailNormalized !== normalizeChapterEmail(input.verifiedRecipientEmail))) membershipFail(\"named_seat_invitation_unavailable\");\n const target = { ...input, applicationId: String(seat!.applicationId), skuId: String(seat!.skuId) };\n await loadMembershipAuthorityState(db, target);\n const member = await membershipLoad(db, \"networkMembership\", String(seat!.primaryMembershipId)); requireMembershipScope(member, target);\n if (![\"pending_acceptance\", \"pending_approval\", \"pending_primary\", \"active\"].includes(String(seat!.status)) ||\n ![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status)) ||\n now >= Number(member.termEndsAt) || (!seat!.acceptedAt && now >= Number(seat!.acceptanceEndsAt))) membershipFail(\"named_seat_invitation_unavailable\");\n return { seatId: input.seatId, primaryApplicationId: target.applicationId, skuId: target.skuId, recipientName: String(seat!.recipientName),\n status: String(seat!.status), acceptanceEndsAt: Number(seat!.acceptanceEndsAt), termEndsAt: Number(seat!.termEndsAt) };\n}\n\n/** Recipient access requires both current primary membership and this exact bound seat's entitlement. */\nexport async function readNamedSeatAccess(db: ChapterDb, input: MembershipQuoteTarget & { seatId: string; recipientUserId: string; recipientApplicationId: string },\n now: number): Promise<MembershipAccessReceipt> {\n const primary = await readMembershipAccess(db, input, now), seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n if (seat.recipientUserId !== input.recipientUserId || seat.recipientApplicationId !== input.recipientApplicationId) membershipFail(\"named_seat_identity_mismatch\");\n const entitlement = await membershipLoad(db, \"networkEntitlement\", String(seat.entitlementId)); requireMembershipScope(entitlement, input);\n return { ...primary, allowed: primary.allowed && seat.status === \"active\" && entitlement.status === \"active\" &&\n entitlement.seatId === input.seatId && entitlement.recipientUserId === input.recipientUserId &&\n entitlement.recipientApplicationId === input.recipientApplicationId, revision: Math.max(primary.revision, Number(seat.revision)) };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipChapterEffect } from \"./membership-effects\";\nimport { loadMembershipAuthorityState, membershipLoad, requireMembershipScope } from \"./membership-authority-state\";\nimport { readNamedSeatAccess } from \"./membership-seat-invitation\";\n\n/** Minimal chapter-owned delivery data, fetched over the authenticated runtime edge, never from a browser payload. */\nexport interface MembershipChapterEffectData extends MembershipChapterEffect {\n recipientName: string; recipientEmail: string; recipientUserId: string | null; recipientApplicationId: string | null;\n acceptanceEndsAt: number; termEndsAt: number; applicable: boolean;\n}\n/** Read current effect eligibility and the named recipient from the authoritative seat, not a stale queued message. */\nexport async function readMembershipChapterEffect(db: ChapterDb, input: MembershipChapterEffect, now: number): Promise<MembershipChapterEffectData> {\n await loadMembershipAuthorityState(db, input);\n const effect = await membershipLoad(db, \"membershipEffect\", input.effectId);\n const seat = await membershipLoad(db, \"networkSeat\", input.seatId); requireMembershipScope(seat, input);\n const member = await membershipLoad(db, \"networkMembership\", String(seat.primaryMembershipId)); requireMembershipScope(member, input);\n if (!effect || effect.kind !== input.kind || effect.seatId !== seat.id || effect.membershipId !== member.id ||\n [\"chapterId\", \"environment\", \"runtime\"].some(key => effect[key] !== seat[key]) ||\n ![\"invite_named_recipient\", \"grant_named_recipient_access\", \"revoke_named_recipient_access\"].includes(input.kind)) throw new Error(\"invalid chapter effect\");\n let applicable: boolean;\n if (input.kind === \"invite_named_recipient\") applicable = seat.status === \"pending_acceptance\" && seat.acceptedAt === undefined &&\n now < Number(seat.acceptanceEndsAt) && now < Number(member.termEndsAt) &&\n [\"paid_pending_approval\", \"active\", \"cancel_at_term_end\"].includes(String(member.status));\n else if (input.kind === \"revoke_named_recipient_access\") applicable = [\"refund_pending\", \"refunded\"].includes(String(seat.status));\n else applicable = (await readNamedSeatAccess(db, { ...input, recipientUserId: String(seat.recipientUserId),\n recipientApplicationId: String(seat.recipientApplicationId) }, now)).allowed;\n return { ...input, recipientName: String(seat.recipientName), recipientEmail: String(seat.recipientEmailNormalized),\n recipientUserId: typeof seat.recipientUserId === \"string\" ? seat.recipientUserId : null,\n recipientApplicationId: typeof seat.recipientApplicationId === \"string\" ? seat.recipientApplicationId : null,\n acceptanceEndsAt: Number(seat.acceptanceEndsAt), termEndsAt: Number(seat.termEndsAt), applicable };\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipAuthorityPeer } from \"./membership-authority-handler\";\nimport { getVaultSecret } from \"./auth\";\nimport { prepareNamedMembershipSeatPayment } from \"./membership-seat-checkout\";\nimport { reserveNamedMembershipSeat } from \"./membership-seat-reservation\";\nimport { confirmNamedMembershipSeatPayment } from \"./membership-seat-payment\";\nimport { completeNamedSeatRenewal } from \"./membership-seat-renewal\";\nimport { acceptNamedSeatRecipient, approveNamedSeatRecipient } from \"./membership-seat-recipient\";\nimport { confirmNamedSeatProviderRefund } from \"./membership-seat-provider-refund\";\nimport { completeNamedSeatRefund, requestNamedSeatRefund } from \"./membership-seat-refund\";\nimport { membershipLoad, requireMembershipScope } from \"./membership-authority-state\";\nimport { readNamedSeatOffer } from \"./membership-seat-offer\";\nimport { readNamedSeatInvitation, readNamedSeatAccess } from \"./membership-seat-invitation\";\nimport { readMembershipChapterEffect } from \"./membership-chapter-effect\";\nimport type { MembershipChapterEffect } from \"./membership-effects\";\n\nconst recipient = [\"seatId\", \"recipientApplicationId\", \"recipientUserId\", \"verifiedRecipientEmail\"];\nexport const MEMBERSHIP_SEAT_ACTION_FIELDS: Record<string, string[]> = {\n \"seat-offer\": [],\n \"seat-invitation\": [\"seatId\", \"recipientUserId\", \"verifiedRecipientEmail\"],\n \"seat-access\": [\"seatId\", \"recipientUserId\", \"recipientApplicationId\"],\n \"seat-checkouts\": [\"recipientName\", \"recipientEmail\", \"purchaserEmail\", \"purchaserUserId\"],\n \"seat-reservations\": [\"recipientName\", \"recipientEmail\", \"purchaserEmail\", \"purchaserUserId\"],\n \"seat-payments\": [\"seatId\", \"eventId\"],\n \"seat-refunds\": [\"seatId\", \"eventId\"],\n \"seat-accept\": recipient,\n \"seat-approve\": recipient,\n \"seat-decline\": recipient,\n \"seat-effect\": [\"seatId\", \"effectId\", \"kind\"],\n};\n/** Dispatch only authenticated, scope-mapped named-seat commands; no provider Price or amount is accepted from the peer. */\nexport async function handleMembershipSeatAction(action: string, db: ChapterDb, peer: MembershipAuthorityPeer,\n input: Record<string, unknown>, now: number, stripeSecretName: string): Promise<unknown> {\n if (!peer.seatPriceId) throw new Error(\"named seats are not configured\");\n if (action === \"seat-invitation\") return readNamedSeatInvitation(db, { ...peer, seatId: String(input.seatId),\n recipientUserId: String(input.recipientUserId), verifiedRecipientEmail: String(input.verifiedRecipientEmail) }, now);\n const target = { appId: peer.appId, chapterId: peer.chapterId, environment: peer.environment, runtime: peer.runtime,\n applicationId: String(input.applicationId), skuId: String(input.skuId) };\n if (action === \"seat-effect\") return readMembershipChapterEffect(db, { ...target, seatId: String(input.seatId),\n effectId: String(input.effectId), kind: String(input.kind) as MembershipChapterEffect[\"kind\"] }, now);\n if (action === \"seat-offer\") return readNamedSeatOffer(db, target, now);\n if (action === \"seat-reservations\") {\n const seat = await reserveNamedMembershipSeat(db, { ...target, priceId: peer.seatPriceId,\n recipientName: String(input.recipientName), recipientEmail: String(input.recipientEmail), purchaserEmail: String(input.purchaserEmail),\n purchaserUserId: String(input.purchaserUserId) }, now);\n return { seatId: seat.id, amountCents: seat.amountCents, currency: seat.currency, termEndsAt: seat.termEndsAt };\n }\n if (action === \"seat-access\") return readNamedSeatAccess(db, { ...target, seatId: String(input.seatId),\n recipientUserId: String(input.recipientUserId), recipientApplicationId: String(input.recipientApplicationId) }, now);\n const recipientInput = { ...target, seatId: String(input.seatId), recipientApplicationId: String(input.recipientApplicationId),\n recipientUserId: String(input.recipientUserId), verifiedRecipientEmail: String(input.verifiedRecipientEmail) };\n if (action === \"seat-accept\") return acceptNamedSeatRecipient(db, recipientInput, now);\n if (action === \"seat-approve\") return approveNamedSeatRecipient(db, recipientInput, now);\n const secret = await getVaultSecret(db, stripeSecretName);\n if (!secret) throw new Error(\"network Stripe provider is unavailable\");\n if (action === \"seat-decline\") {\n const seat = await membershipLoad(db, \"networkSeat\", recipientInput.seatId); requireMembershipScope(seat, target);\n if (seat.recipientApplicationId !== recipientInput.recipientApplicationId || seat.recipientUserId !== recipientInput.recipientUserId) {\n throw new Error(\"named seat recipient mismatch\");\n }\n await requestNamedSeatRefund(db, { ...target, seatId: recipientInput.seatId, reason: \"declined\" }, now);\n await completeNamedSeatRefund(db, recipientInput.seatId, secret, now);\n const refunded = await membershipLoad(db, \"networkSeat\", recipientInput.seatId);\n if (refunded?.status !== \"refunded\" || refunded.refundedCents !== seat.amountCents) throw new Error(\"named seat refund unconfirmed\");\n return { seatId: seat.id, status: \"refunded\", refundedCents: refunded.refundedCents, subscriptionCanceled: false };\n }\n if (action === \"seat-checkouts\") return prepareNamedMembershipSeatPayment(db, { ...target, priceId: peer.seatPriceId,\n recipientName: String(input.recipientName), recipientEmail: String(input.recipientEmail), purchaserEmail: String(input.purchaserEmail),\n purchaserUserId: String(input.purchaserUserId) }, secret, now);\n const evidence = { ...target, seatId: String(input.seatId), eventId: String(input.eventId) };\n if (action === \"seat-payments\") {\n const receipt = await confirmNamedMembershipSeatPayment(db, evidence, now);\n if (receipt.status === \"refund_pending\") await completeNamedSeatRefund(db, evidence.seatId, secret, now);\n else await completeNamedSeatRenewal(db, evidence.seatId, secret, now);\n return { seatId: evidence.seatId, reconciled: true };\n }\n if (action === \"seat-refunds\") {\n await confirmNamedSeatProviderRefund(db, evidence, now);\n await completeNamedSeatRefund(db, evidence.seatId, secret, now);\n return { seatId: evidence.seatId, reconciled: true };\n }\n throw new Error(\"unknown named seat command\");\n}\n","import { signFederatedRequest } from \"@odla-ai/db\";\nimport { readBoundedJson } from \"./bounded-json-response\";\nimport { MEMBERSHIP_AUTHORITY_PATH } from \"./membership-authority-handler\";\nimport { membershipOfferIdForRequest, verifyIssuedMembershipOffer, type IssuedMembershipOffer } from \"./membership-offer-store\";\nimport { verifyMembershipCheckoutBinding, type MembershipCheckoutBinding, type MembershipCheckoutBindingInput } from \"./membership-checkout-binding\";\nimport type { ConfirmMembershipPaymentInput, MembershipPaymentReceipt } from \"./membership-payment-authority\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { verifyMembershipPaymentReceipt } from \"./membership-authority-receipt\";\nimport type { NamedSeatRecipientInput } from \"./membership-seat-recipient\";\nimport type { MembershipRefundReceipt } from \"./membership-refund-authority\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport type { MembershipRenewalReceipt } from \"./membership-renewal-authority\";\nimport { verifyMembershipAccessReceipt, type MembershipAccessReceipt } from \"./membership-access-authority\";\nimport { namedSeatOfferDigest, type NamedSeatOffer } from \"./membership-seat-offer\";\nimport type { NamedSeatInvitation, NamedSeatInvitationRequest } from \"./membership-seat-invitation\";\nimport type { MembershipChapterEffect } from \"./membership-effects\";\nimport type { MembershipChapterEffectData } from \"./membership-chapter-effect\";\n\n/** Inputs supplied by an authenticated chapter backend; no browser credentials cross this edge. */\nexport interface RequestMembershipOfferOptions {\n secret: string;\n targetUrl: string;\n appId: string;\n chapterId: string;\n environment: string;\n runtime: string;\n applicationId: string;\n skuId: string;\n requestId: string;\n /** A configured service binding may replace public fetch, but must not fall back when absent. */\n fetch?: typeof globalThis.fetch;\n}\n\n/** Request and verify one durable network offer before any payment provider call. */\nexport async function requestMembershipCommercialOffer(options: RequestMembershipOfferOptions): Promise<IssuedMembershipOffer> {\n const result = await requestAuthority(options, \"offers\", { applicationId: options.applicationId, skuId: options.skuId, requestId: options.requestId });\n return verifyIssuedMembershipOffer(result.offer, {\n ...options, offerId: await membershipOfferIdForRequest(options), now: Date.now(), lifetimeMs: 60000,\n });\n}\n\n/** Bind the exact consent and Price before Stripe is contacted. */\nexport async function requestMembershipCheckoutBinding(options: MembershipCheckoutBindingInput &\n Pick<RequestMembershipOfferOptions, \"secret\" | \"targetUrl\" | \"fetch\">): Promise<MembershipCheckoutBinding> {\n const result = await requestAuthority(options, \"checkouts\", { applicationId: options.applicationId, skuId: options.skuId,\n offerId: options.offerId, offerDigest: options.offerDigest, quoteDigest: options.quoteDigest, priceId: options.priceId });\n return verifyMembershipCheckoutBinding(result.binding, options);\n}\n\ntype AuthorityTransport = Pick<RequestMembershipOfferOptions, \"secret\" | \"targetUrl\" | \"fetch\">;\n/** Fetch current delivery state; the caller cannot substitute an email, account, term, or entitlement. */\nexport async function requestMembershipChapterEffect(options: MembershipChapterEffect & AuthorityTransport): Promise<MembershipChapterEffectData> {\n const result = await requestAuthority(options, \"seat-effect\", { applicationId: options.applicationId, skuId: options.skuId,\n seatId: options.seatId, effectId: options.effectId, kind: options.kind });\n const row = result.seat as MembershipChapterEffectData;\n if (!row || [\"appId\", \"chapterId\", \"environment\", \"runtime\", \"applicationId\", \"skuId\", \"seatId\", \"effectId\", \"kind\"].some(\n key => row[key as keyof MembershipChapterEffectData] !== options[key as keyof MembershipChapterEffect]) ||\n typeof row.applicable !== \"boolean\" || typeof row.recipientName !== \"string\" || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(row.recipientEmail) ||\n !Number.isSafeInteger(row.acceptanceEndsAt) || !Number.isSafeInteger(row.termEndsAt) ||\n (row.recipientUserId !== null && !/^user_[A-Za-z0-9_]+$/.test(row.recipientUserId)) ||\n (row.recipientApplicationId !== null && typeof row.recipientApplicationId !== \"string\")) throw new Error(\"invalid chapter effect receipt\");\n return row;\n}\n/** Only the named buyer's prepared payment details; no network credentials or canonical PII. */\nexport interface NamedSeatCheckoutReceipt {\n seatId: string; paymentIntentId: string; clientSecret: string; amountCents: number; currency: string; termEndsAt: number; status: string;\n}\n/** Result of attesting one verified recipient's acceptance or completed Journey. */\nexport interface NamedSeatRecipientReceipt { seatId: string; status: string; recipientApplicationId: string }\n/** Full seat-only refund. The purchaser's primary subscription is not canceled. */\nexport interface NamedSeatRefundReceipt { seatId: string; status: \"refunded\"; refundedCents: number; subscriptionCanceled: false }\n/** Refund a declined recipient's exact bound seat; the caller authenticates the chapter operator. */\nexport async function requestNamedSeatDecline(options: NamedSeatRecipientInput & AuthorityTransport): Promise<NamedSeatRefundReceipt> {\n const result = await requestAuthority(options, \"seat-decline\", { applicationId: options.applicationId, skuId: options.skuId, seatId: options.seatId,\n recipientApplicationId: options.recipientApplicationId, recipientUserId: options.recipientUserId, verifiedRecipientEmail: options.verifiedRecipientEmail });\n const seat = result.seat as NamedSeatRefundReceipt;\n if (!seat || seat.seatId !== options.seatId || seat.status !== \"refunded\" || seat.subscriptionCanceled !== false ||\n !Number.isSafeInteger(seat.refundedCents) || seat.refundedCents <= 0) throw new Error(\"invalid named seat refund receipt\");\n return seat;\n}\n/** Verified purchaser identity and their named recipient, with no caller-selected pricing. */\nexport type NamedSeatCheckoutRequest = MembershipQuoteTarget & { recipientName: string; recipientEmail: string; purchaserEmail: string; purchaserUserId: string };\n/** Reserve the exact recipient before freezing local consent, without contacting a payment provider. */\nexport async function requestNamedSeatReservation(options: NamedSeatCheckoutRequest & AuthorityTransport): Promise<Pick<NamedSeatCheckoutReceipt, \"seatId\" | \"amountCents\" | \"currency\" | \"termEndsAt\">> {\n const result = await requestAuthority(options, \"seat-reservations\", { applicationId: options.applicationId, skuId: options.skuId,\n recipientName: options.recipientName, recipientEmail: options.recipientEmail, purchaserEmail: options.purchaserEmail, purchaserUserId: options.purchaserUserId });\n const seat = result.seat as NamedSeatCheckoutReceipt;\n const expected = (await membershipOfferIdForRequest({ ...options, requestId: \"named_seat\" })).replace(/^offer_/, \"seat_\");\n if (!seat || seat.seatId !== expected || !Number.isSafeInteger(seat.amountCents) || seat.amountCents <= 0 ||\n !/^[a-z]{3}$/.test(seat.currency) || !Number.isSafeInteger(seat.termEndsAt)) throw new Error(\"invalid seat reservation receipt\");\n return { seatId: seat.seatId, amountCents: seat.amountCents, currency: seat.currency, termEndsAt: seat.termEndsAt };\n}\n/** Reference to an independent network Stripe fact, never caller-supplied payment amounts. */\nexport type NamedSeatEvidenceRequest = MembershipQuoteTarget & { seatId: string; eventId: string };\n\n/** Read an authenticated purchaser's seat terms and existing named recipient. */\nexport async function requestNamedSeatOffer(options: MembershipQuoteTarget & AuthorityTransport): Promise<NamedSeatOffer> {\n const result = await requestAuthority(options, \"seat-offer\", { applicationId: options.applicationId, skuId: options.skuId });\n const offer = result.seat as NamedSeatOffer;\n if (!offer || offer.membershipId !== await networkMembershipId(options) || !Number.isSafeInteger(offer.amountCents) || offer.amountCents <= 0 ||\n !/^[a-z]{3}$/.test(offer.currency) || ![\"month\", \"year\"].includes(offer.interval) || typeof offer.eligible !== \"boolean\" || typeof offer.autoRenew !== \"boolean\" ||\n !Number.isSafeInteger(offer.termEndsAt) || !Number.isSafeInteger(offer.purchaseEndsAt) ||\n offer.digest !== await namedSeatOfferDigest(offer)) throw new Error(\"invalid named seat offer\");\n return offer;\n}\n/** Look up one invitation only after the chapter verifies the recipient's current primary email. */\nexport async function requestNamedSeatInvitation(options: NamedSeatInvitationRequest & AuthorityTransport): Promise<NamedSeatInvitation> {\n const result = await requestAuthority(options, \"seat-invitation\", { seatId: options.seatId, recipientUserId: options.recipientUserId,\n verifiedRecipientEmail: options.verifiedRecipientEmail });\n const row = result.seat as NamedSeatInvitation;\n if (!row || row.seatId !== options.seatId || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{2,159}$/.test(row.primaryApplicationId) ||\n typeof row.skuId !== \"string\" || !row.skuId || typeof row.recipientName !== \"string\" || !Number.isSafeInteger(row.termEndsAt) ||\n !Number.isSafeInteger(row.acceptanceEndsAt) || ![\"pending_acceptance\", \"pending_approval\", \"pending_primary\", \"active\"].includes(row.status)) {\n throw new Error(\"invalid named seat invitation receipt\");\n }\n return row;\n}\n/** Check the exact recipient's current entitlement rather than relying on a cached account role. */\nexport async function requestNamedSeatAccess(options: MembershipQuoteTarget & { seatId: string; recipientUserId: string; recipientApplicationId: string } & AuthorityTransport): Promise<MembershipAccessReceipt> {\n const result = await requestAuthority(options, \"seat-access\", { applicationId: options.applicationId, skuId: options.skuId,\n seatId: options.seatId, recipientUserId: options.recipientUserId, recipientApplicationId: options.recipientApplicationId });\n return verifyMembershipAccessReceipt(result.seat, options, Date.now());\n}\n\n/** Prepare one named purchase through the configured network Price, never a caller-selected Price. */\nexport async function requestNamedSeatCheckout(options: NamedSeatCheckoutRequest & AuthorityTransport): Promise<NamedSeatCheckoutReceipt> {\n const result = await requestAuthority(options, \"seat-checkouts\", { applicationId: options.applicationId, skuId: options.skuId,\n recipientName: options.recipientName, recipientEmail: options.recipientEmail, purchaserEmail: options.purchaserEmail, purchaserUserId: options.purchaserUserId });\n const seat = result.seat as NamedSeatCheckoutReceipt;\n const expected = (await membershipOfferIdForRequest({ ...options, requestId: \"named_seat\" })).replace(/^offer_/, \"seat_\");\n if (!seat || seat.seatId !== expected || !/^pi_[A-Za-z0-9_]+$/.test(seat.paymentIntentId) || typeof seat.clientSecret !== \"string\" ||\n !Number.isSafeInteger(seat.amountCents) || seat.amountCents <= 0 || !/^[a-z]{3}$/.test(seat.currency) ||\n !Number.isSafeInteger(seat.termEndsAt) || ![\"payment_processing\", \"renewal_pending\", \"pending_acceptance\", \"pending_approval\", \"active\"].includes(seat.status)) {\n throw new Error(\"invalid named seat checkout receipt\");\n }\n return seat;\n}\n/** Forward only the reference to independently verified network payment evidence. */\nexport async function requestNamedSeatPayment(options: NamedSeatEvidenceRequest & AuthorityTransport) { return seatEvidence(options, \"seat-payments\"); }\n/** Forward a complete seat refund without changing the purchaser's membership. */\nexport async function requestNamedSeatRefund(options: NamedSeatEvidenceRequest & AuthorityTransport) { return seatEvidence(options, \"seat-refunds\"); }\nasync function seatEvidence(options: NamedSeatEvidenceRequest & AuthorityTransport, action: \"seat-payments\" | \"seat-refunds\") {\n const result = await requestAuthority(options, action, { applicationId: options.applicationId, skuId: options.skuId, seatId: options.seatId, eventId: options.eventId });\n const seat = result.seat as { seatId: string; reconciled: boolean };\n if (!seat || seat.seatId !== options.seatId || seat.reconciled !== true) throw new Error(\"invalid named seat evidence receipt\");\n return { seatId: seat.seatId, reconciled: true as const };\n}\n/** Claim only the verified named recipient's invitation. */\nexport async function requestNamedSeatAcceptance(options: NamedSeatRecipientInput & AuthorityTransport) { return seatRecipient(options, \"seat-accept\"); }\n/** Attest that recipient's own completed Journey. */\nexport async function requestNamedSeatApproval(options: NamedSeatRecipientInput & AuthorityTransport) { return seatRecipient(options, \"seat-approve\"); }\nasync function seatRecipient(options: NamedSeatRecipientInput & AuthorityTransport, action: \"seat-accept\" | \"seat-approve\"): Promise<NamedSeatRecipientReceipt> {\n const result = await requestAuthority(options, action, { applicationId: options.applicationId, skuId: options.skuId, seatId: options.seatId,\n recipientApplicationId: options.recipientApplicationId, recipientUserId: options.recipientUserId, verifiedRecipientEmail: options.verifiedRecipientEmail });\n const seat = result.seat as NamedSeatRecipientReceipt;\n if (!seat || seat.seatId !== options.seatId || seat.recipientApplicationId !== options.recipientApplicationId ||\n ![\"pending_approval\", \"pending_primary\", \"active\"].includes(seat.status)) throw new Error(\"invalid named seat recipient receipt\");\n return seat;\n}\n/** Reconcile local provider references against independently signed network Stripe facts. */\nexport async function requestMembershipPayment(options: ConfirmMembershipPaymentInput & AuthorityTransport): Promise<MembershipPaymentReceipt> {\n const result = await requestAuthority(options, \"payments\", { applicationId: options.applicationId, skuId: options.skuId,\n eventId: options.eventId, providerSubscriptionId: options.providerSubscriptionId, providerCustomerId: options.providerCustomerId });\n return verifyMembershipPaymentReceipt(result.membership, options);\n}\n/** Attest durable chapter Journey approval; the network alone assigns order and entitlement. */\nexport async function requestMembershipApproval(options: MembershipQuoteTarget & AuthorityTransport): Promise<MembershipPaymentReceipt> {\n const result = await requestAuthority(options, \"approvals\", { applicationId: options.applicationId, skuId: options.skuId });\n return verifyMembershipPaymentReceipt(result.membership, options);\n}\n/** Refund only the network's frozen initial invoice and cancel its subscription. Caller must authenticate the operator first. */\nexport async function requestMembershipRefund(options: MembershipQuoteTarget & AuthorityTransport): Promise<MembershipRefundReceipt> {\n const result = await requestAuthority(options, \"refunds\", { applicationId: options.applicationId, skuId: options.skuId });\n const refund = result.refund as MembershipRefundReceipt;\n if (!refund || refund.membershipId !== await networkMembershipId(options) || refund.status !== \"refunded\" || refund.subscriptionCanceled !== true ||\n !Number.isSafeInteger(refund.refundedCents) || refund.refundedCents <= 0) throw new Error(\"invalid membership refund receipt\");\n return refund;\n}\n\n/** Advance billing only from independently verified network invoice evidence. */\nexport async function requestMembershipRenewal(options: MembershipQuoteTarget & { eventId: string } & AuthorityTransport): Promise<MembershipRenewalReceipt> {\n const result = await requestAuthority(options, \"renewals\", { applicationId: options.applicationId, skuId: options.skuId, eventId: options.eventId });\n const row = result.renewal as MembershipRenewalReceipt;\n if (!row || row.membershipId !== await networkMembershipId(options) || !Number.isSafeInteger(row.termEndsAt) || row.termEndsAt <= 0 ||\n !Number.isSafeInteger(row.graceEndsAt) || row.graceEndsAt < 0 || typeof row.autoRenew !== \"boolean\" ||\n ![\"active\", \"paid_pending_approval\", \"cancel_at_term_end\", \"payment_grace\", \"lapsed\", \"refund_pending\", \"refunded\", \"canceled\", \"declined\"].includes(row.status)) {\n throw new Error(\"invalid membership renewal receipt\");\n }\n return { membershipId: row.membershipId, status: row.status, termEndsAt: row.termEndsAt, graceEndsAt: row.graceEndsAt, autoRenew: row.autoRenew };\n}\n\nasync function requestAuthority(options: Pick<RequestMembershipOfferOptions, \"secret\" | \"targetUrl\" | \"fetch\" | \"runtime\" | \"appId\">,\n action: \"offers\" | \"checkouts\" | \"payments\" | \"approvals\" | \"refunds\" | \"renewals\" | \"access\" | \"seat-offer\" | \"seat-reservations\" | \"seat-checkouts\" | \"seat-payments\" | \"seat-refunds\" | \"seat-accept\" | \"seat-approve\" | \"seat-invitation\" | \"seat-access\" | \"seat-decline\" | \"seat-effect\",\n input: Record<string, string>): Promise<Record<string, unknown>> {\n const origin = new URL(options.targetUrl);\n if (origin.protocol !== \"https:\" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== \"/\" ||\n !/^[a-z0-9]{2,12}$/.test(options.runtime)) throw new TypeError(\"invalid membership authority target\");\n const url = new URL(`${MEMBERSHIP_AUTHORITY_PATH}/${options.runtime}/${action}`, origin);\n const body = JSON.stringify(input);\n const signed = await signFederatedRequest({ secret: options.secret, sender: options.appId, method: \"POST\", url, body });\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => { controller.abort(); reject(new Error(\"membership authority timed out\")); }, 10000);\n });\n try {\n const response = await Promise.race([(options.fetch ?? globalThis.fetch)(url, { method: \"POST\", redirect: \"manual\",\n signal: controller.signal, headers: { ...signed, \"content-type\": \"application/json\" }, body }), deadline]);\n if (!response.ok) { await response.body?.cancel(); throw new Error(`membership authority rejected ${action}`); }\n const result = await Promise.race([readBoundedJson(response, controller.signal, 16384, \"membership offer receipt\"), deadline]);\n if (!result || typeof result !== \"object\" || (result as { ok?: unknown }).ok !== true) throw new TypeError(\"invalid membership offer receipt\");\n return result as Record<string, unknown>;\n } finally { clearTimeout(timer); }\n}\n\n/** Read current entitlement for one authenticated member; network outages must fail closed. */\nexport async function requestMembershipAccess(options: MembershipQuoteTarget & AuthorityTransport): Promise<MembershipAccessReceipt> {\n const result = await requestAuthority(options, \"access\", { applicationId: options.applicationId, skuId: options.skuId });\n return verifyMembershipAccessReceipt(result.access, options, Date.now());\n}\n","/** Internal bounded reader shared by server-to-server receipts. Never retains raw error bodies. */\nexport async function readBoundedJson(response: Response, signal: AbortSignal, maxBytes: number, label: string): Promise<unknown> {\n const reader = response.body?.getReader();\n if (!reader) throw new TypeError(`invalid ${label}`);\n const cancel = () => { void reader.cancel().catch(() => {}); };\n signal.addEventListener(\"abort\", cancel, { once: true });\n let size = 0;\n let text = \"\";\n const decoder = new TextDecoder();\n try {\n while (true) {\n if (signal.aborted) throw new Error(`${label} timed out`);\n const { done, value } = await reader.read();\n if (signal.aborted) throw new Error(`${label} timed out`);\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) throw new TypeError(`${label} exceeds limit`);\n text += decoder.decode(value, { stream: true });\n }\n try { return JSON.parse(text + decoder.decode()); }\n catch { throw new TypeError(`invalid ${label}`); }\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n await reader.cancel().catch(() => {});\n reader.releaseLock();\n }\n}\n","import type { MembershipPaymentReceipt } from \"./membership-payment-authority\";\nimport { networkMembershipId } from \"./membership-payment-authority\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\n\n/** Validate a trusted transport response before using it to advance a chapter Journey. */\nexport async function verifyMembershipPaymentReceipt(value: unknown, target: MembershipQuoteTarget): Promise<MembershipPaymentReceipt> {\n const row = value as MembershipPaymentReceipt | undefined;\n if (!row || row.membershipId !== await networkMembershipId(target) ||\n ![\"paid_pending_approval\", \"active\", \"cancel_at_term_end\", \"payment_grace\", \"lapsed\", \"refund_pending\", \"refunded\", \"canceled\"].includes(row.status) ||\n typeof row.cohort !== \"string\" || row.cohort.length < 1 || row.cohort.length > 160 ||\n !Number.isSafeInteger(row.initialTermStartedAt) || row.initialTermStartedAt < 0 ||\n !Number.isSafeInteger(row.initialTermEndsAt) || row.initialTermEndsAt <= row.initialTermStartedAt ||\n (row.memberNumber !== undefined && (!Number.isSafeInteger(row.memberNumber) || row.memberNumber < 1))) {\n throw new Error(\"invalid membership authority receipt\");\n }\n return { membershipId: row.membershipId, status: row.status, cohort: row.cohort,\n initialTermStartedAt: row.initialTermStartedAt, initialTermEndsAt: row.initialTermEndsAt,\n ...(row.memberNumber !== undefined ? { memberNumber: row.memberNumber } : {}) };\n}\n","import { initStripe, stripeRequest } from \"@odla-ai/stripe\";\nimport { listStripeObjects } from \"./network-commercial-reconcile\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport { loadMembershipAuthorityState, membershipClock, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\nimport type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\n\n/** Close an unpaid seat when its primary closes or its purchase window ends.\n * A captured payment waits for independent payment evidence and the full-refund workflow.\n * An unknown create result stays pending unless its exact provider object is recovered.\n */\nexport async function cancelUnpaidNamedSeat(db: ChapterDb, target: MembershipQuoteTarget & { seatId: string }, secretKey: string, now: number): Promise<boolean> {\n membershipClock(now);\n const state = await loadMembershipAuthorityState(db, target);\n let seat = await membershipLoad(db, \"networkSeat\", target.seatId); requireMembershipScope(seat, target);\n if (seat.status === \"canceled\") return true;\n if (![\"payment_pending\", \"payment_processing\", \"payment_canceling\"].includes(String(seat.status))) return false;\n const member = await membershipLoad(db, \"networkMembership\", String(seat.primaryMembershipId)); requireMembershipScope(member, target);\n if (![\"refunded\", \"declined\", \"lapsed\"].includes(String(member.status)) && now <= Number(seat.seatPurchaseEndsAt) && now < Number(member.termEndsAt)) return false;\n const neverStarted = seat.status === \"payment_pending\" && !seat.providerPaymentIntentId;\n if (seat.status !== \"payment_canceling\") {\n await db.transact([membershipUpdate(\"networkSeat\", target.seatId, { status: neverStarted ? \"canceled\" : \"payment_canceling\",\n revision: Number(seat.revision) + 1, updatedAt: now })], { guards: [\n { ns: \"networkSeat\", id: target.seatId, exists: true, equals: { revision: seat.revision, status: seat.status } },\n { ns: \"networkMembership\", id: String(member.id), exists: true, equals: { revision: member.revision } },\n { ns: \"membershipAuthorityState\", id: String(state.id), exists: true, equals: { mode: \"authoritative\", revision: state.revision } },\n ] });\n if (neverStarted) return true;\n seat = await membershipLoad(db, \"networkSeat\", target.seatId); requireMembershipScope(seat, target);\n }\n const metadata = { ...stripePartitionMetadata(target), applicationId: target.applicationId, membershipId: seat.primaryMembershipId, seatId: seat.id };\n const request = async (method: \"GET\" | \"POST\", path: string, params?: Record<string, string>) => {\n const result = await stripeRequest<Record<string, any>>({ secretKey }, method, path, params,\n method === \"POST\" ? { idempotencyKey: `named-seat-cancel:${seat!.id}` } : undefined);\n if (!result.ok || !result.body) throw new Error(\"seat cancellation provider pending\");\n return result.body;\n };\n let payment: Record<string, any>;\n if (seat.providerPaymentIntentId) payment = await request(\"GET\", `/v1/payment_intents/${encodeURIComponent(String(seat.providerPaymentIntentId))}`);\n else {\n const snapshot = await listStripeObjects(initStripe({ secretKey }), \"/v1/payment_intents\", { customer: String(seat.providerCustomerId) });\n const matches = snapshot.objects.filter(row => (row.metadata as Record<string, unknown>)?.seatId === target.seatId);\n if (!snapshot.complete || matches.length !== 1) throw new Error(\"seat payment creation outcome unresolved\");\n payment = matches[0]!;\n }\n const valid = (p: Record<string, any>) => /^pi_[A-Za-z0-9_]+$/.test(p.id) && (!seat!.providerPaymentIntentId || p.id === seat!.providerPaymentIntentId) &&\n p.customer === seat!.providerCustomerId && p.amount === seat!.amountCents && p.currency === seat!.currency &&\n p.livemode === (target.environment === \"prod\") && Object.entries(metadata).every(([key, value]) => p.metadata?.[key] === value);\n if (!valid(payment)) throw new Error(\"seat cancellation payment mismatch\");\n if (!seat.providerPaymentIntentId) await db.transact([membershipUpdate(\"networkSeat\", target.seatId, { providerPaymentIntentId: payment.id })], {\n guards: [{ ns: \"networkSeat\", id: target.seatId, exists: true, equals: { status: \"payment_canceling\" }, absent: [\"providerPaymentIntentId\"] }],\n });\n if (payment.status === \"succeeded\" || payment.amount_received > 0) throw new Error(\"paid seat requires payment evidence and full refund\");\n if (payment.status !== \"canceled\") {\n if (![\"requires_payment_method\", \"requires_confirmation\", \"requires_action\", \"processing\"].includes(payment.status)) throw new Error(\"seat payment outcome unresolved\");\n const id = payment.id;\n payment = await request(\"POST\", `/v1/payment_intents/${encodeURIComponent(id)}/cancel`, { cancellation_reason: \"abandoned\" });\n if (payment.id !== id) throw new Error(\"seat cancellation receipt mismatch\");\n }\n if (!valid(payment) || payment.status !== \"canceled\" || payment.amount_received !== 0) throw new Error(\"seat cancellation unconfirmed\");\n await db.transact([membershipUpdate(\"networkSeat\", target.seatId, { status: \"canceled\", revision: Number(seat.revision) + 1, updatedAt: now })], {\n guards: [{ ns: \"networkSeat\", id: target.seatId, exists: true, equals: { status: \"payment_canceling\", providerPaymentIntentId: payment.id } }],\n });\n return true;\n}\n","import type { ChapterDb } from \"./types\";\nimport type { MembershipQuoteTarget } from \"./membership-quote-projection\";\nimport { loadMembershipAuthorityState, membershipClock, membershipLoad, membershipUpdate, requireMembershipScope } from \"./membership-authority-state\";\nimport { completeNamedSeatRenewal } from \"./membership-seat-renewal\";\nimport { completeNamedSeatRefund, requestNamedSeatRefund } from \"./membership-seat-refund\";\nimport { refundNetworkMembership } from \"./membership-refund-authority\";\nimport { cancelUnpaidNamedSeat } from \"./membership-seat-cancel\";\n\n/** Exact configured chapter/runtime serviced by one scheduled network worker. */\nexport type MembershipEffectScope = Pick<MembershipQuoteTarget, \"appId\" | \"chapterId\" | \"environment\" | \"runtime\">;\n/** Downstream requests carry only identifiers; the signed chapter receiver reads current state and deduplicates by effectId. */\nexport interface MembershipChapterEffect extends MembershipQuoteTarget {\n effectId: string; seatId: string; kind: \"invite_named_recipient\" | \"grant_named_recipient_access\" | \"revoke_named_recipient_access\";\n}\n/** Recover provider effects and expired invitations from durable state, independently of browser/webhook retries.\n * The optional chapter adapter must return a durable, idempotent receipt. An absent adapter leaves work visibly pending.\n * Provider HTTP timeouts, ambiguous receipts and scope conflicts never become success or an unbounded automatic retry loop.\n */\nexport async function drainMembershipEffects(db: ChapterDb, options: {\n scope: MembershipEffectScope; stripeSecretKey: string; limit?: number;\n deliverChapterEffect?: (input: MembershipChapterEffect) => Promise<{ effectId: string; complete: true }>;\n}, now: number): Promise<{ complete: number; pending: number; expired: number; more: boolean }> {\n membershipClock(now);\n const limit = options.limit ?? 25, scope = options.scope;\n if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !options.stripeSecretKey) throw new TypeError(\"invalid membership recovery configuration\");\n await loadMembershipAuthorityState(db, scope);\n const matches = (row: Record<string, unknown>) => Object.entries(scope).every(([key, value]) => row[key] === value);\n let expired = 0, pending = 0, complete = 0, more = false;\n for (const status of [\"payment_pending\", \"payment_processing\", \"payment_canceling\"]) {\n const seats = (await db.query({ networkSeat: { $: { where: { ...scope, status }, order: { updatedAt: \"asc\" }, limit: limit + 1 } } })).networkSeat ?? [];\n more ||= seats.length > limit;\n for (const seat of seats.slice(0, limit)) {\n if (!matches(seat)) throw new Error(\"membership recovery scope mismatch\");\n try { if (await cancelUnpaidNamedSeat(db, { ...scope, applicationId: String(seat.applicationId), skuId: String(seat.skuId),\n seatId: String(seat.id) }, options.stripeSecretKey, now)) complete++; } catch { pending++; }\n }\n }\n for (const status of [\"renewal_pending\", \"pending_acceptance\"]) {\n const seats = (await db.query({ networkSeat: { $: { where: { ...scope, status }, order: { acceptanceEndsAt: \"asc\" }, limit: limit + 1 } } })).networkSeat ?? [];\n more ||= seats.length > limit;\n for (const seat of seats.slice(0, limit)) {\n if (!matches(seat)) throw new Error(\"membership recovery scope mismatch\");\n if (seat.acceptedAt !== undefined || now < Number(seat.acceptanceEndsAt)) continue;\n try { await requestNamedSeatRefund(db, { ...scope, applicationId: String(seat.applicationId), skuId: String(seat.skuId),\n seatId: String(seat.id), reason: \"expired\" }, now); expired++; } catch { pending++; }\n }\n }\n const effects = (await db.query({ membershipEffect: { $: { where: { chapterId: scope.chapterId, environment: scope.environment,\n runtime: scope.runtime, status: \"pending\" }, order: { updatedAt: \"asc\" }, limit: limit + 1 } } })).membershipEffect ?? [];\n more ||= effects.length > limit;\n for (const effect of effects.slice(0, limit)) {\n const member = await membershipLoad(db, \"networkMembership\", String(effect.membershipId));\n if (!member || !matches(member) || [\"chapterId\", \"environment\", \"runtime\"].some(key => effect[key] !== member[key])) {\n throw new Error(\"membership effect scope mismatch\");\n }\n const target = { ...scope, applicationId: String(member.applicationId), skuId: String(member.skuId) };\n const seat = effect.seatId ? await membershipLoad(db, \"networkSeat\", String(effect.seatId)) : undefined;\n if (effect.seatId) { requireMembershipScope(seat, target); if (seat.primaryMembershipId !== member.id) throw new Error(\"membership seat scope mismatch\"); }\n try {\n const attempts = Number(effect.attempts);\n if (!Number.isSafeInteger(attempts) || attempts < 0) throw new Error(\"invalid membership effect attempt\");\n await db.transact([membershipUpdate(\"membershipEffect\", String(effect.id), { attempts: attempts + 1, updatedAt: now })], {\n guards: [{ ns: \"membershipEffect\", id: String(effect.id), exists: true, equals: { status: \"pending\", attempts } }],\n });\n switch (effect.kind) {\n case \"refund_membership\": await refundNetworkMembership(db, target, options.stripeSecretKey, now); break;\n case \"refund_seat_with_primary\":\n if (seat?.status === \"canceled\") break;\n await requestNamedSeatRefund(db, { ...target, seatId: String(effect.seatId), reason: \"primary_closed\" }, now);\n await completeNamedSeatRefund(db, String(effect.seatId), options.stripeSecretKey, now); break;\n case \"refund_seat\": await completeNamedSeatRefund(db, String(effect.seatId), options.stripeSecretKey, now); break;\n case \"attach_seat_renewal\":\n if (![\"refund_pending\", \"refunded\"].includes(String(seat?.status))) await completeNamedSeatRenewal(db, String(effect.seatId), options.stripeSecretKey, now);\n break;\n case \"invite_named_recipient\":\n case \"grant_named_recipient_access\":\n case \"revoke_named_recipient_access\": {\n if (!seat) throw new Error(\"named seat effect missing seat\");\n // An obsolete invitation/grant must not escape after the seat closed. Revocation still needs a receiver receipt.\n if (effect.kind !== \"revoke_named_recipient_access\" && [\"refund_pending\", \"refunded\"].includes(String(seat.status))) break;\n if (!options.deliverChapterEffect) throw new Error(\"chapter effect receiver unavailable\");\n const receipt = await options.deliverChapterEffect({ ...target, effectId: String(effect.id), seatId: String(effect.seatId), kind: effect.kind });\n if (receipt.effectId !== effect.id || receipt.complete !== true) throw new Error(\"chapter effect receipt unconfirmed\");\n break;\n }\n default: throw new Error(\"unsupported membership effect\");\n }\n const current = await membershipLoad(db, \"membershipEffect\", String(effect.id));\n if (current?.status !== \"complete\") await db.transact([membershipUpdate(\"membershipEffect\", String(effect.id), { status: \"complete\", updatedAt: now })], {\n guards: [{ ns: \"membershipEffect\", id: String(effect.id), exists: true, equals: { status: \"pending\", attempts: attempts + 1 } }],\n });\n complete++;\n } catch { pending++; }\n }\n return { complete, pending, expired, more };\n}\n","import type { Attr, AttrType, DbRules, Entity } from \"./types\";\nconst attr = (type: AttrType, optional = false, unique = false, indexed = false): Attr => ({ type, optional, unique, indexed });\nconst id = () => attr(\"string\", false, true, true);\nconst key = () => attr(\"string\", false, false, true);\n\n/** Opt-in network-scope schema. Do not install as independent chapter authorities. */\nexport const membershipOfferEntities: Record<string, Entity> = {\n membershipAuthorityState: { attrs: {\n id: id(), chapterId: key(), environment: key(), mode: key(), revision: attr(\"number\"),\n cohortCounts: attr(\"json\"), nextMemberNumber: attr(\"number\"), updatedAt: attr(\"number\"),\n } },\n membershipCheckoutOffer: { attrs: {\n id: id(), applicationId: key(), appId: key(), chapterId: key(), environment: key(), runtime: key(), skuId: key(),\n issuedAt: attr(\"number\"), expiresAt: attr(\"number\"), digest: key(), contract: attr(\"json\"),\n approvedFoundingCount: attr(\"number\"), authorityRevision: attr(\"number\"),\n } },\n membershipOfferCheckout: { attrs: {\n id: id(), appId: key(), chapterId: key(), environment: key(), runtime: key(), applicationId: key(), skuId: key(),\n offerId: key(), offerDigest: attr(\"string\"), quoteDigest: attr(\"string\"), priceId: attr(\"string\"), boundAt: attr(\"number\"),\n } },\n};\n/** Browser callers cannot read, issue or alter commercial promises. */\nexport const membershipOfferRules: DbRules = Object.fromEntries(Object.keys(membershipOfferEntities).map(ns =>\n [ns, { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" }]));\n","import type { Attr, AttrType, DbRules, Entity } from \"./types\";\nconst attr = (type: AttrType, optional = false, unique = false, indexed = false): Attr => ({ type, optional, unique, indexed });\nconst id = () => attr(\"string\", false, true, true);\nconst key = (optional = false) => attr(\"string\", optional, false, true);\nconst scope = () => ({ appId: key(), chapterId: key(), environment: key(), runtime: key(), applicationId: key(), skuId: key() });\nconst times = () => ({ revision: attr(\"number\"), createdAt: attr(\"number\"), updatedAt: attr(\"number\") });\n\n/** Authoritative network purchase records, installed once in the network scope.\n * A canonical Person link is optional until explicit reconciliation; source identity is not.\n * These records must never be populated by a shadow projection writer.\n */\nexport const membershipAuthorityEntities: Record<string, Entity> = {\n networkMembership: { attrs: {\n id: id(), membershipId: key(), ...scope(), personId: key(true), baseSkuId: key(), status: key(),\n founding: attr(\"boolean\"), cohort: key(), memberNumber: attr(\"number\", true, false, true),\n purchaseOfferId: key(), purchaseOfferDigest: key(), providerInitialInvoiceId: key(),\n providerSubscriptionId: key(), providerCustomerId: key(), providerPriceId: key(), namedSeatId: key(true),\n offeringVersionId: key(), offeringSnapshot: attr(\"json\"), discountPolicyVersionId: key(true), discountSnapshot: attr(\"json\", true),\n baseAmountCents: attr(\"number\"), amountCents: attr(\"number\"), renewalAmountCents: attr(\"number\"), currency: key(), interval: key(),\n initialTermStartedAt: attr(\"number\"), initialTermEndsAt: attr(\"number\"), termStartedAt: attr(\"number\"), termEndsAt: attr(\"number\"),\n seatPurchaseEndsAt: attr(\"number\"), autoRenew: attr(\"boolean\"), refundedCents: attr(\"number\"), journeyApprovedAt: attr(\"number\", true),\n cancellationRequestedAt: attr(\"number\", true), graceEndsAt: attr(\"number\", true), ...times(),\n refundRequestedAt: attr(\"number\", true),\n } },\n networkEntitlement: { attrs: {\n id: id(), ...scope(), membershipId: key(), seatId: key(true), kind: key(), status: key(),\n termStartedAt: attr(\"number\"), termEndsAt: attr(\"number\"), offeringSnapshot: attr(\"json\"), sourceEventId: key(), ...times(),\n recipientUserId: key(true), recipientApplicationId: key(true), acceptedAt: attr(\"number\", true), journeyApprovedAt: attr(\"number\", true),\n } },\n networkSeat: { attrs: {\n id: id(), ...scope(), primaryMembershipId: key(), purchaserUserId: key(), recipientName: attr(\"string\"), recipientEmailNormalized: key(), recipientClaimId: key(),\n priceId: key(), primaryPriceId: key(), amountCents: attr(\"number\"), currency: key(), interval: key(),\n providerCustomerId: key(), providerSubscriptionId: key(), providerPaymentIntentId: key(true), providerSubscriptionItemId: key(true),\n status: key(), preparedAt: attr(\"number\"), termEndsAt: attr(\"number\"), seatPurchaseEndsAt: attr(\"number\"), offeringSnapshot: attr(\"json\"),\n purchasedAt: attr(\"number\", true), acceptanceEndsAt: attr(\"number\", true, false, true), termStartedAt: attr(\"number\", true), paymentEventId: key(true),\n entitlementId: key(true), recipientUserId: key(true), recipientApplicationId: key(true),\n acceptedAt: attr(\"number\", true), journeyApprovedAt: attr(\"number\", true), ...times(),\n refundReason: attr(\"string\", true), refundedCents: attr(\"number\", true), providerRefundIds: attr(\"json\", true),\n } },\n networkSeatRecipient: { attrs: { id: id(), appId: key(), chapterId: key(), environment: key(), runtime: key(), seatId: key(), recipientEmailNormalized: key(), createdAt: attr(\"number\") } },\n membershipEffect: { attrs: { id: id(), chapterId: key(), environment: key(), runtime: key(), membershipId: key(), seatId: key(true),\n kind: key(), status: key(), attempts: attr(\"number\"), providerObjectId: key(true), error: attr(\"string\", true),\n createdAt: attr(\"number\"), updatedAt: attr(\"number\", false, false, true) } },\n};\n/** Backend-only authority; browser roles, including a network admin, cannot directly change these rows. */\nexport const membershipAuthorityRules: DbRules = Object.fromEntries(Object.keys(membershipAuthorityEntities).map(ns =>\n [ns, { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" }]));\n","import type { MemberPageAudience, MemberPageUpsellOffer } from \"./member-content\";\n\nexport const ID = /^[a-z][a-z0-9-]{0,79}$/;\nexport const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nexport const ROOT_KEYS = new Set([\"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"pages\", \"upsellOverrides\"]);\nexport const SOURCE_KEYS = new Set([\"type\", \"appId\"]);\nexport const TARGET_KEYS = new Set([\"chapterId\", \"environment\"]);\nexport const PAGE_KEYS = new Set([\"id\", \"slug\", \"title\", \"summary\", \"navigation\", \"audience\", \"teaserMarkdown\", \"bodyMarkdown\", \"upsell\"]);\nexport const NAV_KEYS = new Set([\"section\", \"order\", \"parentId\"]);\nexport const AUDIENCE_KEYS = new Set([\"kind\", \"tierIds\"]);\nexport const UPSELL_KEYS = new Set([\"owner\", \"offer\"]);\nexport const OFFER_KEYS = new Set([\"tierId\", \"label\", \"bodyMarkdown\", \"ctaLabel\"]);\nexport const OVERRIDE_KEYS = new Set([\"pageId\", \"offer\"]);\nexport const MAX_PAGES = 100;\nexport const MAX_MARKDOWN = 65_536;\nexport const MAX_TEXT = 240;\n\nexport const record = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nexport function unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]): void {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nexport function textValue(value: unknown, path: string, errors: string[], max = MAX_TEXT, required = false): string | undefined {\n if (value === undefined) {\n if (required) errors.push(`${path} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") {\n errors.push(`${path} must be a string`);\n return undefined;\n }\n const valueText = value.trim();\n if (required && !valueText) errors.push(`${path} is required`);\n if (valueText.length > max) errors.push(`${path} must be at most ${max.toLocaleString(\"en-US\")} characters`);\n return valueText;\n}\n\nexport function offerValue(\n value: unknown,\n path: string,\n errors: string[],\n tiers: ReadonlySet<string>,\n audience?: MemberPageAudience,\n): MemberPageUpsellOffer | undefined {\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n return undefined;\n }\n unknownKeys(raw, OFFER_KEYS, path, errors);\n const tierId = textValue(raw.tierId, `${path}.tierId`, errors, 80, true) ?? \"\";\n if (tierId && !ID.test(tierId)) errors.push(`${path}.tierId must be a lowercase kebab-case id`);\n if (tiers.size && !tiers.has(tierId)) errors.push(`${path}.tierId must reference a declared tier`);\n if (audience?.kind === \"tiers\" && tierId && !audience.tierIds.includes(tierId)) {\n errors.push(`${path}.tierId must grant access to this page`);\n }\n const label = textValue(raw.label, `${path}.label`, errors);\n const bodyMarkdown = textValue(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN);\n const ctaLabel = textValue(raw.ctaLabel, `${path}.ctaLabel`, errors);\n return {\n tierId,\n ...(label ? { label } : {}),\n ...(bodyMarkdown ? { bodyMarkdown } : {}),\n ...(ctaLabel ? { ctaLabel } : {}),\n };\n}\n","import {\n MEMBER_CONTENT_SCHEMA_VERSION,\n type MemberContentDocument,\n type MemberContentPage,\n type MemberContentSource,\n type MemberContentTarget,\n type MemberContentValidationOptions,\n type MemberContentValidationResult,\n type MemberPageAudience,\n type MemberPageNavigation,\n type MemberPageUpsell,\n type MemberPageUpsellOverride,\n} from \"./member-content\";\nimport {\n AUDIENCE_KEYS,\n ID,\n MAX_MARKDOWN,\n MAX_PAGES,\n MAX_TEXT,\n NAV_KEYS,\n OVERRIDE_KEYS,\n PAGE_KEYS,\n ROOT_KEYS,\n SLUG,\n SOURCE_KEYS,\n TARGET_KEYS,\n UPSELL_KEYS,\n offerValue,\n record,\n textValue,\n unknownKeys,\n} from \"./member-content-validation-helpers\";\n\n/** Validate one complete parent or chapter authoring layer with actionable paths. */\nexport function validateMemberContentDocument(\n input: unknown,\n options: MemberContentValidationOptions = {},\n): MemberContentValidationResult {\n const errors: string[] = [];\n const root = record(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== MEMBER_CONTENT_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n if (!Number.isInteger(root.revision) || Number(root.revision) < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isInteger(root.generatedAt) || Number(root.generatedAt) < 0) errors.push(\"document.generatedAt must be a non-negative integer timestamp\");\n\n const sourceRaw = record(root.source);\n let source: MemberContentSource = { type: \"chapter\", appId: \"invalid\" };\n if (!sourceRaw) errors.push(\"document.source must be an object\");\n else {\n unknownKeys(sourceRaw, SOURCE_KEYS, \"document.source\", errors);\n const type = sourceRaw.type;\n const appId = textValue(sourceRaw.appId, \"document.source.appId\", errors, 63, true) ?? \"\";\n if (type !== \"parent\" && type !== \"chapter\") errors.push(\"document.source.type must be parent or chapter\");\n if (appId && !ID.test(appId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (options.sourceType && type !== options.sourceType) errors.push(`document.source.type must be ${options.sourceType}`);\n if (options.sourceAppId && appId !== options.sourceAppId) errors.push(`document.source.appId must be ${options.sourceAppId}`);\n if (type === \"parent\" || type === \"chapter\") source = { type, appId };\n }\n\n let target: MemberContentTarget | undefined;\n if (root.target !== undefined) {\n const targetRaw = record(root.target);\n if (!targetRaw) errors.push(\"document.target must be an object\");\n else {\n unknownKeys(targetRaw, TARGET_KEYS, \"document.target\", errors);\n const chapterId = textValue(targetRaw.chapterId, \"document.target.chapterId\", errors, 63, true) ?? \"\";\n const environment = textValue(targetRaw.environment, \"document.target.environment\", errors, 80, true) ?? \"\";\n target = { chapterId, environment };\n }\n }\n if (source.type === \"parent\" && !target) errors.push(\"document.target is required for parent content\");\n if (source.type === \"chapter\" && target) errors.push(\"document.target is not supported for chapter content\");\n\n if (!Array.isArray(root.pages)) errors.push(\"document.pages must be an array\");\n const rawPages = Array.isArray(root.pages) ? root.pages : [];\n if (rawPages.length > MAX_PAGES) errors.push(`document.pages supports at most ${MAX_PAGES} entries`);\n const tierIds = new Set((options.tiers ?? []).map((tier) => tier.id));\n const knownParentIds = new Set((options.parentPages ?? []).map((page) => page.id));\n const ids = new Set<string>();\n const slugs = new Set<string>();\n const pages: MemberContentPage[] = [];\n for (const [index, value] of rawPages.slice(0, MAX_PAGES).entries()) {\n const path = `document.pages[${index}]`;\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n continue;\n }\n unknownKeys(raw, PAGE_KEYS, path, errors);\n const id = textValue(raw.id, `${path}.id`, errors, 80, true) ?? \"\";\n const slug = textValue(raw.slug, `${path}.slug`, errors, 120, true) ?? \"\";\n const title = textValue(raw.title, `${path}.title`, errors, MAX_TEXT, true) ?? \"\";\n if (id && !ID.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (slug && !SLUG.test(slug)) errors.push(`${path}.slug must be a lowercase URL slug`);\n if (ids.has(id) || knownParentIds.has(id)) errors.push(`${path}.id duplicates page \"${id}\"`);\n if (slugs.has(slug) || (options.parentPages ?? []).some((page) => page.slug === slug)) errors.push(`${path}.slug duplicates \"${slug}\"`);\n ids.add(id);\n slugs.add(slug);\n\n const navRaw = record(raw.navigation);\n let navigation: MemberPageNavigation = { section: \"General\", order: index };\n if (!navRaw) errors.push(`${path}.navigation must be an object`);\n else {\n unknownKeys(navRaw, NAV_KEYS, `${path}.navigation`, errors);\n const section = textValue(navRaw.section, `${path}.navigation.section`, errors, 120, true) ?? \"\";\n const order = navRaw.order;\n if (!Number.isInteger(order) || Number(order) < 0 || Number(order) > 1_000_000) {\n errors.push(`${path}.navigation.order must be an integer from 0 to 1,000,000`);\n }\n const parentId = textValue(navRaw.parentId, `${path}.navigation.parentId`, errors, 80);\n navigation = { section, order: Number.isInteger(order) ? Number(order) : index, ...(parentId ? { parentId } : {}) };\n }\n\n const audienceRaw = record(raw.audience);\n let audience: MemberPageAudience = { kind: \"all-members\" };\n if (!audienceRaw) errors.push(`${path}.audience must be an object`);\n else {\n unknownKeys(audienceRaw, AUDIENCE_KEYS, `${path}.audience`, errors);\n if (audienceRaw.kind === \"all-members\") {\n if (audienceRaw.tierIds !== undefined) errors.push(`${path}.audience.tierIds is not supported for all-members`);\n } else if (audienceRaw.kind === \"tiers\") {\n if (!Array.isArray(audienceRaw.tierIds) || audienceRaw.tierIds.length === 0) {\n errors.push(`${path}.audience.tierIds must be a non-empty array`);\n }\n const values = Array.isArray(audienceRaw.tierIds) ? audienceRaw.tierIds : [];\n const normalized: string[] = [];\n for (const [tierIndex, value] of values.entries()) {\n const tier = textValue(value, `${path}.audience.tierIds[${tierIndex}]`, errors, 80, true) ?? \"\";\n if (normalized.includes(tier)) errors.push(`${path}.audience.tierIds duplicates \"${tier}\"`);\n if (tierIds.size && !tierIds.has(tier)) errors.push(`${path}.audience.tierIds references undeclared tier \"${tier}\"`);\n normalized.push(tier);\n }\n audience = { kind: \"tiers\", tierIds: normalized };\n } else errors.push(`${path}.audience.kind must be all-members or tiers`);\n }\n\n const summary = textValue(raw.summary, `${path}.summary`, errors, 2_000);\n const teaserMarkdown = textValue(raw.teaserMarkdown, `${path}.teaserMarkdown`, errors, MAX_MARKDOWN);\n const bodyMarkdown = textValue(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN, true) ?? \"\";\n let upsell: MemberPageUpsell | undefined;\n if (raw.upsell !== undefined) {\n const upsellRaw = record(raw.upsell);\n if (!upsellRaw) errors.push(`${path}.upsell must be an object`);\n else {\n unknownKeys(upsellRaw, UPSELL_KEYS, `${path}.upsell`, errors);\n const owner = upsellRaw.owner;\n if (owner !== \"parent\" && owner !== \"chapter\") errors.push(`${path}.upsell.owner must be parent or chapter`);\n if (source.type === \"chapter\" && owner === \"parent\") errors.push(`${path}.upsell.owner cannot be parent on a chapter page`);\n if (source.type === \"parent\" && owner === \"parent\" && upsellRaw.offer === undefined) errors.push(`${path}.upsell.offer is required when the parent owns the offer`);\n if (source.type === \"parent\" && owner === \"chapter\" && upsellRaw.offer !== undefined) errors.push(`${path}.upsell.offer must be set by the chapter after delegation`);\n const offer = upsellRaw.offer === undefined ? undefined : offerValue(upsellRaw.offer, `${path}.upsell.offer`, errors, tierIds, audience);\n if (owner === \"parent\") upsell = { owner, offer: offer ?? { tierId: \"\" } };\n else if (owner === \"chapter\") upsell = { owner, ...(offer ? { offer } : {}) };\n }\n }\n pages.push({ id, slug, title, ...(summary ? { summary } : {}), navigation, audience, ...(teaserMarkdown ? { teaserMarkdown } : {}), bodyMarkdown, ...(upsell ? { upsell } : {}) });\n }\n\n const allIds = new Set([...knownParentIds, ...ids]);\n for (const [index, page] of pages.entries()) {\n const parentId = page.navigation.parentId;\n if (parentId && !allIds.has(parentId)) errors.push(`document.pages[${index}].navigation.parentId references unknown page \"${parentId}\"`);\n if (parentId === page.id) errors.push(`document.pages[${index}].navigation.parentId cannot reference itself`);\n }\n for (const page of pages) {\n const seen = new Set([page.id]);\n let parentId = page.navigation.parentId;\n while (parentId) {\n if (seen.has(parentId)) {\n errors.push(`document.pages contains a navigation cycle at \"${page.id}\"`);\n break;\n }\n seen.add(parentId);\n parentId = pages.find((candidate) => candidate.id === parentId)?.navigation.parentId;\n }\n }\n\n let upsellOverrides: MemberPageUpsellOverride[] | undefined;\n if (root.upsellOverrides !== undefined) {\n if (source.type !== \"chapter\") errors.push(\"document.upsellOverrides is supported only for chapter content\");\n if (!Array.isArray(root.upsellOverrides)) errors.push(\"document.upsellOverrides must be an array\");\n const values = Array.isArray(root.upsellOverrides) ? root.upsellOverrides : [];\n const seen = new Set<string>();\n upsellOverrides = [];\n for (const [index, value] of values.entries()) {\n const path = `document.upsellOverrides[${index}]`;\n const raw = record(value);\n if (!raw) {\n errors.push(`${path} must be an object`);\n continue;\n }\n unknownKeys(raw, OVERRIDE_KEYS, path, errors);\n const pageId = textValue(raw.pageId, `${path}.pageId`, errors, 80, true) ?? \"\";\n if (seen.has(pageId)) errors.push(`${path}.pageId duplicates \"${pageId}\"`);\n seen.add(pageId);\n const parentPage = (options.parentPages ?? []).find((page) => page.id === pageId);\n if (!parentPage) errors.push(`${path}.pageId must reference a parent page`);\n else if (parentPage.upsell?.owner !== \"chapter\") errors.push(`${path}.pageId does not delegate upsell authority to the chapter`);\n const offer = offerValue(raw.offer, `${path}.offer`, errors, tierIds, parentPage?.audience);\n if (offer) upsellOverrides.push({ pageId, offer });\n }\n }\n if (errors.length) return { ok: false, errors };\n return { ok: true, value: {\n schemaVersion: MEMBER_CONTENT_SCHEMA_VERSION,\n revision: Number(root.revision),\n generatedAt: Number(root.generatedAt),\n source,\n ...(target ? { target } : {}),\n pages,\n ...(upsellOverrides ? { upsellOverrides } : {}),\n } };\n}\n\n/** Validate or fail closed with every actionable document error. */\nexport function memberContentDocument(input: unknown, options: MemberContentValidationOptions = {}): MemberContentDocument {\n const result = validateMemberContentDocument(input, options);\n if (!result.ok) throw new TypeError(`Invalid member content document: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","/** Versioned contract for authenticated member content. */\nexport const MEMBER_CONTENT_SCHEMA_VERSION = 1 as const;\n/** Authenticated member projection endpoint. */\nexport const MEMBER_CONTENT_PATH = \"/api/member-content\" as const;\n/** Dedicated signed Parent → Chapter content-delivery endpoint. */\nexport const MEMBER_CONTENT_CONTROL_PATH = \"/api/member-content-control\" as const;\n\n/** Authority that authored one independently stored member-content layer. */\nexport type MemberContentSourceType = \"parent\" | \"chapter\";\n/** Stable author identity attached to every member-content document and page. */\nexport interface MemberContentSource { type: MemberContentSourceType; appId: string }\n/** Chapter deployment that a parent member-content revision is intended for. */\nexport interface MemberContentTarget { chapterId: string; environment: string }\n\n/** Navigation is data, so agents do not have to coordinate route code. */\nexport interface MemberPageNavigation {\n section: string;\n order: number;\n parentId?: string;\n}\n\n/** Explicit sets avoid unsafe assumptions that commercial tiers form a ladder. */\nexport type MemberPageAudience =\n | { kind: \"all-members\" }\n | { kind: \"tiers\"; tierIds: readonly string[] };\n\n/** Authored offer copy. Price and provider identity deliberately do not live here. */\nexport interface MemberPageUpsellOffer {\n tierId: string;\n label?: string;\n bodyMarkdown?: string;\n ctaLabel?: string;\n}\n\n/** Parent offer authority is explicit; a Chapter can edit only a delegated offer. */\nexport type MemberPageUpsell =\n | { owner: \"parent\"; offer: MemberPageUpsellOffer }\n | { owner: \"chapter\"; offer?: MemberPageUpsellOffer };\n\n/** Authored member page whose body is disclosed only after server-side projection. */\nexport interface MemberContentPage {\n id: string;\n slug: string;\n title: string;\n summary?: string;\n navigation: MemberPageNavigation;\n audience: MemberPageAudience;\n /** Safe Markdown shown while the body is withheld. */\n teaserMarkdown?: string;\n /** Never serialized to a viewer whose audience does not match. */\n bodyMarkdown: string;\n upsell?: MemberPageUpsell;\n}\n\n/** Chapter-owned offer attached to a Parent page that delegated offer authority. */\nexport interface MemberPageUpsellOverride { pageId: string; offer: MemberPageUpsellOffer }\n\n/** One complete source layer. Parent and Chapter layers are stored independently. */\nexport interface MemberContentDocument {\n schemaVersion: typeof MEMBER_CONTENT_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: MemberContentSource;\n target?: MemberContentTarget;\n pages: readonly MemberContentPage[];\n upsellOverrides?: readonly MemberPageUpsellOverride[];\n}\n\n/** Provider-neutral tier facts used to validate access and resolve safe offers. */\nexport interface MemberContentTierAuthority {\n id: string;\n name?: string;\n priceCents?: number;\n active?: boolean;\n}\n\n/** Local authority supplied while validating a member-content document. */\nexport interface MemberContentValidationOptions {\n sourceType?: MemberContentSourceType;\n sourceAppId?: string;\n tiers?: readonly MemberContentTierAuthority[];\n parentPages?: readonly MemberContentPage[];\n}\n\n/** Validated document or an actionable collection of contract errors. */\nexport type MemberContentValidationResult =\n | { ok: true; value: MemberContentDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Composed member page retaining the identity of its authoring layer. */\nexport interface EffectiveMemberContentPage extends MemberContentPage { source: MemberContentSource }\n/** Deterministically ordered parent and chapter layers with their source revisions. */\nexport interface EffectiveMemberContent {\n pages: readonly EffectiveMemberContentPage[];\n parentRevision: number | null;\n chapterRevision: number | null;\n}\n/** Server-authoritative identity facts used for member-content disclosure. */\nexport interface MemberContentViewer { tierId: string | null; admin: boolean }\n/** Authored upsell joined to active chapter tier name and price authority. */\nexport interface ResolvedMemberPageUpsell extends MemberPageUpsellOffer { tierName: string; priceCents: number }\n\n/** Viewer-safe page result; locked projections never carry bodyMarkdown. */\nexport interface MemberContentPageProjection {\n id: string;\n slug: string;\n title: string;\n summary?: string;\n navigation: MemberPageNavigation;\n audience: MemberPageAudience;\n source: MemberContentSource;\n access: \"allowed\" | \"locked\";\n teaserMarkdown?: string;\n bodyMarkdown?: string;\n upsell?: ResolvedMemberPageUpsell;\n}\n\n/** Complete viewer-safe member navigation and revision projection. */\nexport interface MemberContentProjection {\n pages: readonly MemberContentPageProjection[];\n viewer: { tierId: string | null; admin: boolean };\n revisions: { parent: number | null; chapter: number | null };\n}\n\n/** Canonical parent document and digest transmitted over the signed control edge. */\nexport interface MemberContentEnvelope { digest: string; document: MemberContentDocument }\n/** Durable Chapter acknowledgement for an accepted or idempotently replayed revision. */\nexport interface MemberContentReceipt {\n ok: true;\n target: MemberContentTarget;\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable rejection reasons returned by the signed member-content control endpoint. */\nexport type MemberContentRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n\nexport { memberContentDocument, validateMemberContentDocument } from \"./member-content-validation\";\n\nconst pageOrder = (a: EffectiveMemberContentPage, b: EffectiveMemberContentPage): number =>\n a.navigation.section.localeCompare(b.navigation.section)\n || a.navigation.order - b.navigation.order\n || a.title.localeCompare(b.title)\n || a.id.localeCompare(b.id);\n\n/** Compose immutable Parent content with independently stored Chapter content. */\nexport function composeMemberContent(\n parent: MemberContentDocument | null | undefined,\n chapter: MemberContentDocument | null | undefined,\n): EffectiveMemberContent {\n const pages: EffectiveMemberContentPage[] = [];\n const parentPages = new Map<string, EffectiveMemberContentPage>();\n for (const page of parent?.pages ?? []) {\n const effective = { ...page, source: parent!.source };\n parentPages.set(page.id, effective);\n pages.push(effective);\n }\n for (const override of chapter?.upsellOverrides ?? []) {\n const page = parentPages.get(override.pageId);\n if (page?.upsell?.owner === \"chapter\") page.upsell = { owner: \"chapter\", offer: override.offer };\n }\n for (const page of chapter?.pages ?? []) {\n if (parentPages.has(page.id) || pages.some((candidate) => candidate.slug === page.slug)) {\n throw new TypeError(`Chapter member page \"${page.id}\" conflicts with parent content`);\n }\n pages.push({ ...page, source: chapter!.source });\n }\n return {\n pages: pages.sort(pageOrder),\n parentRevision: parent?.revision ?? null,\n chapterRevision: chapter?.revision ?? null,\n };\n}\n\nconst allowed = (page: MemberContentPage, viewer: MemberContentViewer): boolean =>\n viewer.admin\n || page.audience.kind === \"all-members\"\n || (viewer.tierId !== null && page.audience.tierIds.includes(viewer.tierId));\n\n/** Restricted bodies are omitted and authored offers are joined to live tier authority. */\nexport function projectMemberContent(\n content: EffectiveMemberContent,\n viewer: MemberContentViewer,\n tiers: readonly MemberContentTierAuthority[],\n): MemberContentProjection {\n const authority = new Map(tiers.filter((tier) => tier.active !== false).map((tier) => [tier.id, tier]));\n return {\n viewer: { ...viewer },\n revisions: { parent: content.parentRevision, chapter: content.chapterRevision },\n pages: content.pages.map((page) => {\n const canRead = allowed(page, viewer);\n const offer = !canRead ? page.upsell?.offer : undefined;\n const tier = offer ? authority.get(offer.tierId) : undefined;\n const upsell = offer && tier && typeof tier.name === \"string\" && typeof tier.priceCents === \"number\"\n ? { ...offer, tierName: tier.name, priceCents: tier.priceCents }\n : undefined;\n return {\n id: page.id,\n slug: page.slug,\n title: page.title,\n ...(page.summary ? { summary: page.summary } : {}),\n navigation: page.navigation,\n audience: page.audience,\n source: page.source,\n access: canRead ? \"allowed\" as const : \"locked\" as const,\n ...(page.teaserMarkdown ? { teaserMarkdown: page.teaserMarkdown } : {}),\n ...(canRead ? { bodyMarkdown: page.bodyMarkdown } : {}),\n ...(upsell ? { upsell } : {}),\n };\n }),\n };\n}\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"member content contains an unsupported value\");\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record).sort().flatMap((key) => {\n const item = record[key];\n return item === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(item)}`];\n });\n return `{${entries.join(\",\")}}`;\n}\n\n/** Serialize JSON-like member content with recursively sorted object keys. */\nexport function canonicalMemberContent(value: unknown): string {\n return canonicalValue(value);\n}\n\n/** Compute the canonical SHA-256 digest for one Parent content revision. */\nexport async function memberContentDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalMemberContent(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one content document with the exact digest the follower acknowledges. */\nexport async function createMemberContentEnvelope(document: import(\"./member-content\").MemberContentDocument) {\n return { document, digest: await memberContentDigest(document) };\n}\n","import {\n BUILDER_LIBRARY_SCHEMA_VERSION,\n type BuilderLibraryDocument,\n type BuilderLibraryResource,\n type BuilderLibraryScope,\n type BuilderLibraryValidationOptions,\n type BuilderLibraryValidationResult,\n} from \"./builder-library\";\n\nconst ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst APP_ID = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst MAX_RESOURCES = 200;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_TEXT = 500;\nconst MAX_TAGS = 20;\nconst KINDS = new Set([\"document\", \"note\", \"link\", \"inspiration\", \"image\", \"file\"]);\nconst STATUSES = new Set([\"draft\", \"published\", \"archived\"]);\nconst ROOT_KEYS = new Set([\"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"resources\"]);\nconst SOURCE_KEYS = new Set([\"type\", \"appId\"]);\nconst TARGET_KEYS = new Set([\"appId\", \"environment\"]);\nconst RESOURCE_KEYS = new Set([\"id\", \"kind\", \"title\", \"summary\", \"tags\", \"scope\", \"status\", \"revision\", \"bodyMarkdown\", \"url\", \"brandAsset\", \"provenance\"]);\nconst SCOPE_KEYS = new Set([\"kind\", \"chapterId\"]);\nconst ASSET_KEYS = new Set([\"bookId\", \"assetId\", \"filename\"]);\nconst PROVENANCE_KEYS = new Set([\"createdBy\", \"createdAt\", \"updatedBy\", \"updatedAt\", \"promotedFrom\"]);\nconst PROMOTION_KEYS = new Set([\"chapterId\", \"resourceId\", \"resourceRevision\", \"documentRevision\", \"promotedBy\", \"promotedAt\"]);\n\nconst record = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\n\nfunction unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]) {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nfunction text(value: unknown, path: string, errors: string[], max = MAX_TEXT, required = true): string | undefined {\n if (value === undefined && !required) return undefined;\n if (typeof value !== \"string\" || (required && !value.trim())) {\n errors.push(`${path} must be a non-empty string`);\n return undefined;\n }\n const result = value.trim();\n if (result.length > max) errors.push(`${path} must be at most ${max} characters`);\n return result;\n}\n\nfunction integer(value: unknown, path: string, errors: string[], minimum = 1): number {\n if (!Number.isSafeInteger(value) || Number(value) < minimum) errors.push(`${path} must be an integer >= ${minimum}`);\n return Number(value);\n}\n\nfunction scopeValue(value: unknown, path: string, errors: string[]): BuilderLibraryScope | null {\n const raw = record(value);\n if (!raw) { errors.push(`${path} must be an object`); return null; }\n unknownKeys(raw, SCOPE_KEYS, path, errors);\n if (raw.kind === \"global\" || raw.kind === \"built_not_found\") {\n if (raw.chapterId !== undefined) errors.push(`${path}.chapterId is allowed only for chapter scope`);\n return { kind: raw.kind };\n }\n if (raw.kind === \"chapter\") {\n const chapterId = text(raw.chapterId, `${path}.chapterId`, errors, 63) ?? \"\";\n if (chapterId && !APP_ID.test(chapterId)) errors.push(`${path}.chapterId must be a lowercase app slug`);\n return { kind: \"chapter\", chapterId };\n }\n errors.push(`${path}.kind must be chapter, built_not_found, or global`);\n return null;\n}\n\nfunction resourceValue(value: unknown, path: string, errors: string[]): BuilderLibraryResource | null {\n const raw = record(value);\n if (!raw) { errors.push(`${path} must be an object`); return null; }\n unknownKeys(raw, RESOURCE_KEYS, path, errors);\n const id = text(raw.id, `${path}.id`, errors, 80) ?? \"\";\n if (id && !ID.test(id)) errors.push(`${path}.id must be lowercase kebab-case`);\n const kind = text(raw.kind, `${path}.kind`, errors) ?? \"\";\n if (!KINDS.has(kind)) errors.push(`${path}.kind is unsupported`);\n const title = text(raw.title, `${path}.title`, errors, 240) ?? \"\";\n const summary = text(raw.summary, `${path}.summary`, errors, 1_000, false);\n const status = text(raw.status, `${path}.status`, errors) ?? \"\";\n if (!STATUSES.has(status)) errors.push(`${path}.status must be draft, published, or archived`);\n const revision = integer(raw.revision, `${path}.revision`, errors);\n const scope = scopeValue(raw.scope, `${path}.scope`, errors) ?? { kind: \"global\" as const };\n const tags = Array.isArray(raw.tags) ? raw.tags.map((tag, index) => text(tag, `${path}.tags[${index}]`, errors, 80) ?? \"\") : [];\n if (!Array.isArray(raw.tags)) errors.push(`${path}.tags must be an array`);\n if (tags.length > MAX_TAGS) errors.push(`${path}.tags may contain at most ${MAX_TAGS} items`);\n if (new Set(tags).size !== tags.length) errors.push(`${path}.tags must be unique`);\n const bodyMarkdown = text(raw.bodyMarkdown, `${path}.bodyMarkdown`, errors, MAX_MARKDOWN, false);\n const url = text(raw.url, `${path}.url`, errors, 2_048, false);\n if (url) {\n try { if (new URL(url).protocol !== \"https:\") errors.push(`${path}.url must use https`); }\n catch { errors.push(`${path}.url must be a valid https URL`); }\n }\n const asset = raw.brandAsset === undefined ? null : record(raw.brandAsset);\n if (raw.brandAsset !== undefined && !asset) errors.push(`${path}.brandAsset must be an object`);\n if (asset) unknownKeys(asset, ASSET_KEYS, `${path}.brandAsset`, errors);\n const brandAsset = asset ? {\n bookId: text(asset.bookId, `${path}.brandAsset.bookId`, errors, 160) ?? \"\",\n assetId: text(asset.assetId, `${path}.brandAsset.assetId`, errors, 160) ?? \"\",\n ...(asset.filename === undefined ? {} : { filename: text(asset.filename, `${path}.brandAsset.filename`, errors, 240) ?? \"\" }),\n } : undefined;\n if ((kind === \"document\" || kind === \"note\") && !bodyMarkdown) errors.push(`${path}.bodyMarkdown is required for ${kind}`);\n if ((kind === \"link\" || kind === \"inspiration\") && !url) errors.push(`${path}.url is required for ${kind}`);\n if ((kind === \"image\" || kind === \"file\") && !brandAsset) errors.push(`${path}.brandAsset is required for ${kind}`);\n if (!([\"document\", \"note\"].includes(kind)) && bodyMarkdown) errors.push(`${path}.bodyMarkdown is not allowed for ${kind}`);\n if (!([\"link\", \"inspiration\"].includes(kind)) && url) errors.push(`${path}.url is not allowed for ${kind}`);\n if (!([\"image\", \"file\"].includes(kind)) && brandAsset) errors.push(`${path}.brandAsset is not allowed for ${kind}`);\n const provenanceRaw = record(raw.provenance);\n if (!provenanceRaw) errors.push(`${path}.provenance must be an object`);\n if (provenanceRaw) unknownKeys(provenanceRaw, PROVENANCE_KEYS, `${path}.provenance`, errors);\n const promotedRaw = provenanceRaw?.promotedFrom === undefined ? null : record(provenanceRaw.promotedFrom);\n if (provenanceRaw?.promotedFrom !== undefined && !promotedRaw) errors.push(`${path}.provenance.promotedFrom must be an object`);\n if (promotedRaw) unknownKeys(promotedRaw, PROMOTION_KEYS, `${path}.provenance.promotedFrom`, errors);\n const promotedFrom = promotedRaw ? {\n chapterId: text(promotedRaw.chapterId, `${path}.provenance.promotedFrom.chapterId`, errors, 63) ?? \"\",\n resourceId: text(promotedRaw.resourceId, `${path}.provenance.promotedFrom.resourceId`, errors, 80) ?? \"\",\n resourceRevision: integer(promotedRaw.resourceRevision, `${path}.provenance.promotedFrom.resourceRevision`, errors),\n documentRevision: integer(promotedRaw.documentRevision, `${path}.provenance.promotedFrom.documentRevision`, errors),\n promotedBy: text(promotedRaw.promotedBy, `${path}.provenance.promotedFrom.promotedBy`, errors, 320) ?? \"\",\n promotedAt: integer(promotedRaw.promotedAt, `${path}.provenance.promotedFrom.promotedAt`, errors, 0),\n } : undefined;\n const provenance = {\n createdBy: text(provenanceRaw?.createdBy, `${path}.provenance.createdBy`, errors, 320) ?? \"\",\n createdAt: integer(provenanceRaw?.createdAt, `${path}.provenance.createdAt`, errors, 0),\n updatedBy: text(provenanceRaw?.updatedBy, `${path}.provenance.updatedBy`, errors, 320) ?? \"\",\n updatedAt: integer(provenanceRaw?.updatedAt, `${path}.provenance.updatedAt`, errors, 0),\n ...(promotedFrom ? { promotedFrom } : {}),\n };\n return { id, kind: kind as BuilderLibraryResource[\"kind\"], title, ...(summary ? { summary } : {}), tags, scope, status: status as BuilderLibraryResource[\"status\"], revision, ...(bodyMarkdown ? { bodyMarkdown } : {}), ...(url ? { url } : {}), ...(brandAsset ? { brandAsset } : {}), provenance };\n}\n\n/** Strictly validate size, shape, authority, and the closed scope enum. */\nexport function validateBuilderLibraryDocument(\n value: unknown,\n options: BuilderLibraryValidationOptions = {},\n): BuilderLibraryValidationResult {\n const errors: string[] = [];\n const raw = record(value);\n if (!raw) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(raw, ROOT_KEYS, \"document\", errors);\n if (raw.schemaVersion !== BUILDER_LIBRARY_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n const revision = integer(raw.revision, \"document.revision\", errors);\n const generatedAt = integer(raw.generatedAt, \"document.generatedAt\", errors, 0);\n const sourceRaw = record(raw.source);\n if (!sourceRaw) errors.push(\"document.source must be an object\");\n if (sourceRaw) unknownKeys(sourceRaw, SOURCE_KEYS, \"document.source\", errors);\n const sourceType = sourceRaw?.type;\n if (sourceType !== \"chapter\" && sourceType !== \"built_not_found\") errors.push(\"document.source.type must be chapter or built_not_found\");\n const sourceAppId = text(sourceRaw?.appId, \"document.source.appId\", errors, 63) ?? \"\";\n if (sourceAppId && !APP_ID.test(sourceAppId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (options.sourceType && sourceType !== options.sourceType) errors.push(`document.source.type must be ${options.sourceType}`);\n if (options.sourceAppId && sourceAppId !== options.sourceAppId) errors.push(`document.source.appId must be ${options.sourceAppId}`);\n const targetRaw = raw.target === undefined ? null : record(raw.target);\n if (raw.target !== undefined && !targetRaw) errors.push(\"document.target must be an object\");\n if (targetRaw) unknownKeys(targetRaw, TARGET_KEYS, \"document.target\", errors);\n const target = targetRaw ? {\n appId: text(targetRaw.appId, \"document.target.appId\", errors, 63) ?? \"\",\n environment: text(targetRaw.environment, \"document.target.environment\", errors, 80) ?? \"\",\n } : undefined;\n if (options.targetAppId && target?.appId !== options.targetAppId) errors.push(`document.target.appId must be ${options.targetAppId}`);\n if (!Array.isArray(raw.resources)) errors.push(\"document.resources must be an array\");\n const inputs = Array.isArray(raw.resources) ? raw.resources : [];\n if (inputs.length > MAX_RESOURCES) errors.push(`document.resources may contain at most ${MAX_RESOURCES} items`);\n const resources = inputs.map((item, index) => resourceValue(item, `document.resources[${index}]`, errors)).filter(Boolean) as BuilderLibraryResource[];\n const ids = resources.map(({ id }) => id);\n if (new Set(ids).size !== ids.length) errors.push(\"document.resources ids must be unique\");\n for (const resource of resources) {\n if (sourceType === \"chapter\" && (resource.scope.kind !== \"chapter\" || resource.scope.chapterId !== sourceAppId)) {\n errors.push(`document.resources.${resource.id}: Chapter sources may author only their own chapter scope`);\n }\n if (sourceType === \"built_not_found\" && resource.scope.kind === \"chapter\"\n && !(options.allowedChapterIds ?? []).includes(resource.scope.chapterId)) {\n errors.push(`document.resources.${resource.id}: Built Not Found may target only configured Chapters`);\n }\n }\n if (errors.length) return { ok: false, errors };\n return { ok: true, value: { schemaVersion: 1, revision, generatedAt, source: { type: sourceType as BuilderLibraryDocument[\"source\"][\"type\"], appId: sourceAppId }, ...(target ? { target } : {}), resources } };\n}\n","/** Versioned contract for private Builder Library source material. */\nexport const BUILDER_LIBRARY_SCHEMA_VERSION = 1 as const;\n/** Authenticated admin inventory and local-authoring endpoint. */\nexport const BUILDER_LIBRARY_ADMIN_PATH = \"/api/admin/builder-library\" as const;\n/** Authenticated, published-only agent manifest endpoint. */\nexport const BUILDER_LIBRARY_MANIFEST_PATH = \"/api/admin/builder-library/manifest\" as const;\n/** Built Not Found-only audited Chapter-to-global promotion endpoint. */\nexport const BUILDER_LIBRARY_PROMOTE_PATH = \"/api/admin/builder-library/promote\" as const;\n/** Dedicated signed federation receiver for Builder Library documents. */\nexport const BUILDER_LIBRARY_CONTROL_PATH = \"/api/builder-library-control\" as const;\n\n/** Authority kind attached to one complete Builder Library document. */\nexport type BuilderLibrarySourceType = \"chapter\" | \"built_not_found\";\n/** Stable authority identity attached to a Builder Library document. */\nexport interface BuilderLibrarySource { type: BuilderLibrarySourceType; appId: string }\n/** Exact app deployment that a signed Builder Library revision targets. */\nexport interface BuilderLibraryTarget { appId: string; environment: string }\n\n/** Exactly one visibility scope. There are deliberately no groups or audience arrays. */\nexport type BuilderLibraryScope =\n | { kind: \"chapter\"; chapterId: string }\n | { kind: \"built_not_found\" }\n | { kind: \"global\" };\n\n/** Supported private source-material representations. */\nexport type BuilderLibraryResourceKind = \"document\" | \"note\" | \"link\" | \"inspiration\" | \"image\" | \"file\";\n/** Explicit authoring lifecycle; only published resources enter agent manifests. */\nexport type BuilderLibraryResourceStatus = \"draft\" | \"published\" | \"archived\";\n\n/** Durable Brand identity only; URLs, bytes, and storage credentials never enter a manifest. */\nexport interface BuilderLibraryBrandAssetRef {\n bookId: string;\n assetId: string;\n filename?: string;\n}\n\n/** Immutable origin recorded when Built Not Found promotes Chapter material. */\nexport interface BuilderLibraryPromotionProvenance {\n chapterId: string;\n resourceId: string;\n resourceRevision: number;\n documentRevision: number;\n promotedBy: string;\n promotedAt: number;\n}\n\n/** Server-authored creation/update history for one resource. */\nexport interface BuilderLibraryResourceProvenance {\n createdBy: string;\n createdAt: number;\n updatedBy: string;\n updatedAt: number;\n promotedFrom?: BuilderLibraryPromotionProvenance;\n}\n\n/** One bounded, revisioned private source item. */\nexport interface BuilderLibraryResource {\n id: string;\n kind: BuilderLibraryResourceKind;\n title: string;\n summary?: string;\n tags: readonly string[];\n scope: BuilderLibraryScope;\n status: BuilderLibraryResourceStatus;\n revision: number;\n bodyMarkdown?: string;\n url?: string;\n brandAsset?: BuilderLibraryBrandAssetRef;\n provenance: BuilderLibraryResourceProvenance;\n}\n\n/** Complete local or federated authoring layer. */\nexport interface BuilderLibraryDocument {\n schemaVersion: typeof BUILDER_LIBRARY_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: BuilderLibrarySource;\n target?: BuilderLibraryTarget;\n resources: readonly BuilderLibraryResource[];\n}\n\n/** Validation constraints that bind a document to its trusted source and target. */\nexport interface BuilderLibraryValidationOptions {\n sourceType?: BuilderLibrarySourceType;\n sourceAppId?: string;\n targetAppId?: string;\n /** Chapter IDs a Built Not Found document may address. An empty or omitted\n * allowlist keeps the historical global-or-private-only behavior. */\n allowedChapterIds?: readonly string[];\n}\n\n/** A validated document or actionable strict-contract errors. */\nexport type BuilderLibraryValidationResult =\n | { ok: true; value: BuilderLibraryDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Principal whose closed-scope visibility is projected. */\nexport type BuilderLibraryViewer =\n | { kind: \"built_not_found\" }\n | { kind: \"chapter\"; chapterId: string };\n\n/** Bounded agent input. It contains references, never private asset bytes or credentials. */\nexport interface BuilderLibraryManifest {\n schemaVersion: typeof BUILDER_LIBRARY_SCHEMA_VERSION;\n generatedAt: number;\n viewer: BuilderLibraryViewer;\n revisions: readonly { source: BuilderLibrarySource; revision: number }[];\n resources: readonly BuilderLibraryResource[];\n truncated: boolean;\n}\n\n/** Canonical document and digest transmitted over the signed library edge. */\nexport interface BuilderLibraryEnvelope { digest: string; document: BuilderLibraryDocument }\n/** Durable acknowledgement for an accepted or idempotently replayed revision. */\nexport interface BuilderLibraryReceipt {\n ok: true;\n target: BuilderLibraryTarget;\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\nexport { validateBuilderLibraryDocument } from \"./builder-library-validation\";\n\n/** Apply the closed visibility matrix. */\nexport function canViewBuilderLibraryResource(\n resource: BuilderLibraryResource,\n viewer: BuilderLibraryViewer,\n): boolean {\n if (viewer.kind === \"built_not_found\") return true;\n return resource.scope.kind === \"global\"\n || (resource.scope.kind === \"chapter\" && resource.scope.chapterId === viewer.chapterId);\n}\n\n/** Produce deterministic, published-only input for a site-building agent. */\nexport function buildBuilderLibraryManifest(\n documents: readonly BuilderLibraryDocument[],\n viewer: BuilderLibraryViewer,\n generatedAt = Date.now(),\n limit = 100,\n): BuilderLibraryManifest {\n const ordered = documents\n .flatMap((document) => document.resources.map((resource) => ({ document, resource })))\n .filter(({ resource }) => resource.status === \"published\" && canViewBuilderLibraryResource(resource, viewer))\n .sort((a, b) => a.resource.title.localeCompare(b.resource.title)\n || a.document.source.appId.localeCompare(b.document.source.appId)\n || a.resource.id.localeCompare(b.resource.id));\n return {\n schemaVersion: BUILDER_LIBRARY_SCHEMA_VERSION,\n generatedAt,\n viewer,\n revisions: documents.map(({ source, revision }) => ({ source, revision })),\n resources: ordered.slice(0, limit).map(({ resource }) => resource),\n truncated: ordered.length > limit,\n };\n}\n\n/** Build the exact signed layer for one peer; private and sibling material\n * never crosses to a Chapter. */\nexport function projectBuilderLibraryDelivery(\n document: BuilderLibraryDocument,\n target: BuilderLibraryTarget,\n): BuilderLibraryDocument {\n return {\n ...document,\n target,\n resources: document.source.type === \"built_not_found\"\n ? document.resources.filter((resource) => resource.scope.kind === \"global\"\n || (resource.scope.kind === \"chapter\" && resource.scope.chapterId === target.appId))\n : document.resources,\n };\n}\n\n/** Copy a Chapter item into global authority while preserving its exact origin. */\nexport function promoteBuilderLibraryResource(input: {\n resource: BuilderLibraryResource;\n chapterDocumentRevision: number;\n actor: string;\n promotedAt: number;\n globalId?: string;\n}): BuilderLibraryResource {\n if (input.resource.scope.kind !== \"chapter\") throw new TypeError(\"only a Chapter-scoped resource can be promoted\");\n const chapterId = input.resource.scope.chapterId;\n return {\n ...input.resource,\n id: input.globalId ?? `${chapterId}-${input.resource.id}`,\n scope: { kind: \"global\" },\n revision: 1,\n provenance: {\n createdBy: input.actor,\n createdAt: input.promotedAt,\n updatedBy: input.actor,\n updatedAt: input.promotedAt,\n promotedFrom: {\n chapterId,\n resourceId: input.resource.id,\n resourceRevision: input.resource.revision,\n documentRevision: input.chapterDocumentRevision,\n promotedBy: input.actor,\n promotedAt: input.promotedAt,\n },\n },\n };\n}\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"Builder Library contains an unsupported value\");\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).sort().flatMap((key) => record[key] === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(record[key])}`]).join(\",\")}}`;\n}\n\n/** Serialize Builder Library JSON with recursively sorted object keys. */\nexport function canonicalBuilderLibrary(value: unknown): string { return canonicalValue(value); }\n\n/** Compute a canonical SHA-256 digest for one signed library revision. */\nexport async function builderLibraryDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalBuilderLibrary(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one validated document with the exact digest its target acknowledges. */\nexport async function createBuilderLibraryEnvelope(document: import(\"./builder-library\").BuilderLibraryDocument) {\n return { document, digest: await builderLibraryDigest(document) };\n}\n","// The chapter email pipeline: durable delivery decisions, a non-production fail-safe,\n// and template rendering. Every property here is easy to get wrong and expensive\n// to get wrong, so the correctness-critical decisions — the dedupe check (E1),\n// the dev-redirect / log-only fail-safe (E2), and template rendering (E4) — are\n// PURE and fully tested in this module. The worker supplies the transport +\n// odla-db and performs the actual send + emailLog write around these decisions.\n//\n// Chapter's operational templates ({ subject, text, enabled? }) are\n// transactional lifecycle mail by construction — a site owner edits the copy in\n// Settings but cannot reclassify one as marketing. Consent-gated marketing blasts\n// go through @odla-ai/crm, which owns the transactional-vs-marketing template\n// class as code (E3), so relabeling copy can never bypass the consent gate.\n\n/** One owner-editable template row on the group. `enabled` absent = enabled. */\nexport interface EmailTemplateRow {\n subject: string;\n text: string;\n enabled?: boolean;\n}\n\n/** The `groups`-row fields the email pipeline reads. */\nexport interface EmailGroup {\n id: string;\n name: string;\n replyTo: string;\n /** Non-prod debug inbox: all mail redirects here outside prod (E2). */\n debugEmail?: string;\n refundPolicyText?: string;\n commitmentText?: string;\n normsText?: string;\n emailTemplates: Record<string, EmailTemplateRow>;\n}\n\n/** `{{placeholder}}` substitution; unknown placeholders render empty. */\nexport function render(template: string, vars: Record<string, string>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => vars[key] ?? \"\");\n}\n\n/** Group-level vars every template receives, under the caller's vars. */\nfunction groupVars(group: EmailGroup, vars: Record<string, string>): Record<string, string> {\n return {\n ...vars,\n refundPolicyText: group.refundPolicyText ?? \"\",\n commitmentText: group.commitmentText ?? \"\",\n normsText: group.normsText ?? \"\",\n };\n}\n\n/**\n * Re-render a template's body for history/preview (E4): the CRM comms history\n * reads back emails whose body predates `emailLog.body` by rendering the current\n * template with the recipient's vars. Same substitution + group vars as the send\n * path. `null` for an unknown template. Reflects the copy as it reads today, not\n * necessarily the exact bytes originally sent (only `emailLog.body` is byte-exact).\n */\nexport function renderTemplateBody(group: EmailGroup, template: string, vars: Record<string, string>): string | null {\n const tpl = group.emailTemplates?.[template];\n if (!tpl) return null;\n return render(tpl.text, groupVars(group, vars));\n}\n\n/**\n * E1 (confirmed delivery): given prior `emailLog` rows for a `dedupeKey`, has the\n * mail already been delivered? A prior row with **no error** means yes — the\n * caller short-circuits the resend. Pending/uncertain rows carry an error marker;\n * the orchestration layer must reconcile those rather than blindly resending.\n */\nexport function isAlreadySent(priorRows: ReadonlyArray<{ error?: unknown }>): boolean {\n return priorRows.some((row) => !row.error);\n}\n\n/** The pure delivery decision produced by {@link planDelivery}. */\nexport type DeliveryDecision =\n | { deliver: false; reason: \"template-missing\" | \"disabled\" }\n | {\n deliver: true;\n /** Which transport to use — `log-only` records the send but delivers nothing. */\n transport: \"cloudflare\" | \"log-only\";\n to: string;\n subject: string;\n text: string;\n /** True when redirected to the non-prod debug inbox. */\n redirected: boolean;\n };\n\n/**\n * The pure delivery decision (E2 fail-safe + E3 enabled). Given the env, group,\n * template, recipient, and whether a real Cloudflare transport is wired:\n * - missing template → not delivered (`template-missing`);\n * - disabled template and not forced → not delivered (`disabled`);\n * - **non-prod with a debug inbox** → REDIRECT to it, `\"[dev] \"` subject prefix,\n * a dev-redirect note in the body, so test applicants never receive real mail;\n * - **non-prod with NO debug inbox** → force `log-only` (deliver nothing) — the\n * fail-safe that protects every site's test data;\n * - prod → deliver via the real transport (`cloudflare` if wired, else `log-only`).\n */\nexport function planDelivery(input: {\n envName: string;\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n /** Whether a Cloudflare Email Service transport (binding + verified from) is wired. */\n cloudflareReady: boolean;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}): DeliveryDecision {\n const tpl = input.group.emailTemplates?.[input.template];\n if (!tpl) return { deliver: false, reason: \"template-missing\" };\n if (tpl.enabled === false && !input.force) return { deliver: false, reason: \"disabled\" };\n\n const vars = groupVars(input.group, input.vars);\n const isProd = input.envName === \"prod\";\n const redirect = !isProd && !!input.group.debugEmail;\n const transport: \"cloudflare\" | \"log-only\" =\n !isProd && !redirect ? \"log-only\" : input.cloudflareReady ? \"cloudflare\" : \"log-only\";\n const to = redirect ? (input.group.debugEmail as string) : input.to;\n const subject = (redirect ? \"[dev] \" : \"\") + render(tpl.subject, vars);\n const text = redirect\n ? `(dev redirect; original recipient: ${input.to})\\n\\n` + render(tpl.text, vars)\n : render(tpl.text, vars);\n return { deliver: true, transport, to, subject, text, redirected: redirect };\n}\n","// sendTemplated — the operational-email orchestration that wires the pure email\n// decisions (./email: isAlreadySent E1, planDelivery E2/E3) to odla-db + a\n// transport. Structural (takes a ChapterDb + a sender), so it's FakeDb-testable\n// like submitApplication/projectSharedRecord. The worker's lifecycle routes call\n// it to send the prep / payment-confirmation / admin-alert mail.\n//\n// Persist a claimed attempt BEFORE transport I/O. A non-idempotent transport\n// cannot guarantee exactly-once delivery across a lost reply. Uncertain attempts\n// remain visible and require evidence-based reconciliation, never blind resend.\nimport { isAlreadySent, planDelivery } from \"./email\";\nimport type { EmailGroup } from \"./email\";\nimport type { ChapterDb } from \"./types\";\n\n/** The canonical lifecycle email templates chapter fires, in send-order. Owner-\n * editable copy lives on the group row; this is the fixed set the admin email\n * editor + test route iterate. */\nexport const EMAIL_TEMPLATE_NAMES = [\"adminNotification\", \"paymentConfirmation\", \"prepEmail\", \"onboardingInvite\"] as const;\n\n/** One of {@link EMAIL_TEMPLATE_NAMES}. */\nexport type EmailTemplateName = (typeof EMAIL_TEMPLATE_NAMES)[number];\n\n/** The mail transport (the worker's Cloudflare SEND_EMAIL binding). */\nexport interface MailSender {\n send(payload: { from: string; to: string[]; subject: string; text?: string; replyTo?: string }): Promise<{ messageId: string }>;\n}\n\n/** Deps for {@link sendTemplated} — the db, the env name (drives the fail-safe),\n * the transport + from (absent ⇒ log-only), and injected clock/id. */\nexport interface NotifyDeps {\n db: ChapterDb;\n envName: string;\n sender?: MailSender;\n from?: string;\n /** Runtime-local non-production inbox; never changes the shared chapter setting. */\n debugEmail?: string;\n now: () => number;\n newId: () => string;\n}\n\n/** One templated send. `dedupeKey` identifies one durable delivery workflow. */\nexport interface NotifyInput {\n group: EmailGroup;\n template: string;\n to: string;\n vars: Record<string, string>;\n dedupeKey: string;\n applicationId?: string;\n /** The admin test route may send a disabled template. */\n force?: boolean;\n}\n\n/** The outcome. `sent:true` includes the already-sent short-circuit. */\nexport interface NotifyResult {\n sent: boolean;\n reason?: string;\n}\n\n/**\n * Claim before sending. Confirmed sends short-circuit; uncertain sends never\n * automatically repeat. Non-production redirect/log-only safeguards still apply.\n */\nexport async function sendTemplated(deps: NotifyDeps, input: NotifyInput): Promise<NotifyResult> {\n const { emailLog } = await deps.db.query({ emailLog: { $: { where: { dedupeKey: input.dedupeKey } } } });\n const prior = (Array.isArray(emailLog) ? emailLog : []) as Array<Record<string, unknown>>;\n if (isAlreadySent(prior)) return { sent: true, reason: \"already-sent\" };\n if (prior.length > 1 || (prior.length === 1 && prior[0]!.deliveryState !== \"retry_ready\")) {\n return { sent: false, reason: \"delivery-uncertain\" };\n }\n\n const cloudflareReady = Boolean(deps.sender && deps.from);\n // An explicitly configured but invalid override must not fall back to another\n // developer's shared inbox. Production ignores this development-only setting.\n const override = deps.debugEmail?.trim();\n const group = deps.envName !== \"prod\" && deps.debugEmail !== undefined\n ? { ...input.group, debugEmail: override && /^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$/.test(override) ? override : undefined }\n : input.group;\n const decision = planDelivery({\n envName: deps.envName,\n group,\n template: input.template,\n to: input.to,\n vars: input.vars,\n cloudflareReady,\n force: input.force,\n });\n if (!decision.deliver) return { sent: false, reason: decision.reason };\n\n const previous = prior[0];\n if (previous && (previous.groupId !== input.group.id || previous.template !== input.template || previous.to !== decision.to ||\n previous.transport !== decision.transport || previous.applicationId !== input.applicationId)) return { sent: false, reason: \"delivery-identity-conflict\" };\n const hash = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(input.dedupeKey));\n const id = previous ? String(previous.id) : `email_${Array.from(new Uint8Array(hash), b => b.toString(16).padStart(2, \"0\")).join(\"\")}`;\n const attempt = Number(previous?.deliveryAttempt ?? 0) + 1;\n if (!Number.isSafeInteger(attempt) || attempt < 1) return { sent: false, reason: \"delivery-state-invalid\" };\n const row: Record<string, unknown> = {\n id,\n groupId: input.group.id,\n to: decision.to,\n template: input.template,\n subject: previous?.subject ?? decision.subject,\n body: previous?.body ?? decision.text,\n transport: decision.transport,\n redirected: decision.redirected,\n dedupeKey: input.dedupeKey,\n sentAt: deps.now(),\n deliveryState: decision.transport === \"log-only\" ? \"sent\" : \"sending\",\n deliveryAttempt: attempt,\n error: decision.transport === \"log-only\" ? \"\" : \"delivery-pending\",\n ...(input.applicationId ? { applicationId: input.applicationId } : {}),\n };\n try {\n const claim = await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: row }], {\n mutationId: `email-claim:${id}:${attempt}`, guards: [previous ? { ns: \"emailLog\", id, exists: true,\n equals: { deliveryState: \"retry_ready\", ...(previous.deliveryAttempt !== undefined ? { deliveryAttempt: previous.deliveryAttempt } : {}) },\n ...(previous.deliveryAttempt === undefined ? { absent: [\"deliveryAttempt\"] } : {}) } : { ns: \"emailLog\", id, exists: false }],\n });\n if (claim.duplicate) return { sent: false, reason: \"delivery-uncertain\" };\n } catch (error) {\n if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error;\n return { sent: false, reason: \"delivery-uncertain\" };\n }\n if (decision.transport === \"log-only\") return { sent: true };\n let messageId: string;\n try {\n const response = await deps.sender!.send({ from: deps.from!, to: [decision.to], subject: String(row.subject),\n text: String(row.body), replyTo: input.group.replyTo });\n if (!response || typeof response.messageId !== \"string\" || !response.messageId) throw new Error(\"missing delivery receipt\");\n messageId = response.messageId;\n } catch {\n await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: { deliveryState: \"uncertain\", error: \"delivery-uncertain\" } }], {\n guards: [{ ns: \"emailLog\", id, exists: true, equals: { deliveryState: \"sending\", deliveryAttempt: attempt } }],\n });\n return { sent: false, reason: \"delivery-uncertain\" };\n }\n await deps.db.transact([{ t: \"update\", ns: \"emailLog\", id, attrs: { deliveryState: \"sent\", error: \"\", messageId, sentAt: deps.now() } }], {\n mutationId: `email-confirmed:${id}:${attempt}`, guards: [{ ns: \"emailLog\", id, exists: true,\n equals: { deliveryState: \"sending\", deliveryAttempt: attempt } }],\n });\n return { sent: true };\n}\n\n/** Project a `groups` row into the {@link EmailGroup} the email pipeline reads. */\nexport function emailGroupFrom(row: Record<string, unknown>): EmailGroup {\n const str = (v: unknown): string | undefined => (typeof v === \"string\" ? v : undefined);\n const templates = row.emailTemplates && typeof row.emailTemplates === \"object\" ? row.emailTemplates : {};\n return {\n id: String(row.id),\n name: String(row.name ?? \"\"),\n replyTo: str(row.replyTo) ?? \"\",\n debugEmail: str(row.debugEmail),\n refundPolicyText: str(row.refundPolicyText),\n commitmentText: str(row.commitmentText),\n normsText: str(row.normsText),\n emailTemplates: templates as EmailGroup[\"emailTemplates\"],\n };\n}\n","import type { ChapterDb } from \"./types\";\n\n/** Evidence from an authenticated operator resolving an uncertain provider outcome. */\nexport interface LifecycleDeliveryResolution {\n id: string; groupId: string; expectedAttempt: number; expectedState: \"sending\" | \"uncertain\";\n decision: \"confirmed_delivered\" | \"confirmed_not_delivered\"; actorId: string; reason: string; messageId?: string;\n}\n/** Resolve only the exact reviewed attempt. This never sends mail itself.\n * A confirmed non-delivery permits the original workflow to retry its frozen payload.\n * It must not be used merely because a message has not yet appeared in an inbox.\n */\nexport async function reconcileLifecycleDelivery(db: ChapterDb, input: LifecycleDeliveryResolution, now: number): Promise<void> {\n if (!input.actorId || !input.reason || input.reason.trim().length < 10 || input.reason.length > 2000 ||\n !Number.isSafeInteger(input.expectedAttempt) || input.expectedAttempt < 1 || !Number.isSafeInteger(now) ||\n ![\"sending\", \"uncertain\"].includes(input.expectedState) ||\n ![\"confirmed_delivered\", \"confirmed_not_delivered\"].includes(input.decision)) throw new TypeError(\"invalid delivery resolution\");\n const row = (await db.query({ emailLog: { $: { where: { id: input.id }, limit: 1 } } })).emailLog?.[0];\n if (!row || row.groupId !== input.groupId || row.deliveryState !== input.expectedState || row.deliveryAttempt !== input.expectedAttempt) {\n throw new Error(\"delivery resolution conflict\");\n }\n // A freshly started attempt is not evidence of failure; allow its provider call to finish first.\n if (!Number.isSafeInteger(row.sentAt) || now < Number(row.sentAt) ||\n (input.expectedState === \"sending\" && now - Number(row.sentAt) < 15 * 60000)) throw new Error(\"delivery attempt still in progress\");\n const history = Array.isArray(row.deliveryResolution) ? row.deliveryResolution : [];\n const delivered = input.decision === \"confirmed_delivered\";\n await db.transact([{ t: \"update\", ns: \"emailLog\", id: input.id, attrs: {\n deliveryState: delivered ? \"sent\" : \"retry_ready\", error: delivered ? \"\" : \"delivery-retry-approved\",\n ...(input.messageId ? { messageId: input.messageId } : {}),\n deliveryResolution: [...history, { attempt: input.expectedAttempt, decision: input.decision, actorId: input.actorId,\n reason: input.reason.trim(), resolvedAt: now, ...(input.messageId ? { messageId: input.messageId } : {}) }],\n } }], { mutationId: `email-resolve:${input.id}:${input.expectedAttempt}:${input.decision}`,\n guards: [{ ns: \"emailLog\", id: input.id, exists: true, equals: { groupId: input.groupId,\n deliveryState: input.expectedState, deliveryAttempt: input.expectedAttempt } }] });\n}\n","// Payments primitives. Generic Stripe form encoding and webhook authenticity\n// live in @odla-ai/stripe; Chapter keeps only membership-specific readiness,\n// event normalization, and write sets. This preserves Chapter's public exports\n// while making the provider plumbing reusable by every app.\nexport { stripeForm, verifyStripeSignature } from \"@odla-ai/stripe\";\nimport { membershipInvoiceEvidence, membershipInvoicePeriodEnd, type MembershipInvoiceEvidence } from \"./membership-invoice-evidence\";\n\n// ── readiness + Stripe wire helpers ──\n\n/** A group row's payment configuration, as far as readiness cares. */\nexport interface PaymentsGroup {\n stripePublishableKey?: string | null;\n stripePriceId?: string | null;\n}\n\n/** Whether a group can take payment: a publishable key + a price id (both on the\n * group row) AND a secret key (the vault). Anything missing drops the join\n * flow's payment step (paymentsReady:false) rather than half-charging. */\nexport function paymentsReady(group: PaymentsGroup, hasSecretKey: boolean): boolean {\n return Boolean(group.stripePublishableKey && group.stripePriceId && hasSecretKey);\n}\n\n/** The Stripe idempotency key for creating an application's subscription — one\n * per application, so a client retry can't orphan a second subscription. */\nexport function subscriptionIdempotencyKey(applicationId: string): string {\n return `sub:${applicationId}`;\n}\n\n/** The db mutationId for a webhook-driven application write. A separate signed\n * event receipt fences replays and event-id collisions across every write in\n * the route; this id keeps the application mutation itself idempotent. */\nexport function webhookMutationId(eventId: string): string {\n return `stripe:${eventId}`;\n}\n\n// ── webhook normalization (pure; the worker owns the db lookup + writes) ──\n\n/** A raw Stripe event, as far as normalization cares. */\nexport interface StripeEvent {\n id: string;\n type: string;\n data?: { object?: Record<string, unknown> };\n}\n\n/** A normalized, provider-agnostic webhook event. `kind` drives the db write;\n * the application is resolved from `applicationId` (metadata) or `customerId`. */\nexport type WebhookEvent = (\n | { kind: \"gift_paid\"; giftIntentId: string; providerObjectId: string }\n | { kind: \"gift_revoked\"; giftIntentId: string; reason: \"refunded\" | \"canceled\" }\n | { kind: \"seat_paid\" | \"seat_refunded\"; seatId: string; applicationId?: string; customerId?: string }\n | { kind: \"first_payment\"; applicationId?: string; customerId?: string; renewalAt?: number; invoice?: MembershipInvoiceEvidence }\n | { kind: \"renewal\"; applicationId?: string; customerId?: string; renewalAt?: number }\n | { kind: \"renewal_failed\"; applicationId?: string; customerId?: string }\n | { kind: \"subscription_changed\"; applicationId?: string; customerId?: string }\n | { kind: \"refunded\"; applicationId?: string; customerId?: string }\n | { kind: \"canceled\"; applicationId?: string; customerId?: string }\n | { kind: \"ignored\"; type: string }\n) & { appId?: string; environment?: string; dataEnvironment?: string; runtime?: string; chapterId?: string };\n\n/** Resolve the application reference on a Stripe object: `applicationId` from\n * metadata (direct, then subscription_details, then nested\n * parent.subscription_details), plus the customer id for the db fallback. */\nexport function findApplicationRef(obj: Record<string, unknown>): {\n applicationId?: string;\n customerId?: string;\n appId?: string;\n environment?: string;\n dataEnvironment?: string;\n runtime?: string;\n chapterId?: string;\n} {\n const metaOf = (v: unknown): Record<string, unknown> =>\n v && typeof v === \"object\" ? ((v as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (m: Record<string, unknown>): string | undefined =>\n typeof m.applicationId === \"string\" ? m.applicationId : undefined;\n const candidates = [\n metaOf(obj),\n metaOf(obj.subscription_details),\n metaOf((obj.parent as Record<string, unknown> | undefined)?.subscription_details),\n ];\n const applicationId = candidates.map(pick).find(Boolean);\n const appId = candidates.map((metadata) => typeof metadata.odlaAppId === \"string\" ? metadata.odlaAppId : undefined).find(Boolean);\n const environment = candidates.map((metadata) => typeof metadata.odlaEnvironment === \"string\" ? metadata.odlaEnvironment : undefined).find(Boolean);\n const dataEnvironment = candidates.map((metadata) => typeof metadata.odlaDataEnvironment === \"string\" ? metadata.odlaDataEnvironment : undefined).find(Boolean);\n const runtime = candidates.map((metadata) => typeof metadata.odlaRuntime === \"string\" ? metadata.odlaRuntime : undefined).find(Boolean);\n const chapterId = candidates.map((metadata) => typeof metadata.chapterId === \"string\" ? metadata.chapterId : undefined).find(Boolean);\n const customerId = typeof obj.customer === \"string\" ? obj.customer : undefined;\n return {\n ...(applicationId ? { applicationId } : {}),\n ...(customerId ? { customerId } : {}),\n ...(appId ? { appId } : {}),\n ...(environment ? { environment } : {}),\n ...(dataEnvironment ? { dataEnvironment } : {}),\n ...(runtime ? { runtime } : {}),\n ...(chapterId ? { chapterId } : {}),\n };\n}\n\n/** Resolve gift purchase metadata from direct or invoice subscription metadata. */\nexport function findGiftRef(obj: Record<string, unknown>): {\n giftIntentId?: string; providerObjectId: string; appId?: string;\n environment?: string; dataEnvironment?: string; runtime?: string;\n chapterId?: string;\n} {\n const metaOf = (value: unknown): Record<string, unknown> =>\n value && typeof value === \"object\" ? ((value as Record<string, unknown>).metadata as Record<string, unknown>) ?? {} : {};\n const pick = (metadata: Record<string, unknown>): string | undefined =>\n typeof metadata.giftIntentId === \"string\" ? metadata.giftIntentId : undefined;\n const parent = obj.parent as Record<string, unknown> | undefined;\n const subscription = obj.subscription_details ?? parent?.subscription_details;\n const giftIntentId = pick(metaOf(obj)) ?? pick(metaOf(subscription));\n const subscriptionId = typeof obj.subscription === \"string\"\n ? obj.subscription\n : typeof (subscription as Record<string, unknown> | undefined)?.subscription === \"string\"\n ? String((subscription as Record<string, unknown>).subscription)\n : undefined;\n const candidates = [metaOf(obj), metaOf(subscription)];\n const pickIdentity = (name: string) => candidates\n .map((metadata) => typeof metadata[name] === \"string\" ? String(metadata[name]) : undefined).find(Boolean);\n const appId = pickIdentity(\"odlaAppId\");\n const environment = pickIdentity(\"odlaEnvironment\");\n const dataEnvironment = pickIdentity(\"odlaDataEnvironment\");\n const runtime = pickIdentity(\"odlaRuntime\");\n const chapterId = pickIdentity(\"chapterId\");\n return {\n ...(giftIntentId ? { giftIntentId } : {}),\n providerObjectId: subscriptionId ?? String(obj.id ?? \"\"),\n ...(appId ? { appId } : {}),\n ...(environment ? { environment } : {}),\n ...(dataEnvironment ? { dataEnvironment } : {}),\n ...(runtime ? { runtime } : {}),\n ...(chapterId ? { chapterId } : {}),\n };\n}\n\n/** Normalize a verified Stripe event into a {@link WebhookEvent}. `invoice.paid`\n * splits into first_payment vs renewal by `billing_reason`; refunds and\n * cancellations map directly; everything else is ignored (acked, not retried). */\nexport function normalizeWebhookEvent(event: StripeEvent, options: { requireProviderPayment?: boolean } = {}): WebhookEvent {\n const obj = event.data?.object ?? {};\n // Stripe emits charge.refunded for partial refunds too. Only a complete,\n // validated refund revokes a membership or gift; partial refunds are not a\n // terminal membership event.\n if (event.type === \"charge.refunded\" && (!Number.isSafeInteger(obj.amount) || Number(obj.amount) <= 0 ||\n obj.amount_refunded !== obj.amount || obj.refunded !== true)) return { kind: \"ignored\", type: event.type };\n const gift = findGiftRef(obj);\n if (gift.giftIntentId) {\n const { giftIntentId, providerObjectId, ...identity } = gift;\n if (event.type === \"payment_intent.succeeded\" ||\n (event.type === \"invoice.paid\" && obj.billing_reason === \"subscription_create\")) {\n return { kind: \"gift_paid\", giftIntentId, providerObjectId, ...identity };\n }\n if (event.type === \"charge.refunded\") return { kind: \"gift_revoked\", giftIntentId, ...identity, reason: \"refunded\" };\n if (event.type === \"customer.subscription.deleted\") return { kind: \"gift_revoked\", giftIntentId, ...identity, reason: \"canceled\" };\n return { kind: \"ignored\", type: event.type };\n }\n const ref = findApplicationRef(obj);\n const seatId = (obj.metadata as Record<string, unknown> | undefined)?.seatId;\n if (typeof seatId === \"string\" && seatId) {\n // A seat shares the purchaser's customer/application metadata. Its refund must\n // never fall through to the primary membership's refundedPatch.\n if (!options.requireProviderPayment) return { kind: \"ignored\", type: event.type };\n if (event.type === \"payment_intent.succeeded\") return { kind: \"seat_paid\", seatId, ...ref };\n if (event.type === \"charge.refunded\") return { kind: \"seat_refunded\", seatId, ...ref };\n return { kind: \"ignored\", type: event.type };\n }\n // Network authority requires an actual provider payment, not a manually paid invoice.\n // Keep legacy adapters on their existing invoice.paid subscription until explicitly upgraded.\n if ((event.type === \"invoice.paid\" && options.requireProviderPayment) ||\n (event.type === \"invoice.payment_succeeded\" && !options.requireProviderPayment)) return { kind: \"ignored\", type: event.type };\n switch (event.type) {\n case \"invoice.payment_failed\":\n return options.requireProviderPayment && obj.billing_reason === \"subscription_cycle\" ?\n { kind: \"renewal_failed\", ...ref } : { kind: \"ignored\", type: event.type };\n case \"invoice.paid\": case \"invoice.payment_succeeded\": {\n if (obj.billing_reason !== \"subscription_create\" && obj.billing_reason !== \"subscription_cycle\") {\n return { kind: \"ignored\", type: event.type };\n }\n const renewalAt = membershipInvoicePeriodEnd(obj);\n const kind = obj.billing_reason === \"subscription_create\" ? \"first_payment\" : \"renewal\";\n return { kind, ...ref, ...(renewalAt !== undefined ? { renewalAt } : {}),\n ...(kind === \"first_payment\" ? { invoice: membershipInvoiceEvidence(obj) } : {}) };\n }\n case \"charge.refunded\":\n return { kind: \"refunded\", ...ref };\n case \"customer.subscription.updated\":\n return options.requireProviderPayment ? { kind: \"subscription_changed\", ...ref } : { kind: \"ignored\", type: event.type };\n case \"customer.subscription.deleted\":\n return options.requireProviderPayment ? { kind: \"subscription_changed\", ...ref } : { kind: \"canceled\", ...ref };\n default:\n return { kind: \"ignored\", type: event.type };\n }\n}\n\n// ── webhook write-set builders (the authoritative writers of paid/refunded) ──\n\n/** First-payment patch: advance submitted→paid_pending_vetting (never any other\n * transition) and record the renewal date. Empty when nothing changed, so the\n * caller can skip the write. */\nexport function firstPaymentPatch(currentStatus: string, renewalAt?: number): { status?: \"paid_pending_vetting\"; renewalAt?: number } {\n return {\n ...(currentStatus === \"submitted\" ? { status: \"paid_pending_vetting\" as const } : {}),\n ...(renewalAt !== undefined ? { renewalAt } : {}),\n };\n}\n\n/** Renewal-invoice patch: just the new renewal date. */\nexport function renewalPatch(renewalAt: number): { renewalAt: number } {\n return { renewalAt };\n}\n\n/** A verified full refund closes the paid lifecycle and its renewal display. */\nexport function refundedPatch(): { status: \"refunded\"; renewalAt: 0 } {\n return { status: \"refunded\", renewalAt: 0 };\n}\n\n/** Subscription-cancellation patch. */\nexport function canceledPatch(): { canceled: true; renewalAt: 0 } {\n return { canceled: true, renewalAt: 0 };\n}\n","/** Current wire version for parent-authored admission decisions. */\nexport const ADMISSION_GRANTS_SCHEMA_VERSION = 1 as const;\n/** Dedicated signed Parent → Chapter delivery endpoint. */\nexport const ADMISSION_GRANTS_PATH = \"/api/admission-grants\" as const;\n\n/** Whether an exact email can skip or must retain the Chapter interview. */\nexport type AdmissionDecision = \"waive_interview\" | \"require_interview\";\n\n/** One bounded admission decision. Email is PII and never enters public config. */\nexport interface AdmissionGrantInput {\n id: string;\n email: string;\n decision: AdmissionDecision;\n note?: string;\n expiresAt?: number;\n}\n\n/** Complete desired Parent state for one Chapter and environment. */\nexport interface AdmissionGrantDocument {\n schemaVersion: typeof ADMISSION_GRANTS_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: { appId: string; actor: string };\n target: { chapterId: string; environment: string };\n grants: readonly AdmissionGrantInput[];\n}\n\n/** Canonical desired-state document paired with its integrity digest. */\nexport interface AdmissionGrantEnvelope {\n digest: string;\n document: AdmissionGrantDocument;\n}\n\n/** Chapter acknowledgement for an accepted or idempotently replayed revision. */\nexport interface AdmissionGrantReceipt {\n ok: true;\n target: { chapterId: string; environment: string };\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable machine-readable rejection reasons returned by a Chapter receiver. */\nexport type AdmissionGrantRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n","const encoder = new TextEncoder();\n\nfunction canonicalValue(value: unknown): string {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\" || typeof value === \"string\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) return `[${value.map(canonicalValue).join(\",\")}]`;\n if (typeof value !== \"object\") throw new TypeError(\"signup control contains an unsupported value\");\n const record = value as Record<string, unknown>;\n const entries = Object.keys(record).sort().flatMap((key) => {\n const item = record[key];\n return item === undefined ? [] : [`${JSON.stringify(key)}:${canonicalValue(item)}`];\n });\n return `{${entries.join(\",\")}}`;\n}\n\n/** Serialize JSON-like signup state with recursively sorted object keys. */\nexport function canonicalSignupControl(value: unknown): string {\n return canonicalValue(value);\n}\n\n/** Compute the protocol's canonical SHA-256 digest for desired signup state. */\nexport async function signupControlDigest(document: unknown): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonicalSignupControl(document)));\n return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** Pair one desired-state document with its canonical digest for delivery. */\nexport async function createSignupControlEnvelope(document: import(\"./signup-control-contract\").SignupControlDocument) {\n return { document, digest: await signupControlDigest(document) };\n}\n","import type { ChapterDb } from \"./types\";\n\n/** Bounded, complete admission reads using the database's supported page size. */\nexport async function readAdmissionRows(db: ChapterDb, namespace: \"admissionGrants\" | \"leaderAdmissionAssignments\",\n where: Record<string, string>, maximum: number): Promise<Array<Record<string, unknown>>> {\n const rows: Array<Record<string, unknown>> = [];\n for (let offset = 0; offset <= maximum; offset += 500) {\n const result = await db.query({ [namespace]: { $: { where, order: { id: \"asc\" }, limit: 500, offset } } });\n const page = Array.isArray(result[namespace]) ? result[namespace] : [];\n rows.push(...page);\n if (rows.length > maximum) throw new Error(\"admission_assignment_limit\");\n if (page.length < 500) break;\n }\n return rows;\n}\n","import type {\n AdmissionDecision,\n AdmissionGrantDocument,\n AdmissionGrantEnvelope,\n AdmissionGrantInput,\n} from \"./admission-grants-contract\";\nimport { ADMISSION_GRANTS_SCHEMA_VERSION } from \"./admission-grants-contract\";\nimport type { ChapterDb, DbOp } from \"./types\";\nimport { signupControlDigest } from \"./signup-control-canonical\";\nimport { normalizeChapterEmail } from \"./email-identity\";\nimport { readAdmissionRows } from \"./admission-store-read\";\n\nconst ID = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;\nconst MAX_GRANTS = 2_000;\nconst MAX_NOTE = 2_000;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst isAdmissionEmail = (value: string): boolean => EMAIL_RE.test(value);\n\n/** Exact email natural key: trim and lowercase, with no provider alias rules. */\nexport function normalizeAdmissionEmail(email: string): string {\n return normalizeChapterEmail(email);\n}\n\n/** Validated normalized admission document or all contract errors. */\nexport type AdmissionGrantValidation =\n | { ok: true; value: AdmissionGrantDocument }\n | { ok: false; errors: readonly string[] };\n\n/** Validate and normalize a complete Parent admission document. */\nexport function validateAdmissionGrantDocument(input: unknown): AdmissionGrantValidation {\n const errors: string[] = [];\n const root = input && typeof input === \"object\" ? input as Record<string, unknown> : {};\n if (root.schemaVersion !== ADMISSION_GRANTS_SCHEMA_VERSION) errors.push(\"document.schemaVersion must be 1\");\n const revision = Number(root.revision);\n const generatedAt = Number(root.generatedAt);\n if (!Number.isSafeInteger(revision) || revision < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isFinite(generatedAt) || generatedAt <= 0) errors.push(\"document.generatedAt must be epoch milliseconds\");\n const source = root.source && typeof root.source === \"object\" ? root.source as Record<string, unknown> : {};\n const target = root.target && typeof root.target === \"object\" ? root.target as Record<string, unknown> : {};\n const sourceId = typeof source.appId === \"string\" ? source.appId : \"\";\n const sourceActor = typeof source.actor === \"string\" ? source.actor.trim() : \"\";\n const chapterId = typeof target.chapterId === \"string\" ? target.chapterId : \"\";\n const environment = typeof target.environment === \"string\" ? target.environment : \"\";\n if (!ID.test(sourceId)) errors.push(\"document.source.appId must be an identifier\");\n if (!sourceActor || sourceActor.length > 256) errors.push(\"document.source.actor must be 1-256 characters\");\n if (!ID.test(chapterId)) errors.push(\"document.target.chapterId must be an identifier\");\n if (!ID.test(environment)) errors.push(\"document.target.environment must be an identifier\");\n if (!Array.isArray(root.grants)) errors.push(\"document.grants must be an array\");\n const rawGrants = Array.isArray(root.grants) ? root.grants : [];\n if (rawGrants.length > MAX_GRANTS) errors.push(`document.grants supports at most ${MAX_GRANTS} entries`);\n const grants: AdmissionGrantInput[] = [];\n const seenIds = new Set<string>();\n const seenEmails = new Set<string>();\n for (const [index, raw] of rawGrants.slice(0, MAX_GRANTS).entries()) {\n const grant = raw && typeof raw === \"object\" ? raw as Record<string, unknown> : {};\n const id = typeof grant.id === \"string\" ? grant.id : \"\";\n const email = typeof grant.email === \"string\" ? grant.email.trim() : \"\";\n const normalized = normalizeAdmissionEmail(email);\n const decision = grant.decision;\n const note = typeof grant.note === \"string\" ? grant.note.trim() : undefined;\n const expiresAt = grant.expiresAt === undefined ? undefined : Number(grant.expiresAt);\n if (!ID.test(id)) errors.push(`document.grants[${index}].id must be an identifier`);\n if (seenIds.has(id)) errors.push(`document.grants repeats id \"${id}\"`);\n if (!isAdmissionEmail(normalized)) errors.push(`document.grants[${index}].email must be valid`);\n if (seenEmails.has(normalized)) errors.push(`document.grants repeats email \"${normalized}\"`);\n if (decision !== \"waive_interview\" && decision !== \"require_interview\") {\n errors.push(`document.grants[${index}].decision is invalid`);\n }\n if (note && note.length > MAX_NOTE) errors.push(`document.grants[${index}].note is too long`);\n if (expiresAt !== undefined && (!Number.isFinite(expiresAt) || expiresAt <= 0)) {\n errors.push(`document.grants[${index}].expiresAt must be epoch milliseconds`);\n }\n seenIds.add(id);\n seenEmails.add(normalized);\n grants.push({\n id,\n email,\n decision: decision as AdmissionDecision,\n ...(note ? { note } : {}),\n ...(expiresAt !== undefined ? { expiresAt } : {}),\n });\n }\n if (errors.length) return { ok: false, errors };\n return {\n ok: true,\n value: {\n schemaVersion: ADMISSION_GRANTS_SCHEMA_VERSION,\n revision,\n generatedAt,\n source: { appId: sourceId, actor: sourceActor },\n target: { chapterId, environment },\n grants,\n },\n };\n}\n\n/** Pair a validated desired-state document with its canonical digest. */\nexport async function createAdmissionGrantEnvelope(document: AdmissionGrantDocument): Promise<AdmissionGrantEnvelope> {\n const checked = validateAdmissionGrantDocument(document);\n if (!checked.ok) throw new TypeError(`Invalid admission grant document: ${checked.errors.join(\"; \")}`);\n return { document: checked.value, digest: await signupControlDigest(checked.value) };\n}\n\n/** Materialized local or Parent admission decision stored by a Chapter. */\nexport interface AdmissionGrantRow {\n id: string;\n sourceGrantId: string;\n sourceScope: \"local\" | \"parent\";\n sourceId: string;\n targetId: string;\n email: string;\n emailNormalized: string;\n decision: AdmissionDecision;\n active: boolean;\n createdAt: number;\n note?: string;\n expiresAt?: number;\n revokedAt?: number;\n consumedAt?: number;\n consumedApplicationId?: string;\n}\n\nconst rows = (value: unknown): Array<Record<string, unknown>> => Array.isArray(value) ? value : [];\n\nfunction asGrant(row: Record<string, unknown>): AdmissionGrantRow | null {\n if (typeof row.id !== \"string\" || typeof row.emailNormalized !== \"string\") return null;\n if (row.sourceScope !== \"local\" && row.sourceScope !== \"parent\") return null;\n if (row.decision !== \"waive_interview\" && row.decision !== \"require_interview\") return null;\n return row as unknown as AdmissionGrantRow;\n}\n\n/** Resolve the effective current decision. Local rows always outrank Parent rows. */\nexport async function findAdmissionGrant(\n db: ChapterDb,\n targetId: string,\n email: string,\n now: number,\n): Promise<AdmissionGrantRow | null> {\n const emailNormalized = normalizeAdmissionEmail(email);\n if (!isAdmissionEmail(emailNormalized)) return null;\n const result = await db.query({ admissionGrants: { $: { where: { emailNormalized }, limit: 100 } } });\n const active = rows(result.admissionGrants)\n .map(asGrant)\n .filter((grant): grant is AdmissionGrantRow => Boolean(\n grant && grant.targetId === targetId && grant.active === true && !grant.revokedAt &&\n (!grant.expiresAt || grant.expiresAt > now) && !grant.consumedApplicationId,\n ))\n .sort((a, b) => {\n const scope = Number(b.sourceScope === \"local\") - Number(a.sourceScope === \"local\");\n return scope || b.createdAt - a.createdAt;\n });\n return active[0] ?? null;\n}\n\n/** Stored receipt for one signed Parent admission revision. */\nexport interface AdmissionGrantRevisionRow {\n id: string;\n sourceId: string;\n targetId: string;\n environment: string;\n revision: number;\n digest: string;\n active: boolean;\n receivedAt: number;\n}\n\nasync function hasAdmissionRevision(\n db: ChapterDb,\n sourceId: string,\n targetId: string,\n environment: string,\n): Promise<boolean> {\n const where = { sourceId, targetId, environment };\n if (db.aggregate) {\n return Number((await db.aggregate(\"admissionGrantRevisions\", { count: true }, { where })).count ?? 0) > 0;\n }\n const found = await db.query({ admissionGrantRevisions: {} });\n return rows(found.admissionGrantRevisions).some((row) =>\n row.sourceId === sourceId && row.targetId === targetId && row.environment === environment);\n}\n\n/** Read the newest received revision without issuing an ordered query over empty history. */\nexport async function loadLatestAdmissionRevision(\n db: ChapterDb,\n sourceId: string,\n targetId: string,\n environment: string,\n): Promise<AdmissionGrantRevisionRow | null> {\n if (!await hasAdmissionRevision(db, sourceId, targetId, environment)) return null;\n const result = await db.query({ admissionGrantRevisions: { $: {\n where: { sourceId, targetId, environment }, order: { revision: \"desc\" }, limit: 1,\n } } });\n const row = rows(result.admissionGrantRevisions)\n .sort((a, b) => Number(b.revision ?? 0) - Number(a.revision ?? 0))[0];\n return row ? row as unknown as AdmissionGrantRevisionRow : null;\n}\n\n/** Replace only Parent-authored rows; local Chapter decisions remain untouched. */\nexport async function materializeAdmissionGrants(\n db: ChapterDb,\n envelope: AdmissionGrantEnvelope,\n previous: AdmissionGrantRevisionRow | null,\n receivedAt: number,\n): Promise<void> {\n const { document, digest } = envelope;\n const current = await readAdmissionRows(db, \"admissionGrants\", {\n sourceScope: \"parent\", sourceId: document.source.appId, targetId: document.target.chapterId,\n }, 10_000);\n const incomingIds = new Set(document.grants.map((grant) => `admission:parent:${document.source.appId}:${grant.id}`));\n const ops: DbOp[] = [];\n for (const row of current) {\n const id = String(row.id ?? \"\");\n if (id && !incomingIds.has(id)) ops.push({ t: \"update\", ns: \"admissionGrants\", id, attrs: {\n active: false, revokedAt: receivedAt, revokedBy: document.source.actor,\n updatedAt: receivedAt, updatedBy: document.source.actor,\n } });\n }\n for (const grant of document.grants) {\n const id = `admission:parent:${document.source.appId}:${grant.id}`;\n const existing = current.find((row) => row.id === id);\n ops.push({ t: \"update\", ns: \"admissionGrants\", id, attrs: {\n id,\n sourceGrantId: grant.id,\n sourceScope: \"parent\",\n sourceId: document.source.appId,\n targetId: document.target.chapterId,\n email: grant.email,\n emailNormalized: normalizeAdmissionEmail(grant.email),\n decision: grant.decision,\n ...(grant.note ? { note: grant.note } : {}),\n ...(grant.expiresAt ? { expiresAt: grant.expiresAt } : {}),\n active: true,\n sourceRevision: document.revision,\n createdAt: Number(existing?.createdAt ?? receivedAt),\n createdBy: String(existing?.createdBy ?? document.source.actor),\n updatedAt: receivedAt,\n updatedBy: document.source.actor,\n } });\n const retract = [\n ...(!grant.note && existing?.note !== undefined ? [\"note\"] : []),\n ...(grant.expiresAt === undefined && existing?.expiresAt !== undefined ? [\"expiresAt\"] : []),\n ];\n if (retract.length) ops.push({ t: \"retract\", ns: \"admissionGrants\", id, attrs: retract });\n }\n if (previous?.active) ops.push({ t: \"update\", ns: \"admissionGrantRevisions\", id: previous.id, attrs: { active: false } });\n const revisionId = `admission-revision:${document.source.appId}:${document.target.environment}:${document.revision}`;\n ops.push({ t: \"update\", ns: \"admissionGrantRevisions\", id: revisionId, attrs: {\n id: revisionId,\n sourceId: document.source.appId,\n targetId: document.target.chapterId,\n environment: document.target.environment,\n revision: document.revision,\n digest,\n active: true,\n receivedAt,\n } });\n await db.transact(ops, { mutationId: `admission-grants:${document.source.appId}:${document.target.environment}:${document.revision}:${digest}` });\n}\n","import { canBook, canApprove } from \"./pipeline\";\nimport type { ResolvedPipeline } from \"./types\";\n\n/** Canonical next action or browser-visible step after application submission. */\nexport type JoinContinuation = \"payment\" | \"paymentPending\" | \"booking\" | \"approve\" | \"accepted\";\n\n/** One server-side decision for submit, resume, and payment completion. */\nexport function resolveJoinContinuation(input: {\n status: string;\n initialStatus: string;\n pipeline: ResolvedPipeline;\n payable: boolean;\n subscriptionStarted: boolean;\n interviewWaived: boolean;\n}): JoinContinuation | null {\n if (input.status === \"approved\") return \"accepted\";\n if (input.status !== input.initialStatus && !canBook(input.status, input.pipeline) && !canApprove(input.status, input.pipeline)) return null;\n if (input.interviewWaived) {\n if (input.status === input.initialStatus) {\n if (!input.payable) return \"approve\";\n return input.subscriptionStarted ? \"paymentPending\" : \"payment\";\n }\n return canApprove(input.status, input.pipeline) ? \"approve\" : null;\n }\n if (!input.payable) return canBook(input.status, input.pipeline) ? \"booking\" : null;\n if (input.status === input.initialStatus) {\n return input.subscriptionStarted ? \"paymentPending\" : \"payment\";\n }\n if (canBook(input.status, input.pipeline)) return \"booking\";\n return null;\n}\n","/** Current nested gift-catalog version inside signup-control. */\nexport const GIFT_OFFER_CATALOG_VERSION = 1 as const;\n/** Maximum signed gift SKUs accepted in one catalog revision. */\nexport const MAX_GIFT_OFFERS = 20;\n\n/** Membership tier or standalone entitlement fulfilled by redemption. */\nexport type GiftOfferTarget =\n | { type: \"tier\"; tierId: string }\n | { type: \"entitlement\"; entitlementKey: string };\n\n/** Server-authored gift SKU; provider identifiers never reach public config. */\nexport interface GiftOffer {\n id: string;\n target: GiftOfferTarget;\n billingMode: \"one_time\" | \"subscription\";\n stripePriceId: string;\n priceCents: number;\n currency: string;\n redemptionLifetimeHours: number;\n activeFrom?: number;\n activeUntil?: number;\n title: string;\n description: string;\n ctaLabel: string;\n}\n\n/** Versioned bounded collection delegated through signed signup control. */\nexport interface GiftOfferCatalog {\n schemaVersion: typeof GIFT_OFFER_CATALOG_VERSION;\n offers: readonly GiftOffer[];\n}\n\n/** Provider-free gift offer shape rendered by Chapter and exact CMS previews. */\nexport type PublicGiftOffer = Omit<GiftOffer, \"stripePriceId\" | \"target\">;\n\n/** Result of validating and normalizing an untrusted gift catalog. */\nexport type GiftOfferValidation =\n | { ok: true; value: GiftOfferCatalog }\n | { ok: false; errors: readonly string[] };\n\nconst ID = /^[a-z][a-z0-9-]{1,79}$/;\nconst PRICE = /^price_[A-Za-z0-9]{12,}$/;\nconst CURRENCY = /^[a-z]{3}$/;\nconst record = (value: unknown): Record<string, unknown> | null =>\n value && typeof value === \"object\" && !Array.isArray(value) ? value as Record<string, unknown> : null;\nconst text = (value: unknown, path: string, errors: string[], max: number): string => {\n if (typeof value !== \"string\" || !value.trim()) { errors.push(`${path} is required`); return \"\"; }\n if (value.trim().length > max) errors.push(`${path} must be at most ${max} characters`);\n return value.trim();\n};\n\n/** Validate and normalize gift offers against the same document's tier ids. */\nexport function validateGiftOfferCatalog(input: unknown, tierIds: ReadonlySet<string>): GiftOfferValidation {\n const errors: string[] = [];\n const root = record(input);\n if (!root) return { ok: false, errors: [\"document.giftOffers must be an object\"] };\n for (const key of Object.keys(root)) if (key !== \"schemaVersion\" && key !== \"offers\") errors.push(`document.giftOffers.${key} is not supported`);\n if (root.schemaVersion !== GIFT_OFFER_CATALOG_VERSION) errors.push(\"document.giftOffers.schemaVersion must be 1\");\n if (!Array.isArray(root.offers)) errors.push(\"document.giftOffers.offers must be an array\");\n const rawOffers = Array.isArray(root.offers) ? root.offers : [];\n if (rawOffers.length > MAX_GIFT_OFFERS) errors.push(`document.giftOffers.offers supports at most ${MAX_GIFT_OFFERS} entries`);\n const ids = new Set<string>();\n const offers: GiftOffer[] = [];\n for (const [index, raw] of rawOffers.slice(0, MAX_GIFT_OFFERS).entries()) {\n const path = `document.giftOffers.offers[${index}]`;\n const item = record(raw);\n if (!item) { errors.push(`${path} must be an object`); continue; }\n const allowed = new Set([\"id\", \"target\", \"billingMode\", \"stripePriceId\", \"priceCents\", \"currency\", \"redemptionLifetimeHours\", \"activeFrom\", \"activeUntil\", \"title\", \"description\", \"ctaLabel\"]);\n for (const key of Object.keys(item)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n const id = text(item.id, `${path}.id`, errors, 80);\n if (id && !ID.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (ids.has(id)) errors.push(`${path}.id duplicates \"${id}\"`);\n ids.add(id);\n const targetRaw = record(item.target);\n let target: GiftOfferTarget = { type: \"entitlement\", entitlementKey: \"invalid\" };\n if (targetRaw?.type === \"tier\") {\n const tierId = text(targetRaw.tierId, `${path}.target.tierId`, errors, 80);\n if (!tierIds.has(tierId)) errors.push(`${path}.target.tierId must reference a declared tier`);\n target = { type: \"tier\", tierId };\n } else if (targetRaw?.type === \"entitlement\") {\n const entitlementKey = text(targetRaw.entitlementKey, `${path}.target.entitlementKey`, errors, 80);\n if (entitlementKey && !ID.test(entitlementKey)) errors.push(`${path}.target.entitlementKey must be a lowercase kebab-case id`);\n target = { type: \"entitlement\", entitlementKey };\n } else errors.push(`${path}.target.type must be tier or entitlement`);\n if (item.billingMode !== \"one_time\" && item.billingMode !== \"subscription\") errors.push(`${path}.billingMode must be one_time or subscription`);\n const stripePriceId = text(item.stripePriceId, `${path}.stripePriceId`, errors, 128);\n if (stripePriceId && !PRICE.test(stripePriceId)) errors.push(`${path}.stripePriceId must be a real Stripe Price id`);\n if (!Number.isSafeInteger(item.priceCents) || Number(item.priceCents) < 1 || Number(item.priceCents) > 100_000_000) errors.push(`${path}.priceCents must be an integer from 1 to 100,000,000`);\n const currency = typeof item.currency === \"string\" ? item.currency.trim().toLowerCase() : \"\";\n if (!CURRENCY.test(currency)) errors.push(`${path}.currency must be a lowercase ISO currency code`);\n const lifetime = Number(item.redemptionLifetimeHours);\n if (!Number.isSafeInteger(lifetime) || lifetime < 1 || lifetime > 8_760) errors.push(`${path}.redemptionLifetimeHours must be an integer from 1 to 8760`);\n const activeFrom = item.activeFrom === undefined ? undefined : Number(item.activeFrom);\n const activeUntil = item.activeUntil === undefined ? undefined : Number(item.activeUntil);\n if (activeFrom !== undefined && (!Number.isSafeInteger(activeFrom) || activeFrom < 1)) errors.push(`${path}.activeFrom must be epoch milliseconds`);\n if (activeUntil !== undefined && (!Number.isSafeInteger(activeUntil) || activeUntil < 1)) errors.push(`${path}.activeUntil must be epoch milliseconds`);\n if (activeFrom !== undefined && activeUntil !== undefined && activeUntil <= activeFrom) errors.push(`${path}.activeUntil must follow activeFrom`);\n offers.push({\n id, target, billingMode: item.billingMode as GiftOffer[\"billingMode\"], stripePriceId,\n priceCents: Number(item.priceCents), currency, redemptionLifetimeHours: lifetime,\n ...(activeFrom !== undefined ? { activeFrom } : {}), ...(activeUntil !== undefined ? { activeUntil } : {}),\n title: text(item.title, `${path}.title`, errors, 160), description: text(item.description, `${path}.description`, errors, 2_000),\n ctaLabel: text(item.ctaLabel, `${path}.ctaLabel`, errors, 120),\n });\n }\n return errors.length ? { ok: false, errors } : { ok: true, value: { schemaVersion: 1, offers } };\n}\n\n/** Whether an offer is active at an exact server time. */\nexport const giftOfferActive = (offer: GiftOffer, now: number): boolean =>\n (!offer.activeFrom || offer.activeFrom <= now) && (!offer.activeUntil || offer.activeUntil > now);\n\n/** Public provider-free active catalog projection. */\nexport function publicGiftOffers(catalog: GiftOfferCatalog | undefined, now: number): PublicGiftOffer[] {\n return (catalog?.offers ?? []).filter((offer) => giftOfferActive(offer, now)).map(({ stripePriceId: _stripe, target: _target, ...offer }) => offer);\n}\n\n/** Resolve one currently active server-authoritative offer. */\nexport function findGiftOffer(catalog: GiftOfferCatalog | undefined, offerId: string, now: number): GiftOffer | null {\n return catalog?.offers.find((offer) => offer.id === offerId && giftOfferActive(offer, now)) ?? null;\n}\n","// Leader → follower projection of a deliberately allowlisted CRM field set.\n//\n// Invariants (package-enforced so no site re-derives them):\n// - One-way: the chapter never writes back to the hub through this path.\n// - Idempotent: every received record carries the leader's stable site +\n// record identity. A structured crm_record_origin row maps that identity to\n// the local CRM record, so a re-share updates instead of duplicating even\n// after an email/domain changes. Legacy tags remain as a migration bridge.\n// - Natural-key convergence: a person unifies by primary email and a business\n// by its configured domain slot (then name), so an arriving applicant and a\n// prior leader share compose into one person.\n// - Operational state stays local. Pipeline/account/billing state is not copied\n// into another site's authority; the push transfers the shared record fields.\n//\n// Reuses @odla-ai/crm's record ops (full validation via crm.prepare), driven by\n// the resolved chapter CRM engine + the structural ChapterDb.\nimport {\n createRecord,\n getRecordByOrigin,\n updateRecord,\n upsertRecordOrigin,\n} from \"@odla-ai/crm\";\nimport type { Crm, CrmRecord } from \"@odla-ai/crm\";\nimport { ensureProjectedPerson } from \"./crm-person-projection\";\nexport { projectApplicant, type Applicant } from \"./applicant-projection\";\nimport type { ChapterDb, ResolvedNetworkTarget } from \"./types\";\nimport {\n DEFAULT_SHARE_FIELDS,\n type NormalizedSharedRecord,\n type ProjectionDeps,\n type SharedBusiness,\n type SharedPerson,\n type SharedRecord,\n} from \"./network-contract\";\nexport { DEFAULT_SHARE_FIELDS } from \"./network-contract\";\nexport type {\n NetworkRollup, NetworkRollupTarget,\n NetworkSnapshot,\n ProjectionDeps,\n SharedBusiness,\n SharedPerson,\n SharedRecord,\n SharedRecordV1,\n SharedRecordV2,\n} from \"./network-contract\";\n\n/** Map a shared prospect to a crm `person` input (only the fields the default\n * person type accepts). Name falls back to first+last, then the email. */\nexport function sharedPersonInput(person: SharedPerson): Record<string, unknown> {\n const email = person.email.toLowerCase();\n const fullName = [person.firstName, person.lastName].filter(Boolean).join(\" \").trim();\n const input: Record<string, unknown> = { name: person.name ?? fullName ?? email, email };\n if (input.name === \"\") input.name = email;\n if (person.firstName) input.firstName = person.firstName;\n if (person.lastName) input.lastName = person.lastName;\n if (person.phone) input.phone = person.phone;\n if (person.linkedin) input.linkedin = person.linkedin;\n return input;\n}\n\nfunction shortHash(value: string): string {\n let a = 0x811c9dc5;\n let b = 0x9e3779b9;\n for (let i = 0; i < value.length; i += 1) {\n const n = value.charCodeAt(i);\n a = Math.imul(a ^ n, 0x01000193);\n b = Math.imul(b ^ n, 0x85ebca6b);\n }\n return `${(a >>> 0).toString(36)}${(b >>> 0).toString(36)}`;\n}\n\n/** Backward-compatible display tag retained while structured origin rows are\n * the durable leader-id → local-record mapping. */\nexport function networkSourceTag(type: string, hubRecordId: string, sourceId?: string): string {\n const typeKey = type.toLowerCase();\n const readable = /^[a-z0-9_-]+$/.test(hubRecordId);\n const prefix = sourceId ? `network:${sourceId.toLowerCase()}:${typeKey}` : `network:${typeKey}`;\n const raw = `${prefix}:${hubRecordId}`;\n if (readable && raw.length <= 64) return raw;\n return `network:${typeKey.slice(0, 16)}:${shortHash(`${sourceId ?? \"\"}\\u0000${type}\\u0000${hubRecordId}`)}`;\n}\n\n/** Normalize the backwards-compatible person/business shapes into the versioned\n * generic record envelope the receiver writes. */\nexport function normalizeSharedRecord(\n record: SharedPerson | SharedBusiness | SharedRecord,\n fallbackSourceId = \"legacy-source\",\n): NormalizedSharedRecord {\n if (\"input\" in record && record.version === 2) {\n return {\n version: 2,\n sourceId: record.source.siteId,\n sourceRecordId: record.source.recordId,\n type: record.type,\n input: record.input,\n };\n }\n if (\"input\" in record) {\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: record.type,\n input: record.input,\n };\n }\n if (\"type\" in record && record.type === \"company\") {\n const input: Record<string, unknown> = { name: record.name };\n for (const key of [\"domain\", \"industry\", \"location\", \"linkedin\", \"notes\"] as const) {\n if (record[key]) input[key] = record[key];\n }\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: \"company\",\n input,\n };\n }\n return {\n version: 1,\n sourceId: fallbackSourceId,\n sourceRecordId: record.hubRecordId,\n type: \"person\",\n input: sharedPersonInput(record),\n };\n}\n\n/** Build the allowlisted payload sent from one leader CRM record to a target.\n * A target with an explicit `fields` map only accepts the types it lists. */\nexport function sharedRecordFromCrm(\n crm: Crm,\n record: CrmRecord,\n target: ResolvedNetworkTarget,\n sourceId?: string,\n): SharedRecord {\n if (target.fields && !target.fields[record.type]) {\n throw new Error(`${target.name} does not accept \"${record.type}\" records`);\n }\n const def = crm.type(record.type);\n const fields = target.fields?.[record.type] ?? DEFAULT_SHARE_FIELDS[record.type];\n if (!fields) {\n throw new Error(`${target.name} requires an explicit field allowlist for \"${record.type}\" records`);\n }\n const nameField = def.nameField ?? \"name\";\n const input: Record<string, unknown> = {};\n for (const field of new Set([nameField, ...fields])) {\n const value = record.fields?.[field];\n if (value !== undefined) input[field] = value;\n }\n if (input[nameField] === undefined) input[nameField] = record.name;\n return sourceId\n ? { version: 2, source: { siteId: sourceId, recordId: record.id }, type: record.type, input }\n : { version: 1, type: record.type, hubRecordId: record.id, input };\n}\n\n\nasync function findSharedRecord(\n deps: ProjectionDeps,\n record: NormalizedSharedRecord,\n tag: string,\n): Promise<Record<string, unknown> | undefined> {\n const structured = await getRecordByOrigin(\n { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId },\n record.sourceId,\n record.sourceRecordId,\n );\n if (structured) return structured as unknown as Record<string, unknown>;\n const mapped = await deps.db.query({ crm_tag: { $: { where: { tag }, limit: 1 } } });\n const mappedId = mapped.crm_tag?.[0]?.recordId;\n if (typeof mappedId === \"string\") {\n const found = await deps.db.query({ crm_record: { $: { where: { id: mappedId }, limit: 1 } } });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const def = deps.crm.type(record.type);\n const emailField = def.emailField;\n if (emailField && typeof record.input[emailField] === \"string\") {\n const primaryEmail = record.input[emailField].toLowerCase();\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, primaryEmail }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const domain = record.input.domain;\n const domainSlot = def.fields.domain?.slot;\n if (typeof domain === \"string\" && domainSlot) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, [domainSlot]: domain }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n const nameField = def.nameField ?? \"name\";\n const name = record.input[nameField];\n if (record.type === \"company\" && typeof name === \"string\" && name.trim()) {\n const found = await deps.db.query({\n crm_record: { $: { where: { type: record.type, name: name.trim() }, limit: 1 } },\n });\n if (found.crm_record?.[0]) return found.crm_record[0];\n }\n return undefined;\n}\n\n/**\n * Upsert a leader-shared CRM record into this follower. Accepts the original\n * person wire shape plus the versioned generic shape. Re-shares resolve through\n * a durable provenance tag; people/businesses also converge by natural key.\n */\nexport async function projectSharedRecord(\n deps: ProjectionDeps,\n shared: SharedPerson | SharedBusiness | SharedRecord,\n options: { sourceId?: string; sourceUrl?: string } = {},\n): Promise<{ recordId: string }> {\n const record = normalizeSharedRecord(shared, options.sourceId);\n if (!record.type.trim() || !record.sourceId.trim() || !record.sourceRecordId.trim()) {\n throw new Error(\"type, source site id, and source record id must be non-empty\");\n }\n if (options.sourceId && options.sourceId !== record.sourceId) {\n throw new Error(\"signed sender does not match payload source\");\n }\n const tag = networkSourceTag(record.type, record.sourceRecordId, record.version === 2 ? record.sourceId : undefined);\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const existing = await findSharedRecord(deps, record, tag);\n let recordId: string;\n if (existing && typeof existing.id === \"string\") {\n // Do not use one permanent mutation id for updates: a later leader edit is a\n // new desired state and must not be mistaken for a retry of an older push.\n await updateRecord(crmDeps, { id: existing.id, input: record.input });\n recordId = existing.id;\n } else if (record.type === \"person\" && typeof record.input.email === \"string\") {\n const projected = await ensureProjectedPerson(deps, record.input);\n recordId = String(projected.record.id);\n if (!projected.created) await updateRecord(crmDeps, { id: recordId, input: record.input });\n } else {\n // A deterministic id makes concurrent first deliveries converge even when\n // both requests observe no provenance row before either transaction lands.\n recordId = `network_${shortHash(`${record.sourceId}\\u0000${record.type}\\u0000${record.sourceRecordId}`)}`;\n await createRecord({ ...crmDeps, newId: () => recordId }, {\n type: record.type,\n input: record.input,\n mutationId: `share-create:${tag}`,\n });\n }\n await deps.db.transact(\n [{ t: \"update\", ns: \"crm_tag\", id: tag, attrs: { key: `${recordId}:${tag}`, recordId, tag, createdAt: deps.now() } }],\n { mutationId: `share-map:${tag}:${recordId}` },\n );\n await upsertRecordOrigin(crmDeps, {\n recordId,\n sourceId: record.sourceId,\n sourceRecordId: record.sourceRecordId,\n ...(options.sourceUrl ? { sourceUrl: options.sourceUrl } : {}),\n payloadVersion: record.version,\n });\n return { recordId };\n}\n","import { createRecord, type CrmTransactGuard, type ConsentState } from \"@odla-ai/crm\";\nimport type { ProjectionDeps } from \"./network-contract\";\n\n/** All local account/application creators converge on the same person key.\n * Existing records keep their IDs. Ambiguous or archived matches require an\n * explicit repair, never an arbitrary first-row merge or resurrection. */\nexport async function ensureProjectedPerson(deps: ProjectionDeps, input: Record<string, unknown>,\n options: { stage?: string | null; guards?: CrmTransactGuard[]; emailConsent?: { state: ConsentState; source: string } } = {},\n): Promise<{ record: Record<string, unknown>; created: boolean }> {\n const email = String(input.email ?? \"\").trim().toLowerCase();\n if (!email) throw new Error(\"crm_projection_email_required\");\n const find = async () => {\n const records = (await deps.db.query({ crm_record: { $: {\n where: { type: \"person\", primaryEmail: email }, limit: 2,\n } } })).crm_record ?? [];\n if (records.length > 1) throw new Error(\"crm_projection_identity_ambiguous\");\n if (records[0]?.archived === true) throw new Error(\"crm_projection_identity_archived\");\n return records[0];\n };\n const existing = await find();\n if (existing) return { record: existing, created: false };\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(`chapter:person:v1:${email}`)));\n const id = `person-${Array.from(digest, byte => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n try {\n const created = await createRecord({ ...deps, db: deps.db as never }, {\n id, type: \"person\", input: { ...input, email }, ...options,\n });\n return { record: created.record as unknown as Record<string, unknown>, created: true };\n } catch (error) {\n if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error;\n // A concurrent account/application creator won. Re-read its committed row;\n // never replay a stale create over profile, stage, or consent edits.\n const winner = await find();\n if (!winner) throw error;\n return { record: winner, created: false };\n }\n}\n","import { updateRecord, setStage } from \"@odla-ai/crm\";\nimport { ensureProjectedPerson } from \"./crm-person-projection\";\nimport type { ProjectionDeps } from \"./network-contract\";\nimport { sharedPersonInput } from \"./network\";\nimport { applicationCrmFields } from \"./crm-application-fields\";\n\n// Resolve an existing crm_record person by lowercased primaryEmail and update it,\n// else create one under the given mutationId for the arriving applicant.\nasync function upsertPerson(\n deps: ProjectionDeps,\n opts: { email: string; input: Record<string, unknown>; mutationId: string },\n): Promise<{ recordId: string }> {\n const email = opts.email.toLowerCase();\n const crmDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const { record, created } = await ensureProjectedPerson(deps, { ...opts.input, email });\n if (!created) await updateRecord(crmDeps, { id: String(record.id), input: opts.input, mutationId: opts.mutationId });\n const initial = deps.crm.initialStage(\"person\");\n if (!created && record.stage == null && initial) {\n // An account can apply later. Enter its actual application pipeline once,\n // without resetting a concurrently approved/refunded member to submitted.\n await setStage(crmDeps, { id: String(record.id), to: initial, authorId: \"system\",\n expectedStage: null, mutationId: `${opts.mutationId}:enter-pipeline` });\n }\n return { recordId: String(record.id) };\n}\n\n/** An arriving applicant, as far as the CRM projection cares. `extra` carries the\n * site-configured `crmFields` (values from the application), merged on top of the\n * built-in identity/contact set. */\nexport interface Applicant {\n applicationId: string;\n tierId?: string;\n email: string;\n firstName?: string;\n lastName?: string;\n phone?: string;\n linkedin?: string;\n extra?: Record<string, unknown>;\n}\n\n/**\n * Project an arriving applicant into this chapter's `crm_record`, so a new\n * application shows up in the CRM immediately, unified by email with any prior\n * record. Idempotent per application (`apply:${applicationId}`). Best-effort at\n * the call site — a projection failure never fails the application.\n *\n * `extra` fields (a site's `crmFields`) are merged on top of the base person. If\n * an extra field is not on the crm person type, crm validation throws — so the\n * projection retries with the base person alone, ensuring a misconfigured\n * enrichment never silently drops the applicant from the CRM entirely.\n */\nexport async function projectApplicant(deps: ProjectionDeps, applicant: Applicant): Promise<{ recordId: string }> {\n const base = sharedPersonInput({\n email: applicant.email,\n firstName: applicant.firstName,\n lastName: applicant.lastName,\n phone: applicant.phone,\n linkedin: applicant.linkedin,\n hubRecordId: applicant.applicationId,\n });\n Object.assign(base, applicationCrmFields(deps.crm, applicant));\n const mutationId = `apply:${applicant.applicationId}`;\n const extra = applicant.extra ?? {};\n if (Object.keys(extra).length === 0) return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n try {\n return await upsertPerson(deps, { email: applicant.email, input: {\n ...base, ...extra, ...applicationCrmFields(deps.crm, applicant),\n }, mutationId });\n } catch {\n return upsertPerson(deps, { email: applicant.email, input: base, mutationId });\n }\n}\n","import type { Crm } from \"@odla-ai/crm\";\n\n/** Project lifecycle links only into fields the host CRM explicitly declared. */\nexport function applicationCrmFields(crm: Crm, app: { applicationId?: unknown; tierId?: unknown }): Record<string, unknown> {\n const fields = crm.type(\"person\").fields;\n const result: Record<string, unknown> = {};\n if (fields.applicationId && typeof app.applicationId === \"string\") result.applicationId = app.applicationId;\n if (typeof app.tierId === \"string\") {\n if (fields.tierId) result.tierId = app.tierId;\n else if (fields.tier) result.tier = app.tierId;\n }\n return result;\n}\n","// The OPERATIONAL slice of the one-way person projection: applications\n// -> crm_record, mirroring pipeline stage, a billing snapshot, and the Clerk\n// identity link. `network.ts` projects identity/contact on submit; this adds the\n// operational state the admin surface and the hub read from, so the pipeline\n// stays authoritative in `applications.status` while the CRM carries one\n// relationship surface over the person. Fired AFTER the authoritative write and\n// wrapped in `.catch` at every call site: a CRM hiccup never 5xxs a lifecycle op.\n//\n// Account-only people use crm-account-projection, never this billing/stage path.\n// Generalized from the reference site: the field set is the site's\n// configured `crmFields`, not a hardcoded list.\nimport { updateRecord, setStage, linkIdentity } from \"@odla-ai/crm\";\nimport { ensureProjectedPerson } from \"./crm-person-projection\";\nimport { syncAccountToCrm } from \"./crm-account-projection\";\nimport { sharedPersonInput } from \"./network\";\nimport type { ProjectionDeps } from \"./network\";\nimport type { Chapter, ChapterDb } from \"./types\";\nimport { applicationCrmFields } from \"./crm-application-fields\";\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : v == null ? \"\" : String(v));\n\n/** Build the projection deps from a worker request's db + context.\n *\n * Shared so every route that writes `applications.status` mirrors it the same\n * way. Status is written from four places (admin approve, admin PATCH, the\n * Stripe webhook, and booking) and the admin dashboard reads its pipeline from\n * `crm_record.stage`, so a route that skips the mirror silently reports the\n * wrong funnel. */\nexport const crmDeps = (\n db: ChapterDb,\n ctx: { chapter: Chapter },\n): ProjectionDeps & { chapter: Chapter } => ({\n crm: ctx.chapter.crm,\n db,\n now: () => Date.now(),\n newId: () => crypto.randomUUID(),\n chapter: ctx.chapter,\n});\n\n/** The crm `person` input for one application row: the built-in identity/contact\n * fields plus each configured `crmFields` value present on the row. */\nexport function personInputFromApp(chapter: Chapter, app: Record<string, unknown>): Record<string, unknown> {\n const input = sharedPersonInput({\n email: str(app.email),\n firstName: str(app.firstName) || undefined,\n lastName: str(app.lastName) || undefined,\n phone: str(app.phone) || undefined,\n linkedin: str(app.linkedin) || undefined,\n hubRecordId: str(app.id),\n });\n for (const f of chapter.application.crmFields) {\n if (app[f] !== undefined) input[f] = app[f];\n }\n Object.assign(input, applicationCrmFields(chapter.crm, { applicationId: app.id, tierId: app.tierId }));\n return input;\n}\n\n// Promoted billing-facet columns derived from the application's Stripe fields +\n// status. Written directly (not through createRecord/updateRecord, which never\n// touch promoted columns), so they never clobber the person input.\nfunction billingColumns(app: Record<string, unknown>): Record<string, unknown> {\n const status = str(app.status);\n const paid = Boolean(app.stripeSubscriptionId) && status !== \"refunded\";\n const billingStatus = status === \"refunded\" ? \"refunded\" : app.canceled === true ? \"canceled\" : paid ? \"active\" : \"none\";\n const cols: Record<string, unknown> = { billingStatus };\n if (app.stripeCustomerId) cols.stripeCustomerId = str(app.stripeCustomerId);\n if (app.stripeSubscriptionId) cols.subscriptionId = str(app.stripeSubscriptionId);\n const renewal = typeof app.renewalAt === \"number\" ? app.renewalAt\n : typeof app.renewalAt === \"string\" ? Date.parse(app.renewalAt) : NaN;\n if (billingStatus !== \"canceled\" && billingStatus !== \"refunded\" && Number.isFinite(renewal) && renewal > 0) cols.renewalAt = renewal;\n return cols;\n}\n\n/** Upsert the person record for one application and mirror its stage, billing\n * snapshot, and Clerk identity. Account-only identities must use\n * syncAccountToCrm. Throws on failure (the backfill route\n * counts; the operational call sites wrap in `.catch`). */\nexport async function syncApplicationToCrm(\n deps: ProjectionDeps & { chapter: Chapter },\n opts: { app: Record<string, unknown>; stage?: string },\n): Promise<string | null> {\n if (!opts.app.id) throw new Error(\"crm_application_id_required\");\n const emailKey = str(opts.app.email).toLowerCase();\n if (!emailKey) return null;\n // The narrower shape the crm record helpers take (no chapter).\n const recordDeps = { crm: deps.crm, db: deps.db as never, now: deps.now, newId: deps.newId };\n const input = personInputFromApp(deps.chapter, opts.app);\n\n const stage = opts.stage || undefined;\n const { record: existing, created } = await ensureProjectedPerson(deps, input, { stage });\n const recordId = String(existing.id);\n if (!created) await updateRecord(recordDeps, { id: recordId, input });\n\n // Stage mirror: move only on an actual change, under a stable mutationId so a\n // replay never piles up duplicate stage_change activities. Best-effort — a\n // stage not on the crm person type must not fail the whole sync.\n if (!created && stage && existing.stage !== stage) {\n await setStage(recordDeps, { id: recordId, to: stage, authorId: \"system\", mutationId: `crm:stage:${recordId}:${existing.updatedAt}:${stage}` });\n }\n\n const billing = billingColumns(opts.app);\n await deps.db.transact([\n { t: \"update\", ns: \"crm_record\", id: recordId, attrs: billing },\n // Optional typed dates are removed with a retract, never an invalid null.\n ...(!(\"renewalAt\" in billing) ? [{ t: \"retract\" as const, ns: \"crm_record\", id: recordId, attrs: [\"renewalAt\"] }] : []),\n ]);\n\n // Identity link: stamps clerkUserId when a $users row matches the email; a\n // no-op until the person has an account. Best-effort — a just-created record\n // can briefly lag the read, and the link retries on the next sync.\n await linkIdentity(recordDeps, { recordId, email: emailKey, mutationId: `crm:link:${recordId}:${emailKey}` }).catch(() => undefined);\n\n return recordId;\n}\n\n/** Backfill / repair: project every application (newest per person) and every\n * `$users` row into the CRM without giving accounts an application or stage.\n * Pages are bounded; callers receive errors rather than a false success. */\nexport async function backfillCrm(deps: ProjectionDeps & { chapter: Chapter }): Promise<{ synced: number; errors: Array<{ email: string; error: string }> }> {\n const data = await deps.db.query({\n applications: { $: { order: { createdAt: \"desc\" }, limit: 1000 } },\n });\n const seen = new Set<string>();\n let synced = 0;\n const errors: Array<{ email: string; error: string }> = [];\n\n const run = async (app: Record<string, unknown>, stage?: string): Promise<void> => {\n const key = str(app.email).toLowerCase();\n if (!key || seen.has(key)) return; // newest-first: one record per person\n seen.add(key);\n try {\n await syncApplicationToCrm(deps, { app, stage });\n synced += 1;\n } catch (err) {\n errors.push({ email: key, error: err instanceof Error ? err.message : String(err) });\n }\n };\n\n for (const a of (data.applications ?? []) as Array<Record<string, unknown>>) await run(a, str(a.status));\n for (let offset = 0; ; offset += 200) {\n const users = (await deps.db.query({ $users: { $: { order: { id: \"asc\" }, limit: 200, offset } } })).$users ?? [];\n for (const u of users) {\n try { if (await syncAccountToCrm(deps, String(u.id))) synced += 1; }\n catch (err) { errors.push({ email: str(u.email), error: err instanceof Error ? err.message : String(err) }); }\n }\n if (users.length < 200) break;\n }\n return { synced, errors };\n}\n","import type { CrmTransactGuard } from \"@odla-ai/crm\";\nimport type { ProjectionDeps } from \"./network-contract\";\nimport { ensureProjectedPerson } from \"./crm-person-projection\";\n\n/** Project a server-owned account identity, not a membership/application.\n * Exact subject wins over email; existing profile, consent, stage and billing\n * are never overwritten. No role is copied and no membership is manufactured.\n * Conflicts fail visibly to the repair caller and are retried after resolution. */\nexport async function syncAccountToCrm(deps: ProjectionDeps, userId: string): Promise<string | null> {\n const user = (await deps.db.query({ $users: { $: { where: { id: userId }, limit: 1 } } })).$users?.[0];\n if (!user || user.deleted === true || typeof user.email !== \"string\" || !user.email.trim()) return null;\n const linked = (await deps.db.query({ crm_record: { $: { where: { type: \"person\", clerkUserId: userId }, limit: 2 } } })).crm_record ?? [];\n if (linked.length > 1) throw new Error(\"crm_projection_identity_ambiguous\");\n if (linked.length === 1) return String(linked[0]!.id); // Includes archived profiles: never resurrect.\n const email = user.email.trim().toLowerCase();\n const peers = (await deps.db.query({ $users: { $: { where: { email }, limit: 2 } } })).$users ?? [];\n if (peers.length !== 1 || peers[0]?.id !== userId) throw new Error(\"crm_projection_identity_ambiguous\");\n const userGuard: CrmTransactGuard = { ns: \"$users\", id: userId, exists: true,\n equals: { email: user.email, ...(user.deleted !== undefined ? { deleted: user.deleted } : {}) },\n ...(user.deleted === undefined ? { absent: [\"deleted\"] } : {}),\n };\n const { record } = await ensureProjectedPerson(deps, {\n name: typeof user.name === \"string\" && user.name.trim() ? user.name : email, email,\n }, { stage: null, guards: [userGuard], emailConsent: { state: \"unsubscribed\", source: \"account-no-marketing-consent\" } });\n if (record.clerkUserId === userId) return String(record.id);\n if (record.clerkUserId != null) throw new Error(\"crm_projection_identity_conflict\");\n try { await deps.db.transact([{ t: \"update\", ns: \"crm_record\", id: String(record.id), attrs: { clerkUserId: userId } }], {\n guards: [userGuard, { ns: \"crm_record\", id: String(record.id), exists: true,\n equals: { type: \"person\", primaryEmail: email,\n ...(record.archived !== undefined ? { archived: record.archived } : {}),\n ...(record.clerkUserId === null ? { clerkUserId: null } : {}),\n }, absent: [...(record.clerkUserId === undefined ? [\"clerkUserId\"] : []), ...(record.archived === undefined ? [\"archived\"] : [])],\n }],\n }); } catch (error) {\n if ((error as { code?: string }).code !== \"transact_guard_failed\") throw error;\n const current = (await deps.db.query({ crm_record: { $: { where: { id: record.id }, limit: 1 } } })).crm_record?.[0];\n if (current?.clerkUserId !== userId) throw error;\n }\n return String(record.id);\n}\n","// Pure aggregation helpers for the admin dashboard: a weekly time-series bucketer\n// and the annualized-run-rate math for a Stripe subscription. Kept out of the\n// route so both dashboard and billing share one definition and it is unit-tested\n// without a network call.\n\n/** Bucket `{ t, v }` points into the last `weeks` weekly buckets ending at `now`\n * (epoch ms), summing `v` per bucket. Returns oldest→newest `{ weekStart, value\n * }`, so a caller renders a sparkline directly. Points outside the window are\n * ignored. */\nexport function bucketSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n weeks = 12,\n): Array<{ weekStart: number; value: number }> {\n const WEEK = 7 * 86_400_000;\n const end = now;\n const start = end - weeks * WEEK;\n const buckets = Array.from({ length: weeks }, (_, i) => ({ weekStart: start + i * WEEK, value: 0 }));\n for (const p of points) {\n if (!Number.isFinite(p.t) || p.t < start || p.t > end) continue;\n const idx = Math.min(weeks - 1, Math.floor((p.t - start) / WEEK));\n const bucket = buckets[idx];\n if (bucket) bucket.value += Number.isFinite(p.v) ? p.v : 0;\n }\n return buckets;\n}\n\n/** Labels and current/previous values for one dashboard comparison window. */\nexport interface DashboardMetricSeries {\n labels: string[];\n current: number[];\n previous: number[];\n}\n\n/** Week-over-week and month-over-month series consumed by MetricWidget. */\nexport interface DashboardMetricData {\n wow: DashboardMetricSeries;\n mom: DashboardMetricSeries;\n}\n\nfunction periodSeries(\n points: Array<{ t: number; v: number }>,\n now: number,\n count: number,\n periodMs: number,\n): DashboardMetricSeries {\n const start = now - count * periodMs;\n const previousStart = start - count * periodMs;\n const current = Array.from({ length: count }, () => 0);\n const previous = Array.from({ length: count }, () => 0);\n for (const point of points) {\n if (!Number.isFinite(point.t) || !Number.isFinite(point.v)) continue;\n if (point.t >= start && point.t <= now) {\n const index = Math.min(count - 1, Math.floor((point.t - start) / periodMs));\n current[index] = (current[index] ?? 0) + point.v;\n } else if (point.t >= previousStart && point.t < start) {\n const index = Math.min(count - 1, Math.floor((point.t - previousStart) / periodMs));\n previous[index] = (previous[index] ?? 0) + point.v;\n }\n }\n const labels = current.map((_, index) =>\n new Date(start + index * periodMs).toISOString().slice(5, 10));\n return { labels, current, previous };\n}\n\n/** MetricWidget-ready daily and weekly comparison windows. */\nexport function dashboardMetricData(\n points: Array<{ t: number; v: number }>,\n now: number,\n): DashboardMetricData {\n const DAY = 86_400_000;\n return {\n wow: periodSeries(points, now, 7, DAY),\n mom: periodSeries(points, now, 4, 7 * DAY),\n };\n}\n\n/** Annualized cents for a Stripe subscription: sum each item's\n * `unit_amount * quantity`, ×12 for monthly intervals. A yearly interval is\n * taken as-is. Returns 0 for a shape with no priced items. */\nexport function subAnnualCents(sub: Record<string, unknown>): number {\n const items = ((sub.items as { data?: Array<Record<string, unknown>> } | undefined)?.data ?? []);\n let cents = 0;\n for (const it of items) {\n const price = (it.price ?? {}) as { unit_amount?: number; recurring?: { interval?: string } };\n const per = (price.unit_amount ?? 0) * ((it.quantity as number) ?? 1);\n cents += price.recurring?.interval === \"month\" ? per * 12 : per;\n }\n return cents;\n}\n","// The Stripe payments provider — the only I/O half of payments. Talks to the\n// Stripe REST API over @odla-ai/stripe's fetch transport, and maps 1:1 onto the\n// membership-specific event normalization in ./payments. The worker\n// resolves secrets from the vault per request and constructs this; the routes own\n// every db write so idempotency stays at the db layer.\nimport { stripeRequest, verifyStripeSignature, type StripeRequestResult } from \"@odla-ai/stripe\";\nimport { normalizeWebhookEvent } from \"./payments\";\nimport { stripePartitionMetadata } from \"./stripe-runtime\";\nimport { refundSubscriptionPayment, type SubscriptionRefundInput } from \"./payments-refund\";\nimport { tagSubscriptionPayment } from \"./subscription-payment-identity\";\nimport type { StripeEvent, WebhookEvent } from \"./payments\";\nimport { verifySubscriptionPrice, verifySubscriptionResult, subscriptionContractMismatch, type SubscriptionPriceContract } from \"./subscription-provider-contract\";\nimport { subscriptionBillingParams, prepareSubscriptionBillingTerms } from \"./subscription-billing-terms\";\n\n/** Inputs to create an application's base-SKU subscription with separately issued billing terms. */\nexport interface CreateSubscriptionInput extends SubscriptionPriceContract {\n appId: string;\n chapterId: string;\n environment: string;\n runtime?: string;\n applicationId: string;\n groupId: string;\n email: string;\n name: string;\n priceId: string;\n existingCustomerId?: string;\n /** Retrieve the exact persisted subscription on replay; never create another. */\n existingSubscriptionId?: string;\n}\n\n/** The client secret to confirm card entry, plus the ids to persist. */\nexport interface CreateSubscriptionResult {\n customerId: string;\n subscriptionId: string;\n clientSecret: string;\n}\n\n/** The outcome of a full refund. */\nexport interface RefundResult {\n refundedCents: number | null;\n subscriptionCanceled: boolean;\n}\n\n/** The capabilities the payment routes depend on — Stripe is one impl. */\nexport interface PaymentsProvider {\n createSubscription(input: CreateSubscriptionInput): Promise<CreateSubscriptionResult>;\n ingestWebhook(\n rawBody: string,\n sigHeader: string,\n ): Promise<{ ok: true; eventId: string; event: WebhookEvent } | { ok: false; reason: \"bad_signature\" }>;\n refund(input: SubscriptionRefundInput): Promise<RefundResult>;\n}\n\n/** The result of a Stripe Backend API call: ok + status + parsed JSON body. */\nexport type StripeResult = StripeRequestResult<Record<string, unknown>>;\n\n/** Call the Stripe Backend API (form-encoded, Bearer sk_). Exposed so the admin\n * billing/dashboard reads and the refund route share one Stripe client instead\n * of each re-deriving the auth + encoding. */\nexport async function stripeCall(\n sk: string,\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n params?: Record<string, unknown>,\n idempotencyKey?: string,\n): Promise<StripeResult> {\n return stripeRequest(\n { secretKey: sk },\n method,\n path,\n params,\n idempotencyKey ? { idempotencyKey } : {},\n );\n}\n\nfunction fail(op: string, r: StripeResult): never {\n const err = new Error(`stripe ${op} failed: ${r.status}`) as Error & { code: string };\n err.code = \"stripe_error\";\n throw err;\n}\n\nfunction clientSecretOf(sub: Record<string, unknown>): string | undefined {\n const inv = sub.latest_invoice as Record<string, unknown> | undefined;\n const confirmation = inv?.confirmation_secret as Record<string, unknown> | undefined;\n const intent = inv?.payment_intent as Record<string, unknown> | undefined;\n const secret = confirmation?.client_secret ?? intent?.client_secret;\n return typeof secret === \"string\" ? secret : undefined;\n}\n\nfunction requireSecret(secretKey: string | undefined): string {\n if (!secretKey) {\n const err = new Error(\"stripe secret key missing\") as Error & { code: string };\n err.code = \"not_configured\";\n throw err;\n }\n return secretKey;\n}\n\n/** Build the Stripe provider. `secretKey` powers charging/refunds; `webhookSecret`\n * powers webhook ingest. Each is resolved from the vault per request, so the\n * webhook route can construct an ingest-only provider without the secret key. */\nexport function createStripeProvider(config: { secretKey?: string; webhookSecret?: string; requireProviderPayment?: boolean }): PaymentsProvider {\n const { secretKey, webhookSecret } = config;\n return {\n async createSubscription(input) {\n const sk = requireSecret(secretKey);\n const meta = {\n applicationId: input.applicationId,\n groupId: input.groupId,\n email: input.email,\n ...stripePartitionMetadata(input),\n ...(input.billingTerms ? { offeringVersionId: input.billingTerms.offeringVersionId,\n ...(input.billingTerms.discount ? { discountPolicyVersionId: input.billingTerms.discount.policyVersionId } : {}) } : {}),\n };\n let customerId = input.existingCustomerId;\n if ((customerId && !/^cus_[A-Za-z0-9]+$/.test(customerId)) ||\n (input.existingSubscriptionId && (!customerId || !/^sub_[A-Za-z0-9]+$/.test(input.existingSubscriptionId)))) subscriptionContractMismatch();\n const productId = await verifySubscriptionPrice(sk, input, Boolean(input.existingSubscriptionId));\n if (input.billingTerms?.discount && !productId) subscriptionContractMismatch();\n await prepareSubscriptionBillingTerms(sk, { ...input, discountProductId: productId }, Boolean(input.existingSubscriptionId));\n const billingParams = subscriptionBillingParams(input, productId);\n if (!customerId) {\n const cust = await stripeCall(\n sk,\n \"POST\",\n \"/v1/customers\",\n { email: input.email, name: input.name, metadata: meta },\n `cus:${input.applicationId}`,\n );\n if (!cust.ok) fail(\"customer create\", cust);\n if (typeof cust.body.id !== \"string\" || !/^cus_[A-Za-z0-9]+$/.test(cust.body.id)) subscriptionContractMismatch();\n customerId = cust.body.id;\n }\n let sub = input.existingSubscriptionId ? await stripeCall(sk, \"GET\",\n `/v1/subscriptions/${encodeURIComponent(input.existingSubscriptionId)}`, {\n \"expand[0]\": \"latest_invoice.confirmation_secret\", \"expand[1]\": \"latest_invoice.payment_intent\",\n ...(input.billingTerms?.discount ? { \"expand[2]\": \"discounts\" } : {}),\n }) : await stripeCall(\n sk,\n \"POST\",\n \"/v1/subscriptions\",\n {\n customer: customerId,\n \"items[0][price]\": input.priceId,\n payment_behavior: \"default_incomplete\",\n \"payment_settings[save_default_payment_method]\": \"on_subscription\",\n \"payment_settings[payment_method_types][0]\": \"card\",\n \"expand[0]\": \"latest_invoice.confirmation_secret\",\n \"expand[1]\": \"latest_invoice.payment_intent\",\n metadata: meta,\n ...billingParams,\n },\n // Hardening: one subscription per application, so a client\n // retry between create and the db write can't orphan a second one.\n `sub:${input.applicationId}`,\n );\n if (!sub.ok) fail(\"subscription create\", sub);\n // A once-only benefit can already be consumed by the initial invoice.\n // Read its expanded evidence without changing the idempotent POST's\n // parameters: recovery must reuse subscriptions created before this fix.\n if (input.billingTerms?.discount?.duration === \"once\" && Array.isArray(sub.body.discounts) && sub.body.discounts.length === 0) {\n const subscriptionId = sub.body.id;\n if (typeof subscriptionId !== \"string\" || !/^sub_[A-Za-z0-9]+$/.test(subscriptionId)) subscriptionContractMismatch();\n const expanded = await stripeCall(sk, \"GET\", `/v1/subscriptions/${encodeURIComponent(subscriptionId)}`, {\n \"expand[0]\": \"latest_invoice.confirmation_secret\", \"expand[1]\": \"latest_invoice.payment_intent\",\n \"expand[2]\": \"discounts\", \"expand[3]\": \"latest_invoice.discounts\",\n });\n if (!expanded.ok) fail(\"subscription invoice evidence\", expanded);\n if (expanded.body.id !== subscriptionId) subscriptionContractMismatch();\n sub = expanded;\n }\n verifySubscriptionResult(sub.body, input, customerId!, meta);\n const invoice = sub.body.latest_invoice as Record<string, unknown> | undefined;\n const clientSecret = clientSecretOf(sub.body);\n if (!clientSecret) fail(\"subscription confirmation-secret missing\", sub);\n await tagSubscriptionPayment(sk, invoice!, customerId!, meta, clientSecret, input.applicationId);\n return { customerId, subscriptionId: String(sub.body.id), clientSecret };\n },\n\n async ingestWebhook(rawBody, sigHeader) {\n if (!webhookSecret || !(await verifyStripeSignature(rawBody, sigHeader, webhookSecret))) {\n return { ok: false, reason: \"bad_signature\" };\n }\n const event = JSON.parse(rawBody) as StripeEvent;\n return { ok: true, eventId: event.id, event: normalizeWebhookEvent(event, { requireProviderPayment: config.requireProviderPayment }) };\n },\n\n async refund(input) {\n return refundSubscriptionPayment(requireSecret(secretKey), input);\n },\n };\n}\n","import { normalizeChapterEmail } from \"./email-identity\";\n\n/** Minimal backend-only identity proof used by signup; never returned publicly. */\nexport interface SignupAccount {\n id: string;\n private_metadata?: { applicationId?: unknown };\n}\n\n/** Look up one exact normalized identifier, failing closed on provider errors. */\nexport async function findSignupAccount(secret: string, email: string, fetchImpl: typeof fetch = fetch): Promise<SignupAccount | null> {\n const response = await fetchImpl(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(normalizeChapterEmail(email))}&limit=2`, {\n headers: { authorization: `Bearer ${secret}` }, redirect: \"manual\", signal: AbortSignal.timeout(5000),\n });\n if (!response.ok) throw new Error(\"signup account lookup unavailable\");\n const users: unknown = await response.json();\n if (!Array.isArray(users) || users.length > 1 ||\n (users.length === 1 && (typeof users[0]?.id !== \"string\" || !users[0].id))) {\n throw new Error(\"signup account lookup unavailable\");\n }\n return users[0] ?? null;\n}\n\n/** Only the original server-authored application may recover a partial create. */\nexport function belongsToSignup(account: SignupAccount, applicationId: unknown): boolean {\n return typeof applicationId === \"string\" && applicationId.length > 0 && account.private_metadata?.applicationId === applicationId;\n}\n","import { belongsToSignup, findSignupAccount } from \"./clerk-signup\";\n// Apply-time account provisioning. When an application arrives, the worker mints\n// a Clerk invitation so the applicant gets a path into their member area — the\n// generalized server-side account step. Chapter calls the Clerk\n// Backend API directly over fetch (the effective vault name\n// `clerk_secret_key`, resolved by odla-db from reserved `$clerk_secret`), mirroring\n// @odla-ai/auth-clerk's createInvitation but self-contained, so it never pulls the\n// auth-clerk UI package into the worker bundle. A configured account model is a\n// required application-side effect; its caller surfaces failure and retries it.\n\n/** The outcome of provisioning. An existing identifier is a conflict unless\n * the account proves it belongs to the original application being retried. */\nexport interface ClerkResult {\n ok: boolean;\n status: number;\n /** Stable Clerk user id returned by a successful fresh account create. */\n userId?: string;\n existed?: boolean;\n /** Legacy result field; signup never refreshes an existing account. */\n refreshed?: boolean;\n}\n\nasync function rejectedCreate(res: Response): Promise<ClerkResult> {\n const body = typeof res.json === \"function\" ? await res.json().catch(() => null) as\n { errors?: Array<{ code?: string }> } | null : null;\n const existed = Array.isArray(body?.errors) && body.errors.some(error => error?.code === \"form_identifier_exists\" || error?.code === \"duplicate_record\");\n return { ok: false, status: res.status, ...(existed ? { existed: true } : {}) };\n}\n\n/** Inputs for a Clerk invitation. */\nexport interface ClerkInviteInput {\n email: string;\n /** Where the accept-invitation link lands (usually the member area). */\n redirectUrl?: string;\n /** Written to the invitation's `public_metadata`. Clerk application\n * invitations cannot carry private metadata, so never put applicant profile\n * fields here. Chapter completes that backend-only write after acceptance. */\n publicMetadata?: Record<string, unknown>;\n}\n\n/** Build the Clerk Backend API invitation request (path + JSON body). Pure, so\n * the wire shape is testable without a network call. */\nexport function clerkInviteRequest(input: ClerkInviteInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/invitations\",\n body: {\n email_address: input.email,\n notify: true,\n ...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),\n ...(input.publicMetadata ? { public_metadata: input.publicMetadata } : {}),\n },\n };\n}\n\n/** POST a new invitation. Existing identifiers and all validation failures are\n * rejected; invitations never authorize changes to an existing account. */\nexport async function createClerkInvitation(\n secretKey: string,\n input: ClerkInviteInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkInviteRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return res.ok ? { ok: true, status: res.status } : rejectedCreate(res);\n}\n\n/** Inputs for a server-side Clerk user create. */\nexport interface ClerkUserInput {\n email: string;\n firstName?: string;\n lastName?: string;\n /** Backend-authored, browser-readable claims such as `role`. */\n publicMetadata?: Record<string, unknown>;\n /** Backend-only account signals and profile data. */\n privateMetadata?: Record<string, unknown>;\n /** @deprecated Ignored. Use an explicitly authorized metadata update for repairs;\n * signup must never modify an account found by email. */\n repairMetadata?: ClerkMetadataInput;\n}\n\n/** Build the Clerk Backend API user-create request. The account is created\n * passwordless (the member signs in via the site's Clerk flow), so join step 3\n * can say the account is ready — the \"create\" alternative to an invitation. */\nexport function clerkUserRequest(input: ClerkUserInput): { path: string; body: Record<string, unknown> } {\n return {\n path: \"/v1/users\",\n body: {\n email_address: [input.email],\n skip_password_requirement: true,\n ...(input.firstName ? { first_name: input.firstName } : {}),\n ...(input.lastName ? { last_name: input.lastName } : {}),\n ...(input.publicMetadata !== undefined ? { public_metadata: input.publicMetadata } : {}),\n ...(input.privateMetadata !== undefined ? { private_metadata: input.privateMetadata } : {}),\n },\n };\n}\n\n/** One merge-PATCH to the metadata fields Clerk exposes on its Backend API. */\nexport interface ClerkMetadataInput {\n publicMetadata?: Record<string, unknown>;\n privateMetadata?: Record<string, unknown>;\n}\n\n/** Merge metadata into an existing Clerk user. Nested `null` values remove old\n * keys, which Chapter uses to migrate its former public profile into private\n * metadata without disturbing the public `role` claim. */\nexport async function updateClerkUserMetadata(\n secretKey: string,\n userId: string,\n input: ClerkMetadataInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<boolean> {\n const res = await fetchImpl(`https://api.clerk.com/v1/users/${encodeURIComponent(userId)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify({\n ...(input.publicMetadata !== undefined ? { public_metadata: input.publicMetadata } : {}),\n ...(input.privateMetadata !== undefined ? { private_metadata: input.privateMetadata } : {}),\n }),\n });\n return res.ok;\n}\n\n/** Look a Clerk account up by email and merge its metadata.\n *\n * Returns `false` when no matching user can be resolved or Clerk rejects the\n * lookup or update. This is an explicit administrative repair primitive;\n * never call it from public signup or use email knowledge as authorization.\n */\nexport async function updateClerkUserMetadataByEmail(\n secretKey: string,\n email: string,\n input: ClerkMetadataInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<boolean> {\n const id = await existingClerkUserId(secretKey, email, fetchImpl);\n return id ? updateClerkUserMetadata(secretKey, id, input, fetchImpl) : false;\n}\n\nasync function existingClerkUserId(secretKey: string, email: string, fetchImpl: typeof fetch): Promise<string | null> {\n const auth = { authorization: `Bearer ${secretKey}` };\n const found = await fetchImpl(`https://api.clerk.com/v1/users?email_address=${encodeURIComponent(email)}&limit=2`, { headers: auth });\n if (!found.ok) return null;\n const users = (await found.json().catch(() => null)) as Array<{ id?: unknown }> | null;\n return Array.isArray(users) && users.length === 1 && typeof users[0]?.id === \"string\" ? users[0].id : null;\n}\n\n/** Create a new passwordless account. A provider collision never patches the\n * existing account. A retry may return its id only when backend-private metadata\n * already names the same original application, preserving all current claims. */\nexport async function createClerkUser(\n secretKey: string,\n input: ClerkUserInput,\n fetchImpl: typeof fetch = fetch,\n): Promise<ClerkResult> {\n const { path, body } = clerkUserRequest(input);\n const res = await fetchImpl(`https://api.clerk.com${path}`, {\n method: \"POST\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n if (res.ok) {\n const body = (typeof res.json === \"function\"\n ? await res.json().catch(() => null)\n : null) as { id?: unknown } | null;\n return {\n ok: true,\n status: res.status,\n ...(typeof body?.id === \"string\" && body.id ? { userId: body.id } : {}),\n };\n }\n const failure = await rejectedCreate(res);\n if (!failure.existed) return failure;\n const account = await findSignupAccount(secretKey, input.email, fetchImpl).catch(() => null);\n return account && belongsToSignup(account, input.privateMetadata?.applicationId)\n ? { ok: true, status: res.status, existed: true, userId: account.id }\n : failure;\n}\n","// The odla->Clerk write half: server-side Clerk role read/list/write, the gap\n// beside clerk.ts's create/invite/heal. Private-mode roles live in private_metadata;\n// legacy claim callers explicitly retain the public source during adoption. An\n// absent role means the lowest rung (\"provisional\") — chapter never writes it at\n// create. Account profile signals live in backend-only `private_metadata`; the\n// role write is a MERGE-PATCH of only `{ role }`, so it cannot clobber them.\n// Chapter calls the Clerk Backend API over fetch with the vault\n// `clerk_secret_key`.\n\nimport type { ResolvedAuth } from \"./types\";\n\nconst CLERK_API = \"https://api.clerk.com\";\nconst DEFAULT_ROLE = \"provisional\";\nconst PAGE = 100;\n\n/** Backend metadata field selected for all role reads and writes. */\nexport type ClerkRoleMetadata = \"public\" | \"private\";\n/** Resolve one source for authorization, roster, guards and lifecycle writers. */\nexport function clerkRoleMetadata(auth: ResolvedAuth): ClerkRoleMetadata {\n return auth.source === \"clerk\" ? \"private\" : \"public\";\n}\n\n/** A Clerk user as chapter's role layer sees it. `role` defaults to the lowest\n * rung when the selected metadata source carries none. Raw public/private metadata is\n * returned only from this backend helper; `profile` and `applicationId` are the\n * normalized Chapter-owned private signals. */\nexport interface ClerkUserRecord {\n id: string;\n email?: string;\n role: string;\n publicMetadata: Record<string, unknown>;\n privateMetadata: Record<string, unknown>;\n profile: Record<string, unknown>;\n applicationId?: string;\n}\n\n// The Clerk Backend API user object — only the fields chapter reads.\ninterface ClerkApiUser {\n id?: unknown;\n email_addresses?: Array<{ email_address?: unknown }>;\n public_metadata?: Record<string, unknown>;\n private_metadata?: Record<string, unknown>;\n}\n\nfunction toRecord(u: ClerkApiUser, source: ClerkRoleMetadata): ClerkUserRecord | null {\n if (typeof u.id !== \"string\") return null;\n const pm = (u.public_metadata ?? {}) as Record<string, unknown>;\n const privateMetadata = (u.private_metadata ?? {}) as Record<string, unknown>;\n const rawProfile = privateMetadata.profile;\n const profile = rawProfile && typeof rawProfile === \"object\" && !Array.isArray(rawProfile)\n ? rawProfile as Record<string, unknown>\n : {};\n const applicationId = typeof privateMetadata.applicationId === \"string\"\n ? privateMetadata.applicationId\n : undefined;\n const metadata = source === \"private\" ? privateMetadata : pm;\n const role = typeof metadata.role === \"string\" && metadata.role ? metadata.role : DEFAULT_ROLE;\n const email = u.email_addresses?.[0]?.email_address;\n return {\n id: u.id,\n email: typeof email === \"string\" ? email : undefined,\n role,\n publicMetadata: pm,\n privateMetadata,\n profile,\n ...(applicationId ? { applicationId } : {}),\n };\n}\n\nasync function clerkGet(path: string, secretKey: string, fetchImpl: typeof fetch): Promise<unknown> {\n const res = await fetchImpl(`${CLERK_API}${path}`, {\n // workerd supports manual/follow, not redirect:error. Never forward the\n // credential on redirects; the status check below rejects every 3xx.\n headers: { authorization: `Bearer ${secretKey}` }, redirect: \"manual\", signal: AbortSignal.timeout(5000),\n });\n if (!res.ok) throw new Error(`clerk GET ${path} → ${res.status}`);\n return res.json();\n}\n\n/** Look a Clerk user up by email. `null` when no such user — or when the lookup\n * fails (a role gate treats an unresolvable user as absent, matching the site's\n * own fallback). Role defaults to provisional when unset. */\nexport async function clerkGetUserByEmail(secretKey: string, email: string, fetchImpl: typeof fetch = fetch, source: ClerkRoleMetadata = \"public\"): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, secretKey, fetchImpl).catch(() => null);\n const user = Array.isArray(data) ? (data[0] as ClerkApiUser | undefined) : undefined;\n return user ? toRecord(user, source) : null;\n}\n\n/** Fetch a Clerk user by id, for role-change gating. `null` when missing or on a\n * failed lookup. Role defaults to provisional when unset. */\nexport async function clerkGetUser(secretKey: string, id: string, fetchImpl: typeof fetch = fetch, source: ClerkRoleMetadata = \"public\"): Promise<ClerkUserRecord | null> {\n const data = await clerkGet(`/v1/users/${encodeURIComponent(id)}`, secretKey, fetchImpl).catch(() => null);\n const record = data ? toRecord(data as ClerkApiUser, source) : null;\n return record?.id === id ? record : null;\n}\n\n/** List ALL Clerk users with their roles, auto-paginating. A membership community\n * outgrows one page, and a fixed `limit=100` would silently drop members from the\n * admin roster with no error — so this pages (offset in steps of {@link PAGE})\n * until a short page. A page fetch that fails THROWS rather than returning a\n * partial list, so the caller never mistakes a truncated roster for the whole. */\nexport async function clerkListUsers(secretKey: string, fetchImpl: typeof fetch = fetch, source: ClerkRoleMetadata = \"public\"): Promise<ClerkUserRecord[]> {\n const out: ClerkUserRecord[] = [];\n for (let offset = 0; ; offset += PAGE) {\n const data = await clerkGet(`/v1/users?limit=${PAGE}&offset=${offset}`, secretKey, fetchImpl);\n if (!Array.isArray(data)) throw new Error(\"clerk user roster returned an invalid page\");\n const page = data as ClerkApiUser[];\n for (const u of page) {\n const record = toRecord(u, source);\n if (record) out.push(record);\n }\n if (page.length < PAGE) break;\n }\n return out;\n}\n\n/** Merge only the selected role key. Private mode removes the legacy public role\n * atomically while preserving profiles/foreign keys. No private-to-public fallback. */\nexport async function clerkSetRole(secretKey: string, id: string, role: string, fetchImpl: typeof fetch = fetch, source: ClerkRoleMetadata = \"public\"): Promise<boolean> {\n const res = await fetchImpl(`${CLERK_API}/v1/users/${encodeURIComponent(id)}/metadata`, {\n method: \"PATCH\",\n headers: { authorization: `Bearer ${secretKey}`, \"content-type\": \"application/json\" },\n redirect: \"manual\", signal: AbortSignal.timeout(5000),\n body: JSON.stringify(source === \"private\"\n ? { private_metadata: { role }, public_metadata: { role: null } }\n : { public_metadata: { role } }),\n });\n return res.ok;\n}\n","import type { ClerkUserRecord } from \"./clerk-roles\";\n\n/** Operator-supplied evidence for EVERY active runtime sharing this Clerk instance.\n * Resolve the expected inventory from odla, not from only the current checkout.\n * Readiness means the private-role build is staged and old role writers paused. */\nexport interface PrivateRoleRuntimeProof {\n runtime: string;\n version: string;\n privateRoleReady: boolean;\n roleWritesPaused: boolean;\n}\n/** Fresh operator-reviewed inventory for a dev-only migration dry run.\n * This evidence is not write authority and the planner performs no provider I/O. */\nexport interface PrivateRoleMigrationInput {\n environment: string;\n expectedRuntimes: readonly string[];\n runtimes: readonly PrivateRoleRuntimeProof[];\n /** Existing active protected odla grants, resolved by exact Clerk subject.\n * Never derive this set from public/private Clerk metadata or legacy tables. */\n protectedSuperAdminUserIds: readonly string[];\n users: readonly ClerkUserRecord[];\n ladder: readonly string[];\n}\n\n/** Dry-run only: does not change Clerk, odla roles, runtime configuration or keys.\n * Conflicting sources require review. A successful plan is NOT an atomic lock;\n * keep all writers paused and re-read the exact role fields before each write.\n * Resume requires a new plan; never replay a stale snapshot over newer roles. */\nexport function planPrivateRoleMigration(input: PrivateRoleMigrationInput) {\n const blockers: string[] = [];\n const changes: Array<{ userId: string; role: string; publicRole: unknown; privateRole: unknown }> = [];\n if (input.environment !== \"dev\") blockers.push(\"dev_only\");\n if (!input.ladder.length || new Set(input.ladder).size !== input.ladder.length ||\n input.ladder.some(role => !role || role === \"super_admin\")) blockers.push(\"invalid_role_ladder\");\n const expected = new Set(input.expectedRuntimes);\n if (!expected.size || expected.size !== input.expectedRuntimes.length || input.expectedRuntimes.some(id => !id)) blockers.push(\"runtime_inventory_required\");\n if (input.runtimes.length !== expected.size || new Set(input.runtimes.map(r => r.runtime)).size !== expected.size ||\n input.runtimes.some(r => !expected.has(r.runtime))) blockers.push(\"runtime_inventory_mismatch\");\n for (const runtime of input.expectedRuntimes) {\n const proof = input.runtimes.find(r => r.runtime === runtime);\n if (!proof?.version || !proof.privateRoleReady || !proof.roleWritesPaused) blockers.push(`runtime_not_ready:${runtime}`);\n }\n const ids = new Set<string>();\n let alreadyCurrent = 0;\n for (const user of input.users) {\n if (!user.id.startsWith(\"user_\") || ids.has(user.id)) { blockers.push(\"invalid_user_inventory\"); continue; }\n ids.add(user.id);\n const publicRole = user.publicMetadata.role;\n const privateRole = user.privateMetadata.role;\n const present = (role: unknown) => role !== undefined && role !== null;\n const valid = (role: unknown): role is string => typeof role === \"string\" && input.ladder.includes(role);\n if ((present(publicRole) && !valid(publicRole)) || (present(privateRole) && !valid(privateRole))) {\n blockers.push(`invalid_role:${user.id}`); continue;\n }\n if (present(publicRole) && present(privateRole) && publicRole !== privateRole) {\n blockers.push(`role_conflict:${user.id}`); continue;\n }\n const role = (privateRole ?? publicRole ?? input.ladder[0]) as string;\n if (privateRole === role && !Object.hasOwn(user.publicMetadata, \"role\")) alreadyCurrent++;\n else changes.push({ userId: user.id, role, publicRole, privateRole });\n }\n // A protected operator may have no ordinary membership or Clerk admin role.\n // The exact active odla grant is independent authority; never promote a\n // provider role simply to make this preflight pass.\n if (!input.protectedSuperAdminUserIds.some(id => ids.has(id))) blockers.push(\"protected_operator_grant_required\");\n return { ready: blockers.length === 0, blockers, changes, alreadyCurrent, totalUsers: input.users.length };\n}\n","// The Clerk capability descriptor: documentation-as-data — \"what settings/secrets\n// does turning Clerk on need?\", \"what must the CLI provision?\", and \"what data\n// syncs, in which direction?\". It lives here (not in the browser package\n// @odla-ai/auth-clerk) because the sync contract is implemented by odla-db + the\n// platform webhook (provider->odla) and by chapter's clerk.ts (odla->provider),\n// neither of which is browser code. auth-clerk stays a pure UI package. Data only:\n// it describes the capability, it performs none of it.\n\n/** Which auth mode a secret is required for: `\"client\"` (publishable key only) or\n * `\"full\"` (server-side profile/role reads + writes, needing the vault secret). */\nexport type SecretMode = \"client\" | \"full\";\n\n/** A configuration value the capability needs (e.g. the publishable key). */\nexport interface IntegrationSetting {\n key: string;\n description: string;\n /** Safe to ship to the browser? (publishable keys are; secrets are not). */\n public: boolean;\n /** Expected value shape, e.g. a \"pk_\" prefix. */\n pattern?: string;\n /** Stored per environment (dev/prod)? */\n perEnv: boolean;\n /** Where the value is stored and read from. */\n source: string;\n}\n\n/**\n * A secret the capability needs, held in the tenant vault.\n *\n * Structurally the odla CLI's `IntegrationSecret`: `name` is the effective\n * runtime vault name, so `odla-ai doctor`, `odla-ai secrets status`, and the\n * repo's `check:secrets` gate can hold this declaration against the name the\n * package requests. The Clerk backend key is stored once in the reserved\n * `$clerk_secret` slot and odla-db resolves its released `clerk_secret_key`\n * compatibility name. `mode` is chapter's own addition and the CLI ignores it.\n */\nexport interface IntegrationSecret {\n /** Effective runtime vault name. Dedicated platform commands may keep the\n * canonical value in a reserved slot and resolve this compatibility name. */\n name: string;\n description: string;\n pattern?: string;\n /** Auth mode that requires this secret (\"full\" pulls user profiles). */\n mode: SecretMode;\n /** Whether the capability is broken without it. Both Clerk secrets are\n * needed only by auth mode \"full\", so both are optional. */\n required?: boolean;\n}\n\n/** One data-sync contract. A capability may declare several (e.g. an inbound\n * webhook mirror AND an outbound write), so {@link IntegrationDescriptor.syncs}\n * is a list. The mechanism is declared, not reimplemented here. */\nexport interface IntegrationSync {\n engine: string;\n direction: \"provider->odla\" | \"odla->provider\" | \"bidirectional\";\n entity: string;\n fields: string[];\n webhook?: string;\n onDelete?: string;\n}\n\n/** The provisioning split: human, CLI, and doctor-assertable steps. */\nexport interface IntegrationProvision {\n /** Steps a human performs (out-of-band, e.g. in the Clerk dashboard). */\n human: string[];\n /** Steps the odla CLI automates. */\n cli: string[];\n /** Checks `odla doctor` should assert. */\n doctor: string[];\n}\n\n/** Documentation-as-data for a provider capability, consumed by the odla CLI,\n * `odla doctor`, and the docs. */\nexport interface IntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n settings: IntegrationSetting[];\n secrets: IntegrationSecret[];\n /** Every data-sync contract the capability declares, each with its direction. */\n syncs: IntegrationSync[];\n provision: IntegrationProvision;\n}\n\n/**\n * The concrete {@link IntegrationDescriptor} for the Clerk capability. Declares\n * the one public `setting` (the `pk_*` publishable key, served to the SPA), the\n * `secrets` auth mode `\"full\"` needs in the tenant vault, BOTH sync directions —\n * the inbound `$users` webhook mirror (`provider->odla`) and the outbound\n * selected private-role (or legacy public-role) / private-profile write via `clerk_secret_key` (`odla->provider`,\n * chapter's `clerk.ts`) — and the `provision` split. Data only; it performs\n * none of it.\n */\nexport const clerkIntegration: IntegrationDescriptor = {\n id: \"clerk\",\n title: \"Clerk end-user auth\",\n npm: \"@odla-ai/chapter\",\n settings: [\n {\n key: \"publishableKey\",\n description: \"Clerk publishable key (pk_*). Public by design; served to the SPA (loads clerk-js from Clerk's CDN via @odla-ai/auth-clerk).\",\n public: true,\n pattern: \"pk_\",\n perEnv: true,\n source: \"apps-registry auth[env].publishableKey (from odla.config.mjs auth.clerk.<env>)\",\n },\n ],\n secrets: [\n {\n // odla-db reads this exact name (CLERK_WEBHOOK_SECRET_NAME in the\n // platform's clerk-webhook.ts); it is also what `odla-ai secrets set`\n // writes. It read \"CLERK_WEBHOOK_SECRET\" until 0.30.0, which sent\n // adopters to store the value under a name nothing looks up.\n name: \"clerk_webhook_secret\",\n description: \"Svix signing secret for Clerk user webhooks — verifies $users sync events.\",\n pattern: \"whsec_\",\n mode: \"full\",\n required: false,\n },\n {\n name: \"clerk_secret_key\",\n description: \"Effective Clerk backend key (sk_*), stored canonically by set-clerk-key in reserved $clerk_secret — powers account creation, private roles (legacy public roles during adoption), private profile signals, and odla-db user resolution.\",\n pattern: \"sk_\",\n mode: \"full\",\n required: false,\n },\n ],\n syncs: [\n {\n engine: \"@odla-ai/db $users (Clerk webhook -> tenant graph)\",\n direction: \"provider->odla\",\n entity: \"$users\",\n // Matches the webhook mapper: the mirror carries id + primary email + name + avatar.\n fields: [\"id\", \"email\", \"name\", \"imageUrl\"],\n webhook: \"whsec_ (svix-signed)\",\n onDelete: \"tombstone (never row-delete)\",\n },\n {\n engine: \"@odla-ai/chapter clerk.ts (Clerk Backend API via vault clerk_secret_key)\",\n direction: \"odla->provider\",\n entity: \"clerk user\",\n // Separate metadata fields so a public role write cannot expose or\n // clobber backend-only account/profile signals.\n fields: [\n \"private_metadata.role\",\n \"public_metadata.role\",\n \"private_metadata.applicationId\",\n \"private_metadata.profile\",\n ],\n onDelete: \"n/a (writes only)\",\n },\n ],\n provision: {\n human: [\n \"Run `npx clerk auth login` — the one interactive step; the agent then creates + configures the Clerk app with the Clerk CLI (no pk_ to hand-paste).\",\n 'For auth mode \"full\": create the Clerk user-sync webhook, store its whsec_, and transfer the sk_ with `odla-ai secrets set-clerk-key --env <env> --stdin` (write-only).',\n ],\n cli: [\n \"Clerk CLI (`npx clerk apps create/link/config patch`) creates + configures the instance and pulls the pk_.\",\n \"odla `provision` records it: setAuth(env, publishableKey) -> apps-registry (issuer/JWKS derived from the key).\",\n \"odla `secrets set-clerk-key` stores one environment-scoped reserved credential consumed by odla-db and Chapter.\",\n ],\n doctor: [\n \"registry auth[env] present when the app mounts <SignIn>?\",\n 'auth mode \"full\" => whsec_ present and the effective clerk_secret_key reports set via the reserved Clerk credential status?',\n ],\n },\n};\n","// The member session — what GET /api/me returns to a signed-in applicant/member.\n// Ported from the reference application's summary + /api/me reconciliation. The\n// SHAPING is pure and package-enforced so no site re-derives it; the worker owns\n// only the I/O around it (locating the application by email, reconciling the\n// meeting against the calendar) and hands the resolved rows here.\n//\n// Two invariants live here, not in a site:\n// - `paid` is DERIVED, never a stored flag: a subscription exists and the\n// application wasn't refunded. Sites can't drift a stale boolean out of sync\n// with Stripe.\n// - the live meeting row wins: its startAt/meetUrl/timezone override whatever\n// the application row cached, and a non-scheduled meeting (a cancellation\n// adopted from the calendar) forces meetingAt back to null.\n\n/** An application row, as far as the session cares about it. */\nexport interface ApplicationRecord {\n id: string;\n firstName?: string | null;\n lastName?: string | null;\n email?: string | null;\n status: string;\n meetingAt?: number | null;\n meetingLink?: string | null;\n createdAt?: number | null;\n stripeSubscriptionId?: string | null;\n renewalAt?: number | null;\n canceled?: boolean;\n tierId?: string | null;\n}\n\n/** The reconciled meeting row (already adopted against the calendar), or null. */\nexport interface MeetingRecord {\n status: string;\n startAt?: number | null;\n meetUrl?: string | null;\n timezone?: string | null;\n}\n\n/** The stable, non-meeting fields of an application (safe to expose to its own\n * owner). */\nexport interface ApplicationSummary {\n id: string;\n firstName: string | null;\n lastName: string | null;\n email: string | null;\n status: string;\n createdAt: number | null;\n meetingLink: string | null;\n paid: boolean;\n renewalAt: number | null;\n canceled: boolean;\n /** Server-authoritative membership tier selected on this application. */\n tierId: string | null;\n}\n\n/** A summary plus the reconciled meeting fields — the `application` the member\n * area renders. */\nexport interface MemberApplication extends ApplicationSummary {\n meetingAt: number | null;\n meetUrl: string | null;\n timezone: string;\n}\n\n/** The full GET /api/me payload for a signed-in user. */\nexport interface MemberSession {\n userId: string;\n email: string | null;\n role: string;\n superAdmin: boolean;\n application: MemberApplication | null;\n}\n\n/** Derive the summary fields from an application row. `paid` is computed, not\n * read, so it can never contradict Stripe. */\nexport function applicationSummary(app: ApplicationRecord): ApplicationSummary {\n return {\n id: app.id,\n firstName: app.firstName ?? null,\n lastName: app.lastName ?? null,\n email: app.email ?? null,\n status: app.status,\n createdAt: app.createdAt ?? null,\n meetingLink: app.meetingLink ?? null,\n paid: Boolean(app.stripeSubscriptionId) && app.status !== \"refunded\",\n renewalAt: app.renewalAt ?? null,\n canceled: app.canceled === true,\n tierId: app.tierId ?? null,\n };\n}\n\n/** Fold a (possibly absent, already-reconciled) meeting into the application the\n * member area renders. The live meeting overrides the application's cached\n * meeting fields; a non-`scheduled` meeting clears the booking. */\nexport function memberApplication(\n app: ApplicationRecord,\n meeting: MeetingRecord | null | undefined,\n defaultTimezone: string,\n): MemberApplication {\n const summary = applicationSummary(app);\n let meetingAt = app.meetingAt ?? null;\n let meetUrl: string | null = null;\n let timezone = defaultTimezone;\n if (meeting) {\n timezone = meeting.timezone ?? timezone;\n if (meeting.status === \"scheduled\") {\n meetingAt = meeting.startAt ?? null;\n meetUrl = meeting.meetUrl ?? null;\n } else {\n meetingAt = null;\n }\n }\n return { ...summary, meetingAt, meetUrl, timezone };\n}\n\n/** Identity of the signed-in user, from the verified session. */\nexport interface SessionUser {\n userId: string;\n email?: string | null;\n role: string;\n}\n\n/** Assemble the GET /api/me payload. `application` is null when the user has no\n * application on file (an admin who never applied, or a brand-new account). */\nexport function memberSession(\n user: SessionUser,\n opts: { application: MemberApplication | null; superAdmin: boolean },\n): MemberSession {\n return {\n userId: user.userId,\n email: user.email ?? null,\n role: user.role,\n superAdmin: opts.superAdmin,\n application: opts.application,\n };\n}\n","// Brand tokens (H4). defineChapter accepts a `brand` block; this turns it into a\n// `:root { --…: … }` CSS block, so a chapter re-skins the WHOLE UI — the\n// @odla-ai/ui components, the admin shell, and the member islands, which all read\n// --ui-* design tokens — from one config instead of hand-writing inline CSS.\n//\n// Pure string generation, so it is unit-testable and can be emitted at\n// build/SSR time into the page <head> (no flash of unstyled content), or via the\n// <BrandStyle> component from @odla-ai/chapter/ui.\nimport type { ChapterBrand, ChapterBrandTokens } from \"./types\";\n\n// A palette entry is either a direct custom property (already `--…`, e.g.\n// `--ui-accent` to retheme components) or a bare name we expose as `--<name>`\n// (e.g. `moss` → `--moss`, for a site to reference in its own CSS).\nfunction paletteVar(key: string): string {\n return key.startsWith(\"--\") ? key : `--${key}`;\n}\n\n// Strip characters that could break out of a `--var: value;` declaration or the\n// surrounding <style>. Brand config is trusted author input, so this is a\n// belt-and-suspenders guard, not a security boundary.\nfunction cleanValue(value: string): string {\n return value.replace(/[<>{};]/g, \"\").trim();\n}\n\nfunction paletteDecls(palette: Record<string, string> | undefined): string[] {\n const decls: string[] = [];\n for (const [key, value] of Object.entries(palette ?? {})) {\n if (typeof value === \"string\" && value.trim()) decls.push(`${paletteVar(key)}: ${cleanValue(value)};`);\n }\n return decls;\n}\n\nconst TOKEN_VARS: Record<keyof ChapterBrandTokens, string> = {\n background: \"--ui-bg\",\n surface: \"--ui-surface\",\n surface2: \"--ui-surface-2\",\n text: \"--ui-text\",\n textMuted: \"--ui-text-muted\",\n textFaint: \"--ui-text-faint\",\n border: \"--ui-border\",\n borderStrong: \"--ui-border-strong\",\n accent: \"--ui-accent\",\n accentStrong: \"--ui-accent-strong\",\n accentSoft: \"--ui-accent-soft\",\n onAccent: \"--ui-on-accent\",\n good: \"--ui-good\",\n warn: \"--ui-warn\",\n danger: \"--ui-danger\",\n chart1: \"--ui-chart-1\",\n chart2: \"--ui-chart-2\",\n chart3: \"--ui-chart-3\",\n chart4: \"--ui-chart-4\",\n chart5: \"--ui-chart-5\",\n chart6: \"--ui-chart-6\",\n chartPositive: \"--ui-chart-pos\",\n chartNegative: \"--ui-chart-neg\",\n contentWidth: \"--ui-content-width\",\n panelRadius: \"--ui-radius-lg\",\n panelShadow: \"--ui-shadow\",\n masterDetailColumns: \"--ui-master-detail-columns\",\n masterDetailMinHeight: \"--ui-master-detail-min-height\",\n pagePadding: \"--chapter-admin-page-padding\",\n workspacePadding: \"--chapter-admin-workspace-padding\",\n};\n\nfunction semanticDecls(tokens: ChapterBrandTokens | undefined): string[] {\n return Object.entries(tokens ?? {}).flatMap(([key, value]) =>\n typeof value === \"string\" && value.trim()\n ? [`${TOKEN_VARS[key as keyof ChapterBrandTokens]}: ${cleanValue(value)};`]\n : [],\n );\n}\n\n/**\n * Build the CSS that maps a chapter's brand onto the design tokens the UI reads:\n * each `palette` entry becomes a custom property (light, and dark unless\n * `paletteDark` overrides), and `fonts` (display/body/numeral) map to\n * `--ui-font-display` / `--ui-font-sans` / `--ui-font-numeral`. The dark block is\n * emitted under both `:root[data-theme=\"dark\"]` (the odla-ui theme toggle) and\n * `@media (prefers-color-scheme: dark)`. Returns \"\" when there is nothing to\n * theme. These are brand OVERRIDES on top of a base theme — they do not replace\n * the theme layer the components need (see {@link brandTokens} usage in the docs).\n */\nexport function brandTokens(\n brand: ChapterBrand | undefined,\n options: { selector?: string } = {},\n): string {\n if (!brand) return \"\";\n const light = [...paletteDecls(brand.palette), ...semanticDecls(brand.tokens)];\n const fonts = brand.fonts;\n if (fonts?.display) light.push(`--ui-font-display: ${cleanValue(fonts.display)};`);\n if (fonts?.body) light.push(`--ui-font-sans: ${cleanValue(fonts.body)};`);\n if (fonts?.numeral) light.push(`--ui-font-numeral: ${cleanValue(fonts.numeral)};`);\n const dark = [...paletteDecls(brand.paletteDark), ...semanticDecls(brand.tokensDark)];\n const invert = paletteDecls(brand.paletteInvert);\n const selector = options.selector ?? \":root\";\n const darkSelector = selector === \":root\" ? ':root[data-theme=\"dark\"]' : `${selector}[data-theme=\"dark\"]`;\n const systemSelector = selector === \":root\"\n ? ':root:not([data-theme=\"light\"])'\n : `${selector}:not([data-theme=\"light\"])`;\n\n let css = light.length ? `${selector} {\\n ${light.join(\"\\n \")}\\n}\\n` : \"\";\n if (dark.length) {\n const block = `{\\n ${dark.join(\"\\n \")}\\n}`;\n css += `${darkSelector} ${block}\\n@media (prefers-color-scheme: dark) {\\n ${systemSelector} ${block}\\n}\\n`;\n }\n if (invert.length) {\n const invertSelector = selector === \":root\"\n ? \".ui-invert\"\n : `${selector}.ui-invert, ${selector} .ui-invert`;\n css += `${invertSelector} {\\n color-scheme: dark;\\n ${invert.join(\"\\n \")}\\n}\\n`;\n }\n return css;\n}\n\n/** Structural output accepted from `@odla-ai/brand`'s pure token compiler. */\nexport interface CompiledChapterBrandTokens {\n light: Record<string, string>;\n dark: Record<string, string>;\n}\n\n/**\n * Turn a complete compiled token pair into Chapter's brand contract without\n * coupling Chapter's runtime to the brand-book/agent package. Explicit values in\n * `base` win, so a host can make final per-site adjustments after compilation.\n */\nexport function chapterBrandFromTokens(\n compiled: CompiledChapterBrandTokens,\n base: ChapterBrand = {},\n): ChapterBrand {\n return {\n ...base,\n palette: { ...compiled.light, ...base.palette },\n paletteDark: { ...compiled.dark, ...base.paletteDark },\n paletteInvert: { ...compiled.dark, ...base.paletteInvert },\n };\n}\n","// The Google → chapter half of the bidirectional calendar sync. Booking writes\n// events TO the platform calendar (0.4.0's create/reschedule); this ADOPTS edits\n// FROM it: when the owner moves or cancels the intro call directly in Google,\n// reconcile mirrors that onto our canonical `meetings` row and the `application`\n// projection. Chapter never calls Google — the worker reads live events through\n// @odla-ai/calendar's upcoming() (platform-brokered) and applies the ops this\n// returns. Pure + testable; adoption policy (owner edits win) matches the shipped\n// original production worker.\n\n/** A `meetings` row, as far as reconciliation cares. */\nexport interface MeetingForReconcile {\n id: string;\n applicationId: string;\n googleEventId?: string | null;\n status: string;\n startAt?: number | null;\n endAt?: number | null;\n}\n\n/** One live calendar event (a subset of @odla-ai/calendar's Booking). */\nexport interface LiveEvent {\n eventId: string;\n status?: string;\n startAt?: number;\n endAt?: number;\n}\n\n/** An adopt decision: mirror a Google move/cancel onto our rows. */\nexport interface ReconcileDecision {\n meetingId: string;\n applicationId: string;\n kind: \"cancelled\" | \"moved\";\n /** Attrs to write onto the `meetings` row. */\n meetingPatch: Record<string, unknown>;\n /** Attrs to write onto the `applications` row (the projection). */\n applicationPatch: Record<string, unknown>;\n}\n\n/** Meetings still worth reconciling: a scheduled booking with a Google event that\n * starts in the future (or within the last hour, to catch a just-passed edit). */\nexport function isReconcilable(meeting: MeetingForReconcile, now: number): boolean {\n return meeting.status === \"scheduled\" && Boolean(meeting.googleEventId) && (meeting.startAt ?? 0) > now - 3_600_000;\n}\n\n/**\n * Diff canonical `meetings` against the live calendar events and return the adopt\n * decisions — only for meetings that actually changed (a still-matching meeting\n * is omitted). A meeting whose event vanished or is `cancelled` in Google is\n * adopted as cancelled (application `meetingAt` zeroed — 0 means \"was booked,\n * then cancelled\"); a meeting whose event moved adopts the new window (duration\n * preserved when the event omits `endAt`).\n */\nexport function reconcileMeetings(\n meetings: readonly MeetingForReconcile[],\n events: readonly LiveEvent[],\n now: number,\n): ReconcileDecision[] {\n const byEvent = new Map(events.map((e) => [e.eventId, e]));\n const decisions: ReconcileDecision[] = [];\n for (const m of meetings) {\n if (!isReconcilable(m, now) || !m.googleEventId) continue;\n const g = byEvent.get(m.googleEventId);\n if (!g || g.status === \"cancelled\") {\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"cancelled\",\n meetingPatch: { status: \"cancelled\", drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: 0, meetingLink: \"\" },\n });\n } else if (g.startAt !== undefined && g.startAt !== m.startAt) {\n const duration = (m.endAt ?? 0) - (m.startAt ?? 0);\n decisions.push({\n meetingId: m.id,\n applicationId: m.applicationId,\n kind: \"moved\",\n meetingPatch: { startAt: g.startAt, endAt: g.endAt ?? g.startAt + duration, drift: \"none\", adoptedFromGoogleAt: now },\n applicationPatch: { meetingAt: g.startAt },\n });\n }\n }\n return decisions;\n}\n","// Scheduling core — config resolution + the booking invariants, ported from the\n// proven production worker. Everything here is PURE (no @odla-ai/calendar, no\n// db), so the correctness properties are unit-testable and package-enforced; the\n// worker route owns only the I/O (FreeBusy, computeBookableSlots, calendar\n// create/reschedule, the db writes) and calls these.\n//\n// Package-enforced invariants:\n// - the `meetings` row is canonical; applications.meetingAt and the calendar\n// event are projections written from it.\n// - one intro event per application, forever: a rebooking RESCHEDULES the\n// existing event (preserving its Meet link + invite thread), never creates a\n// second — see {@link bookingDecision} + {@link introIdempotencyKey}.\n// - status never moves backward on booking; you can only book from a pipeline\n// stage in `bookableFrom` — see `canBook` in ./pipeline + applicationBookingUpdate.\n// - endAt is always derived server-side, never client-supplied — see\n// {@link endForSlot}.\nimport type { ChapterScheduling } from \"./types\";\n\n/** A fully-resolved scheduling config (every field present). */\nexport interface ResolvedScheduling {\n slotMinutes: number;\n days: readonly number[];\n startHour: number;\n endHour: number;\n timezone: string;\n minNoticeHours: number;\n windowDays: number;\n summaryTemplate: string;\n}\n\n/** Proven defaults: 45-minute weekday slots, 9–5 Pacific, 24h notice,\n * a 14-day window. The summary is generic (a chapter's group seed supplies a\n * name-branded one). */\nexport const SCHEDULING_DEFAULTS: ResolvedScheduling = {\n slotMinutes: 45,\n days: [1, 2, 3, 4, 5],\n startHour: 9,\n endHour: 17,\n timezone: \"America/Los_Angeles\",\n minNoticeHours: 24,\n windowDays: 14,\n summaryTemplate: \"Introduction call with {{firstName}} {{lastName}}\",\n};\n\nfunction isValidTimeZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(undefined, { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a group's scheduling config against the defaults, validating every\n * bound at config-write time (throws on a bad config, so a\n * misconfiguration surfaces immediately rather than yielding empty slots).\n * `windowDays` is capped at 62 because Google FreeBusy is.\n */\nexport function resolveScheduling(config?: ChapterScheduling): ResolvedScheduling {\n const result = validateScheduling(config);\n if (result.ok) return result.value;\n const detail = Object.entries(result.errors)\n .map(([field, message]) => `${field}: ${message}`)\n .join(\" \");\n throw new Error(`scheduling: ${detail}`);\n}\n\n/** Validation messages keyed by form field. */\nexport type SchedulingErrors = Record<string, string>;\n\n/**\n * Validate a scheduling config field by field, collecting owner-readable messages\n * rather than throwing on the first problem. An admin settings form needs to say\n * *which* field is wrong and why — \"pick at least one day\" beats a stack trace —\n * so the admin route returns these directly. {@link resolveScheduling} is the\n * throwing wrapper for internal/config-time use.\n */\nexport function validateScheduling(\n config?: ChapterScheduling,\n): { ok: true; value: ResolvedScheduling } | { ok: false; errors: SchedulingErrors } {\n const d = config ?? {};\n const c: ResolvedScheduling = {\n slotMinutes: d.slotMinutes ?? SCHEDULING_DEFAULTS.slotMinutes,\n days: d.days ?? SCHEDULING_DEFAULTS.days,\n startHour: d.startHour ?? SCHEDULING_DEFAULTS.startHour,\n endHour: d.endHour ?? SCHEDULING_DEFAULTS.endHour,\n timezone: d.timezone ?? SCHEDULING_DEFAULTS.timezone,\n minNoticeHours: d.minNoticeHours ?? SCHEDULING_DEFAULTS.minNoticeHours,\n windowDays: d.windowDays ?? SCHEDULING_DEFAULTS.windowDays,\n summaryTemplate: d.summaryTemplate ?? SCHEDULING_DEFAULTS.summaryTemplate,\n };\n const errors: SchedulingErrors = {};\n if (!(c.slotMinutes >= 15 && c.slotMinutes <= 240)) {\n errors.slotMinutes = \"Slot length must be between 15 and 240 minutes.\";\n }\n if (!(c.windowDays >= 1 && c.windowDays <= 62)) {\n errors.windowDays = \"Booking window must be between 1 and 62 days (the calendar caps look-ahead at 62).\";\n }\n if (!(c.minNoticeHours >= 0 && c.minNoticeHours <= 336)) {\n errors.minNoticeHours = \"Minimum notice must be between 0 and 336 hours.\";\n }\n if (!(c.startHour >= 0 && c.startHour < c.endHour && c.endHour <= 24)) {\n errors.hours = \"Hours must satisfy 0 ≤ start < end ≤ 24.\";\n }\n const days = [...c.days];\n if (!days.length) errors.days = \"Pick at least one day.\";\n else if (!days.every((n) => Number.isInteger(n) && n >= 0 && n <= 6)) {\n errors.days = \"Days must be weekday numbers, 0 (Sunday) through 6 (Saturday).\";\n }\n if (typeof c.timezone !== \"string\" || !isValidTimeZone(c.timezone)) {\n errors.timezone = `\"${String(c.timezone)}\" is not a valid IANA timezone (for example \"America/Los_Angeles\").`;\n }\n if (typeof c.summaryTemplate !== \"string\") errors.summaryTemplate = \"Calendar summary template must be text.\";\n return Object.keys(errors).length > 0 ? { ok: false, errors } : { ok: true, value: { ...c, days } };\n}\n\n/** Statuses a member may book/reschedule from (early pipeline only). */\n// Booking eligibility is answered by the configured pipeline — canBook(status,\n// pipeline) in ./pipeline — not a hardcoded status list, so a chapter that\n// customizes its stages gets one consistent answer.\n\n/** The availability window: `[now, now + windowDays]` in epoch ms. */\nexport function slotWindow(now: number, windowDays: number): { from: number; to: number } {\n return { from: now, to: now + windowDays * 86_400_000 };\n}\n\n/** The slot's end instant, always derived from its start (never client-supplied). */\nexport function endForSlot(startAt: number, slotMinutes: number): number {\n return startAt + slotMinutes * 60_000;\n}\n\n/** Double-book pre-check: the requested start must land exactly on a currently\n * bookable slot boundary. */\nexport function isSlotAvailable(slots: readonly { startAt: number }[], startAt: number): boolean {\n return slots.some((s) => s.startAt === startAt);\n}\n\n/** Render a meeting summary from its template (`{{firstName}}`/`{{lastName}}`). */\nexport function renderSummary(template: string, app: { firstName?: string | null; lastName?: string | null }): string {\n return template.replace(\"{{firstName}}\", app.firstName ?? \"\").replace(\"{{lastName}}\", app.lastName ?? \"\");\n}\n\n/** The prior scheduled meeting for an application, as far as booking cares. */\nexport interface ExistingMeeting {\n id: string;\n googleEventId?: string | null;\n meetUrl?: string | null;\n htmlLink?: string | null;\n}\n\n/** Decide reschedule-vs-create: reschedule iff there's an existing event to move,\n * so the Meet link + invite thread survive and no second event is minted. */\nexport function bookingDecision(existing: ExistingMeeting | null | undefined): { reschedule: boolean; eventId: string | null } {\n const eventId = existing?.googleEventId ?? null;\n return { reschedule: Boolean(eventId), eventId };\n}\n\n/** The create idempotency key — one intro event per application, forever, so a\n * retried create returns the same booking rather than a duplicate. */\nexport function introIdempotencyKey(applicationId: string): string {\n return `application:${applicationId}:intro`;\n}\n\n/** The canonical `meetings` row for a first booking. A `type` (not `interface`)\n * so it stays assignable to a db op's `attrs` (Record<string, unknown>). */\nexport type NewMeetingRow = {\n id: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n status: \"scheduled\";\n googleEventId: string;\n meetUrl?: string;\n htmlLink?: string;\n drift: \"none\";\n createdAt: number;\n};\n\n/** Build the new `meetings` row after the calendar created the event. Optional\n * scalars are omitted (never null), per the odla-db porting rule. */\nexport function meetingCreateRow(i: {\n meetingId: string;\n applicationId: string;\n groupId: string;\n startAt: number;\n endAt: number;\n timezone: string;\n googleEventId: string;\n meetUrl?: string | null;\n htmlLink?: string | null;\n createdAt: number;\n}): NewMeetingRow {\n return {\n id: i.meetingId,\n applicationId: i.applicationId,\n groupId: i.groupId,\n startAt: i.startAt,\n endAt: i.endAt,\n timezone: i.timezone,\n status: \"scheduled\",\n googleEventId: i.googleEventId,\n ...(i.meetUrl ? { meetUrl: i.meetUrl } : {}),\n ...(i.htmlLink ? { htmlLink: i.htmlLink } : {}),\n drift: \"none\",\n createdAt: i.createdAt,\n };\n}\n\n/** The `meetings`-row patch for a reschedule (same row id, moved in place). */\nexport type MeetingReschedulePatch = {\n startAt: number;\n endAt: number;\n drift: \"none\";\n};\n\n/** Patch to move an existing meeting to a new window. */\nexport function meetingRescheduleUpdate(startAt: number, endAt: number): MeetingReschedulePatch {\n return { startAt, endAt, drift: \"none\" };\n}\n\n/** The `applications`-row patch after a booking. */\nexport type ApplicationBookingPatch = {\n meetingAt: number;\n meetingLink?: string;\n status?: \"call_scheduled\";\n};\n\n/** Project the booking onto the application row: cache the time, adopt the\n * calendar link if any, and advance the status to `call_scheduled` unless it is\n * already there (never backward). */\nexport function applicationBookingUpdate(\n currentStatus: string,\n startAt: number,\n htmlLink?: string | null,\n): ApplicationBookingPatch {\n return {\n meetingAt: startAt,\n ...(htmlLink ? { meetingLink: htmlLink } : {}),\n ...(currentStatus !== \"call_scheduled\" ? { status: \"call_scheduled\" as const } : {}),\n };\n}\n","// Reading tiers out of the database. Kept apart from tiers.ts so the decision\n// logic there stays pure and directly testable, and apart from the route\n// modules so both the join config and the checkout resolve tiers identically —\n// a page that offers a tier the checkout would refuse is the bug this prevents.\nimport type { ChapterDb } from \"./types\";\nimport { offerableTiers, resolveTiers, type ChapterTier, type TierGroup } from \"./tiers\";\n\n/** A `groups` row as the tier loader needs it. */\nexport type TierGroupRow = TierGroup & { id?: string };\n\nfunction rowToTier(row: Record<string, unknown>, groupId: string): ChapterTier {\n if (!row || typeof row !== \"object\" || Array.isArray(row) || typeof row.id !== \"string\" || !row.id ||\n (row.groupId !== undefined && row.groupId !== groupId) ||\n !Number.isSafeInteger(row.priceCents) || Number(row.priceCents) < 0 ||\n (row.currency !== undefined && (typeof row.currency !== \"string\" || !/^[a-z]{3}$/.test(row.currency))) ||\n (row.interval !== undefined && row.interval !== \"month\" && row.interval !== \"year\")) {\n throw Object.assign(new Error(\"stored membership tier is invalid\"), { code: \"tiers_unavailable\" });\n }\n return {\n id: String(row.id ?? \"\"),\n groupId: String(row.groupId ?? groupId),\n name: String(row.name ?? \"\"),\n priceCents: typeof row.priceCents === \"number\" ? row.priceCents : 0,\n ...(typeof row.currency === \"string\" && row.currency ? { currency: row.currency } : {}),\n ...(row.interval === \"year\" || row.interval === \"month\" ? { interval: row.interval } : {}),\n ...(typeof row.stripePriceId === \"string\" && row.stripePriceId\n ? { stripePriceId: row.stripePriceId }\n : {}),\n ...(typeof row.blurb === \"string\" ? { blurb: row.blurb } : {}),\n sortOrder: typeof row.sortOrder === \"number\" ? row.sortOrder : 0,\n // A row that never set `active` is offered; only an explicit false retires\n // a tier, so a half-seeded row cannot silently hide a membership.\n active: row.active !== false,\n };\n}\n\n/**\n * Every tier a group offers, ordered, including the implicit tier synthesized\n * for a chapter with a successfully read empty tier collection. Unavailable,\n * malformed, or unprovisioned storage fails closed; it must never turn an\n * outage into an implicit free or legacy-price membership. Retiring all stored\n * tiers leaves no offers rather than reviving the legacy group price.\n */\nexport async function loadTiers(db: ChapterDb, group: TierGroupRow): Promise<ChapterTier[]> {\n const groupId = String(group.id ?? \"\");\n let rows: unknown;\n try {\n rows = (await db.query({\n tiers: { $: { where: { groupId }, order: { sortOrder: \"asc\" }, limit: 100 } },\n }) as Record<string, unknown>).tiers;\n } catch {\n throw Object.assign(new Error(\"membership tiers are unavailable\"), { code: \"tiers_unavailable\" });\n }\n if (!Array.isArray(rows)) throw Object.assign(new Error(\"membership tiers response is invalid\"), { code: \"tiers_unavailable\" });\n const list = rows.map((row) => rowToTier(row as Record<string, unknown>, groupId));\n return resolveTiers(group, list);\n}\n\n/** The tiers a join page may show: active, and joinable as configured. */\nexport async function loadOfferableTiers(\n db: ChapterDb,\n group: TierGroupRow,\n hasSecretKey: boolean,\n): Promise<ChapterTier[]> {\n return offerableTiers(await loadTiers(db, group), group, hasSecretKey);\n}\n","import type { FieldConditions } from \"@odla-ai/crm\";\nimport type { MembershipPageDocument } from \"./membership-page\";\nimport type { ChapterScheduling } from \"./types\";\nimport type { GiftOfferCatalog } from \"./gift-offers\";\nimport type { TierPaymentPolicy } from \"./payment-quote\";\n\n/** Current wire-format version for complete signup-control documents. */\nexport const SIGNUP_CONTROL_SCHEMA_VERSION = 1 as const;\n/** Package-owned follower endpoint for signed signup-control delivery. */\nexport const SIGNUP_CONTROL_PATH = \"/api/signup-control\" as const;\n\n/** One authoritative membership tier in a signup-control revision. */\nexport interface SignupControlTier {\n id: string;\n name: string;\n available: boolean;\n sortOrder: number;\n priceCents: number;\n /** ISO currency; omitted only by pre-field schema-v1 documents. */\n currency?: string;\n /** Recurring interval; omitted only by pre-field schema-v1 documents. */\n interval?: \"year\" | \"month\";\n stripePriceId?: string;\n blurb?: string;\n}\n\n/** A bounded application contract. Fields must already exist in the follower schema. */\nexport interface SignupControlApplication {\n required: readonly string[];\n optional: readonly string[];\n conditions?: Readonly<Record<string, FieldConditions>>;\n copy?: Readonly<Record<string, string>>;\n}\n\n/** Delegated legal and trust copy used by the packaged join journey. */\nexport interface SignupControlPolicy {\n disclaimerText: string;\n refundPolicyText: string;\n /** Plain-language merchant identity displayed before payment consent. */\n merchantDisclosureText?: string;\n trustCopy?: string;\n commitmentText?: string;\n normsText?: string;\n /** Price-specific refund/trust copy, keyed by an explicitly declared tier. */\n tierPolicies?: Readonly<Record<string, TierPaymentPolicy>>;\n}\n\n/** Bounded semantic design tokens delegated to the chapter signup surface. */\nexport interface SignupControlTheme {\n /** Includes color, spacing, and typography tokens such as font families. */\n tokens: Readonly<Record<string, string | number>>;\n}\n\n/** Complete desired state delivered by a controlling hub. */\nexport interface SignupControlDocument {\n schemaVersion: typeof SIGNUP_CONTROL_SCHEMA_VERSION;\n revision: number;\n generatedAt: number;\n source: { appId: string };\n target: { chapterId: string; environment: string; stripeMode: \"test\" | \"live\" };\n tiers: readonly SignupControlTier[];\n membershipPage: MembershipPageDocument;\n application?: SignupControlApplication;\n policy?: SignupControlPolicy;\n scheduling?: ChapterScheduling;\n theme?: SignupControlTheme;\n giftOffers?: GiftOfferCatalog;\n}\n\n/** Digest travels beside the document so the exact desired state is attestable. */\nexport interface SignupControlEnvelope {\n digest: string;\n document: SignupControlDocument;\n /** Signed transport identity, deliberately excluded from the shared document digest. */\n deliveryTarget?: SignupControlRuntimeTarget;\n}\n\n/** Exact deployment receiving a shared data-environment revision. */\nexport interface SignupControlRuntimeTarget {\n appId: string;\n environment: string;\n runtime: string;\n}\n\n/** Exact follower acknowledgement for one accepted or replayed revision. */\nexport interface SignupControlReceipt {\n ok: true;\n target: { chapterId: string; environment: string; appId?: string; runtime?: string };\n revision: number;\n digest: string;\n status: \"accepted\" | \"replayed\";\n acknowledgedAt: number;\n}\n\n/** Stable reason codes returned when a follower refuses desired state. */\nexport type SignupControlRejection =\n | \"invalid_document\"\n | \"invalid_digest\"\n | \"wrong_source\"\n | \"wrong_target\"\n | \"wrong_environment\"\n | \"wrong_runtime\"\n | \"wrong_stripe_mode\"\n | \"stale_revision\"\n | \"conflicting_revision\"\n | \"materialization_failed\";\n\n/** Normalized document result returned by the package validator. */\nexport type SignupControlValidation =\n | { ok: true; value: SignupControlDocument }\n | { ok: false; errors: readonly string[] };\n","/** The first stable, shared Chapter membership-page renderer contract. */\nexport const MEMBERSHIP_PAGE_RENDERER = \"membership-cards-v1\" as const;\n\n/** Fixed visual emphasis choices supported by the versioned card renderer. */\nexport type MembershipTierVariant = \"standard\" | \"featured\" | \"supporting\";\n\n/** A bounded, token-rendered aside within one membership card. */\nexport interface MembershipTierCallout {\n label?: string;\n bodyMarkdown: string;\n}\n\n/** Scarcity copy displayed without changing tier availability or checkout. */\nexport interface MembershipTierCapacity {\n total: number;\n label?: string;\n}\n\n/**\n * Presentation attached to one server-authoritative membership tier.\n *\n * Price, free/paid state, identity, and application targeting deliberately do\n * not live here. They are resolved from the public Chapter join config so\n * authored marketing copy can never change what checkout charges.\n */\nexport interface MembershipTierPresentation {\n tierId: string;\n variant?: MembershipTierVariant;\n badge?: string;\n summaryMarkdown?: string;\n priceEyebrow?: string;\n compareAtPriceCents?: number;\n billingLabel?: string;\n priceNoteMarkdown?: string;\n capacity?: MembershipTierCapacity;\n benefits?: readonly string[];\n callout?: MembershipTierCallout;\n ctaLabel?: string;\n}\n\n/** A bounded document that can be reviewed once and rendered by any Chapter host. */\nexport interface MembershipPageDocument {\n schemaVersion: 1;\n renderer: typeof MEMBERSHIP_PAGE_RENDERER;\n tiers: readonly MembershipTierPresentation[];\n footnoteMarkdown?: string;\n}\n\n/** Minimal server-authoritative tier identity and charged amount used during validation. */\nexport interface MembershipTierAuthority {\n id: string;\n priceCents: number;\n}\n\n/** Live tier authority used to reject missing, unknown, or misleading presentation. */\nexport interface MembershipPageValidationOptions {\n /** When supplied, every live tier must occur exactly once in the document. */\n tiers?: readonly MembershipTierAuthority[];\n}\n\n/** A normalized document or the complete actionable list of validation failures. */\nexport type MembershipPageValidationResult =\n | { ok: true; value: MembershipPageDocument }\n | { ok: false; errors: readonly string[] };\n\nconst TIER_ID = /^[a-z][a-z0-9-]{0,79}$/;\nconst VARIANTS = new Set<MembershipTierVariant>([\"standard\", \"featured\", \"supporting\"]);\nconst ROOT_KEYS = new Set([\"schemaVersion\", \"renderer\", \"tiers\", \"footnoteMarkdown\"]);\nconst TIER_KEYS = new Set([\n \"tierId\", \"variant\", \"badge\", \"summaryMarkdown\", \"priceEyebrow\",\n \"compareAtPriceCents\", \"billingLabel\", \"priceNoteMarkdown\", \"capacity\",\n \"benefits\", \"callout\", \"ctaLabel\",\n]);\nconst CALLOUT_KEYS = new Set([\"label\", \"bodyMarkdown\"]);\nconst CAPACITY_KEYS = new Set([\"total\", \"label\"]);\nconst MAX_TIERS = 20;\nconst MAX_BENEFITS = 24;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_LABEL = 160;\n\nconst objectRecord = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowed: ReadonlySet<string>,\n path: string,\n errors: string[],\n): void {\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n }\n}\n\nfunction boundedString(\n value: unknown,\n path: string,\n errors: string[],\n max: number,\n required = false,\n): string | undefined {\n if (value === undefined) {\n if (required) errors.push(`${path} is required`);\n return undefined;\n }\n if (typeof value !== \"string\") {\n errors.push(`${path} must be a string`);\n return undefined;\n }\n const text = value.trim();\n if (required && !text) errors.push(`${path} is required`);\n if (text.length > max) errors.push(`${path} must be at most ${max.toLocaleString(\"en-US\")} characters`);\n return text;\n}\n\n/**\n * Validate and normalize a membership-page document without evaluating code,\n * accepting HTML, or allowing authored links/styles. Markdown slots are later\n * rendered by @odla-ai/ui's bounded safe Markdown component.\n */\nexport function validateMembershipPageDocument(\n input: unknown,\n options: MembershipPageValidationOptions = {},\n): MembershipPageValidationResult {\n const errors: string[] = [];\n const root = objectRecord(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n rejectUnknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== 1) errors.push(\"document.schemaVersion must be 1\");\n if (root.renderer !== MEMBERSHIP_PAGE_RENDERER) {\n errors.push(`document.renderer must be \\\"${MEMBERSHIP_PAGE_RENDERER}\\\"`);\n }\n if (!Array.isArray(root.tiers)) errors.push(\"document.tiers must be an array\");\n const rawTiers = Array.isArray(root.tiers) ? root.tiers : [];\n if (Array.isArray(root.tiers) && rawTiers.length === 0) errors.push(\"document.tiers must include at least one tier\");\n if (rawTiers.length > MAX_TIERS) errors.push(`document.tiers supports at most ${MAX_TIERS} entries`);\n\n const authority = new Map((options.tiers ?? []).map((tier) => [tier.id, tier]));\n const seen = new Set<string>();\n const tiers: MembershipTierPresentation[] = [];\n for (const [index, raw] of rawTiers.slice(0, MAX_TIERS).entries()) {\n const path = `document.tiers[${index}]`;\n const item = objectRecord(raw);\n if (!item) {\n errors.push(`${path} must be an object`);\n continue;\n }\n rejectUnknownKeys(item, TIER_KEYS, path, errors);\n const tierId = boundedString(item.tierId, `${path}.tierId`, errors, 80, true) ?? \"\";\n if (tierId && !TIER_ID.test(tierId)) errors.push(`${path}.tierId must be a lowercase kebab-case id`);\n if (seen.has(tierId)) errors.push(`${path}.tierId duplicates \\\"${tierId}\\\"`);\n seen.add(tierId);\n if (authority.size && !authority.has(tierId)) errors.push(`${path}.tierId \\\"${tierId}\\\" is not an offered tier`);\n\n const variant = item.variant;\n if (variant !== undefined && (typeof variant !== \"string\" || !VARIANTS.has(variant as MembershipTierVariant))) {\n errors.push(`${path}.variant must be standard, featured, or supporting`);\n }\n const compareAt = item.compareAtPriceCents;\n if (compareAt !== undefined && (!Number.isInteger(compareAt) || Number(compareAt) < 0 || Number(compareAt) > 100_000_000)) {\n errors.push(`${path}.compareAtPriceCents must be an integer from 0 to 100,000,000`);\n }\n const actual = authority.get(tierId)?.priceCents;\n if (Number.isInteger(compareAt) && actual !== undefined && Number(compareAt) <= actual) {\n errors.push(`${path}.compareAtPriceCents must be greater than the authoritative tier price`);\n }\n\n let benefits: string[] | undefined;\n if (item.benefits !== undefined) {\n if (!Array.isArray(item.benefits)) errors.push(`${path}.benefits must be an array`);\n else {\n if (item.benefits.length > MAX_BENEFITS) errors.push(`${path}.benefits supports at most ${MAX_BENEFITS} entries`);\n benefits = item.benefits.slice(0, MAX_BENEFITS).flatMap((benefit, benefitIndex) => {\n const text = boundedString(benefit, `${path}.benefits[${benefitIndex}]`, errors, 2_000, true);\n return text ? [text] : [];\n });\n }\n }\n\n let callout: MembershipTierCallout | undefined;\n if (item.callout !== undefined) {\n const rawCallout = objectRecord(item.callout);\n if (!rawCallout) errors.push(`${path}.callout must be an object`);\n else {\n rejectUnknownKeys(rawCallout, CALLOUT_KEYS, `${path}.callout`, errors);\n const bodyMarkdown = boundedString(rawCallout.bodyMarkdown, `${path}.callout.bodyMarkdown`, errors, MAX_MARKDOWN, true);\n const label = boundedString(rawCallout.label, `${path}.callout.label`, errors, MAX_LABEL);\n if (bodyMarkdown) callout = { ...(label ? { label } : {}), bodyMarkdown };\n }\n }\n\n let capacity: MembershipTierCapacity | undefined;\n if (item.capacity !== undefined) {\n const rawCapacity = objectRecord(item.capacity);\n if (!rawCapacity) errors.push(`${path}.capacity must be an object`);\n else {\n rejectUnknownKeys(rawCapacity, CAPACITY_KEYS, `${path}.capacity`, errors);\n const total = rawCapacity.total;\n if (!Number.isInteger(total) || Number(total) < 1 || Number(total) > 1_000_000) {\n errors.push(`${path}.capacity.total must be an integer from 1 to 1,000,000`);\n }\n const label = boundedString(rawCapacity.label, `${path}.capacity.label`, errors, MAX_LABEL);\n if (Number.isInteger(total) && Number(total) >= 1 && Number(total) <= 1_000_000) {\n capacity = { total: Number(total), ...(label ? { label } : {}) };\n }\n }\n }\n\n const badge = boundedString(item.badge, `${path}.badge`, errors, MAX_LABEL);\n const summaryMarkdown = boundedString(item.summaryMarkdown, `${path}.summaryMarkdown`, errors, MAX_MARKDOWN);\n const priceEyebrow = boundedString(item.priceEyebrow, `${path}.priceEyebrow`, errors, MAX_LABEL);\n const billingLabel = boundedString(item.billingLabel, `${path}.billingLabel`, errors, MAX_LABEL);\n const priceNoteMarkdown = boundedString(item.priceNoteMarkdown, `${path}.priceNoteMarkdown`, errors, MAX_MARKDOWN);\n const ctaLabel = boundedString(item.ctaLabel, `${path}.ctaLabel`, errors, MAX_LABEL);\n tiers.push({\n tierId,\n ...(typeof variant === \"string\" && VARIANTS.has(variant as MembershipTierVariant) ? { variant: variant as MembershipTierVariant } : {}),\n ...(badge ? { badge } : {}),\n ...(summaryMarkdown ? { summaryMarkdown } : {}),\n ...(priceEyebrow ? { priceEyebrow } : {}),\n ...(Number.isInteger(compareAt) ? { compareAtPriceCents: Number(compareAt) } : {}),\n ...(billingLabel ? { billingLabel } : {}),\n ...(priceNoteMarkdown ? { priceNoteMarkdown } : {}),\n ...(capacity ? { capacity } : {}),\n ...(benefits ? { benefits } : {}),\n ...(callout ? { callout } : {}),\n ...(ctaLabel ? { ctaLabel } : {}),\n });\n }\n if (authority.size) {\n for (const tierId of authority.keys()) {\n if (!seen.has(tierId)) errors.push(`document.tiers is missing offered tier \\\"${tierId}\\\"`);\n }\n }\n const footnoteMarkdown = boundedString(root.footnoteMarkdown, \"document.footnoteMarkdown\", errors, MAX_MARKDOWN);\n if (errors.length) return { ok: false, errors };\n return {\n ok: true,\n value: {\n schemaVersion: 1,\n renderer: MEMBERSHIP_PAGE_RENDERER,\n tiers,\n ...(footnoteMarkdown ? { footnoteMarkdown } : {}),\n },\n };\n}\n\n/** Validate a document or fail closed with all actionable validation errors. */\nexport function membershipPageDocument(\n input: unknown,\n options: MembershipPageValidationOptions = {},\n): MembershipPageDocument {\n const result = validateMembershipPageDocument(input, options);\n if (!result.ok) throw new TypeError(`Invalid membership page document: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","import { resolveApplication } from \"./member\";\nimport { validateMembershipPageDocument } from \"./membership-page\";\nimport { validateScheduling } from \"./scheduling\";\nimport { validateGiftOfferCatalog } from \"./gift-offers\";\nimport type {\n SignupControlApplication,\n SignupControlDocument,\n SignupControlPolicy,\n SignupControlTheme,\n SignupControlTier,\n SignupControlValidation,\n} from \"./signup-control-contract\";\n\nconst SLUG = /^[a-z0-9][a-z0-9-]{1,62}$/;\nconst ENVIRONMENT = /^[a-z][a-z0-9_-]{0,62}$/;\nconst TIER = /^[a-z][a-z0-9-]{0,79}$/;\nconst PRICE = /^price_[A-Za-z0-9]{12,}$/;\nconst ROOT_KEYS = new Set([\n \"schemaVersion\", \"revision\", \"generatedAt\", \"source\", \"target\", \"tiers\",\n \"membershipPage\", \"application\", \"policy\", \"scheduling\", \"theme\", \"giftOffers\",\n]);\nconst TIER_KEYS = new Set([\"id\", \"name\", \"available\", \"sortOrder\", \"priceCents\", \"currency\", \"interval\", \"stripePriceId\", \"blurb\"]);\n\nconst recordOf = (value: unknown): Record<string, unknown> | null =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n\nfunction unknownKeys(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string, errors: string[]): void {\n for (const key of Object.keys(value)) if (!allowed.has(key)) errors.push(`${path}.${key} is not supported`);\n}\n\nfunction text(value: unknown, path: string, errors: string[], max = 65_536): string {\n if (typeof value !== \"string\" || !value.trim()) {\n errors.push(`${path} is required`);\n return \"\";\n }\n if (value.length > max) errors.push(`${path} must be at most ${max} characters`);\n return value.trim();\n}\n\nfunction tiersOf(value: unknown, errors: string[]): SignupControlTier[] {\n if (!Array.isArray(value) || !value.length) {\n errors.push(\"document.tiers must be a non-empty array\");\n return [];\n }\n if (value.length > 20) errors.push(\"document.tiers supports at most 20 entries\");\n const seen = new Set<string>();\n return value.slice(0, 20).flatMap((raw, index) => {\n const path = `document.tiers[${index}]`;\n const item = recordOf(raw);\n if (!item) {\n errors.push(`${path} must be an object`);\n return [];\n }\n unknownKeys(item, TIER_KEYS, path, errors);\n const id = text(item.id, `${path}.id`, errors, 80);\n if (id && !TIER.test(id)) errors.push(`${path}.id must be a lowercase kebab-case id`);\n if (seen.has(id)) errors.push(`${path}.id duplicates \"${id}\"`);\n seen.add(id);\n const name = text(item.name, `${path}.name`, errors, 160);\n if (typeof item.available !== \"boolean\") errors.push(`${path}.available must be boolean`);\n if (!Number.isInteger(item.sortOrder) || Number(item.sortOrder) < 0) errors.push(`${path}.sortOrder must be a non-negative integer`);\n if (!Number.isInteger(item.priceCents) || Number(item.priceCents) < 0 || Number(item.priceCents) > 100_000_000) {\n errors.push(`${path}.priceCents must be an integer from 0 to 100,000,000`);\n }\n if (item.stripePriceId !== undefined && (typeof item.stripePriceId !== \"string\" || !PRICE.test(item.stripePriceId))) {\n errors.push(`${path}.stripePriceId must be a real Stripe Price id`);\n }\n if (item.available === true && Number(item.priceCents) > 0 && !item.stripePriceId) {\n errors.push(`${path}.stripePriceId is required for an available paid tier`);\n }\n if (item.currency !== undefined && (typeof item.currency !== \"string\" || !/^[a-z]{3}$/.test(item.currency))) {\n errors.push(`${path}.currency must be a lowercase ISO currency code`);\n }\n if (item.interval !== undefined && item.interval !== \"year\" && item.interval !== \"month\") {\n errors.push(`${path}.interval must be year or month`);\n }\n const blurb = item.blurb === undefined ? undefined : text(item.blurb, `${path}.blurb`, errors, 4_000);\n return [{\n id, name, available: item.available === true,\n sortOrder: Number(item.sortOrder) || 0,\n priceCents: Number(item.priceCents) || 0,\n ...(typeof item.currency === \"string\" ? { currency: item.currency } : {}),\n ...(item.interval === \"year\" || item.interval === \"month\" ? { interval: item.interval } : {}),\n ...(typeof item.stripePriceId === \"string\" ? { stripePriceId: item.stripePriceId } : {}),\n ...(blurb ? { blurb } : {}),\n }];\n });\n}\n\nfunction applicationOf(value: unknown, errors: string[]): SignupControlApplication | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n if (!input) {\n errors.push(\"document.application must be an object\");\n return undefined;\n }\n unknownKeys(input, new Set([\"required\", \"optional\", \"conditions\", \"copy\"]), \"document.application\", errors);\n try {\n const resolved = resolveApplication(input);\n const copy = recordOf(input.copy);\n if (input.copy !== undefined && (!copy || Object.values(copy).some((item) => typeof item !== \"string\"))) {\n errors.push(\"document.application.copy must contain only string values\");\n }\n return {\n required: resolved.required,\n optional: resolved.optional,\n ...(Object.keys(resolved.conditions).length ? { conditions: resolved.conditions } : {}),\n ...(copy ? { copy: copy as Record<string, string> } : {}),\n };\n } catch (error) {\n errors.push(error instanceof Error ? error.message : \"document.application is invalid\");\n return undefined;\n }\n}\n\nfunction policyOf(value: unknown, errors: string[], tiers: readonly SignupControlTier[]): SignupControlPolicy | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n if (!input) {\n errors.push(\"document.policy must be an object\");\n return undefined;\n }\n const allowed = new Set([\n \"disclaimerText\",\n \"refundPolicyText\",\n \"merchantDisclosureText\",\n \"trustCopy\",\n \"commitmentText\",\n \"normsText\",\n ]);\n unknownKeys(input, new Set([...allowed, \"tierPolicies\"]), \"document.policy\", errors);\n const result = {} as Record<string, string>;\n for (const key of allowed) {\n if (input[key] === undefined && key !== \"disclaimerText\" && key !== \"refundPolicyText\") continue;\n result[key] = text(input[key], `document.policy.${key}`, errors);\n }\n const tierPolicies: Record<string, { refundPolicyText: string; trustCopy?: string }> = {};\n if (input.tierPolicies !== undefined) {\n const overrides = recordOf(input.tierPolicies);\n if (!overrides || Object.keys(overrides).length > 20) errors.push(\"document.policy.tierPolicies must be a bounded tier map\");\n else for (const [id, raw] of Object.entries(overrides)) {\n const path = `document.policy.tierPolicies.${id}`;\n const policy = recordOf(raw);\n if (!tiers.some((tier) => tier.id === id) || !policy) { errors.push(`${path} must name a declared tier and policy`); continue; }\n unknownKeys(policy, new Set([\"refundPolicyText\", \"trustCopy\"]), path, errors);\n tierPolicies[id] = { refundPolicyText: text(policy.refundPolicyText, `${path}.refundPolicyText`, errors),\n ...(policy.trustCopy !== undefined ? { trustCopy: text(policy.trustCopy, `${path}.trustCopy`, errors) } : {}) };\n }\n }\n return { ...result, ...(input.tierPolicies !== undefined ? { tierPolicies } : {}) } as unknown as SignupControlPolicy;\n}\n\nfunction themeOf(value: unknown, errors: string[]): SignupControlTheme | undefined {\n if (value === undefined) return undefined;\n const input = recordOf(value);\n const tokens = recordOf(input?.tokens);\n if (!input || !tokens) {\n errors.push(\"document.theme.tokens must be an object\");\n return undefined;\n }\n unknownKeys(input, new Set([\"tokens\"]), \"document.theme\", errors);\n if (Object.keys(tokens).length > 256) errors.push(\"document.theme.tokens supports at most 256 entries\");\n let serializedLength = 0;\n for (const [key, token] of Object.entries(tokens)) {\n if (!/^--ui-[a-z0-9][a-z0-9-]{0,94}$/.test(key)) {\n errors.push(`document.theme.tokens.${key} must be an allowlisted --ui-* custom property`);\n }\n const rendered = String(token).trim();\n serializedLength += key.length + rendered.length + 4;\n if ((typeof token !== \"string\" && typeof token !== \"number\") ||\n (typeof token === \"number\" && !Number.isFinite(token)) ||\n !rendered || rendered.length > 1_000 ||\n /[\\u0000-\\u001f\\u007f\\\\<>{};]|\\/\\*|\\*\\/|(?:^|[^a-z])(?:url|expression)\\s*\\(|@import/i.test(rendered)) {\n errors.push(`document.theme.tokens.${key} must be a bounded breakout-safe CSS value`);\n }\n }\n if (serializedLength > 65_536) errors.push(\"document.theme.tokens exceeds the serialized size bound\");\n return { tokens: tokens as Record<string, string | number> };\n}\n\n/** Validate and normalize one complete desired signup state. */\nexport function validateSignupControlDocument(input: unknown): SignupControlValidation {\n const errors: string[] = [];\n const root = recordOf(input);\n if (!root) return { ok: false, errors: [\"document must be an object\"] };\n unknownKeys(root, ROOT_KEYS, \"document\", errors);\n if (root.schemaVersion !== 1) errors.push(\"document.schemaVersion must be 1\");\n if (!Number.isSafeInteger(root.revision) || Number(root.revision) < 1) errors.push(\"document.revision must be a positive integer\");\n if (!Number.isSafeInteger(root.generatedAt) || Number(root.generatedAt) < 1) errors.push(\"document.generatedAt must be epoch milliseconds\");\n const source = recordOf(root.source);\n const target = recordOf(root.target);\n const appId = text(source?.appId, \"document.source.appId\", errors, 63);\n const chapterId = text(target?.chapterId, \"document.target.chapterId\", errors, 63);\n const environment = text(target?.environment, \"document.target.environment\", errors, 63);\n if (appId && !SLUG.test(appId)) errors.push(\"document.source.appId must be a lowercase app slug\");\n if (chapterId && !SLUG.test(chapterId)) errors.push(\"document.target.chapterId must be a lowercase app slug\");\n if (environment && !ENVIRONMENT.test(environment)) errors.push(\"document.target.environment is invalid\");\n if (target?.stripeMode !== \"test\" && target?.stripeMode !== \"live\") errors.push(\"document.target.stripeMode must be test or live\");\n const tiers = tiersOf(root.tiers, errors);\n const available = tiers.filter((tier) => tier.available).sort((a, b) => a.sortOrder - b.sortOrder);\n const page = validateMembershipPageDocument(root.membershipPage, { tiers: available });\n if (!page.ok) errors.push(...page.errors);\n else if (page.value.tiers.some((tier, index) => tier.tierId !== available[index]?.id)) {\n errors.push(\"document.membershipPage.tiers must follow the available tier display order\");\n }\n const application = applicationOf(root.application, errors);\n const policy = policyOf(root.policy, errors, tiers);\n let scheduling;\n if (root.scheduling !== undefined) {\n const checked = validateScheduling(root.scheduling as never);\n if (!checked.ok) errors.push(...Object.entries(checked.errors).map(([key, value]) => `document.scheduling.${key}: ${value}`));\n else scheduling = root.scheduling;\n }\n const theme = themeOf(root.theme, errors);\n const giftOffers = root.giftOffers === undefined\n ? undefined\n : validateGiftOfferCatalog(root.giftOffers, new Set(tiers.map((tier) => tier.id)));\n if (giftOffers && !giftOffers.ok) errors.push(...giftOffers.errors);\n if (errors.length || !page.ok) return { ok: false, errors };\n return { ok: true, value: {\n schemaVersion: 1,\n revision: Number(root.revision),\n generatedAt: Number(root.generatedAt),\n source: { appId },\n target: { chapterId, environment, stripeMode: target?.stripeMode as \"test\" | \"live\" },\n tiers,\n membershipPage: page.value,\n ...(application ? { application } : {}),\n ...(policy ? { policy } : {}),\n ...(scheduling ? { scheduling } : {}),\n ...(theme ? { theme } : {}),\n ...(giftOffers?.ok ? { giftOffers: giftOffers.value } : {}),\n } };\n}\n","import type { SignupControlTheme } from \"./signup-control-contract\";\n\n/** Stable marker a static document can place where managed signup tokens belong. */\nexport const SIGNUP_CONTROL_THEME_MARKER = \"<!--odla:signup-control-theme-->\" as const;\n/** Stable id shared by the server renderer and browser hydration helper. */\nexport const SIGNUP_CONTROL_THEME_STYLE_ID = \"odla-signup-control-theme\" as const;\n\nconst TOKEN_NAME = /^--ui-[a-z0-9][a-z0-9-]{0,94}$/;\nconst DIGEST = /^sha256:[0-9a-f]{64}$/;\nconst UNSAFE_VALUE = /[\\u0000-\\u001f\\u007f\\\\<>{};]|\\/\\*|\\*\\/|(?:^|[^a-z])(?:url|expression)\\s*\\(|@import/i;\nconst MAX_TOKENS = 256;\nconst MAX_VALUE_LENGTH = 1_000;\nconst MAX_SERIALIZED_LENGTH = 65_536;\n\n/** The active revision shape exposed by `GET /api/join-config`. */\nexport interface SignupControlThemeRevision {\n revision: number;\n digest: string;\n theme?: SignupControlTheme;\n}\n\n/** Identity shared by initial HTML, response caching, and client hydration. */\nexport interface SignupControlThemeMetadata {\n source: \"active\" | \"bootstrap\";\n revision: number | null;\n digest: string | null;\n /** Include this value in any host-owned cache key for transformed HTML. */\n cacheKey: string;\n}\n\n/** A validated style block ready to place in an HTML head. */\nexport interface SignupControlThemeHead {\n css: string;\n head: string;\n metadata: SignupControlThemeMetadata;\n}\n\n/** Minimal DOM surface required by {@link hydrateSignupControlTheme}. */\nexport interface SignupControlThemeStyleTarget {\n textContent: string | null;\n getAttribute(name: string): string | null;\n setAttribute(name: string, value: string): void;\n removeAttribute(name: string): void;\n}\n\n/** Host-owned fallback inputs shared by server rendering and hydration. */\nexport interface SignupControlThemeOptions {\n /** Local site-owned tokens used only when no active managed revision exists. */\n bootstrapTokens?: Readonly<Record<string, string | number>>;\n}\n\nfunction validatedTokens(\n input: Readonly<Record<string, string | number>> | undefined,\n): Readonly<Record<string, string>> {\n const entries = Object.entries(input ?? {});\n if (entries.length > MAX_TOKENS) {\n throw new TypeError(`signup-control theme supports at most ${MAX_TOKENS} tokens`);\n }\n const tokens: Record<string, string> = {};\n let serializedLength = 0;\n for (const [name, raw] of entries.sort(([left], [right]) => left.localeCompare(right))) {\n if (!TOKEN_NAME.test(name)) {\n throw new TypeError(`signup-control theme token \"${name}\" must be an allowlisted --ui-* property`);\n }\n if ((typeof raw !== \"string\" && typeof raw !== \"number\") ||\n (typeof raw === \"number\" && !Number.isFinite(raw))) {\n throw new TypeError(`signup-control theme token \"${name}\" must be a finite string or number`);\n }\n const value = String(raw).trim();\n if (!value || value.length > MAX_VALUE_LENGTH || UNSAFE_VALUE.test(value)) {\n throw new TypeError(`signup-control theme token \"${name}\" has an unsafe or oversized value`);\n }\n serializedLength += name.length + value.length + 4;\n if (serializedLength > MAX_SERIALIZED_LENGTH) {\n throw new TypeError(\"signup-control theme exceeds the serialized size bound\");\n }\n tokens[name] = value;\n }\n return tokens;\n}\n\nfunction cssFor(tokens: Readonly<Record<string, string>>): string {\n const declarations = Object.entries(tokens).map(([name, value]) => ` ${name}: ${value};`);\n return declarations.length ? `:root {\\n${declarations.join(\"\\n\")}\\n}` : \"\";\n}\n\nfunction stateFor(\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions,\n): { css: string; metadata: SignupControlThemeMetadata } {\n if (!revision) {\n return {\n css: cssFor(validatedTokens(options.bootstrapTokens)),\n metadata: { source: \"bootstrap\", revision: null, digest: null, cacheKey: \"signup-control:bootstrap\" },\n };\n }\n if (!Number.isSafeInteger(revision.revision) || revision.revision < 1 || !DIGEST.test(revision.digest)) {\n throw new TypeError(\"signup-control theme revision metadata is invalid\");\n }\n return {\n css: cssFor(validatedTokens(revision.theme?.tokens)),\n metadata: {\n source: \"active\",\n revision: revision.revision,\n digest: revision.digest,\n cacheKey: `signup-control:${revision.digest}`,\n },\n };\n}\n\nfunction attributes(metadata: SignupControlThemeMetadata): string {\n return [\n `id=\"${SIGNUP_CONTROL_THEME_STYLE_ID}\"`,\n `data-signup-control-source=\"${metadata.source}\"`,\n `data-signup-control-cache-key=\"${metadata.cacheKey}\"`,\n ...(metadata.revision === null ? [] : [`data-signup-control-revision=\"${metadata.revision}\"`]),\n ...(metadata.digest === null ? [] : [`data-signup-control-digest=\"${metadata.digest}\"`]),\n ].join(\" \");\n}\n\n/**\n * Render validated signup-control tokens for the initial HTML head. Passing\n * `null` emits the deterministic local bootstrap state; it never performs I/O.\n */\nexport function renderSignupControlThemeHead(\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions = {},\n): SignupControlThemeHead {\n const { css, metadata } = stateFor(revision, options);\n return { css, metadata, head: `<style ${attributes(metadata)}>${css}</style>` };\n}\n\n/**\n * Replace the stable marker (preferred), an earlier Chapter style block, or the\n * closing head tag. The returned HTML always contains exactly one managed block.\n */\nexport function injectSignupControlThemeHead(\n html: string,\n rendered: SignupControlThemeHead,\n marker: string = SIGNUP_CONTROL_THEME_MARKER,\n): string {\n const existing = /<style\\b(?=[^>]*\\bid\\s*=\\s*[\"']odla-signup-control-theme[\"'])[^>]*>[\\s\\S]*?<\\/style>/gi;\n const existingBlocks = html.match(existing) ?? [];\n if (existingBlocks.length > 1) {\n throw new TypeError(\"signup-control theme style block must appear at most once\");\n }\n if (existingBlocks.length === 1) return html.replace(existing, rendered.head);\n const markerIndex = html.indexOf(marker);\n if (markerIndex >= 0) {\n if (html.indexOf(marker, markerIndex + marker.length) >= 0) {\n throw new TypeError(\"signup-control theme marker must appear exactly once\");\n }\n return `${html.slice(0, markerIndex)}${rendered.head}${html.slice(markerIndex + marker.length)}`;\n }\n const closingHead = html.search(/<\\/head\\s*>/i);\n if (closingHead < 0) throw new TypeError(\"signup-control theme requires an HTML head\");\n return `${html.slice(0, closingHead)}${rendered.head}${html.slice(closingHead)}`;\n}\n\n/**\n * Apply a newly fetched revision to the server-rendered style element. When the\n * revision and digest already match, this performs no writes and returns false,\n * so hydration cannot cause a visual token change.\n */\nexport function hydrateSignupControlTheme(\n target: SignupControlThemeStyleTarget,\n revision: SignupControlThemeRevision | null,\n options: SignupControlThemeOptions = {},\n): boolean {\n const next = stateFor(revision, options);\n const currentSource = target.getAttribute(\"data-signup-control-source\");\n const currentRevision = target.getAttribute(\"data-signup-control-revision\");\n const currentDigest = target.getAttribute(\"data-signup-control-digest\");\n if (currentSource === next.metadata.source &&\n currentRevision === (next.metadata.revision === null ? null : String(next.metadata.revision)) &&\n currentDigest === next.metadata.digest) {\n return false;\n }\n target.textContent = next.css;\n target.setAttribute(\"data-signup-control-source\", next.metadata.source);\n target.setAttribute(\"data-signup-control-cache-key\", next.metadata.cacheKey);\n if (next.metadata.revision === null) target.removeAttribute(\"data-signup-control-revision\");\n else target.setAttribute(\"data-signup-control-revision\", String(next.metadata.revision));\n if (next.metadata.digest === null) target.removeAttribute(\"data-signup-control-digest\");\n else target.setAttribute(\"data-signup-control-digest\", next.metadata.digest);\n return true;\n}\n","import type { MembershipTierPresentation } from \"./membership-page\";\n\n/** A presentation overlay parsed from the constrained membership Markdown convention. */\nexport type MembershipTierMarkdownResult =\n | { ok: true; value: MembershipTierPresentation }\n | { ok: false; errors: readonly string[] };\n\nconst MAX_BENEFITS = 24;\nconst MAX_MARKDOWN = 65_536;\nconst MAX_LABEL = 160;\nconst MARKDOWN_SECTION = /^##\\s+(.+?)\\s*$/;\nconst MARKDOWN_HEADING = /^#{1,6}\\s+/;\nconst MARKDOWN_BENEFIT = /^\\s*[-*+]\\s+(.+?)\\s*$/;\n\ntype MembershipMarkdownSection = \"summary\" | \"benefits\" | \"priceNote\" | \"callout\" | \"action\";\n\nfunction markdownSection(rawHeading: string): { section?: MembershipMarkdownSection; calloutLabel?: string } {\n const heading = rawHeading.trim();\n const normalized = heading.toLowerCase();\n if (normalized === \"summary\") return { section: \"summary\" };\n if (normalized === \"benefits\") return { section: \"benefits\" };\n if (normalized === \"price note\" || normalized === \"rate note\") return { section: \"priceNote\" };\n if (normalized === \"action\" || normalized === \"call to action\") return { section: \"action\" };\n const callout = heading.match(/^callout(?:\\s*[:—-]\\s*(.+))?$/i);\n if (callout) return { section: \"callout\", ...(callout[1]?.trim() ? { calloutLabel: callout[1].trim() } : {}) };\n return {};\n}\n\nfunction markdownBenefits(lines: readonly string[], path: string, errors: string[]): string[] {\n const benefits: string[] = [];\n for (const [index, line] of lines.entries()) {\n if (!line.trim()) continue;\n const match = line.match(MARKDOWN_BENEFIT);\n if (!match) {\n errors.push(`${path} line ${index + 1} must be a Markdown bullet`);\n continue;\n }\n const text = (match[1] ?? \"\").trim();\n if (text.length > 2_000) errors.push(`${path} line ${index + 1} must be at most 2,000 characters`);\n if (text) benefits.push(text);\n }\n if (benefits.length > MAX_BENEFITS) errors.push(`${path} supports at most ${MAX_BENEFITS} entries`);\n return benefits.slice(0, MAX_BENEFITS);\n}\n\n/**\n * Apply authored Markdown to the text slots of an existing tier presentation.\n *\n * The convention is deliberately small and reviewable:\n * - prelude prose -> summary; prelude bullets -> benefits\n * - `## Summary`, `## Benefits`, `## Price note`, `## Callout: Label`,\n * and `## Action` target those exact renderer slots\n *\n * Identity, price, scarcity, variants, badges, links, HTML, and CSS remain in\n * the reviewed presentation/authority contract and cannot be authored here.\n */\nexport function applyMembershipTierMarkdown(\n presentation: MembershipTierPresentation,\n source: string,\n): MembershipTierMarkdownResult {\n if (typeof source !== \"string\") return { ok: false, errors: [\"membership Markdown must be a string\"] };\n if (source.length > MAX_MARKDOWN) {\n return { ok: false, errors: [`membership Markdown must be at most ${MAX_MARKDOWN.toLocaleString(\"en-US\")} characters`] };\n }\n if (!source.trim()) return { ok: true, value: { ...presentation } };\n\n const errors: string[] = [];\n const sections = new Map<MembershipMarkdownSection, { lines: string[]; calloutLabel?: string }>();\n const prelude: string[] = [];\n let current: MembershipMarkdownSection | null = null;\n for (const [index, line] of source.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\").entries()) {\n const heading = line.match(MARKDOWN_SECTION);\n if (heading) {\n const headingText = heading[1] ?? \"\";\n const parsed = markdownSection(headingText);\n if (!parsed.section) {\n errors.push(`membership Markdown heading \"${headingText.trim()}\" is not supported`);\n current = null;\n continue;\n }\n if (sections.has(parsed.section)) {\n errors.push(`membership Markdown repeats the ${parsed.section} section`);\n current = parsed.section;\n continue;\n }\n sections.set(parsed.section, { lines: [], ...(parsed.calloutLabel ? { calloutLabel: parsed.calloutLabel } : {}) });\n current = parsed.section;\n continue;\n }\n if (MARKDOWN_HEADING.test(line)) {\n errors.push(`membership Markdown line ${index + 1} uses an unsupported heading`);\n continue;\n }\n if (current) sections.get(current)?.lines.push(line);\n else prelude.push(line);\n }\n\n const preludeBenefits: string[] = [];\n const preludeSummary: string[] = [];\n for (const line of prelude) {\n const benefit = line.match(MARKDOWN_BENEFIT);\n if (benefit) preludeBenefits.push((benefit[1] ?? \"\").trim());\n else preludeSummary.push(line);\n }\n if (preludeBenefits.length > MAX_BENEFITS) errors.push(`membership Markdown prelude supports at most ${MAX_BENEFITS} benefits`);\n if (preludeBenefits.some((benefit) => benefit.length > 2_000)) errors.push(\"membership Markdown benefits must be at most 2,000 characters\");\n\n const summarySection = sections.get(\"summary\");\n const benefitsSection = sections.get(\"benefits\");\n const priceNoteSection = sections.get(\"priceNote\");\n const calloutSection = sections.get(\"callout\");\n const actionSection = sections.get(\"action\");\n const summaryMarkdown = (summarySection?.lines ?? preludeSummary).join(\"\\n\").trim();\n const benefits = benefitsSection\n ? markdownBenefits(benefitsSection.lines, \"membership Markdown Benefits\", errors)\n : preludeBenefits.filter(Boolean).slice(0, MAX_BENEFITS);\n const priceNoteMarkdown = priceNoteSection?.lines.join(\"\\n\").trim();\n const calloutBody = calloutSection?.lines.join(\"\\n\").trim();\n const actionLines = actionSection?.lines.filter((line) => line.trim());\n const ctaLabel = actionLines?.join(\" \").trim();\n if (actionLines && actionLines.length !== 1) errors.push(\"membership Markdown Action must contain exactly one line\");\n if (ctaLabel && ctaLabel.length > MAX_LABEL) errors.push(`membership Markdown Action must be at most ${MAX_LABEL} characters`);\n if (calloutSection && !calloutBody) errors.push(\"membership Markdown Callout must include body copy\");\n if (calloutSection?.calloutLabel && calloutSection.calloutLabel.length > MAX_LABEL) {\n errors.push(`membership Markdown Callout label must be at most ${MAX_LABEL} characters`);\n }\n if (errors.length) return { ok: false, errors };\n\n return {\n ok: true,\n value: {\n ...presentation,\n ...(summaryMarkdown ? { summaryMarkdown } : {}),\n ...(benefitsSection || preludeBenefits.length ? { benefits } : {}),\n ...(priceNoteSection ? { priceNoteMarkdown: priceNoteMarkdown ?? \"\" } : {}),\n ...(calloutSection ? {\n callout: {\n ...(calloutSection.calloutLabel || presentation.callout?.label\n ? { label: calloutSection.calloutLabel ?? presentation.callout?.label }\n : {}),\n bodyMarkdown: calloutBody ?? \"\",\n },\n } : {}),\n ...(actionSection && ctaLabel ? { ctaLabel } : {}),\n },\n };\n}\n\n/** Apply constrained membership Markdown or fail closed with actionable errors. */\nexport function membershipTierPresentationFromMarkdown(\n presentation: MembershipTierPresentation,\n source: string,\n): MembershipTierPresentation {\n const result = applyMembershipTierMarkdown(presentation, source);\n if (!result.ok) throw new TypeError(`Invalid membership Markdown: ${result.errors.join(\"; \")}`);\n return result.value;\n}\n","import {\n canonicalPromotionValue,\n type PromotionAdapterResult,\n type PromotionArtifactInput,\n type PromotionExclusion,\n} from \"@odla-ai/promotion\";\nimport { signupControlDigest } from \"./signup-control-canonical\";\nimport type { SignupControlDocument } from \"./signup-control-contract\";\nimport { validateSignupControlDocument } from \"./signup-control-validate\";\n\n/** Stable adapter identity bound into Chapter artifact provenance. */\nexport const CHAPTER_PROMOTION_ADAPTER = \"@odla-ai/chapter/v1\";\n\n/** One exact, digest-verified signup-control revision to export. */\nexport interface ChapterPromotionInput {\n document: SignupControlDocument;\n digest: string;\n}\n\nconst exclusions = (chapterId: string, paidTierIds: string[]): PromotionExclusion[] => [\n {\n kind: \"chapter.providers\", id: chapterId, reason: \"provider_identity\",\n paths: [\n ...paidTierIds.map((id) => `tiers[${id}].stripePriceId`),\n \"groups.stripePublishableKey\", \"applications.stripeCustomerId\",\n \"applications.stripeSubscriptionId\", \"meetings.googleEventId\",\n ],\n detail: \"Stripe, Clerk, and Google identities are resolved independently in each target environment.\",\n },\n {\n kind: \"chapter.runtime\", id: chapterId, reason: \"runtime_state\",\n paths: [\"applications.*\", \"meetings.*\", \"emailLog.*\", \"crm_*.*\"],\n detail: \"Applicants, meetings, messages, and CRM rows are operational state, not managed signup content.\",\n },\n {\n kind: \"chapter.access\", id: chapterId, reason: \"personal_data\",\n paths: [\"admins.*\", \"superAdmins.*\", \"networkNotes.*\"],\n detail: \"People, access lists, and private network notes remain local to the target environment.\",\n },\n {\n kind: \"chapter.history\", id: chapterId, reason: \"authority_history\",\n paths: [\"signupControls[active=false]\", \"signupControls.*At\", \"signupControls.environment\", \"signupControlHeads.*\"],\n detail: \"The source retains immutable delivery history; only selected published content is exported.\",\n },\n];\n\n/** Export the provider-independent pieces of one exact active signup revision. */\nexport async function exportChapterPromotion(input: ChapterPromotionInput): Promise<PromotionAdapterResult> {\n if (!/^sha256:[0-9a-f]{64}$/.test(input.digest)) throw new TypeError(\"chapter promotion digest is invalid\");\n const checked = validateSignupControlDocument(input.document);\n if (!checked.ok) throw new TypeError(checked.errors.join(\"; \"));\n const document = checked.value;\n if (await signupControlDigest(document) !== input.digest) throw new TypeError(\"chapter promotion digest does not match its document\");\n const revision = `chapter:${document.target.chapterId}:${document.revision}`;\n const promotionProvenance = {\n adapter: CHAPTER_PROMOTION_ADAPTER,\n sourceIds: [`signup-control:${document.revision}`, document.source.appId, document.target.chapterId].sort(),\n receiptDigests: [input.digest as `sha256:${string}`],\n };\n const artifact = (kind: string, id: string, content: unknown): PromotionArtifactInput => ({\n kind, id, sourceRevision: revision, provenance: promotionProvenance,\n content: canonicalPromotionValue(content),\n });\n const chapterId = document.target.chapterId;\n const artifacts = [\n artifact(\"chapter.catalog\", chapterId, {\n chapterId,\n tiers: document.tiers.map(({ stripePriceId: _providerId, ...tier }) => tier),\n }),\n artifact(\"chapter.membership-page\", chapterId, document.membershipPage),\n ...(document.application ? [artifact(\"chapter.application\", chapterId, document.application)] : []),\n ...(document.policy ? [artifact(\"chapter.policy\", chapterId, document.policy)] : []),\n ...(document.scheduling ? [artifact(\"chapter.scheduling\", chapterId, document.scheduling)] : []),\n ...(document.theme ? [artifact(\"chapter.theme\", chapterId, document.theme)] : []),\n ];\n return {\n adapter: CHAPTER_PROMOTION_ADAPTER,\n artifacts,\n exclusions: exclusions(chapterId, document.tiers.filter((tier) => tier.stripePriceId).map((tier) => tier.id)),\n preconditions: [\n {\n code: \"chapter.signup-control.schema\", path: \"services.chapter.signupControl.schemaVersion\", expected: document.schemaVersion,\n detail: \"The target must support this Chapter signup-control document version.\",\n },\n {\n code: \"chapter.identity\", path: \"app.appId\", expected: chapterId,\n detail: \"Chapter content can only target the chapter named by the signed source revision.\",\n },\n ],\n };\n}\n","/** Logical aggregate boundary, not a requirement for a separate database/app. */\nexport type MemberSystemScope = \"network\" | \"chapter\" | \"provider\";\n\n/** Business ownership is independent of the reusable command implementation.\n * Network records live in BNF's existing odla database. Protected platform roles\n * are not business records and remain writable only by odla administration.\n */\nexport const MEMBER_SYSTEM_RECORD_OWNERS = {\n network: \"built-not-found\",\n chapter: \"owning-chapter\",\n provider: \"originating-provider\",\n protectedRoles: \"odla-platform\",\n} as const;\n\n/** Durable authority allowed to write a member-system field. */\nexport type MemberSystemWriter =\n | \"network_person\"\n | \"chapter_journey\"\n | \"network_membership\"\n | \"network_entitlement\"\n | \"network_seat\"\n | \"network_discount_policy\"\n | \"network_referral_ledger\"\n | \"network_investment_ledger\"\n | \"network_commercial_projection\"\n | \"clerk\"\n | \"stripe\";\n\n/** Read model that may receive an allowlisted field. */\nexport type MemberSystemProjection =\n | \"bnf_admin\"\n | \"chapter_admin\"\n | \"chapter_crm\"\n | \"member_self_service\"\n | \"stripe_billing\"\n | \"clerk_identity\";\n\n/** Privacy classification used by projection policy. */\nexport type MemberFieldSensitivity = \"ordinary\" | \"pii\" | \"sensitive\" | \"restricted\";\n/** Access a member has to her own projected field. */\nexport type MemberFieldSelfAccess = \"edit\" | \"read\" | \"none\";\n\n/** One field's scope, writer, projections, sensitivity, and self-service access. */\nexport interface MemberFieldAuthority {\n id: string;\n scope: MemberSystemScope;\n writer: MemberSystemWriter;\n projections: readonly MemberSystemProjection[];\n sensitivity: MemberFieldSensitivity;\n memberAccess: MemberFieldSelfAccess;\n}\n\ninterface AuthorityGroup extends Omit<MemberFieldAuthority, \"id\"> { fields: readonly string[] }\nconst rows = (group: AuthorityGroup): MemberFieldAuthority[] => group.fields.map((id) => ({ ...group, id }));\n\n/** Each field has one aggregate command writer. BNF owns network aggregates and\n * hosts their server commands; bnf_admin names a read projection, not a credential.\n */\nexport const MEMBER_SYSTEM_AUTHORITY_MATRIX: readonly MemberFieldAuthority[] = [\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"pii\", memberAccess: \"edit\",\n fields: [\n \"person.legalName\", \"person.preferredName\", \"person.namePronunciation\", \"person.pronouns\",\n \"person.displayLegalName\", \"person.primaryEmail\", \"person.secondaryEmails\", \"person.phone\",\n \"person.linkedinUrl\", \"person.photo\", \"person.homeAddress\", \"person.fulfillmentFit\", \"person.fulfillmentSize\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"edit\",\n fields: [\n \"person.title\", \"person.company\", \"person.companyObservedAt\", \"person.region\", \"person.whyText\",\n \"person.whyTokens\", \"person.skillsOffered\", \"person.openToRequests\", \"person.directoryPhotoConsent\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"person.linkedinMemberId\", \"person.identityClaims\", \"person.aliases\", \"person.mergeHistory\",\n \"person.introducedByPersonId\", \"person.introducedAt\", \"person.firstTouch\", \"person.globalSuppression\",\n \"person.deceasedAt\", \"person.archivedAt\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"sensitive\", memberAccess: \"edit\",\n fields: [\"person.accreditationSelfCertification\", \"person.accreditationCategory\", \"person.accreditationExpiresAt\"],\n }),\n ...rows({\n scope: \"network\", writer: \"network_person\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"restricted\", memberAccess: \"read\", fields: [\"person.acknowledgements\"],\n }),\n ...rows({\n scope: \"provider\", writer: \"clerk\", projections: [\"clerk_identity\", \"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\"identity.clerkUserIds\", \"identity.clerkEmailVerification\"],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\", \"bnf_admin\"],\n sensitivity: \"ordinary\", memberAccess: \"none\",\n fields: [\n \"journey.chapterId\", \"journey.stage\", \"journey.stageEnteredAt\", \"journey.stageHistory\",\n \"journey.ending\", \"journey.endingReason\", \"journey.source\", \"journey.entryChapterId\",\n \"journey.route\", \"journey.flags\", \"journey.applicationStartedAt\", \"journey.appliedAt\",\n \"journey.paidAt\", \"journey.callBookedAt\", \"journey.metAt\", \"journey.approvedAt\",\n \"journey.onboardedAt\", \"journey.firstLoginAt\", \"journey.firstDealAt\",\n ],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\"],\n sensitivity: \"sensitive\", memberAccess: \"none\",\n fields: [\n \"journey.relationshipOwnerId\", \"journey.lastContactAt\", \"journey.nextAction\", \"journey.owes\",\n \"journey.asks\", \"journey.preparation\", \"journey.notes\",\n ],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"chapter_crm\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"edit\",\n fields: [\"journey.dealFlowConsent\", \"journey.directoryConsent\", \"journey.emailConsent\", \"journey.smsConsent\"],\n }),\n ...rows({\n scope: \"chapter\", writer: \"chapter_journey\", projections: [\"chapter_admin\", \"bnf_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\", fields: [\"journey.memberNumber\"],\n }),\n ...rows({\n scope: \"network\", writer: \"network_membership\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"membership.chapterId\", \"membership.journeyId\", \"membership.termStartsAt\", \"membership.termEndsAt\",\n \"membership.tier\", \"membership.status\", \"membership.joinedAt\", \"membership.autoRenews\",\n \"membership.renewalAt\", \"membership.cancelsAt\", \"membership.graceEndsAt\", \"membership.foundingCohort\",\n \"membership.offeringPolicyVersion\", \"membership.discountPolicyVersion\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_commercial_projection\", projections: [\"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"membership.stripeCustomerId\", \"membership.stripeSubscriptionId\", \"membership.stripePriceId\",\n \"membership.lastInvoiceId\", \"membership.paymentOutcome\", \"membership.refundOutcome\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_discount_policy\", projections: [\"bnf_admin\", \"chapter_admin\", \"stripe_billing\"],\n sensitivity: \"ordinary\", memberAccess: \"none\",\n fields: [\n \"discountPolicy.chapterId\", \"discountPolicy.version\", \"discountPolicy.eligibleOfferingIds\",\n \"discountPolicy.percentOff\", \"discountPolicy.amountOff\", \"discountPolicy.activatesOn\",\n \"discountPolicy.invoiceCount\", \"discountPolicy.expiresAt\", \"discountPolicy.stackingOrder\",\n \"discountPolicy.status\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_entitlement\",\n projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\", \"stripe_billing\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"entitlement.membershipId\", \"entitlement.kind\", \"entitlement.priceCents\", \"entitlement.currency\",\n \"entitlement.payerPersonId\", \"entitlement.purchasedAt\", \"entitlement.termEndsAt\",\n \"entitlement.renewsWithMembership\", \"entitlement.status\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_seat\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"pii\", memberAccess: \"read\",\n fields: [\n \"seat.membershipId\", \"seat.entitlementId\", \"seat.personId\", \"seat.recipientName\", \"seat.recipientEmail\",\n \"seat.role\", \"seat.status\", \"seat.acceptanceExpiresAt\", \"seat.acceptedAt\", \"seat.activatedAt\", \"seat.refundedAt\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_referral_ledger\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"ordinary\", memberAccess: \"read\",\n fields: [\n \"referral.referrerPersonId\", \"referral.referredPersonId\", \"referral.qualifiedMembershipId\",\n \"referral.creditCents\", \"referral.status\", \"referral.appliedInvoiceId\", \"referral.carryForwardCents\",\n \"referral.adjustmentOf\",\n ],\n }),\n ...rows({\n scope: \"network\", writer: \"network_investment_ledger\", projections: [\"bnf_admin\", \"chapter_admin\", \"member_self_service\"],\n sensitivity: \"restricted\", memberAccess: \"read\",\n fields: [\n \"investment.personId\", \"investment.chapterId\", \"investment.season\", \"investment.purpose\",\n \"investment.targetCount\", \"investment.status\", \"investment.amountCents\", \"investment.closedAt\",\n \"investment.sourceReference\",\n ],\n }),\n ...rows({\n scope: \"provider\", writer: \"stripe\", projections: [\"stripe_billing\", \"bnf_admin\", \"chapter_admin\"],\n sensitivity: \"restricted\", memberAccess: \"none\",\n fields: [\n \"commercial.charge\", \"commercial.invoice\", \"commercial.refund\", \"commercial.providerSubscription\",\n \"commercial.paymentMethod\",\n ],\n }),\n];\n\n/** Fields a member may change through self-service. */\nexport const MEMBER_SELF_EDITABLE_FIELDS = new Set(\n MEMBER_SYSTEM_AUTHORITY_MATRIX.filter((row) => row.memberAccess === \"edit\").map((row) => row.id),\n);\n/** Fields that may appear in a member self-service response. */\nexport const MEMBER_SELF_READABLE_FIELDS = new Set(\n MEMBER_SYSTEM_AUTHORITY_MATRIX.filter((row) => row.memberAccess !== \"none\").map((row) => row.id),\n);\n\n/** Serialize only the explicit member self-service allowlist. */\nexport function projectMemberSelf(record: Readonly<Record<string, unknown>>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(record).filter(([field]) => MEMBER_SELF_READABLE_FIELDS.has(field)));\n}\n\n/** Proposed field mutation with optimistic-revision evidence. */\nexport interface MemberSystemWriteIntent {\n field: string;\n actor: MemberSystemWriter | \"bnf\";\n expectedRevision: number;\n actualRevision: number;\n}\n/** Result of checking a proposed mutation against surface, writer, and revision rules. */\nexport type MemberSystemWriteDisposition =\n | \"apply\" | \"reject_bnf_surface\" | \"reject_unknown_field\" | \"reject_wrong_writer\" | \"reject_stale_revision\";\n\n/** Validate an aggregate command, not a user's authorization. A bare BNF surface\n * label is still insufficient: its backend must select the field's specific\n * writer after authenticating and authorizing the caller. This helper cannot\n * constrain an unrestricted database credential or grant protected platform roles.\n */\nexport function classifyMemberSystemWrite(intent: MemberSystemWriteIntent): MemberSystemWriteDisposition {\n if (intent.actor === \"bnf\") return \"reject_bnf_surface\";\n const authority = MEMBER_SYSTEM_AUTHORITY_MATRIX.find((row) => row.id === intent.field);\n if (!authority) return \"reject_unknown_field\";\n if (authority.writer !== intent.actor) return \"reject_wrong_writer\";\n if (intent.expectedRevision !== intent.actualRevision) return \"reject_stale_revision\";\n return \"apply\";\n}\n\n/** Result of validating an authority matrix. */\nexport interface MemberAuthorityValidation { ok: boolean; errors: string[] }\n/** Validate uniqueness, self-service projection, and aggregate scope invariants. */\nexport function validateMemberSystemAuthority(\n matrix: readonly MemberFieldAuthority[] = MEMBER_SYSTEM_AUTHORITY_MATRIX,\n): MemberAuthorityValidation {\n const errors: string[] = [];\n const ids = new Set<string>();\n for (const row of matrix) {\n if (!row.id || !row.id.includes(\".\")) errors.push(`invalid field id \"${row.id}\"`);\n if (ids.has(row.id)) errors.push(`duplicate field authority \"${row.id}\"`);\n ids.add(row.id);\n if (row.memberAccess !== \"none\" && !row.projections.includes(\"member_self_service\")) {\n errors.push(`${row.id} grants member access without a member_self_service projection`);\n }\n if (row.id.startsWith(\"person.\") && (row.scope !== \"network\" || row.writer !== \"network_person\")) {\n errors.push(`${row.id} must be network_person authority`);\n }\n if (row.id.startsWith(\"journey.\") && (row.scope !== \"chapter\" || row.writer !== \"chapter_journey\")) {\n errors.push(`${row.id} must be chapter_journey authority`);\n }\n }\n return { ok: errors.length === 0, errors };\n}\n","/** Provider-free lifecycle contract for the network member system. */\nexport const MEMBER_SYSTEM_CONTRACT_VERSION = 1 as const;\nexport * from \"./member-system-authority\";\n\n/** Ordered chapter Journey stages from first identification through first deal. */\nexport const JOURNEY_STAGES = [\n \"identified\", \"researched\", \"outreach\", \"in_conversation\", \"invited_or_requested\",\n \"application_started\", \"applied\", \"paid_awaiting_conversation\", \"ready_to_book\", \"booked\",\n \"met\", \"approved\", \"onboarded\", \"active\", \"first_deal\",\n] as const;\n/** A chapter Journey stage. */\nexport type JourneyStage = typeof JOURNEY_STAGES[number];\n\n/** Terminal Journey outcomes; refunds remain commercial events. */\nexport const JOURNEY_ENDINGS = [\"passed\", \"declined\", \"withdrew\", \"lapsed\"] as const;\n/** A terminal chapter Journey outcome. */\nexport type JourneyEnding = typeof JOURNEY_ENDINGS[number];\n\n/** Required notice categories that may bypass discretionary contact suppression. */\nexport const REQUIRED_NOTICE_KINDS = [\n \"payment_receipt\", \"refund_confirmation\", \"security_alert\", \"legal_notice\",\n \"membership_status\", \"renewal_notice\", \"cancellation_confirmation\",\n] as const;\n/** A typed required notice allowed despite discretionary contact suppression. */\nexport type RequiredNoticeKind = typeof REQUIRED_NOTICE_KINDS[number];\n\n/** Availability inputs distinguish BNF's browser UI, authority backend and odla. */\nexport interface MemberSystemAvailabilityInput {\n odlaReachable: boolean;\n bnfFrontendReachable: boolean;\n /** Explicit backend health is required; unknown is not evidence of readiness. */\n bnfBackendReachable: boolean;\n}\n/** Capabilities allowed at the current BNF and odla availability state. */\nexport interface MemberSystemAvailability {\n bnfAdministration: boolean;\n chapterWorkflow: boolean;\n memberSelfService: boolean;\n newApplication: boolean;\n newCheckout: boolean;\n providerRenewalsMayContinue: true;\n reason?: \"odla_unavailable\" | \"bnf_backend_unavailable\" | \"bnf_frontend_unavailable\";\n}\n\n/** Only BNF's frontend is optional for dependent chapter execution. */\nexport function memberSystemAvailability(input: MemberSystemAvailabilityInput): MemberSystemAvailability {\n if (!input.odlaReachable || input.bnfBackendReachable !== true) {\n return {\n bnfAdministration: false,\n chapterWorkflow: false,\n memberSelfService: false,\n newApplication: false,\n newCheckout: false,\n providerRenewalsMayContinue: true,\n reason: !input.odlaReachable ? \"odla_unavailable\" : \"bnf_backend_unavailable\",\n };\n }\n return {\n bnfAdministration: input.bnfFrontendReachable,\n chapterWorkflow: true,\n memberSelfService: true,\n newApplication: true,\n newCheckout: true,\n providerRenewalsMayContinue: true,\n ...(!input.bnfFrontendReachable ? { reason: \"bnf_frontend_unavailable\" as const } : {}),\n };\n}\n\n/** Partition metadata supplied by a verified Stripe event. */\nexport interface MemberStripeIdentity {\n appId?: string;\n environment?: string;\n dataEnvironment?: string;\n runtime?: string;\n chapterId?: string;\n}\n/** Exact app, environment, runtime, and chapter partition expected by a consumer. */\nexport interface MemberStripeTarget {\n appId: string;\n environment: string;\n dataEnvironment: string;\n runtime: string;\n chapterId: string;\n}\n/** Safe handling of a verified Stripe event after partition checks. */\nexport type MemberStripeDisposition = \"apply\" | \"apply_legacy\" | \"ignore_sibling\" | \"quarantine_unmatched\";\n\n/** Partition verified Stripe events before any lookup or write. */\nexport function classifyMemberStripeEvent(\n identity: MemberStripeIdentity,\n target: MemberStripeTarget,\n hasProvenLegacyLocalLink: boolean,\n): MemberStripeDisposition {\n const keys = [\"appId\", \"environment\", \"dataEnvironment\", \"runtime\", \"chapterId\"] as const;\n const supplied = keys.filter((key) => identity[key] !== undefined);\n if (supplied.some((key) => identity[key] !== target[key])) return \"ignore_sibling\";\n if (supplied.length === keys.length) return \"apply\";\n return hasProvenLegacyLocalLink ? \"apply_legacy\" : \"quarantine_unmatched\";\n}\n\n/** Stable provider-event identity and content digest used for replay. */\nexport interface MemberSystemEventReceiptInput { id: string; digest: string }\n/** Accepted, duplicate, and colliding provider-event identifiers. */\nexport interface MemberSystemEventReplayPlan {\n accepted: string[];\n replayed: string[];\n collisions: string[];\n}\n/** Plan provider-event replay by stable identifier and digest. */\nexport function planMemberSystemEventReplay(\n events: readonly MemberSystemEventReceiptInput[],\n): MemberSystemEventReplayPlan {\n const seen = new Map<string, string>();\n const plan: MemberSystemEventReplayPlan = { accepted: [], replayed: [], collisions: [] };\n for (const event of events) {\n const digest = seen.get(event.id);\n if (digest === undefined) {\n seen.set(event.id, event.digest);\n plan.accepted.push(event.id);\n } else if (digest === event.digest) plan.replayed.push(event.id);\n else plan.collisions.push(event.id);\n }\n return plan;\n}\n\n/** Fail-closed and replay targets for restoring the member-system projection. */\nexport interface MemberSystemRecoveryObjectives {\n failClosedWithinMs: 0;\n replayProjectionWithinMinutes: number;\n providerEventsRemainReplayable: true;\n requireHumanReviewForCollision: true;\n}\n/** Accepted recovery objectives for the first rollout. */\nexport const MEMBER_SYSTEM_RECOVERY_OBJECTIVES: MemberSystemRecoveryObjectives = {\n failClosedWithinMs: 0,\n replayProjectionWithinMinutes: 15,\n providerEventsRemainReplayable: true,\n requireHumanReviewForCollision: true,\n};\n\n/** Candidate legacy or external row considered for migration. */\nexport interface MemberSystemMigrationRow {\n id: string;\n source: \"silver_salt_current\" | \"external_reimport\" | \"synthetic_fixture\";\n isRealPerson: boolean;\n provenance?: string;\n}\n/** Import, fixture-only, and rejected row identifiers. */\nexport interface MemberSystemMigrationPlan {\n importIds: string[];\n fixtureIds: string[];\n rejectedIds: string[];\n}\n\n/** Existing Silver & Salt rows never migrate; external real contacts need provenance. */\nexport function planMemberSystemMigration(rows: readonly MemberSystemMigrationRow[]): MemberSystemMigrationPlan {\n const plan: MemberSystemMigrationPlan = { importIds: [], fixtureIds: [], rejectedIds: [] };\n for (const row of rows) {\n if (row.source === \"synthetic_fixture\" && !row.isRealPerson) plan.fixtureIds.push(row.id);\n else if (row.source === \"external_reimport\" && row.isRealPerson && row.provenance) plan.importIds.push(row.id);\n else plan.rejectedIds.push(row.id);\n }\n return plan;\n}\n\n/** Non-destructive actions used to stop and reconcile the rollout. */\nexport interface MemberSystemRollbackPlan {\n stopNetworkWrites: true;\n disableBnfMemberMutations: true;\n keepChapterProductionReads: true;\n keepStripeBillingAuthority: true;\n deleteProviderObjects: false;\n reverseProviderPayments: false;\n reconciliationRequired: true;\n}\n/** Produce the non-destructive rollback contract. */\nexport function memberSystemRollbackPlan(): MemberSystemRollbackPlan {\n return {\n stopNetworkWrites: true,\n disableBnfMemberMutations: true,\n keepChapterProductionReads: true,\n keepStripeBillingAuthority: true,\n deleteProviderObjects: false,\n reverseProviderPayments: false,\n reconciliationRequired: true,\n };\n}\n\n/** Synthetic-only inventory. Counts describe current development rows, not members. */\nexport const SILVER_SALT_P0_FIXTURE = {\n sourceInventory: { applications: 36, meetings: 7, emails: 49, realPeople: 0 },\n application: { id: \"fixture_application_001\", personId: \"fixture_person_001\", migrates: false },\n crm: { recordId: \"fixture_crm_001\", email: \"fixture.member@example.invalid\", migrates: false },\n clerk: { userId: \"user_fixture_001\", verifiedEmail: \"fixture.member@example.invalid\", migrates: false },\n stripe: {\n customerId: \"cus_fixture_001\",\n subscriptionId: \"sub_fixture_001\",\n productId: \"prod_fixture_001\",\n priceId: \"price_fixture_001\",\n eventId: \"evt_fixture_001\",\n migrates: false,\n },\n unmatchedStripeEvent: { id: \"evt_fixture_unmatched\", disposition: \"quarantine_unmatched\" },\n legacyStripeEvent: { id: \"evt_fixture_legacy\", requiresProvenLocalLink: true },\n} as const;\n","import type { ChapterDb } from \"./types\";\nimport { membershipAuthorityEntities, membershipAuthorityRules } from \"./schema-membership-authority\";\nimport { membershipOfferEntities, membershipOfferRules } from \"./schema-membership-offers\";\n\n/** Separate authoritative collections inside the network owner's EXISTING database.\n * Legacy networkMembership/networkEntitlement/networkSeat remain shadow/rollback\n * data. This mapping never migrates, copies, or promotes their contents.\n */\nexport const MEMBERSHIP_AUTHORITY_COLLECTIONS = {\n networkMembership: \"membershipRecord\",\n networkEntitlement: \"membershipEntitlement\",\n networkSeat: \"membershipSeat\",\n} as const;\nconst physical = (ns: string): string => Object.hasOwn(MEMBERSHIP_AUTHORITY_COLLECTIONS, ns)\n ? MEMBERSHIP_AUTHORITY_COLLECTIONS[ns as keyof typeof MEMBERSHIP_AUTHORITY_COLLECTIONS] : ns;\nconst writable = new Set([...Object.keys(membershipAuthorityEntities), ...Object.keys(membershipOfferEntities)]);\nconst readable = new Set([...writable, \"membershipOfferingVersion\", \"discountPolicyVersion\",\n \"networkCommercialEvents\", \"networkCommercialExceptions\"]);\nconst check = (ns: string, allowed: Set<string>) => {\n if (!allowed.has(ns)) throw new TypeError(\"namespace outside membership authority contract\");\n return physical(ns);\n};\n\n/** Additive, deny-all descriptor. Compose once in BNF alongside its existing\n * policy and commercial integrations, never in each chapter. No activation seeds:\n * a reviewed authority-state command must explicitly enable a chapter afterward.\n */\nexport function createMembershipAuthorityIntegration() {\n return {\n id: \"chapter-membership-authority\",\n title: \"Network membership authority in the owner database\",\n npm: \"@odla-ai/chapter\",\n schema: { entities: Object.fromEntries(Object.entries({ ...membershipAuthorityEntities, ...membershipOfferEntities })\n .map(([ns, entity]) => [physical(ns), entity])), links: {} },\n rules: Object.fromEntries(Object.entries({ ...membershipAuthorityRules, ...membershipOfferRules })\n .map(([ns, rule]) => [physical(ns), rule])),\n seeds: [],\n };\n}\n\n/** Bind reusable authority commands to their isolated collections in BNF's\n * existing database. Remaps operations AND revision guards in one transaction;\n * allows policy/provider evidence reads but no writes to those or role tables.\n * Only named vault slots are exposed. This is defense against accidental command\n * misuse, NOT isolation from a compromised host holding the underlying app key.\n */\nexport function createMembershipAuthorityStorage(db: ChapterDb, secretNames: readonly string[]): ChapterDb {\n const secrets = new Set(secretNames);\n return {\n async query(query) {\n const entries = Object.entries(query);\n const mapped = Object.fromEntries(entries.map(([ns, spec]) => {\n // Authority queries are flat. Do not permit relation traversal to escape\n // this contract via nested namespace names.\n if (!spec || typeof spec !== \"object\" || Array.isArray(spec) || Object.keys(spec).some(key => key !== \"$\")) {\n throw new TypeError(\"membership authority queries must be flat\");\n }\n return [check(ns, readable), spec];\n }));\n const result = await db.query(mapped);\n return Object.fromEntries(entries.map(([ns]) => [ns, result[physical(ns)] ?? []]));\n },\n async transact(ops, opts) {\n const mapped = ops.map(op => ({ ...op, ns: check(op.ns, writable),\n id: typeof op.id === \"string\" ? op.id : { ...op.id, ns: check(op.id.ns, writable) } }));\n const guards = opts?.guards?.map(guard => ({ ...guard, ns: check(guard.ns, readable) }));\n return db.transact(mapped, { ...opts, ...(guards ? { guards } : {}) });\n },\n secrets: { get(name) {\n if (!secrets.has(name)) return Promise.reject(new TypeError(\"vault slot outside membership authority contract\"));\n return db.secrets.get(name);\n } },\n };\n}\n"],"mappings":";AAEA,SAAS,iBAAiB;;;ACCnB,IAAM,uBAA+B,EAAE,OAAO;AAAA,EACnD,IAAI,EAAE,MAAM,UAAU,QAAQ,MAAM,SAAS,MAAM,UAAU,MAAM;AAAA,EACnE,UAAU,EAAE,MAAM,UAAU,QAAQ,OAAO,SAAS,OAAO,UAAU,MAAM;AAAA,EAC3E,OAAO,EAAE,MAAM,QAAQ,QAAQ,OAAO,SAAS,OAAO,UAAU,MAAM;AACxE,EAAE;;;ACDF,SAAS,sBAAsB,0BAA0B;;;ACDzD,IAAM,wBAAwB;AAQ9B,eAAsB,2BAA2B,cAAuC;AACtF,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,GAAG,qBAAqB,GAAG,YAAY,EAAE;AAChF,QAAM,QAAQ,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC,EAAE,MAAM,GAAG,EAAE;AACtF,QAAM,CAAC,IAAK,MAAM,CAAC,IAAK,KAAQ;AAChC,QAAM,CAAC,IAAK,MAAM,CAAC,IAAK,KAAQ;AAChC,QAAM,MAAM,CAAC,GAAG,KAAK,EAAE,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAChF,SAAO,GAAG,IAAI,MAAM,GAAG,CAA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OAAO;AAAA,IACP,KAAK;AAAA,IACL,QAAQ,EAAE,UAAU,OAAO,YAAY,OAAO,QAAQ,EAAE,GAAG,6BAA6B,GAAG,wBAAwB,CAAC,EACjH,IAAI,CAAC,CAAC,IAAI,MAAM,MAAM,CAAC,SAAS,EAAE,GAAG,MAAM,CAAC,CAAC,GAAG,OAAO,CAAC,EAAE;AAAA,IAC7D,OAAO,OAAO,YAAY,OAAO,QAAQ,EAAE,GAAG,0BAA0B,GAAG,qBAAqB,CAAC,EAC9F,IAAI,CAAC,CAAC,IAAI,IAAI,MAAM,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;AAAA,IAC5C,OAAO,CAAC;AAAA,EACV;AACF;","names":["index","key","allowed","id","row","paymentsReady","tiers","attr","attr","attr","id","attr","id","string","number","json","id","attr","attr","id","row","superAdmins","raw","status","key","id","text","order","DEFAULT_REQUIRED","DEFAULT_OPTIONAL","index","index","readable","SLUG","id","SLUG","SLUG","SLUG","SECRET_NAME","SLUG","index","SLUG","id","key","raw","object","key","identityKeys","status","facts","exceptions","keys","row","rows","rows","row","groups","object","id","projection","exceptions","key","text","encoder","key","row","selected","record","exceptions","index","rows","tiers","fail","id","integer","id","key","row","rows","policy","reject","load","id","row","key","id","key","row","key","id","id","stripeRequest","id","providerId","fail","key","invoice","id","stripeRequest","id","key","status","row","key","id","saved","stripeRequest","status","id","allowed","row","id","stripeRequest","stripeRequest","stripeRequest","reject","key","stripeRequest","couponId","item","row","key","status","status","stripeRequest","fail","stripeRequest","key","row","key","id","key","key","status","key","text","row","row","key","requestNamedSeatRefund","reject","stripeRequest","stripeRequest","matches","row","key","id","scope","matches","row","key","status","attr","id","attr","id","key","SLUG","allowed","key","tiers","raw","ids","index","raw","id","SLUG","order","value","tiers","record","key","ID","MAX_MARKDOWN","MAX_TEXT","ROOT_KEYS","SOURCE_KEYS","TARGET_KEYS","record","unknownKeys","allowed","key","text","integer","raw","id","status","scope","index","ids","encoder","canonicalValue","record","key","key","row","text","emailLog","hash","id","row","str","row","encoder","canonicalValue","record","key","rows","ID","EMAIL_RE","index","raw","id","row","scope","ID","record","text","key","ids","index","raw","allowed","id","createRecord","updateRecord","id","record","readable","raw","record","key","updateRecord","createRecord","updateRecord","setStage","record","status","updateRecord","setStage","key","index","stripeRequest","verifyStripeSignature","stripeRequest","id","body","id","record","id","ids","role","key","meetings","events","row","rows","ROOT_KEYS","MAX_MARKDOWN","allowed","key","text","tiers","index","raw","SLUG","PRICE","ROOT_KEYS","TIER_KEYS","unknownKeys","allowed","key","text","raw","index","id","tiers","DIGEST","raw","MAX_BENEFITS","MAX_MARKDOWN","MAX_LABEL","index","text","id","rows","id","row","record","ids","keys","key","events","rows","row"]}
|