@donotdev/functions 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/guidelines/VERCEL.md +25 -16
  2. package/lib/chunks/{chunk-HZM5X5A7.js → chunk-4BJP372Z.js} +2 -2
  3. package/lib/chunks/chunk-CCEGC2T6.js +22 -0
  4. package/lib/chunks/chunk-CCEGC2T6.js.map +7 -0
  5. package/lib/chunks/{chunk-CVYSXC27.js → chunk-IO4MUTT6.js} +2 -2
  6. package/lib/chunks/chunk-LJXSA7EP.js +151 -0
  7. package/lib/chunks/chunk-LJXSA7EP.js.map +7 -0
  8. package/lib/chunks/chunk-MJ5VZTLM.js +22 -0
  9. package/lib/chunks/chunk-MJ5VZTLM.js.map +7 -0
  10. package/lib/chunks/chunk-NP4Y2LAO.js +22 -0
  11. package/lib/chunks/chunk-NP4Y2LAO.js.map +7 -0
  12. package/lib/chunks/chunk-TBHRDSX5.js +22 -0
  13. package/lib/chunks/chunk-TBHRDSX5.js.map +7 -0
  14. package/lib/chunks/{chunk-522YXGDA.js → chunk-WJUL2W7Y.js} +2 -2
  15. package/lib/chunks/{chunk-522YXGDA.js.map → chunk-WJUL2W7Y.js.map} +2 -2
  16. package/lib/chunks/chunk-Y6BR2QOV.js +22 -0
  17. package/lib/chunks/{chunk-ICNQCRLV.js.map → chunk-Y6BR2QOV.js.map} +4 -4
  18. package/lib/chunks/{monitoring-UCBNPPW2.js → monitoring-B2DYDCYC.js} +2 -2
  19. package/lib/chunks/{rateLimiter-XKECWM33.js → rateLimiter-JCBEG33M.js} +2 -2
  20. package/lib/chunks/{server-24XGDDO3.js → server-YXYTPMRF.js} +2 -2
  21. package/lib/firebase/billing/cancelSubscription.d.ts +2 -1
  22. package/lib/firebase/billing/changePlan.d.ts +2 -1
  23. package/lib/firebase/billing/createCheckoutSession.d.ts +2 -1
  24. package/lib/firebase/billing/createCustomerPortal.d.ts +4 -0
  25. package/lib/firebase/billing/healthCheck.d.ts +2 -0
  26. package/lib/firebase/billing/refreshSubscriptionStatus.d.ts +2 -1
  27. package/lib/firebase/billing/webhookHandler.d.ts +2 -0
  28. package/lib/firebase/index.js +1 -1
  29. package/lib/firebase/index.js.map +4 -4
  30. package/lib/firebase/oauth/exchangeToken.d.ts +21 -4
  31. package/lib/firebase/oauth/providerSecrets.d.ts +22 -0
  32. package/lib/firebase/oauth/refreshToken.d.ts +34 -4
  33. package/lib/shared/index.js +1 -1
  34. package/lib/supabase/index.js +1 -1
  35. package/lib/supabase/index.js.map +4 -4
  36. package/lib/vercel/api/auth/index.d.ts +3 -3
  37. package/lib/vercel/api/crud/index.d.ts +6 -6
  38. package/lib/vercel/api/index.js +1 -1
  39. package/lib/vercel/api/index.js.map +4 -4
  40. package/lib/vercel/api/oauth/index.d.ts +4 -4
  41. package/package.json +5 -5
  42. package/src/firebase/billing/__tests__/secretDeclarations.test.ts +55 -0
  43. package/src/firebase/billing/cancelSubscription.ts +9 -2
  44. package/src/firebase/billing/changePlan.ts +6 -2
  45. package/src/firebase/billing/createCheckoutSession.ts +6 -2
  46. package/src/firebase/billing/createCustomerPortal.ts +8 -1
  47. package/src/firebase/billing/healthCheck.ts +13 -1
  48. package/src/firebase/billing/refreshSubscriptionStatus.ts +14 -2
  49. package/src/firebase/billing/webhookHandler.ts +9 -1
  50. package/src/firebase/oauth/__tests__/tokenFactories.test.ts +99 -0
  51. package/src/firebase/oauth/exchangeToken.ts +53 -8
  52. package/src/firebase/oauth/providerSecrets.ts +65 -0
  53. package/src/firebase/oauth/refreshToken.ts +57 -12
  54. package/src/vercel/__tests__/firebaseOptional.test.ts +24 -0
  55. package/src/vercel/api/auth/index.ts +4 -3
  56. package/src/vercel/api/crud/index.ts +7 -6
  57. package/src/vercel/api/oauth/index.ts +5 -4
  58. package/lib/chunks/chunk-7ODXXXES.js +0 -151
  59. package/lib/chunks/chunk-7ODXXXES.js.map +0 -7
  60. package/lib/chunks/chunk-CP3NNKO5.js +0 -22
  61. package/lib/chunks/chunk-CP3NNKO5.js.map +0 -7
  62. package/lib/chunks/chunk-ICNQCRLV.js +0 -22
  63. package/lib/chunks/chunk-OAZ2JYSD.js +0 -22
  64. package/lib/chunks/chunk-OAZ2JYSD.js.map +0 -7
  65. package/lib/chunks/chunk-OKRR7ST5.js +0 -22
  66. package/lib/chunks/chunk-OKRR7ST5.js.map +0 -7
  67. package/lib/chunks/chunk-PDBNKSBQ.js +0 -22
  68. package/lib/chunks/chunk-PDBNKSBQ.js.map +0 -7
  69. package/lib/chunks/chunk-TJPJXJEK.js +0 -22
  70. package/lib/chunks/chunk-TJPJXJEK.js.map +0 -7
  71. /package/lib/chunks/{chunk-HZM5X5A7.js.map → chunk-4BJP372Z.js.map} +0 -0
  72. /package/lib/chunks/{chunk-CVYSXC27.js.map → chunk-IO4MUTT6.js.map} +0 -0
  73. /package/lib/chunks/{monitoring-UCBNPPW2.js.map → monitoring-B2DYDCYC.js.map} +0 -0
  74. /package/lib/chunks/{rateLimiter-XKECWM33.js.map → rateLimiter-JCBEG33M.js.map} +0 -0
  75. /package/lib/chunks/{server-24XGDDO3.js.map → server-YXYTPMRF.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/shared/errorHandling.ts", "../../src/shared/metadata.ts", "../../src/shared/crud/written.ts", "../../src/shared/crud/bulkCore.ts", "../../src/shared/ai/costTracker.ts", "../../src/shared/denoEnv.ts", "../../src/shared/ai/createAIRoute.ts", "../../src/shared/ai/resolveModelTier.ts", "../../src/shared/ai/classifyAIError.ts", "../../src/shared/billing/apiVersion.ts", "../../src/shared/billing/orderWebhook.ts", "../../src/shared/billing/checkoutPrice.ts", "../../src/shared/billing/checkoutValidation.ts", "../../src/shared/billing/createCheckout.ts", "../../src/shared/billing/helpers/updateUserSubscription.ts", "../../src/shared/billing/idempotencyContract.ts", "../../src/shared/billing/stripePinned.ts", "../../src/shared/billing/tierWebhookEvents.ts", "../../src/shared/billing/webhookHandler.ts", "../../src/shared/billing/supabaseIdempotency.ts"],
4
+ "sourcesContent": ["// packages/functions/src/shared/errorHandling.ts\n\n/**\n * @fileoverview Shared Error Handling\n * @description Platform-agnostic error classification. Always throws DoNotDevError.\n * Platform adapters (Firebase baseFunction, Vercel route handler) catch and convert.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type { EntityHookError, ErrorCode } from '@donotdev/core/server';\nimport { DoNotDevError } from '@donotdev/core/server';\n\n// Re-export DoNotDevError so existing imports from this module continue to work\nexport { DoNotDevError };\n\n/**\n * Classify and throw a DoNotDevError from any unknown error.\n * Pure classification \u2014 no platform imports, no env detection.\n *\n * @param error - The error to handle\n * @throws DoNotDevError always\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function handleError(error: unknown): never {\n // W11: Log only in development to avoid double-logging with platform loggers.\n // Known DoNotDevError, ValiError, and EntityHookError are handled by callers.\n if (\n process.env.NODE_ENV === 'development' &&\n !(error instanceof DoNotDevError) &&\n !(error instanceof Error && error.name === 'ValiError') &&\n !(error instanceof Error && error.name === 'EntityHookError')\n ) {\n console.error('Function error:', error);\n }\n\n // Error classification logic (same for all platforms)\n let code: ErrorCode;\n let message: string;\n let details: unknown;\n\n if (error instanceof DoNotDevError) {\n code = error.code;\n message = error.message;\n details = error.details;\n } else if (\n error &&\n typeof error === 'object' &&\n 'issues' in error &&\n ((error instanceof Error && error.name === 'ValiError') ||\n ('name' in error && error.name === 'ValiError'))\n ) {\n code = 'invalid-argument';\n message = 'Validation failed';\n details = { validationErrors: error.issues };\n } else if (\n error &&\n typeof error === 'object' &&\n 'type' in error &&\n ((error instanceof Error && error.name === 'EntityHookError') ||\n ('name' in error && error.name === 'EntityHookError'))\n ) {\n const entityError = error as EntityHookError;\n switch (entityError.type) {\n case 'PERMISSION_DENIED':\n code = 'permission-denied';\n break;\n case 'NOT_FOUND':\n code = 'not-found';\n break;\n case 'ALREADY_EXISTS':\n code = 'already-exists';\n break;\n case 'VALIDATION_ERROR':\n code = 'invalid-argument';\n break;\n case 'NETWORK_ERROR':\n code = 'unavailable';\n break;\n default:\n code = 'internal';\n }\n message = entityError.message;\n details = undefined;\n } else {\n code = 'internal';\n // W10: Never expose error.message for internal errors \u2014 it may leak\n // internal file paths, SQL queries, or implementation details to clients.\n // Log server-side only; clients always get the generic message.\n message = 'An unexpected error occurred';\n details = undefined;\n }\n\n // For internal errors, always use the generic message regardless of source.\n // Other error codes may carry safe, developer-authored messages.\n if (code === 'internal') {\n message = 'An unexpected error occurred';\n }\n\n throw new DoNotDevError(\n message,\n code,\n details ? { details } : undefined\n );\n}\n", "// packages/functions/src/shared/metadata.ts\n\n/**\n * @fileoverview Document metadata utilities for functions\n * @description Server-safe metadata creation and update utilities\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\n/**\n * Creates metadata for a new document.\n * @param userId - The ID of the user creating the document\n * @returns An object with creation and update timestamps and user IDs\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function createMetadata(userId: string) {\n const now = new Date().toISOString();\n return {\n createdAt: now,\n updatedAt: now,\n createdById: userId,\n updatedById: userId,\n };\n}\n\n/**\n * Creates update metadata for an existing document.\n * @param userId - The ID of the user updating the document\n * @returns An object with update timestamp and user ID\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport function updateMetadata(userId: string) {\n return {\n updatedAt: new Date().toISOString(),\n updatedById: userId,\n };\n}\n", "// packages/functions/src/shared/crud/written.ts\n\n/**\n * @fileoverview What a server write stores\n * @description The server side of a CRUD rule result (`prepareCreate` / `prepareUpdate` /\n * `prepareRemove`, core/schemas crud/): logs the unknown fields (CRUD rule 8: neither\n * silent nor blocking) and returns the stored values or throws. Every server write site\n * (bulk, create, update, entity store) calls it.\n *\n * @version 0.1.0\n * @since 0.3.0\n * @author AMBROISE PARK Consulting\n */\n\nimport { DoNotDevError } from '@donotdev/core/server';\nimport type { PreparedWrite } from '@donotdev/core/server';\n\n/**\n * The values a server write stores.\n *\n * @param result - The CRUD rule result\n * @param collection - Collection written (named in the log and the error)\n * @param locator - Write site / row (e.g. `update`, `inserts[2]`)\n * @returns The rule's `written`\n * @throws {DoNotDevError} `invalid-argument` with `details.validationErrors` (the server wire\n * contract, a Firebase `FunctionsErrorCode`) when the write is invalid\n *\n * @example\n * ```typescript\n * const row = writtenOf(prepareCreate(schemas, payload), collection, 'create');\n * ```\n *\n * @version 0.1.0\n * @since 0.3.0\n * @author AMBROISE PARK Consulting\n */\nexport function writtenOf(\n result: PreparedWrite,\n collection: string,\n locator: string\n): Record<string, unknown> {\n if (result.unknownKeys.length > 0) {\n console.warn(\n `[dndev] ${collection} ${locator}: fields the entity does not have, not written: ${result.unknownKeys.join(', ')}`\n );\n }\n if (result.ok) return result.written;\n const messages = result.issues\n .map((issue) => `${issue.path?.map((p) => String(p.key)).join('.') || 'root'}: ${issue.message}`)\n .join('; ');\n throw new DoNotDevError(\n `Validation failed on ${collection} ${locator}: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: result.issues } }\n );\n}\n", "// packages/functions/src/shared/crud/bulkCore.ts\n\n/**\n * @fileoverview Shared bulk CRUD orchestration core.\n * @description Target-agnostic orchestrator that owns the bulk policy\n * (wire validation, collision detection, per-bucket ACL, per-row schema\n * validation, id minting, metadata stamping, audit, response validation).\n * Target storage is delegated to a caller-supplied `transact` callback \u2014\n * this lets Firestore admin, Supabase RPC, Vercel firebase-admin, future\n * GraphQL and future REST-CRUD server aids share one source of truth for\n * correctness without pulling any platform-specific dependencies here.\n *\n * This module is server-only (`shared/` but never imported from `client/`\n * or `common/`) and designed to stay portable across Node and Deno \u2014 it\n * does not import `fs`, `net`, `firebase-admin`, `supabase-js`, etc.\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport {\n BulkCollisionError,\n BulkRequestSchema,\n BulkResponseSchema,\n detectBulkCollisions,\n DoNotDevError,\n hasRoleAccess,\n createStatus,\n prepareCreate,\n prepareUpdate,\n statusCan,\n updateCheck,\n} from '@donotdev/core/server';\nimport type {\n BulkRequest,\n BulkResponse,\n EntityAccessConfig,\n UserRole,\n} from '@donotdev/core/server';\n\nimport { writtenOf } from './written.js';\n\n// =============================================================================\n// Public types\n// =============================================================================\n\n/**\n * Valibot schema alias accepted by {@link executeBulk}. Kept loose (`any` on\n * the parsed output) so callers can pass entity-specific schemas generated by\n * `createSchemas()` without fighting variance.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)\nexport type BulkRowSchema = v.BaseSchema<unknown, any, v.BaseIssue<unknown>>;\n\n/**\n * A prepared insert row passed to the caller-supplied `transact` callback.\n * When {@link ExecuteBulkParams.mintInsertId} is provided, `id` is the minted\n * value (a client id never addresses a stored document). Otherwise it is the\n * id the client supplied (a pre-minted id other rows reference, BULK_ACROSS.md\n * \"Pre-Minted IDs\"), also kept on `row.id`, or the empty string when the\n * storage layer mints its own.\n */\nexport interface PreparedInsert {\n /** Minted id, else the client-supplied id, else the empty string (the target mints its own). */\n id: string;\n /** Fully stamped row ready for storage. */\n row: Record<string, unknown>;\n}\n\n/**\n * A prepared update passed to `transact`.\n */\nexport interface PreparedUpdate {\n /** Target row id. */\n id: string;\n /** Fully stamped patch ready for storage. */\n patch: Record<string, unknown>;\n}\n\n/**\n * Payload handed to the caller-supplied `transact` callback. All three\n * arrays preserve input order and only include non-empty buckets' work.\n */\nexport interface PreparedBulk {\n inserts: PreparedInsert[];\n updates: PreparedUpdate[];\n deletes: string[];\n}\n\n/**\n * Parameters for {@link executeBulk}.\n *\n * @template TRow - Row type recorded for documentation; runtime is opaque.\n */\nexport interface ExecuteBulkParams<TRow = unknown> {\n /** Collection / table name. Passed through to audit + transact as metadata. */\n collection: string;\n /** Raw wire payload to orchestrate. Parsed with {@link BulkRequestSchema}. */\n ops: BulkRequest;\n /** Valibot schema validating each insert row. */\n createSchema: BulkRowSchema;\n /**\n * `createSchemas(entity).draft`: drafts saved incomplete (CRUD rule 5). Required as soon\n * as a draft row is sent: a draft without it is rejected (`invalid-argument`), never\n * validated as a create.\n */\n draftCreateSchema?: BulkRowSchema;\n /** `createSchemas(entity).update`: update patches (CRUD rules 2, 5). */\n updateSchema: BulkRowSchema;\n /**\n * Reads the stored rows of the updated ids (application field names, keyed by id).\n * Called once, before validation, when the bulk carries updates: the stored row\n * gives each patch its status and a published draft its whole record\n * (`prepareUpdate`, as on the client). An updated id missing\n * from the result is rejected (`not-found`). Required as soon as the bulk carries\n * updates: an update without it is rejected (`internal`, a configuration error),\n * never validated by its patch status alone. Every target passes it: Firestore,\n * Supabase and Vercel read their store; the GraphQL / REST-CRUD server aids\n * forward the consumer's `readStored` option.\n */\n readStored?: (\n ids: readonly string[]\n ) => Promise<ReadonlyMap<string, Record<string, unknown>>>;\n /** Per-bucket required roles. Missing entries are treated as \"no bucket allowed\". */\n access: EntityAccessConfig;\n /** Authenticated caller id (for metadata + audit). */\n uid: string;\n /** Caller's role (for per-bucket ACL). */\n userRole: UserRole;\n /**\n * Target-specific storage. Invoked exactly once when the bulk carries at\n * least one op. Must run all three buckets inside one atomic transaction\n * (writeBatch, runTransaction, Postgres RPC wrapping BEGIN/COMMIT, etc.)\n * and return ids per bucket in input order.\n *\n * The returned shape is validated against `BulkResponseSchema` before\n * being returned to the caller.\n */\n transact: (prepared: PreparedBulk) => Promise<BulkResponse>;\n /**\n * Optional id minting. When provided, every insert is stamped with a\n * freshly-minted id before `transact` runs. When omitted, `id` on each\n * {@link PreparedInsert} is the empty string and the storage layer is\n * expected to mint its own ids (Supabase RPC, GraphQL server, etc.).\n */\n mintInsertId?: () => string;\n /**\n * Optional hook to stamp platform-specific metadata on every insert row\n * (timestamps, createdById, defaults, field-name mapping). Called once per\n * insert row, in input order.\n */\n stampInsertMetadata?: (\n row: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional hook to stamp platform-specific metadata on every update patch.\n */\n stampUpdateMetadata?: (\n patch: Record<string, unknown>,\n uid: string\n ) => Record<string, unknown>;\n /**\n * Optional audit hook. Fires exactly once when `transact` succeeds, with the\n * three op counts. Never fires for empty bulks or rejected validations \u2014\n * matches the \"one audit entry\" contract from `BULK_CRUD_TODO.md` \u00A74.\n */\n audit?: (\n event: string,\n payload: {\n counts: { inserts: number; updates: number; deletes: number };\n }\n ) => void;\n /**\n * Optional rate-limit bookkeeping key. `executeBulk` does NOT perform\n * rate-limit enforcement itself \u2014 the surrounding base-function wrapper\n * already charges one hit at entry. This field is forwarded to `audit()`\n * callers that want to correlate telemetry.\n */\n rateLimitKey?: string;\n}\n\n// =============================================================================\n// Core orchestrator\n// =============================================================================\n\n/**\n * Empty response returned for a no-op bulk. Frozen so accidental mutation\n * from a caller blows up at dev time instead of poisoning the next call.\n */\nconst EMPTY_BULK_RESPONSE: BulkResponse = Object.freeze({\n insertedIds: [],\n updatedIds: [],\n deletedIds: [],\n}) as BulkResponse;\n\n/**\n * Run a bulk CRUD operation against a caller-supplied storage target.\n *\n * **Order of operations** (every step fails loud \u2014 no fallbacks, no partial\n * writes):\n *\n * 1. Parse `ops` with {@link BulkRequestSchema}. Invalid shape \u2192 throws.\n * 2. Collision detection via {@link detectBulkCollisions}. Collision \u2192\n * throws {@link BulkCollisionError}.\n * 3. Empty short-circuit \u2014 if no op carries work, returns a zeroed\n * {@link BulkResponse} without invoking `transact` or `audit`.\n * 4. Per-bucket ACL \u2014 for each populated bucket, asserts the caller's role\n * clears the corresponding `access.{create|update|delete}`. A missing\n * role on a populated bucket is a configuration error and is rejected.\n * 5. Per-row validation \u2014 the CRUD rules (`prepareCreate` / `prepareUpdate`,\n * core/schemas crud/), the stored rows read once with `readStored` (updates\n * without it \u2192 `internal`; an updated id with no stored row \u2192 `not-found`).\n * The first failure throws `validation-failed` (wire: `invalid-argument`)\n * naming `inserts[i]` / `updates[i]`. Unknown fields are logged, not written.\n * What is stored is the rules' `written`, never the raw row.\n * 6. Id minting \u2014 if `mintInsertId` is supplied, every insert gets a fresh\n * id stamped onto its {@link PreparedInsert}. Otherwise a client-supplied\n * `id` is kept (on the row and as `PreparedInsert.id`; the create schema\n * excludes it, it is restored after validation), else `id` is `\"\"` and the\n * storage layer mints its own.\n * 7. Metadata stamping \u2014 `stampInsertMetadata` / `stampUpdateMetadata` run\n * per row / per patch if provided.\n * 8. `transact(prepared)` runs exactly once. Must be atomic. Throws\n * propagate unchanged so the caller's error handler can classify them.\n * 9. Response-shape validation via {@link BulkResponseSchema}. A non-conforming\n * target response throws `DoNotDevError(internal)`.\n * 10. `audit()` fires once with the three op counts.\n *\n * **Not this function's job:** rate-limiting, authentication, HTTP status\n * mapping, target-specific connection pooling, retry policy. All of those\n * belong to the surrounding handler wrapper.\n *\n * @template TRow - Row type (documentation only).\n * @param params - See {@link ExecuteBulkParams}.\n * @returns The validated {@link BulkResponse} from the target.\n *\n * @throws {BulkCollisionError} When the payload contains the same id in\n * two mutually-exclusive buckets.\n * @throws {DoNotDevError} `invalid-argument` on wire-schema failure, per-row\n * validation failure, or collision (wrapped for callers that only rethrow\n * `DoNotDevError`).\n * @throws {DoNotDevError} `not-found` when an updated id has no stored row\n * (`readStored`).\n * @throws {DoNotDevError} `permission-denied` when the caller's role cannot\n * satisfy a populated bucket's access requirement.\n * @throws {DoNotDevError} `internal` when the bulk carries updates but no\n * `readStored` is configured.\n * @throws {DoNotDevError} `internal` when the `transact` return value fails\n * {@link BulkResponseSchema}.\n *\n * @example\n * ```typescript\n * import { executeBulk } from '@donotdev/functions/shared';\n * import { BulkResponseSchema } from '@donotdev/core/server';\n *\n * const response = await executeBulk({\n * collection: 'events',\n * ops: req.body,\n * createSchema,\n * updateSchema,\n * access,\n * uid,\n * userRole,\n * readStored: async (ids) => new Map((await db.getRows(ids)).map((row) => [row.id, row])),\n * mintInsertId: () => crypto.randomUUID(),\n * stampInsertMetadata: (row, uid) => ({\n * ...row,\n * createdById: uid,\n * createdAt: new Date().toISOString(),\n * }),\n * transact: async ({ inserts, updates, deletes }) => {\n * return db.runTransaction(async (tx) => {\n * for (const { id, row } of inserts) tx.set(col.doc(id), row);\n * for (const { id, patch } of updates) tx.update(col.doc(id), patch);\n * for (const id of deletes) tx.delete(col.doc(id));\n * return {\n * insertedIds: inserts.map((i) => i.id),\n * updatedIds: updates.map((u) => u.id),\n * deletedIds: deletes,\n * };\n * });\n * },\n * audit: (event, { counts }) => logger.info(event, counts),\n * });\n * ```\n *\n * @version 0.1.0\n * @since 0.7.0\n * @author AMBROISE PARK Consulting\n */\nexport async function executeBulk<TRow = unknown>(\n params: ExecuteBulkParams<TRow>\n): Promise<BulkResponse> {\n const {\n collection,\n ops,\n createSchema,\n draftCreateSchema,\n updateSchema,\n access,\n uid,\n userRole,\n transact,\n readStored,\n mintInsertId,\n stampInsertMetadata,\n stampUpdateMetadata,\n audit,\n } = params;\n\n // 1. Wire-schema validation. Guarantees the three buckets are arrays of\n // the right shape; per-field entity validation happens in step 5.\n const parsed = v.safeParse(BulkRequestSchema, ops);\n if (!parsed.success) {\n const messages = parsed.issues\n .map(\n (issue) =>\n `${issue.path?.map((p) => p.key).join('.') || 'root'}: ${issue.message}`\n )\n .join('; ');\n throw new DoNotDevError(\n `Bulk payload validation failed: ${messages}`,\n 'invalid-argument',\n { details: { validationErrors: parsed.issues } }\n );\n }\n const request: BulkRequest = parsed.output;\n\n const inserts = request.inserts ?? [];\n const updates = request.updates ?? [];\n const deletes = request.deletes ?? [];\n\n // 2. Collision detection. Rejects ambiguous intents BEFORE any further\n // work so a rate-limit hit + HTTP round-trip never buys a partial\n // validation pass only to fail later.\n const collision = detectBulkCollisions(request);\n if (collision.where !== null) {\n throw new BulkCollisionError(collision.collisions, collision.where);\n }\n\n // 3. Empty bulk short-circuit. Per `BULK_CRUD_TODO.md` \u00A78 this never\n // touches the storage layer, never fires audit, and returns a frozen\n // empty response shared across calls (safe \u2014 consumers never mutate).\n if (inserts.length === 0 && updates.length === 0 && deletes.length === 0) {\n return EMPTY_BULK_RESPONSE;\n }\n\n // 4. Per-bucket ACL. The surrounding base-function wrapper already cleared\n // the weakest role; we re-check each populated bucket so mixed-ACL\n // entities reject precisely. A populated bucket with no configured\n // role is a config error \u2014 fail loud rather than silently allow.\n if (inserts.length > 0) {\n if (!access.create) {\n throw new DoNotDevError(\n `Bulk insert requested on ${collection} but no create role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.create)) {\n throw new DoNotDevError(\n `Access denied for bulk insert on ${collection}. Required: ${access.create}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (updates.length > 0) {\n if (!access.update) {\n throw new DoNotDevError(\n `Bulk update requested on ${collection} but no update role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.update)) {\n throw new DoNotDevError(\n `Access denied for bulk update on ${collection}. Required: ${access.update}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n if (deletes.length > 0) {\n if (!access.delete) {\n throw new DoNotDevError(\n `Bulk delete requested on ${collection} but no delete role is configured`,\n 'permission-denied'\n );\n }\n if (!hasRoleAccess(userRole, access.delete)) {\n throw new DoNotDevError(\n `Access denied for bulk delete on ${collection}. Required: ${access.delete}, your role: ${userRole}`,\n 'permission-denied'\n );\n }\n }\n\n // 5. Per-row validation: the CRUD rules (core/schemas crud/: `prepareCreate`,\n // `prepareUpdate`), as on the client. First failure wins, named by its bucket\n // index. What is stored is the rules' `written`, never the raw row.\n const noDraftSchema = (locator: string): never => {\n throw new DoNotDevError(\n `Validation failed on ${locator}: draft row sent to ${collection} but no draft schema is configured`,\n 'invalid-argument'\n );\n };\n // Without a draft schema, no draft row passes the guards below: `create` only fills the slot.\n const schemas = {\n create: createSchema,\n draft: draftCreateSchema ?? createSchema,\n update: updateSchema,\n };\n const insertRows: { row: Record<string, unknown>; id: string | null }[] = [];\n for (let i = 0; i < inserts.length; i++) {\n const rowObj = inserts[i]! as unknown as Record<string, unknown>;\n if (!draftCreateSchema && statusCan(createStatus(rowObj), 'saveIncomplete')) noDraftSchema(`inserts[${i}]`);\n const row = writtenOf(prepareCreate(schemas, rowObj), collection, `inserts[${i}]`);\n // A client id is a pre-minted id other rows reference: the rules never write\n // `id`, so it travels beside the row.\n insertRows.push({ row, id: typeof rowObj.id === 'string' ? rowObj.id : null });\n }\n // The stored rows give each patch its status and the publish check its record.\n if (updates.length > 0 && !readStored) {\n throw new DoNotDevError(\n `Bulk update requested on ${collection} but no readStored is configured: the stored row decides each patch's rules`,\n 'internal'\n );\n }\n const stored =\n updates.length > 0 && readStored\n ? await readStored(updates.map((u) => u.id))\n : new Map<string, Record<string, unknown>>();\n const updatePatches: Record<string, unknown>[] = [];\n for (let i = 0; i < updates.length; i++) {\n const { id, patch } = updates[i]!;\n const locator = `updates[${i}]`;\n const storedRow = stored.get(id);\n if (!storedRow) {\n throw new DoNotDevError(\n `Document not found on ${locator}: ${collection}/${id}`,\n 'not-found'\n );\n }\n if (!draftCreateSchema && updateCheck(patch as Record<string, unknown>, storedRow).schemaKey === 'draft') {\n noDraftSchema(locator);\n }\n updatePatches.push(\n writtenOf(\n prepareUpdate(schemas, { id, patch: patch as Record<string, unknown>, stored: storedRow }),\n collection,\n locator\n )\n );\n }\n\n // 6. Id minting (if provided). Minting at this layer means `transact`\n // receives stable ids \u2014 crucial for Firestore's retry-able transaction\n // callbacks where the callback body may run more than once.\n // Without minting, a client id is kept (row + PreparedInsert.id) for the\n // target to store; with minting, the minted id wins.\n const preparedInserts: PreparedInsert[] = insertRows.map(({ row, id: clientId }) => {\n const id = mintInsertId ? mintInsertId() : (clientId ?? '');\n const withId = !mintInsertId && clientId !== null ? { ...row, id: clientId } : row;\n const stamped = stampInsertMetadata ? stampInsertMetadata(withId, uid) : withId;\n return { id, row: stamped };\n });\n\n // 7. Update metadata stamping.\n const preparedUpdates: PreparedUpdate[] = updates.map((u, i) => ({\n id: u.id,\n patch: stampUpdateMetadata\n ? stampUpdateMetadata(updatePatches[i]!, uid)\n : updatePatches[i]!,\n }));\n\n // 8. Atomic dispatch. Propagates any `transact` error verbatim \u2014 the\n // surrounding handler wrapper classifies into HTTP / callable codes.\n const raw = await transact({\n inserts: preparedInserts,\n updates: preparedUpdates,\n deletes: [...deletes],\n });\n\n // 9. Response-shape validation at the wire boundary. Drift between a\n // target's return shape and `BulkResponseSchema` would silently corrupt\n // clients that zip ids back onto optimistic entries \u2014 fail loud.\n const responseParse = v.safeParse(BulkResponseSchema, raw);\n if (!responseParse.success) {\n throw new DoNotDevError(\n `Bulk transact() returned an unexpected shape for ${collection}`,\n 'internal'\n );\n }\n\n // 10. One audit entry, counts only (never row ids \u2014 anomaly detection\n // fires on the bulk count per contract \u00A74).\n if (audit) {\n audit(`crud.bulk.${collection}`, {\n counts: {\n inserts: preparedInserts.length,\n updates: preparedUpdates.length,\n deletes: deletes.length,\n },\n });\n }\n\n return responseParse.output;\n}\n\n// =============================================================================\n// Internal helpers\n// =============================================================================\n", "// packages/functions/src/shared/ai/costTracker.ts\n\n/**\n * @fileoverview Server-Side Cost Calculator\n * @description Calculate per-request AI costs using SSOT pricing from `@donotdev/core`.\n * Cost records are written async by platform wrappers (Supabase, Vercel, Firebase).\n *\n * @version 0.1.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { AICostResult, AIUsage } from '@donotdev/core/server';\nimport { AI_TOKEN_PRICING, DEFAULT_AI_MARKUP } from '@donotdev/core/server';\n\n/**\n * Calculate cost from token usage for a given model.\n *\n * @param usage - Token usage counts\n * @param model - Model ID (must exist in AI_TOKEN_PRICING)\n * @param markup - Markup multiplier (default: 4.0)\n * @returns Cost breakdown with provider and billed amounts\n * @throws Error if model is not in pricing table\n */\nexport function calculateCost(\n usage: AIUsage,\n model: string,\n markup: number = DEFAULT_AI_MARKUP\n): AICostResult {\n const pricing = AI_TOKEN_PRICING[model];\n if (!pricing) {\n throw new Error(`Unknown model for cost calculation: ${model}`);\n }\n\n const promptCost = (usage.promptTokens / 1_000_000) * pricing.promptPer1M;\n const completionCost =\n (usage.completionTokens / 1_000_000) * pricing.completionPer1M;\n const providerCost = promptCost + completionCost;\n\n return {\n providerCost,\n billedCost: providerCost * markup,\n markup,\n breakdown: {\n promptTokens: usage.promptTokens,\n completionTokens: usage.completionTokens,\n promptCost,\n completionCost,\n },\n };\n}\n", "// packages/functions/src/shared/denoEnv.ts\n\n/**\n * @fileoverview Typed access to the Deno env from cross-runtime code\n * @description Supabase Edge Functions run on Deno, Firebase/Vercel on Node.\n * This package compiles against the Node lib types, which have no `Deno`\n * global. Internal: not re-exported from any package entry.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\n\n/** The part of the Deno namespace read by this package. */\ninterface DenoEnvNamespace {\n env?: { get(key: string): string | undefined };\n}\n\n/**\n * Deno env accessor, when running on Deno.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\nexport function getDenoEnv(): DenoEnvNamespace['env'] {\n // why: the Deno global is absent from the Node lib types this package compiles against\n return (globalThis as { Deno?: DenoEnvNamespace }).Deno?.env;\n}\n", "// packages/functions/src/shared/ai/createAIRoute.ts\n\n/**\n * @fileoverview AI Route Handler (Vercel AI SDK 7)\n * @description Platform-agnostic handler for AI chat requests using Vercel AI SDK.\n * Handles auth (via platform wrapper), rate limiting (Upstash), streaming, and cost tracking.\n * Streaming responses use the UI message stream protocol read by `@ai-sdk/react`\n * `useChat`; token usage travels as message metadata (`metadata.usage`, AIUsage).\n *\n * @version 0.2.0\n * @since 0.1.0\n * @author AMBROISE PARK Consulting\n */\n\n// `ai` is loaded on first request (handleAIRequest): importing this module must not\n// require the AI SDK, so server entries that re-export it run without it installed.\nimport type { JSONSchema7, LanguageModel, LanguageModelUsage, Tool } from 'ai';\n\nimport type {\n AIChatRequest,\n AICostConfig,\n AICostRecord,\n AIRateLimitConfig,\n AIRouteConfig,\n AIToolDefinition,\n AIUsage,\n} from '@donotdev/core/server';\nimport { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';\n\nimport { calculateCost } from './costTracker.js';\nimport { getDenoEnv } from '../denoEnv.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Per-request options passed to the AI route handler. */\nexport interface AIRouteOptions {\n /** Authenticated user ID */\n userId: string;\n /** Request ID for cost tracking */\n requestId?: string;\n /** Callback to persist cost record (platform-specific) */\n onCostRecord?: (record: AICostRecord) => Promise<void>;\n}\n\n/** Provider factory map - lazily creates provider instances */\ntype ProviderFactory = (apiKey: string) => LanguageModel;\n\n// =============================================================================\n// Provider Resolution\n// =============================================================================\n\n/** Lazily import and create provider models */\nasync function resolveModel(\n provider: string,\n model: string\n): Promise<LanguageModel> {\n const factories: Record<string, () => Promise<ProviderFactory>> = {\n anthropic: async () => {\n const { createAnthropic } = await import('@ai-sdk/anthropic');\n return (apiKey: string) => createAnthropic({ apiKey })(model);\n },\n openai: async () => {\n const { createOpenAI } = await import('@ai-sdk/openai');\n return (apiKey: string) => createOpenAI({ apiKey })(model);\n },\n google: async () => {\n const { createGoogle } = await import('@ai-sdk/google');\n return (apiKey: string) => createGoogle({ apiKey })(model);\n },\n };\n\n const factory = factories[provider];\n if (!factory) {\n throw new Error(`Unsupported AI provider: ${provider}`);\n }\n\n const apiKey = getAIApiKey(provider);\n const createModel = await factory();\n return createModel(apiKey);\n}\n\n// =============================================================================\n// Rate Limiting (reused from old handler)\n// =============================================================================\n\nconst DEFAULT_RATE_LIMIT: AIRateLimitConfig = {\n maxRequests: 30,\n windowMs: 60_000,\n};\n\nlet rateLimiter: {\n check: (userId: string, config: AIRateLimitConfig) => Promise<void>;\n} | null = null;\n\nasync function getRateLimiter() {\n if (rateLimiter) return rateLimiter;\n\n const redisUrl = getEnv('UPSTASH_REDIS_REST_URL');\n const redisToken = getEnv('UPSTASH_REDIS_REST_TOKEN');\n\n if (!redisUrl || !redisToken) {\n console.warn(\n '[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled.'\n );\n rateLimiter = { check: async () => {} };\n return rateLimiter;\n }\n\n try {\n const { Ratelimit } = await import('@upstash/ratelimit');\n const { Redis } = await import('@upstash/redis');\n\n const redis = new Redis({ url: redisUrl, token: redisToken });\n const limiters = new Map<string, InstanceType<typeof Ratelimit>>();\n\n rateLimiter = {\n check: async (userId: string, config: AIRateLimitConfig) => {\n const key = `${config.maxRequests}:${config.windowMs}`;\n let rl = limiters.get(key);\n if (!rl) {\n rl = new Ratelimit({\n redis,\n limiter: Ratelimit.slidingWindow(\n config.maxRequests,\n `${config.windowMs}ms`\n ),\n prefix: 'ai_rl',\n });\n limiters.set(key, rl);\n }\n\n const result = await rl.limit(userId);\n if (!result.success) {\n throw new Error(\n `Rate limit exceeded. Maximum ${config.maxRequests} requests per ${config.windowMs / 1000}s.`\n );\n }\n },\n };\n return rateLimiter;\n } catch (err) {\n console.warn(\n '[AI] Failed to initialize Upstash rate limiter:',\n err instanceof Error ? err.message : err\n );\n rateLimiter = { check: async () => {} };\n return rateLimiter;\n }\n}\n\n// =============================================================================\n// Tool Conversion (JSON Schema \u2192 Vercel AI SDK tool)\n// =============================================================================\n\n/**\n * Convert framework tool definitions to Vercel AI SDK tools.\n * Uses `jsonSchema()` from the AI SDK to pass JSON Schema directly (no zod dependency).\n * Merges request-level tools with config-level tools (request takes precedence).\n */\nfunction resolveTools(\n sdk: Pick<typeof import('ai'), 'tool' | 'jsonSchema'>,\n requestTools?: Record<string, AIToolDefinition>,\n configTools?: Record<string, AIToolDefinition>\n): Record<string, Tool> | undefined {\n const merged = { ...configTools, ...requestTools };\n if (Object.keys(merged).length === 0) return undefined;\n\n const sdkTools: Record<string, Tool> = {};\n for (const [name, def] of Object.entries(merged)) {\n sdkTools[name] = sdk.tool({\n description: def.description,\n inputSchema: sdk.jsonSchema(def.parameters as JSONSchema7),\n });\n }\n return sdkTools;\n}\n\n/** AI SDK usage (input/output tokens) \u2192 framework usage (prompt/completion tokens). */\nfunction toAIUsage(usage: LanguageModelUsage): AIUsage {\n const promptTokens = usage.inputTokens ?? 0;\n const completionTokens = usage.outputTokens ?? 0;\n return {\n promptTokens,\n completionTokens,\n totalTokens: usage.totalTokens ?? promptTokens + completionTokens,\n };\n}\n\n// =============================================================================\n// Core Handler\n// =============================================================================\n\n/**\n * Handle an AI chat request using Vercel AI SDK.\n * Supports both streaming (returns SSE Response) and non-streaming (returns JSON).\n *\n * @param request - Validated AI chat request\n * @param config - Route configuration\n * @param options - Per-request options (userId, cost callback)\n * @returns Response (SSE stream or JSON)\n */\nexport async function handleAIRequest(\n request: AIChatRequest,\n config: AIRouteConfig,\n options: AIRouteOptions\n): Promise<Response> {\n // Validate request\n const validation = validateAIChatRequest(request);\n if (!validation.success) {\n return jsonError(\n `Invalid AI request: ${validation.issues?.map((i) => i.message).join(', ')}`,\n 400\n );\n }\n\n // Resolve provider + model\n const provider = request.provider || config.provider || 'anthropic';\n const providerModels = AI_MODELS[provider as keyof typeof AI_MODELS];\n const model =\n request.model ||\n config.model ||\n providerModels?.default ||\n 'claude-sonnet-4-20250514';\n\n // Validate model against allowed list\n if (providerModels) {\n const allowed = providerModels.models as readonly string[];\n if (!allowed.includes(model)) {\n return jsonError(\n `Model '${model}' is not allowed for provider '${provider}'. Allowed: ${allowed.join(', ')}`,\n 400\n );\n }\n }\n\n // Rate limit\n try {\n const rl = await getRateLimiter();\n await rl.check(\n options.userId,\n config.rateLimitConfig || DEFAULT_RATE_LIMIT\n );\n } catch (err) {\n return jsonError(\n err instanceof Error ? err.message : 'Rate limit exceeded',\n 429\n );\n }\n\n // Resolve AI SDK model\n let languageModel: LanguageModel;\n try {\n languageModel = await resolveModel(provider, model);\n } catch (err) {\n return jsonError(\n `Failed to initialize provider: ${err instanceof Error ? err.message : String(err)}`,\n 500\n );\n }\n\n // Build messages for AI SDK\n const systemMessages = request.messages\n .filter((m) => m.role === 'system')\n .map((m) => m.content);\n const systemPrompt =\n request.systemPrompt ||\n config.systemPrompt ||\n (systemMessages.length > 0 ? systemMessages.join('\\n') : undefined);\n\n const messages = request.messages\n .filter((m) => m.role !== 'system')\n .map((m) => ({\n role: m.role as 'user' | 'assistant',\n content: m.content,\n }));\n\n const maxTokens = request.maxTokens || config.maxTokens || 4096;\n const temperature = request.temperature ?? config.temperature ?? 0.7;\n const requestId = options.requestId || crypto.randomUUID();\n\n // Resolve tools (request-level overrides config-level)\n const sdk = await import('ai');\n const {\n streamText,\n generateText,\n toUIMessageStream,\n createUIMessageStreamResponse,\n } = sdk;\n const tools = resolveTools(sdk, request.tools, config.tools);\n\n // Cost tracking helper\n const recordCost = async (usage: AIUsage) => {\n if (!options.onCostRecord) return;\n\n const markup = config.cost?.markup ?? 4.0;\n const cost = calculateCost(usage, model, markup);\n\n const record: AICostRecord = {\n userId: options.userId,\n model,\n provider,\n usage,\n providerCost: cost.providerCost,\n billedCost: cost.billedCost,\n markup,\n timestamp: new Date().toISOString(),\n requestId,\n };\n\n // Non-blocking - don't let cost recording failure break the response\n options.onCostRecord(record).catch((err) => {\n console.error('[AI] Failed to record cost:', err);\n });\n };\n\n // Streaming vs non-streaming\n if (request.stream !== false) {\n // Streaming (default)\n const result = streamText({\n model: languageModel,\n messages,\n instructions: systemPrompt,\n maxOutputTokens: maxTokens,\n temperature,\n tools,\n onEnd: async ({ usage }) => {\n await recordCost(toAIUsage(usage));\n },\n });\n\n return createUIMessageStreamResponse({\n stream: toUIMessageStream({\n stream: result.stream,\n // Usage for the client's cost display (useAIChat reads metadata.usage).\n messageMetadata: ({ part }) =>\n part.type === 'finish'\n ? { usage: toAIUsage(part.totalUsage) }\n : undefined,\n }),\n });\n }\n\n // Non-streaming\n const result = await generateText({\n model: languageModel,\n messages,\n instructions: systemPrompt,\n maxOutputTokens: maxTokens,\n temperature,\n tools,\n });\n\n const usage = toAIUsage(result.usage);\n\n await recordCost(usage);\n\n // Extract tool calls from result\n const toolCalls =\n result.toolCalls.map((tc) => ({\n id: tc.toolCallId,\n name: tc.toolName,\n args: tc.input as Record<string, unknown>,\n }));\n\n return new Response(\n JSON.stringify({\n message: {\n role: 'assistant',\n content: result.text,\n },\n usage,\n finishReason: result.finishReason,\n toolCalls: toolCalls.length > 0 ? toolCalls : undefined,\n model,\n provider,\n }),\n {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction jsonError(message: string, status: number): Response {\n return new Response(JSON.stringify({ error: message }), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\nfunction getEnv(name: string): string | undefined {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return getDenoEnv()?.get(name);\n }\n return typeof process !== 'undefined' ? process.env[name] : undefined;\n}\n\nfunction getAIApiKey(provider: string): string {\n const providerKeyMap: Record<string, string> = {\n anthropic: 'ANTHROPIC_API_KEY',\n openai: 'OPENAI_API_KEY',\n google: 'GOOGLE_AI_API_KEY',\n };\n\n const providerKey = providerKeyMap[provider];\n if (providerKey) {\n const key = getEnv(providerKey);\n if (key) return key;\n }\n\n const key = getEnv('AI_API_KEY');\n if (!key) {\n throw new Error(\n `Missing API key. Set ${providerKey || 'AI_API_KEY'} environment variable.`\n );\n }\n return key;\n}\n", "// packages/functions/src/shared/ai/resolveModelTier.ts\n\n/**\n * @fileoverview AI Model Tier Resolver\n * @description Resolves the model ID for a given tier via env var chain.\n * Resolution: per-function env \u2192 per-tier env \u2192 static SSOT.\n * Cross-runtime: Deno (edge functions) + Node (Vercel/Firebase).\n *\n * @version 0.1.0\n * @since 0.6.0\n * @author AMBROISE PARK Consulting\n */\n\nimport { AI_TIERS } from '@donotdev/core/server';\nimport type { AITierId } from '@donotdev/core/server';\nimport { getDenoEnv } from '../denoEnv.js';\n\n// =============================================================================\n// Env helper (Deno + Node cross-runtime)\n// =============================================================================\n\nfunction getEnv(name: string): string | undefined {\n if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {\n return getDenoEnv()?.get(name);\n }\n return typeof process !== 'undefined' ? process.env[name] : undefined;\n}\n\n// =============================================================================\n// Resolver\n// =============================================================================\n\n/**\n * Resolve the AI model ID for a given tier.\n *\n * Resolution chain (first non-empty wins):\n * 1. `AI_MODEL_<FUNCTION_NAME>` env var (per-function override)\n * 2. `AI_TIER_<TIER>` env var (per-tier override)\n * 3. `AI_TIERS.<TIER>.defaultModel` (static SSOT from constants)\n *\n * @param tier - The tier ID ('fast', 'standard', 'premium')\n * @param functionName - Optional function name for per-function env var lookup\n * @returns The resolved model ID string\n */\nexport function resolveModelForTier(\n tier: AITierId,\n functionName?: string\n): string {\n // 1. Per-function env var: AI_MODEL_BRAINSTORM, AI_MODEL_SPEC_CHAT, etc.\n if (functionName) {\n const perFn = getEnv(`AI_MODEL_${functionName.toUpperCase()}`);\n if (perFn) return perFn;\n }\n\n // 2. Per-tier env var: AI_TIER_FAST, AI_TIER_STANDARD, AI_TIER_PREMIUM\n const perTier = getEnv(`AI_TIER_${tier.toUpperCase()}`);\n if (perTier) return perTier;\n\n // 3. Static SSOT\n const tierConfig = Object.values(AI_TIERS).find((t) => t.id === tier);\n return tierConfig?.defaultModel ?? AI_TIERS.STANDARD.defaultModel;\n}\n", "// packages/functions/src/shared/ai/classifyAIError.ts\n\n/**\n * @fileoverview AI Error Classifier\n * @description Classifies Anthropic API errors into actionable categories\n * for structured error responses in edge functions.\n *\n * @version 0.1.0\n * @since 0.6.0\n * @author AMBROISE PARK Consulting\n */\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Actionable error category for AI provider failures. */\nexport type AIErrorCode =\n | 'rate_limited'\n | 'overloaded'\n | 'auth_error'\n | 'credits_exhausted'\n | 'network'\n | 'internal';\n\n/** Result of classifying an AI provider error with retry and severity metadata. */\nexport interface ClassifiedAIError {\n code: AIErrorCode;\n retryable: boolean;\n retryAfterMs?: number;\n severity: 'transient' | 'critical';\n}\n\n// =============================================================================\n// Classifier\n// =============================================================================\n\n/**\n * Classify an error from an Anthropic API call into an actionable category.\n *\n * | HTTP/Error | Category | Retryable | Severity |\n * |------------------|--------------------|-----------|------------|\n * | 429 | rate_limited | yes | transient |\n * | 529 / 503 | overloaded | yes | transient |\n * | 401 | auth_error | no | critical |\n * | 402 / credits | credits_exhausted | no | critical |\n * | Network/timeout | network | yes | transient |\n * | Other 5xx | internal | no | critical |\n */\nexport function classifyAIError(err: unknown): ClassifiedAIError {\n const status = extractStatus(err);\n const message = extractMessage(err);\n\n // 429 - Rate limited\n if (status === 429) {\n return {\n code: 'rate_limited',\n retryable: true,\n retryAfterMs: extractRetryAfter(err) ?? 5_000,\n severity: 'transient',\n };\n }\n\n // 529 / 503 - Overloaded\n if (status === 529 || status === 503) {\n return {\n code: 'overloaded',\n retryable: true,\n retryAfterMs: extractRetryAfter(err) ?? 10_000,\n severity: 'transient',\n };\n }\n\n // 401 - Auth error\n if (status === 401) {\n return { code: 'auth_error', retryable: false, severity: 'critical' };\n }\n\n // 402 or insufficient credits\n if (\n status === 402 ||\n message.includes('insufficient') ||\n message.includes('credit')\n ) {\n return {\n code: 'credits_exhausted',\n retryable: false,\n severity: 'critical',\n };\n }\n\n // Network / timeout errors (no HTTP status)\n if (\n !status &&\n (message.includes('fetch') ||\n message.includes('network') ||\n message.includes('ECONNREFUSED') ||\n message.includes('ETIMEDOUT') ||\n message.includes('timeout') ||\n message.includes('aborted') ||\n err instanceof TypeError)\n ) {\n return {\n code: 'network',\n retryable: true,\n retryAfterMs: 3_000,\n severity: 'transient',\n };\n }\n\n // Everything else\n return { code: 'internal', retryable: false, severity: 'critical' };\n}\n\n/**\n * Map a classified error code to an HTTP status for the edge function response.\n */\nexport function mapClassifiedToHTTP(code: AIErrorCode): number {\n switch (code) {\n case 'rate_limited':\n return 429;\n case 'overloaded':\n return 503;\n case 'auth_error':\n return 502;\n case 'credits_exhausted':\n return 502;\n case 'network':\n return 502;\n case 'internal':\n return 500;\n }\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction extractStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object') {\n // Anthropic SDK errors have .status\n if ('status' in err && typeof err.status === 'number') {\n return err.status;\n }\n // Some errors nest status in .error\n if (\n 'error' in err &&\n typeof err.error === 'object' &&\n err.error !== null &&\n 'status' in err.error &&\n typeof err.error.status === 'number'\n ) {\n return err.error.status;\n }\n }\n return undefined;\n}\n\nfunction extractMessage(err: unknown): string {\n if (err instanceof Error) return err.message.toLowerCase();\n if (typeof err === 'string') return err.toLowerCase();\n if (err && typeof err === 'object' && 'message' in err) {\n return String(err.message).toLowerCase();\n }\n return '';\n}\n\nfunction extractRetryAfter(err: unknown): number | undefined {\n if (err && typeof err === 'object') {\n // Anthropic SDK puts headers on the error\n const headers: unknown = 'headers' in err ? err.headers : undefined;\n if (headers && typeof headers === 'object') {\n const retryAfter: unknown =\n 'get' in headers && typeof headers.get === 'function'\n ? headers.get('retry-after')\n : 'retry-after' in headers\n ? headers['retry-after']\n : undefined;\n if (retryAfter) {\n const seconds = Number(retryAfter);\n if (!Number.isNaN(seconds)) return seconds * 1000;\n }\n }\n }\n return undefined;\n}\n", "// packages/functions/src/shared/billing/apiVersion.ts\n\n/**\n * @fileoverview Stripe API version pin\n * @description Single source of truth for the Stripe API version the framework\n * reads. The subscription handlers still read pre-basil fields\n * (`invoice.subscription`, `subscription.current_period_end`), so the pin stays\n * on acacia; StripeOrder needs `collected_information` (2025-02-24.acacia).\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\n/**\n * Stripe API version used by `initStripe` when `STRIPE_API_VERSION` is unset,\n * and the oldest version whose Checkout Session payload StripeOrder can read.\n * Webhook event payloads follow the webhook ENDPOINT's API version (set when\n * the endpoint is created in the Dashboard or API), not this value.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const STRIPE_API_VERSION_PIN = '2025-02-24.acacia';\n", "// packages/functions/src/shared/billing/orderWebhook.ts\n\n/**\n * @fileoverview StripeOrder webhook handling\n * @description Maps Checkout Session events of one-time, multi-line orders to the\n * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`), and\n * `customer.tax_id.updated` to `onTaxIdUpdated`.\n * Hook errors propagate: the webhook answers non-2xx and Stripe retries.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport type {\n CheckoutAddress,\n CheckoutSessionSnapshot,\n OrderHookContext,\n PaidLineItem,\n StripeBackConfig,\n StripeOrderBackItem,\n TaxIdSnapshot,\n} from '@donotdev/core/server';\n\nimport { logger } from '../logger.js';\nimport { STRIPE_API_VERSION_PIN } from './apiVersion.js';\n\n/**\n * Checkout Session events that concern orders.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport type OrderSessionEventType =\n | 'checkout.session.completed'\n | 'checkout.session.async_payment_succeeded'\n | 'checkout.session.async_payment_failed'\n | 'checkout.session.expired';\n\n/**\n * Oldest Stripe API version whose Checkout Session payload StripeOrder can read\n * (`collected_information` was added in 2025-02-24.acacia). Alias of\n * {@link STRIPE_API_VERSION_PIN}.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const MIN_ORDER_API_VERSION = STRIPE_API_VERSION_PIN;\n\n/** Metadata key carrying the app order ID on the Checkout Session. */\nexport const ORDER_ID_METADATA_KEY = 'orderId';\n\n/** Product metadata key carrying the app product ID on each line. */\nexport const PRODUCT_ID_METADATA_KEY = 'productId';\n\nfunction idOf(value: string | { id: string } | null): string | null {\n if (value === null) return null;\n return typeof value === 'string' ? value : value.id;\n}\n\ntype StripeAddressFields = Pick<\n Stripe.Address,\n 'line1' | 'line2' | 'postal_code' | 'city' | 'state' | 'country'\n>;\n\nfunction toAddress(address: StripeAddressFields): CheckoutAddress {\n return {\n line1: address.line1,\n line2: address.line2,\n postalCode: address.postal_code,\n city: address.city,\n state: address.state,\n country: address.country,\n };\n}\n\n/**\n * Map a Stripe Checkout Session to the provider-neutral snapshot given to order hooks.\n *\n * @param session - Checkout Session from a webhook event\n * @returns Snapshot (amounts in the smallest currency unit)\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function toCheckoutSessionSnapshot(\n session: Stripe.Checkout.Session\n): CheckoutSessionSnapshot {\n const details = session.customer_details;\n const shipping = session.collected_information?.shipping_details ?? null;\n return {\n id: session.id,\n paymentStatus: session.payment_status,\n currency: session.currency,\n amountSubtotal: session.amount_subtotal,\n amountTax: session.total_details?.amount_tax ?? null,\n amountShipping: session.total_details?.amount_shipping ?? null,\n amountDiscount: session.total_details?.amount_discount ?? null,\n amountTotal: session.amount_total,\n customerId: idOf(session.customer),\n customer: details\n ? {\n email: details.email,\n name: details.name,\n phone: details.phone,\n businessName: details.business_name,\n address: details.address ? toAddress(details.address) : null,\n taxIds: (details.tax_ids ?? []).map((taxId) => ({\n type: taxId.type,\n value: taxId.value,\n })),\n taxExempt: details.tax_exempt,\n }\n : null,\n shipping: shipping\n ? { name: shipping.name, address: toAddress(shipping.address) }\n : null,\n invoiceId: idOf(session.invoice),\n paymentIntentId: idOf(session.payment_intent),\n metadata: session.metadata ?? {},\n };\n}\n\n/**\n * Read the charged lines of a session back from Stripe.\n *\n * @param stripe - Stripe client\n * @param sessionId - Checkout Session ID\n * @returns Lines with the app product ID and charged amounts\n * @throws When a line carries no app product ID (not created by the framework)\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport async function listPaidLineItems(\n stripe: Stripe,\n sessionId: string\n): Promise<PaidLineItem[]> {\n const lines: PaidLineItem[] = [];\n for await (const item of stripe.checkout.sessions.listLineItems(sessionId, {\n limit: 100,\n expand: ['data.price.product'],\n })) {\n const product = item.price?.product;\n const productId =\n product && typeof product !== 'string' && !product.deleted\n ? product.metadata[PRODUCT_ID_METADATA_KEY]\n : undefined;\n if (!productId) {\n throw new Error(\n `Line item ${item.id} of session ${sessionId} has no ${PRODUCT_ID_METADATA_KEY} product metadata`\n );\n }\n lines.push({\n productId,\n name: item.description ?? '',\n quantity: item.quantity ?? 0,\n amountSubtotal: item.amount_subtotal,\n amountDiscount: item.amount_discount,\n amountTax: item.amount_tax,\n amountTotal: item.amount_total,\n });\n }\n return lines;\n}\n\n/**\n * Route one Checkout Session event of a StripeOrder item to the app hooks.\n *\n * - `completed` + `paid` / `no_payment_required` \u2192 `onOrderPaid`\n * - `completed` + `unpaid` (async method, e.g. SEPA debit) \u2192 wait for the async event\n * - `async_payment_succeeded` \u2192 `onOrderPaid`\n * - `async_payment_failed` \u2192 `onOrderPaymentFailed`\n * - `expired` \u2192 `onOrderExpired`\n *\n * @throws When the event API version is older than {@link MIN_ORDER_API_VERSION},\n * when metadata is incomplete, or when a hook throws\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport async function handleOrderSessionEvent(\n eventType: OrderSessionEventType,\n eventId: string,\n apiVersion: string | null,\n session: Stripe.Checkout.Session,\n billingConfigKey: string,\n orderItem: StripeOrderBackItem,\n stripe: Stripe\n): Promise<void> {\n // API versions are date-prefixed (YYYY-MM-DD.name): compare the dates.\n // event.api_version is the webhook ENDPOINT's version, not STRIPE_API_VERSION.\n if (\n !apiVersion ||\n apiVersion.slice(0, 10) < MIN_ORDER_API_VERSION.slice(0, 10)\n ) {\n throw new Error(\n `Stripe event ${eventId} (order ${session.metadata?.[ORDER_ID_METADATA_KEY] ?? 'unknown'}) was rendered with API version ${apiVersion}; ` +\n `StripeOrder requires ${MIN_ORDER_API_VERSION} or later. Webhook payloads follow the webhook endpoint's API version, ` +\n `not STRIPE_API_VERSION, and an existing endpoint's version cannot be edited: create a new endpoint ` +\n `(POST /v1/webhook_endpoints with api_version=${MIN_ORDER_API_VERSION}), set STRIPE_WEBHOOK_SECRET to its signing secret, ` +\n `disable the old endpoint, then resend the failed events. Stripe retries this event for up to 3 days.`\n );\n }\n\n const metadata = session.metadata ?? {};\n const userId = metadata.userId;\n const orderId = metadata[ORDER_ID_METADATA_KEY];\n if (!userId || !orderId) {\n throw new Error(\n `Order session ${session.id} is missing metadata: userId=${userId}, orderId=${orderId}`\n );\n }\n\n const ctx: OrderHookContext = { userId, orderId, billingConfigKey, eventId };\n const snapshot = toCheckoutSessionSnapshot(session);\n\n const isPaidNow =\n eventType === 'checkout.session.async_payment_succeeded' ||\n (eventType === 'checkout.session.completed' &&\n session.payment_status !== 'unpaid');\n\n if (isPaidNow) {\n const lineItems = await listPaidLineItems(stripe, session.id);\n await orderItem.onOrderPaid(snapshot, lineItems, ctx);\n logger.info('[Webhook] Order paid', {\n orderId,\n billingConfigKey,\n operation: 'order_paid',\n });\n return;\n }\n\n switch (eventType) {\n case 'checkout.session.completed':\n logger.info('[Webhook] Order awaiting async payment', {\n orderId,\n billingConfigKey,\n operation: 'order_payment_pending',\n });\n return;\n case 'checkout.session.async_payment_failed':\n if (orderItem.onOrderPaymentFailed) {\n await orderItem.onOrderPaymentFailed(snapshot, ctx);\n }\n logger.warn('[Webhook] Order payment failed', {\n orderId,\n billingConfigKey,\n operation: 'order_payment_failed',\n });\n return;\n case 'checkout.session.expired':\n if (orderItem.onOrderExpired) {\n await orderItem.onOrderExpired(snapshot, ctx);\n }\n logger.info('[Webhook] Order checkout expired', {\n orderId,\n billingConfigKey,\n operation: 'order_expired',\n });\n return;\n default:\n return;\n }\n}\n\n/**\n * Map a Stripe TaxId to the provider-neutral snapshot given to `onTaxIdUpdated`.\n *\n * @param taxId - TaxId from a `customer.tax_id.updated` event\n * @returns Snapshot\n *\n * @version 0.2.0\n * @since 0.2.3\n * @author AMBROISE PARK Consulting\n */\nexport function toTaxIdSnapshot(taxId: Stripe.TaxId): TaxIdSnapshot {\n return {\n id: taxId.id,\n customerId: idOf(taxId.customer),\n type: taxId.type,\n value: taxId.value,\n country: taxId.country,\n verification: taxId.verification && {\n status: taxId.verification.status,\n verifiedName: taxId.verification.verified_name,\n verifiedAddress: taxId.verification.verified_address,\n },\n };\n}\n\n/**\n * Handle `customer.tax_id.updated`: run `onTaxIdUpdated` of every StripeOrder item\n * that defines it, once per distinct function. Called by `processWebhook` after\n * signature verification and idempotency reservation (same path as order events).\n *\n * @param eventId - Stripe event ID\n * @param taxId - TaxId from the event\n * @param config - App back config\n * @throws When a hook throws (the webhook answers non-2xx and Stripe retries)\n *\n * @version 0.2.0\n * @since 0.2.3\n * @author AMBROISE PARK Consulting\n */\nexport async function handleTaxIdUpdated(\n eventId: string,\n taxId: Stripe.TaxId,\n config: StripeBackConfig\n): Promise<void> {\n const snapshot = toTaxIdSnapshot(taxId);\n const ran = new Set<StripeOrderBackItem['onTaxIdUpdated']>();\n for (const [billingConfigKey, item] of Object.entries(config)) {\n if (item.type !== 'StripeOrder' || !item.onTaxIdUpdated) continue;\n if (ran.has(item.onTaxIdUpdated)) continue;\n ran.add(item.onTaxIdUpdated);\n await item.onTaxIdUpdated(snapshot, { billingConfigKey, eventId });\n logger.info('[Webhook] Tax ID updated', {\n taxIdId: snapshot.id,\n status: snapshot.verification?.status ?? null,\n billingConfigKey,\n operation: 'tax_id_updated',\n });\n }\n if (ran.size === 0) {\n logger.debug('[Webhook] customer.tax_id.updated without onTaxIdUpdated hook', {\n eventId,\n });\n }\n}\n", "// packages/functions/src/shared/billing/checkoutPrice.ts\n\n/**\n * @fileoverview Single-price checkout (StripePayment / StripeSubscription)\n * @description 0.1.x pricing rules and the 0.1.x params \u2192 Stripe params mapping\n * used by `createCheckoutAlgorithm`.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport type {\n CheckoutMode,\n CheckoutSessionParams,\n CreateCheckoutSessionRequest,\n StripePaymentBackItem,\n StripeSubscriptionBackItem,\n} from '@donotdev/core/server';\n\n\n/** Price resolved for a single-price item (0.1.x rules). */\nexport interface PricePlan {\n /** Price charged */\n priceId: string;\n mode: CheckoutMode;\n}\n\n/**\n * 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must\n * match the config priceId when set), else the back-config priceId.\n */\nexport function resolvePricePlan(\n item: StripePaymentBackItem | StripeSubscriptionBackItem,\n request: CreateCheckoutSessionRequest\n): PricePlan {\n const { billingConfigKey: key, priceId } = request;\n const [line] = request.lineItems;\n if (\n request.lineItems.length !== 1 ||\n !line ||\n line.productId !== key ||\n line.quantity !== 1\n ) {\n throw new Error(\n `'${key}' is a single-price item: lineItems must be [{ productId: '${key}', quantity: 1 }]`\n );\n }\n\n const mode: CheckoutMode =\n request.mode ?? (item.type === 'StripeSubscription' ? 'subscription' : 'payment');\n\n if (priceId) {\n if (item.priceId && item.priceId !== priceId) {\n throw new Error('Price ID mismatch with configuration');\n }\n return { priceId, mode };\n }\n\n if (!item.priceId) {\n throw new Error(\n `'${key}' has no priceId in the back config: set one, send a priceId, or use StripeOrder for server-priced lines`\n );\n }\n return { priceId: item.priceId, mode };\n}\n\n/** 0.1.x params \u2192 Stripe params (what the 0.1.x Firebase/Supabase providers sent). */\nexport function toStripeSessionParams(\n params: CheckoutSessionParams\n): Stripe.Checkout.SessionCreateParams {\n const mode = params.mode || 'payment';\n return {\n mode,\n line_items: [\n { price: params.priceId, quantity: 1 },\n ],\n allow_promotion_codes: params.allowPromotionCodes,\n success_url: params.successUrl,\n cancel_url: params.cancelUrl,\n customer_email: params.customerEmail,\n metadata: params.metadata,\n // Renewal/cancellation events read the subscription's own metadata\n ...(mode === 'subscription' && {\n subscription_data: { metadata: params.metadata },\n }),\n };\n}\n", "// packages/functions/src/shared/billing/checkoutValidation.ts\n\n/**\n * @fileoverview Checkout validation helpers\n * @description Fail-loud checks run by `createCheckoutAlgorithm` before calling\n * Stripe: redirect URLs, client metadata, Stripe metadata limits, resolved\n * StripeOrder lines and manual Tax Rates.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport type { ResolvedOrder, ResolvedOrderSession } from '@donotdev/core/server';\n\n/** Stripe `client_reference_id` maximum length (Checkout Session create API). */\nconst MAX_CLIENT_REFERENCE_ID_LENGTH = 200;\n\n/**\n * Stripe metadata limits (https://docs.stripe.com/metadata): 50 keys, keys up\n * to 40 characters without square brackets, values up to 500 characters.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const STRIPE_METADATA_LIMITS = {\n maxKeys: 50,\n maxKeyLength: 40,\n maxValueLength: 500,\n} as const;\n\n/**\n * Validate URL has http/https protocol.\n * Platform-agnostic (no firebase logger dependency).\n */\nexport function validateCheckoutUrl(url: string, name: string): void {\n try {\n const parsed = new URL(url);\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new Error(`Invalid protocol: ${parsed.protocol}`);\n }\n } catch (error) {\n throw new Error(\n `Invalid ${name} URL: ${url}. ${error instanceof Error ? error.message : 'Invalid URL format'}`\n );\n }\n}\n\n/**\n * Sanitize client metadata: enforce string values, strip script injection.\n * Length limits are checked on the final metadata ({@link assertStripeMetadata}).\n */\nexport function sanitizeMetadata(\n metadata: Record<string, unknown>\n): Record<string, string> {\n const sanitized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value !== 'string') {\n throw new Error(\n `Metadata value for key '${key}' must be a string, got ${typeof value}`\n );\n }\n\n sanitized[key] = value\n .replace(/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi, '')\n .replace(/javascript:/gi, '')\n .replace(/on\\w+\\s*=/gi, '');\n }\n\n return sanitized;\n}\n\n/**\n * Throw a validation error when metadata exceeds Stripe's limits\n * ({@link STRIPE_METADATA_LIMITS}), instead of letting Stripe answer 400.\n *\n * @param metadata - Metadata as it will be sent to Stripe\n * @param target - Stripe param the metadata goes to (shown in the error)\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function assertStripeMetadata(\n metadata: Record<string, string | number | null>,\n target: string\n): void {\n const { maxKeys, maxKeyLength, maxValueLength } = STRIPE_METADATA_LIMITS;\n const entries = Object.entries(metadata);\n if (entries.length > maxKeys) {\n throw new Error(\n `${target}: ${entries.length} metadata keys, Stripe allows at most ${maxKeys} (server keys included)`\n );\n }\n for (const [key, value] of entries) {\n if (key.length > maxKeyLength) {\n throw new Error(\n `${target}: metadata key '${key}' is too long (max ${maxKeyLength} characters)`\n );\n }\n if (/[[\\]]/.test(key)) {\n throw new Error(\n `${target}: metadata key '${key}' must not contain square brackets`\n );\n }\n if (value !== null && String(value).length > maxValueLength) {\n throw new Error(\n `${target}: metadata value for key '${key}' is too long (max ${maxValueLength} characters)`\n );\n }\n }\n}\n\n/**\n * Check every metadata map of Checkout Session params (session, subscription,\n * payment intent, invoice, line products) against Stripe's limits.\n *\n * @param params - Session params about to be sent to Stripe\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function assertCheckoutSessionMetadata(\n params: Stripe.Checkout.SessionCreateParams\n): void {\n const targets: Array<[string, Stripe.MetadataParam | '' | undefined]> = [\n ['metadata', params.metadata],\n ['subscription_data.metadata', params.subscription_data?.metadata],\n ['payment_intent_data.metadata', params.payment_intent_data?.metadata],\n [\n 'invoice_creation.invoice_data.metadata',\n params.invoice_creation?.invoice_data?.metadata,\n ],\n ...(params.line_items ?? []).map(\n (line, i): [string, Stripe.MetadataParam | undefined] => [\n `line_items[${i}].price_data.product_data.metadata`,\n line.price_data?.product_data?.metadata,\n ]\n ),\n ];\n for (const [target, metadata] of targets) {\n if (metadata) assertStripeMetadata(metadata, target);\n }\n}\n\n/**\n * Validate the output of an app `resolveLineItems` hook. Fails loud on any\n * malformed line instead of sending it to Stripe.\n */\nexport function assertResolvedOrder(\n order: ResolvedOrder,\n configKey: string\n): void {\n if (!order.orderId) {\n throw new Error(`resolveLineItems for '${configKey}' returned no orderId`);\n }\n if (order.orderId.length > MAX_CLIENT_REFERENCE_ID_LENGTH) {\n throw new Error(\n `resolveLineItems for '${configKey}': orderId is sent as client_reference_id (max ${MAX_CLIENT_REFERENCE_ID_LENGTH} characters), got ${order.orderId.length}`\n );\n }\n if (order.lineItems.length === 0) {\n throw new Error(`resolveLineItems for '${configKey}' returned no lines`);\n }\n if (order.session) assertResolvedOrderSession(order.session, configKey);\n for (const line of order.lineItems) {\n if (!line.productId || !line.name) {\n throw new Error(\n `resolveLineItems for '${configKey}' returned a line without productId or name`\n );\n }\n if (!Number.isInteger(line.unitAmount) || line.unitAmount < 0) {\n throw new Error(\n `Line '${line.productId}': unitAmount must be a non-negative integer (smallest currency unit), got ${line.unitAmount}`\n );\n }\n if (!Number.isInteger(line.quantity) || line.quantity < 1) {\n throw new Error(\n `Line '${line.productId}': quantity must be a positive integer, got ${line.quantity}`\n );\n }\n if (line.taxCode !== undefined && !STRIPE_TAX_CODE.test(line.taxCode)) {\n throw new Error(\n `Line '${line.productId}': taxCode must be a Stripe tax code (txcd_ + 8 digits), got '${line.taxCode}'`\n );\n }\n }\n}\n\n/** Stripe Checkout `expires_at` window (seconds after creation). */\nexport const CHECKOUT_EXPIRY_WINDOW = { minSeconds: 30 * 60, maxSeconds: 24 * 60 * 60 } as const;\n\n/** Stripe invoice footer maximum length. */\nconst MAX_INVOICE_FOOTER_LENGTH = 5000;\n\nconst ORDER_PAYMENT_METHOD_TYPES = ['card', 'sepa_debit'] as const;\n\n/** Stripe Customer ID shape. */\nconst STRIPE_CUSTOMER_ID = /^cus_[A-Za-z0-9]+$/;\n\n/** Stripe tax code shape (https://docs.stripe.com/tax/tax-codes), e.g. `txcd_92010001`. */\nconst STRIPE_TAX_CODE = /^txcd_\\d{8}$/;\n\n/**\n * Validate per-order session options returned by `resolveLineItems`.\n * Item-dependent checks (manual tax, invoice creation) run in `createCheckoutAlgorithm`.\n *\n * @param session - `ResolvedOrder.session`\n * @param configKey - Back config key (shown in errors)\n * @param nowSeconds - Current Unix time (injectable for tests)\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function assertResolvedOrderSession(\n session: ResolvedOrderSession,\n configKey: string,\n nowSeconds: number = Math.floor(Date.now() / 1000)\n): void {\n const { taxRateIds, paymentMethodTypes, expiresAt, invoiceFooter, customerId } =\n session;\n if (customerId !== undefined && !STRIPE_CUSTOMER_ID.test(customerId)) {\n throw new Error(\n `resolveLineItems for '${configKey}': session.customerId must be a Stripe Customer ID (cus_...), got '${customerId}'`\n );\n }\n if (taxRateIds && taxRateIds.some((id) => typeof id !== 'string' || id.length === 0)) {\n throw new Error(\n `resolveLineItems for '${configKey}': session.taxRateIds must be non-empty strings`\n );\n }\n if (paymentMethodTypes) {\n if (paymentMethodTypes.length === 0) {\n throw new Error(\n `resolveLineItems for '${configKey}': session.paymentMethodTypes must not be empty`\n );\n }\n for (const type of paymentMethodTypes) {\n if (!(ORDER_PAYMENT_METHOD_TYPES as readonly string[]).includes(type)) {\n throw new Error(\n `resolveLineItems for '${configKey}': unsupported payment method type '${type}'`\n );\n }\n }\n }\n if (expiresAt !== undefined) {\n const { minSeconds, maxSeconds } = CHECKOUT_EXPIRY_WINDOW;\n if (\n !Number.isInteger(expiresAt) ||\n expiresAt < nowSeconds + minSeconds ||\n expiresAt > nowSeconds + maxSeconds\n ) {\n throw new Error(\n `resolveLineItems for '${configKey}': session.expiresAt must be a Unix time 30 minutes to 24 hours from now (Stripe), got ${expiresAt}`\n );\n }\n }\n if (\n invoiceFooter !== undefined &&\n (invoiceFooter.length === 0 || invoiceFooter.length > MAX_INVOICE_FOOTER_LENGTH)\n ) {\n throw new Error(\n `resolveLineItems for '${configKey}': session.invoiceFooter must be 1 to ${MAX_INVOICE_FOOTER_LENGTH} characters`\n );\n }\n}\n\n/** Inclusive flag per Tax Rate ID: one Stripe call per ID per instance (cold start). */\nconst taxRateInclusiveCache = new Map<string, Promise<boolean>>();\n\n/**\n * StripeOrder manual tax: unit amounts are excl. VAT, but an inclusive Tax Rate\n * overrides `price_data.tax_behavior: 'exclusive'` and carves the tax out of\n * the amount. Throws when any configured rate is inclusive.\n */\nexport async function assertExclusiveTaxRates(\n retrieveTaxRate: (id: string) => Promise<{ inclusive: boolean }>,\n taxRateIds: string[],\n configKey: string\n): Promise<void> {\n for (const id of taxRateIds) {\n let inclusive = taxRateInclusiveCache.get(id);\n if (!inclusive) {\n inclusive = retrieveTaxRate(id).then((rate) => rate.inclusive);\n taxRateInclusiveCache.set(id, inclusive);\n // Failures are not cached: the next checkout retries\n inclusive.catch(() => taxRateInclusiveCache.delete(id));\n }\n if (await inclusive) {\n throw new Error(\n `'${configKey}': Tax Rate '${id}' is inclusive. StripeOrder unit amounts are excl. VAT: use an exclusive Tax Rate (inclusive: false).`\n );\n }\n }\n}\n", "// packages/functions/src/shared/billing/createCheckout.ts\n\n/**\n * @fileoverview Create Checkout Session Algorithm\n * @description Platform-agnostic algorithm for creating Stripe checkout sessions.\n * StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or\n * back-config priceId). StripeOrder items are priced on\n * the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport type {\n BeforeCheckoutOptions,\n CheckoutSessionParams,\n CheckoutSessionResult,\n CreateCheckoutSessionRequest,\n CreateCheckoutSessionRequestInput,\n CreateCheckoutSessionResponse,\n ResolvedOrder,\n StripeBackConfig,\n StripeCheckoutProvider,\n StripeOrderBackItem,\n} from '@donotdev/core/server';\n\nimport { resolvePricePlan, toStripeSessionParams } from './checkoutPrice.js';\nimport {\n assertCheckoutSessionMetadata,\n assertExclusiveTaxRates,\n assertResolvedOrder,\n assertStripeMetadata,\n sanitizeMetadata,\n validateCheckoutUrl,\n} from './checkoutValidation.js';\nimport {\n ORDER_ID_METADATA_KEY,\n PRODUCT_ID_METADATA_KEY,\n} from './orderWebhook.js';\n\n/**\n * Provider that sends full Stripe session params (every item type, StripeOrder included).\n *\n * @example\n * ```typescript\n * const provider: StripeSessionProvider = {\n * async createStripeSession(params) {\n * const session = await stripe.checkout.sessions.create(params);\n * return { id: session.id, url: session.url };\n * },\n * async retrieveTaxRate(id) {\n * const rate = await stripe.taxRates.retrieve(id);\n * return { id: rate.id, inclusive: rate.inclusive };\n * },\n * };\n * ```\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport interface StripeSessionProvider {\n createStripeSession(\n params: Stripe.Checkout.SessionCreateParams\n ): Promise<CheckoutSessionResult>;\n /** Used to reject inclusive Tax Rates on StripeOrder manual tax (cached per instance). */\n retrieveTaxRate(taxRateId: string): Promise<{ id: string; inclusive: boolean }>;\n}\n\n/**\n * Any provider accepted by {@link createCheckoutAlgorithm}.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport type CheckoutProvider = StripeCheckoutProvider | StripeSessionProvider;\n\n/**\n * Provider interface for authentication operations\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport interface AuthCheckoutProvider {\n getUser(userId: string): Promise<{\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)\n customClaims?: Record<string, any>;\n }>;\n}\n\nfunction isSessionProvider(\n provider: CheckoutProvider\n): provider is StripeSessionProvider {\n return 'createStripeSession' in provider;\n}\n\n/** 0.1.x: empty redirect URLs default to FRONTEND_URL pages. */\nfunction resolveRedirectUrl(url: string, path: string): string {\n if (url) return url;\n const frontendUrl = process.env.FRONTEND_URL;\n if (!frontendUrl) {\n throw new Error(`Missing ${path} redirect URL and FRONTEND_URL is not set`);\n }\n return `${frontendUrl}/billing/${path}`;\n}\n\n/** Common session params for StripeOrder. */\ninterface BaseSessionParams {\n successUrl: string;\n cancelUrl: string;\n customerEmail: string | undefined;\n metadata: Record<string, string>;\n}\n\n/**\n * What Checkout writes back to an existing Customer (`customer_update`):\n * - `address` under automatic tax: Stripe Tax needs an address on the Customer, the\n * billing address entered at checkout replaces the saved one;\n * - `shipping` when shipping is collected (Stripe: needs shipping_address_collection);\n * - `name` when tax ID collection is enabled (Stripe: required for existing customers).\n * Undefined when nothing applies (manual tax, no shipping, no tax ID collection).\n */\nfunction customerUpdate(\n item: StripeOrderBackItem,\n taxIdCollectionEnabled: boolean\n): Stripe.Checkout.SessionCreateParams.CustomerUpdate | undefined {\n const update: Stripe.Checkout.SessionCreateParams.CustomerUpdate = {\n ...(item.tax.mode === 'automatic' && { address: 'auto' }),\n ...(item.shipping && { shipping: 'auto' }),\n ...(taxIdCollectionEnabled && { name: 'auto' }),\n };\n return Object.keys(update).length > 0 ? update : undefined;\n}\n\n/**\n * Session params for a StripeOrder: server-priced lines (excl. VAT) and the\n * item's B2B options.\n */\nfunction buildOrderSessionParams(\n item: StripeOrderBackItem,\n order: ResolvedOrder,\n base: BaseSessionParams\n): Stripe.Checkout.SessionCreateParams {\n const options = order.session ?? {};\n const taxRates =\n item.tax.mode === 'manual'\n ? (options.taxRateIds ?? item.tax.taxRateIds)\n : undefined;\n const metadata = { ...base.metadata, [ORDER_ID_METADATA_KEY]: order.orderId };\n const taxIdCollectionEnabled = item.taxIdCollection !== 'disabled';\n const update = customerUpdate(item, taxIdCollectionEnabled);\n\n // Existing Customer: Stripe applies customer_email / customer_creation only when it\n // creates a Customer, so they are replaced by customer + customer_update.\n const customerParams: Pick<\n Stripe.Checkout.SessionCreateParams,\n 'customer' | 'customer_update' | 'customer_email' | 'customer_creation'\n > = options.customerId\n ? {\n customer: options.customerId,\n ...(update && { customer_update: update }),\n }\n : {\n customer_creation: item.customerCreation,\n customer_email: base.customerEmail,\n };\n\n return {\n mode: 'payment',\n client_reference_id: order.orderId,\n line_items: order.lineItems.map((line) => ({\n price_data: {\n currency: item.currency,\n unit_amount: line.unitAmount,\n tax_behavior: 'exclusive',\n product_data: {\n name: line.name,\n ...(line.description && { description: line.description }),\n ...(line.taxCode && { tax_code: line.taxCode }),\n metadata: { [PRODUCT_ID_METADATA_KEY]: line.productId },\n },\n },\n quantity: line.quantity,\n ...(taxRates && taxRates.length > 0 && { tax_rates: taxRates }),\n })),\n automatic_tax: { enabled: item.tax.mode === 'automatic' },\n tax_id_collection: taxIdCollectionEnabled\n ? {\n enabled: true,\n required:\n item.taxIdCollection === 'required' ? 'if_supported' : 'never',\n }\n : { enabled: false },\n billing_address_collection: item.billingAddressCollection,\n ...(item.shipping && {\n shipping_address_collection: {\n // Config validated as uppercase ISO 3166-1 alpha-2; stripe@20 types the param as a closed enum\n allowed_countries: item.shipping\n .allowedCountries as Stripe.Checkout.SessionCreateParams.ShippingAddressCollection.AllowedCountry[],\n },\n ...(item.shipping.shippingRateIds && {\n shipping_options: item.shipping.shippingRateIds.map((id) => ({\n shipping_rate: id,\n })),\n }),\n }),\n ...customerParams,\n invoice_creation: {\n enabled: item.invoiceCreation,\n ...(item.invoiceCreation && {\n invoice_data: {\n metadata,\n ...(options.invoiceFooter && { footer: options.invoiceFooter }),\n },\n }),\n },\n // Per-order methods replace the configuration (Stripe accepts one or the other)\n ...(options.paymentMethodTypes\n ? { payment_method_types: options.paymentMethodTypes }\n : item.paymentMethodConfiguration && {\n payment_method_configuration: item.paymentMethodConfiguration,\n }),\n ...(options.expiresAt !== undefined && { expires_at: options.expiresAt }),\n // Orders: merchant policy from the back config only\n allow_promotion_codes: item.allowPromotionCodes === true,\n success_url: base.successUrl,\n cancel_url: base.cancelUrl,\n metadata,\n payment_intent_data: { metadata },\n };\n}\n\ntype CheckoutArgs =\n | [CheckoutProvider, AuthCheckoutProvider, StripeBackConfig]\n | [string, CheckoutProvider, AuthCheckoutProvider, StripeBackConfig];\n\n/**\n * Create checkout session algorithm\n *\n * 1. Resolve the billing config item and verify the user\n * 2. Single-price items: 0.1.x pricing (request/back-config priceId)\n * 3. `beforeCheckout` hook (block/allow)\n * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line\n * and may set per-order session options (`ResolvedOrder.session`: tax rates,\n * payment methods, expiry, invoice footer, existing Stripe customer)\n * 5. Validate metadata against Stripe limits, create the session through the provider\n *\n * Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after\n * the client metadata and cannot be overwritten by it.\n *\n * Two call shapes:\n * - `(request, userId, stripeProvider, authProvider, billingConfig)`: userId from\n * the provider's auth context (framework providers use this).\n * - 0.1.x `(request, stripeProvider, authProvider, billingConfig)`: userId read from\n * `request.userId` (the caller must set it from its auth context).\n *\n * @example\n * ```typescript\n * const result = await createCheckoutAlgorithm(\n * request,\n * context.uid,\n * stripeSessionProvider,\n * authProvider,\n * billingConfig\n * );\n * ```\n *\n * @param request - Validated client request (0.1.x shape accepted)\n * @param userId - Authenticated user ID (omit in the 0.1.x call shape)\n * @param stripeProvider - {@link StripeSessionProvider}, or 0.1.x {@link StripeCheckoutProvider} (single-price items only)\n * @param authProvider - Verifies the user exists\n * @param billingConfig - App back config\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function createCheckoutAlgorithm(\n request: CreateCheckoutSessionRequestInput,\n userId: string,\n stripeProvider: CheckoutProvider,\n authProvider: AuthCheckoutProvider,\n billingConfig: StripeBackConfig\n): Promise<CreateCheckoutSessionResponse>;\nexport async function createCheckoutAlgorithm(\n request: CreateCheckoutSessionRequestInput,\n stripeProvider: CheckoutProvider,\n authProvider: AuthCheckoutProvider,\n billingConfig: StripeBackConfig\n): Promise<CreateCheckoutSessionResponse>;\nexport async function createCheckoutAlgorithm(\n input: CreateCheckoutSessionRequestInput,\n ...args: CheckoutArgs\n): Promise<CreateCheckoutSessionResponse> {\n const legacyCall = args.length === 3;\n const [userId, stripeProvider, authProvider, billingConfig] =\n args.length === 3 ? [input.userId, ...args] : args;\n if (!userId) {\n throw new Error(\n legacyCall ? 'Missing userId in request' : 'Missing authenticated userId'\n );\n }\n\n const billingConfigKey =\n input.billingConfigKey || input.metadata?.billingConfigKey;\n if (!billingConfigKey) {\n throw new Error('Missing billingConfigKey (request or metadata)');\n }\n const request: CreateCheckoutSessionRequest = {\n ...input,\n billingConfigKey,\n lineItems: input.lineItems ?? [{ productId: billingConfigKey, quantity: 1 }],\n };\n\n const billingItem = billingConfig[billingConfigKey];\n if (!billingItem) {\n throw new Error(`Invalid billing config key: ${billingConfigKey}`);\n }\n\n const isOrder = billingItem.type === 'StripeOrder';\n const plan = isOrder ? undefined : resolvePricePlan(billingItem, request);\n\n // Verify user exists\n await authProvider.getUser(userId);\n\n const clientMetadata = sanitizeMetadata(request.metadata ?? {});\n // Server values AFTER spread \u2014 cannot be overwritten by client\n const metadata = { ...clientMetadata, userId, billingConfigKey };\n // Fail before any hook side effect (StripeOrder creates a pending order)\n assertStripeMetadata(\n isOrder ? { ...metadata, [ORDER_ID_METADATA_KEY]: '' } : metadata,\n 'metadata'\n );\n\n const allowPromotionCodes = request.allowPromotionCodes ?? true;\n\n if (billingItem.beforeCheckout) {\n const options: BeforeCheckoutOptions = {\n ...request,\n userId,\n mode: plan?.mode ?? 'payment',\n priceId: plan?.priceId,\n metadata: request.metadata ?? {},\n allowPromotionCodes,\n };\n const hookResult = await billingItem.beforeCheckout(\n userId,\n options,\n clientMetadata\n );\n if (!hookResult.allowed) {\n throw new Error(\n hookResult.reason || 'Checkout blocked by beforeCheckout hook'\n );\n }\n }\n\n const successUrl = resolveRedirectUrl(request.successUrl, 'success');\n const cancelUrl = resolveRedirectUrl(request.cancelUrl, 'cancel');\n validateCheckoutUrl(successUrl, 'success');\n validateCheckoutUrl(cancelUrl, 'cancel');\n\n let session: CheckoutSessionResult;\n if (billingItem.type === 'StripeOrder') {\n if (!isSessionProvider(stripeProvider)) {\n throw new Error(\n `'${billingConfigKey}' is a StripeOrder: the checkout provider must implement createStripeSession (StripeSessionProvider)`\n );\n }\n if (billingItem.tax.mode === 'manual') {\n await assertExclusiveTaxRates(\n (id) => stripeProvider.retrieveTaxRate(id),\n billingItem.tax.taxRateIds,\n billingConfigKey\n );\n }\n const order = await billingItem.resolveLineItems(request.lineItems, {\n userId,\n billingConfigKey,\n metadata: clientMetadata,\n });\n assertResolvedOrder(order, billingConfigKey);\n const sessionOptions = order.session;\n if (sessionOptions?.taxRateIds) {\n if (billingItem.tax.mode !== 'manual') {\n throw new Error(\n `resolveLineItems for '${billingConfigKey}': session.taxRateIds needs tax.mode 'manual'`\n );\n }\n await assertExclusiveTaxRates(\n (id) => stripeProvider.retrieveTaxRate(id),\n sessionOptions.taxRateIds,\n billingConfigKey\n );\n }\n if (\n billingItem.tax.mode !== 'automatic' &&\n order.lineItems.some((line) => line.taxCode !== undefined)\n ) {\n throw new Error(\n `resolveLineItems for '${billingConfigKey}': line taxCode needs tax.mode 'automatic'`\n );\n }\n if (sessionOptions?.invoiceFooter && !billingItem.invoiceCreation) {\n throw new Error(\n `resolveLineItems for '${billingConfigKey}': session.invoiceFooter needs invoiceCreation`\n );\n }\n const params = buildOrderSessionParams(billingItem, order, {\n successUrl,\n cancelUrl,\n customerEmail: request.customerEmail,\n metadata,\n });\n assertCheckoutSessionMetadata(params);\n session = await stripeProvider.createStripeSession(params);\n } else {\n const params: CheckoutSessionParams = {\n priceId: plan?.priceId,\n currency: request.currency || billingItem.currency || 'eur',\n customerEmail: request.customerEmail,\n metadata,\n allowPromotionCodes,\n successUrl,\n cancelUrl,\n mode: plan?.mode,\n };\n if (isSessionProvider(stripeProvider)) {\n const stripeParams = toStripeSessionParams(params);\n assertCheckoutSessionMetadata(stripeParams);\n session = await stripeProvider.createStripeSession(stripeParams);\n } else {\n session = await stripeProvider.createCheckoutSession(params);\n }\n }\n\n return {\n sessionId: session.id,\n sessionUrl: session.url,\n };\n}\n", "// packages/functions/src/shared/billing/helpers/updateUserSubscription.ts\n\n/**\n * @fileoverview User subscription update utilities\n * @description Functions for updating user subscription data\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport * as v from 'valibot';\n\nimport { SubscriptionClaimsSchema } from '@donotdev/core/server';\nimport type { BillingAuthProvider, SubscriptionUpdate } from '@donotdev/core/server';\n\n/**\n * Platform-agnostic subscription update using dependency injection\n * Works on Firebase Functions, Vercel, AWS Lambda, etc.\n * Validates canonical auth claims; one-time payments may have no billing customer.\n * Billing identifiers are preserved when supplied, never fabricated from a user ID.\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function updateUserSubscription(\n userId: string,\n subscriptionData: SubscriptionUpdate,\n authProvider: BillingAuthProvider\n): Promise<void> {\n const user = await authProvider.getUser(userId);\n const currentClaims = user.customClaims || {};\n\n if (!subscriptionData.tier || !subscriptionData.status) {\n throw new Error('Invalid subscription data: missing tier or status');\n }\n\n const subscriptionClaims = v.parse(SubscriptionClaimsSchema, {\n tier: subscriptionData.tier,\n subscriptionId: subscriptionData.subscriptionId ?? null,\n customerId: subscriptionData.customerId ?? null,\n status: subscriptionData.status,\n // Keep as ISO string - no conversion needed\n subscriptionEnd: subscriptionData.subscriptionEnd,\n cancelAtPeriodEnd: subscriptionData.cancelAtPeriodEnd ?? false,\n updatedAt: new Date().toISOString(),\n isDefault: false,\n });\n\n const updatedClaims = {\n ...currentClaims,\n subscription: subscriptionClaims,\n };\n\n await authProvider.setCustomUserClaims(userId, updatedClaims);\n}\n", "// packages/functions/src/shared/billing/idempotencyContract.ts\n\n/**\n * @fileoverview Webhook idempotency contract\n * @description Store interface, reservation result, lease and retention shared\n * by every idempotency store (in-memory, Firestore, Postgres).\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\n/**\n * Outcome of {@link IdempotencyStore.reserve}.\n * - `reserved`: the caller owns the event and must process it, then call\n * `markProcessed` or `release` with `ownerToken`\n * - `processed`: already processed, skip (answer 2xx)\n * - `in_progress`: another delivery holds a live lease (answer non-2xx so the\n * provider retries later, when that worker finished or its lease expired)\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport type ReservationResult =\n | { state: 'reserved'; ownerToken: string }\n | { state: 'processed' }\n | { state: 'in_progress' };\n\n/**\n * Idempotency store interface\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport interface IdempotencyStore {\n /** Atomically reserve an event for processing. */\n reserve(eventId: string): Promise<ReservationResult>;\n /**\n * Mark a reservation processed. Repeating it for the same owner succeeds.\n * @throws {ReservationLostError} When `ownerToken` no longer owns the event\n */\n markProcessed(eventId: string, ownerToken: string): Promise<void>;\n /**\n * Drop a reservation after a processing failure.\n * @returns `false` when `ownerToken` does not own a pending reservation (nothing changed)\n */\n release(eventId: string, ownerToken: string): Promise<boolean>;\n}\n\n/**\n * Thrown by `markProcessed` when the caller no longer owns the reservation:\n * its lease expired and another delivery retook the event, or the row is gone.\n * Retrying cannot succeed.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport class ReservationLostError extends Error {\n /** Event whose reservation was lost. */\n readonly eventId: string;\n\n constructor(eventId: string) {\n super(\n `Reservation of webhook event ${eventId} is no longer held by this worker (lease retaken or row removed)`\n );\n this.name = 'ReservationLostError';\n this.eventId = eventId;\n }\n}\n\n/**\n * How long a reservation blocks other deliveries of the same event before it\n * is considered abandoned (worker crashed or timed out) and can be retaken.\n *\n * Must exceed the longest request timeout a webhook handler can run under, so\n * a live worker is never overtaken. Official maximums (checked 2026-11-04):\n * - Firebase Functions gen2 HTTP: 60 min\n * (https://firebase.google.com/docs/functions/quotas#time_limits)\n * - Vercel Functions: 800 s, 1800 s with extended max duration\n * (https://vercel.com/docs/functions/configuring-functions/duration)\n * - Supabase Edge Functions: 400 s wall clock on paid plans\n * (https://supabase.com/docs/guides/functions/limits)\n * 70 min = the 60 min maximum + 10 min margin. Stripe retries for up to 3 days.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const RESERVATION_LEASE_MS = 70 * 60 * 1000;\n\n/**\n * How long reservations and processed events are kept before a TTL policy\n * (Firestore `expiresAt`) or the pg_cron cleanup (Postgres) deletes them.\n * Stripe retries for days, not weeks.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const WEBHOOK_EVENT_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\n\n/**\n * New reservation owner token (random UUID). Internal to the stores.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function newOwnerToken(): string {\n return crypto.randomUUID();\n}\n", "// packages/functions/src/shared/billing/stripePinned.ts\n\n/**\n * @fileoverview Typed access to Stripe fields of the pinned API version\n * @description The Stripe SDK types follow the latest API version only, while\n * requests run at `STRIPE_API_VERSION_PIN` (pre-basil). Fields that basil\n * moved (subscription period, invoice subscription) are read here, through one\n * documented cast, instead of `as any` at every call site. Internal: not\n * re-exported from any package entry.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\n/** Subscription fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */\ninterface PinnedSubscriptionFields {\n current_period_start: number;\n current_period_end: number;\n}\n\n/** Invoice fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */\ninterface PinnedInvoiceFields {\n /** Not expanded in webhook payloads: the subscription id, or null for one-off invoices. */\n subscription: string | null;\n}\n\n/**\n * Period fields of a subscription at the pinned API version.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\nexport function pinnedSubscriptionPeriod(\n subscription: Stripe.Subscription\n): PinnedSubscriptionFields {\n // why: SDK v20 types track the latest API (period moved to items); runtime is pinned pre-basil\n return subscription as unknown as PinnedSubscriptionFields;\n}\n\n/**\n * Subscription id of an invoice at the pinned API version.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\nexport function pinnedInvoiceSubscriptionId(\n invoice: Stripe.Invoice\n): string | null {\n // why: SDK v20 types track the latest API (moved to invoice.parent); runtime is pinned pre-basil\n return (invoice as unknown as PinnedInvoiceFields).subscription;\n}\n\n/**\n * Narrows a value to one of a readonly list of literals.\n *\n * @version 0.1.0\n * @since 0.2.2\n * @author AMBROISE PARK Consulting\n */\nexport function isOneOf<T extends string>(\n values: readonly T[],\n value: string\n): value is T {\n const list: readonly string[] = values;\n return list.includes(value);\n}\n", "// packages/functions/src/shared/billing/tierWebhookEvents.ts\n\n/**\n * @fileoverview Stripe webhook handlers for tier items\n * @description StripePayment / StripeSubscription event handlers routed by\n * `processWebhook`: checkout grant (payment_status aware), renewal,\n * cancellation and payment failure.\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport {\n calculateSubscriptionEndDate,\n SUBSCRIPTION_STATUS,\n SUBSCRIPTION_TIERS,\n} from '@donotdev/core/server';\nimport type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';\n\nimport { handleError } from '../errorHandling.js';\nimport { logger } from '../logger.js';\nimport type { OrderSessionEventType } from './orderWebhook.js';\nimport { pinnedInvoiceSubscriptionId, pinnedSubscriptionPeriod } from './stripePinned.js';\n\n/**\n * Checkout Session event of a StripePayment / StripeSubscription item.\n * Grants only once the payment is settled (Stripe fulfillment guide,\n * https://docs.stripe.com/checkout/fulfillment):\n * - `completed` + `paid` / `no_payment_required` \u2192 grant\n * - `completed` + `unpaid` (delayed method, e.g. SEPA debit) \u2192 log, wait\n * - `async_payment_succeeded` \u2192 grant\n * - `async_payment_failed` \u2192 log (nothing was granted)\n * - `expired` \u2192 ignored\n *\n * @throws When `payment_status` is not a known value, or when the grant fails\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport async function handleTierCheckoutEvent(\n eventType: OrderSessionEventType,\n session: Stripe.Checkout.Session,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n const logContext = {\n sessionId: session.id,\n billingConfigKey: session.metadata?.billingConfigKey,\n userId: session.metadata?.userId,\n paymentStatus: session.payment_status,\n };\n switch (eventType) {\n case 'checkout.session.completed':\n if (session.payment_status === 'unpaid') {\n logger.info('[Webhook] Purchase awaiting async payment', {\n ...logContext,\n operation: 'purchase_payment_pending',\n });\n return;\n }\n if (\n session.payment_status !== 'paid' &&\n session.payment_status !== 'no_payment_required'\n ) {\n throw handleError(\n new Error(\n `Checkout session ${session.id} has unknown payment_status ${String(session.payment_status)}`\n )\n );\n }\n await grantCheckoutPurchase(\n session,\n config,\n updateSubscription,\n authProvider\n );\n return;\n case 'checkout.session.async_payment_succeeded':\n await grantCheckoutPurchase(\n session,\n config,\n updateSubscription,\n authProvider\n );\n return;\n case 'checkout.session.async_payment_failed':\n logger.warn('[Webhook] Async purchase payment failed, nothing granted', {\n ...logContext,\n operation: 'purchase_payment_failed',\n });\n return;\n case 'checkout.session.expired':\n logger.debug('[Webhook] Checkout session expired', logContext);\n return;\n }\n}\n\n/**\n * Grant the tier bought in a paid Checkout Session, then run the item hook.\n * Idempotent: it writes the same subscription state again on a replay.\n */\nasync function grantCheckoutPurchase(\n session: Stripe.Checkout.Session,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n const { userId, billingConfigKey } = session.metadata || {};\n\n if (!userId || !billingConfigKey) {\n throw handleError(\n new Error(\n `Missing required metadata: userId=${userId}, billingConfigKey=${billingConfigKey}`\n )\n );\n }\n\n const billingItem = config[billingConfigKey];\n if (!billingItem) {\n throw handleError(\n new Error(`Unknown billing config key: ${billingConfigKey}`)\n );\n }\n\n logger.info('[Webhook] Processing purchase', {\n userId,\n configKey: billingConfigKey,\n type: billingItem.type,\n operation: 'purchase_processing',\n });\n\n // Update subscription\n if (billingItem.type === 'StripePayment') {\n if (!authProvider) {\n throw handleError(\n new Error('Auth provider required for subscription updates')\n );\n }\n await updateSubscription(\n userId,\n {\n tier: billingItem.tier,\n status: SUBSCRIPTION_STATUS.ACTIVE,\n subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),\n customerId: session.customer as string,\n },\n authProvider\n );\n\n // Execute hook with graceful error handling\n if (billingItem.onPurchaseSuccess) {\n try {\n await billingItem.onPurchaseSuccess(userId, session.metadata || {});\n } catch (error) {\n // Hook failures are non-critical - payment already processed\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onPurchaseSuccess',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n }\n\n if (billingItem.type === 'StripeSubscription') {\n if (!authProvider) {\n throw handleError(\n new Error('Auth provider required for subscription updates')\n );\n }\n await updateSubscription(\n userId,\n {\n tier: billingItem.tier,\n status: SUBSCRIPTION_STATUS.ACTIVE,\n subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),\n subscriptionId: session.subscription as string,\n customerId: session.customer as string,\n },\n authProvider\n );\n\n // Execute hook with graceful error handling\n if (billingItem.onSubscriptionCreated) {\n try {\n await billingItem.onSubscriptionCreated(userId, session.metadata || {});\n } catch (error) {\n // Hook failures are non-critical - subscription already created\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onSubscriptionCreated',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n }\n\n logger.info('[Webhook] Purchase processed', {\n userId,\n configKey: billingConfigKey,\n operation: 'purchase_processed',\n });\n}\n\n/**\n * Handle subscription renewal\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function handleInvoicePaymentSucceeded(\n invoice: Stripe.Invoice,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n stripe: Stripe,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n const subscriptionId = pinnedInvoiceSubscriptionId(invoice);\n if (!subscriptionId) return;\n\n // \u2705 FIX: Fetch subscription to get metadata\n const subscription = await stripe.subscriptions.retrieve(subscriptionId);\n const { userId, billingConfigKey } = subscription.metadata || {};\n if (!userId || !billingConfigKey) {\n // G60: Log when subscription metadata is missing \u2014 silent return loses the event\n logger.error(\n '[Webhook] Subscription metadata missing userId or billingConfigKey',\n {\n subscriptionId,\n hasUserId: !!userId,\n hasBillingConfigKey: !!billingConfigKey,\n operation: 'invoice_payment_succeeded_metadata_missing',\n }\n );\n return;\n }\n\n const billingItem = config[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') return;\n\n // Renew subscription\n if (!authProvider) {\n throw handleError(\n new Error('Auth provider required for subscription updates')\n );\n }\n await updateSubscription(\n userId,\n {\n tier: billingItem.tier,\n status: SUBSCRIPTION_STATUS.ACTIVE,\n subscriptionEnd: calculateSubscriptionEndDate(billingItem.duration),\n subscriptionId: subscriptionId,\n customerId: invoice.customer as string,\n },\n authProvider\n );\n\n // Execute hook with graceful error handling\n if (billingItem.onSubscriptionRenewed) {\n try {\n await billingItem.onSubscriptionRenewed(\n userId,\n subscription.metadata || {}\n );\n } catch (error) {\n // Hook failures are non-critical - subscription already renewed\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onSubscriptionRenewed',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n\n logger.info('[Webhook] Subscription renewed', {\n userId,\n billingConfigKey,\n operation: 'subscription_renewed',\n });\n}\n\n/**\n * Handle subscription cancellation\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function handleSubscriptionDeleted(\n subscription: Stripe.Subscription,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n const { userId, billingConfigKey } = subscription.metadata || {};\n if (!userId || !billingConfigKey) return;\n\n const billingItem = config[billingConfigKey];\n if (!billingItem || billingItem.type !== 'StripeSubscription') return;\n\n // Update to cancelled\n if (!authProvider) {\n throw handleError(\n new Error('Auth provider required for subscription updates')\n );\n }\n await updateSubscription(\n userId,\n {\n tier: SUBSCRIPTION_TIERS.FREE,\n status: SUBSCRIPTION_STATUS.CANCELED,\n subscriptionEnd: new Date(\n pinnedSubscriptionPeriod(subscription).current_period_end * 1000\n ).toISOString(),\n subscriptionId: subscription.id,\n customerId: subscription.customer as string,\n },\n authProvider\n );\n\n // Execute hook with graceful error handling\n if (billingItem.onSubscriptionCancelled) {\n try {\n await billingItem.onSubscriptionCancelled(\n userId,\n subscription.metadata || {}\n );\n } catch (error) {\n // Hook failures are non-critical - subscription already cancelled\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onSubscriptionCancelled',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n\n logger.info('[Webhook] Subscription cancelled', {\n userId,\n billingConfigKey,\n operation: 'subscription_cancelled',\n });\n}\n\n/**\n * Handle payment failure\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function handlePaymentFailed(\n invoice: Stripe.Invoice,\n config: StripeBackConfig\n): Promise<void> {\n const { userId, billingConfigKey } = invoice.metadata || {};\n if (!userId || !billingConfigKey) {\n logger.warn('[Webhook] Payment failed - missing metadata', {\n invoiceId: invoice.id,\n hasUserId: !!userId,\n hasBillingConfigKey: !!billingConfigKey,\n operation: 'payment_failed_metadata_missing',\n });\n return;\n }\n\n const billingItem = config[billingConfigKey];\n if (!billingItem) {\n logger.error('[Webhook] Payment failed - unknown billing config', {\n error: new Error(`Unknown billing config key: ${billingConfigKey}`),\n userId,\n billingConfigKey,\n operation: 'payment_failed_unknown_config',\n });\n return;\n }\n\n // Execute hooks with graceful error handling\n if (billingItem.type === 'StripePayment' && billingItem.onPurchaseFailure) {\n try {\n // Pass the actual metadata - we've already validated it exists\n await billingItem.onPurchaseFailure(userId, invoice.metadata || {});\n } catch (error) {\n // Hook failures are non-critical - payment already failed\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onPurchaseFailure',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n\n if (\n billingItem.type === 'StripeSubscription' &&\n billingItem.onPaymentFailed\n ) {\n try {\n await billingItem.onPaymentFailed(userId, invoice.metadata || {});\n } catch (error) {\n // Hook failures are non-critical - payment already failed\n // Log for manual intervention but don't fail the webhook\n logger.error('[Webhook] Hook failed (non-critical)', {\n error: error instanceof Error ? error : new Error(String(error)),\n hookName: 'onPaymentFailed',\n userId,\n operation: 'hook_execution',\n });\n }\n }\n\n logger.warn('[Webhook] Payment failed', {\n userId,\n billingConfigKey,\n operation: 'payment_failed',\n });\n}\n", "// packages/functions/src/shared/billing/webhookHandler.ts\n\n/**\n * @fileoverview Stripe webhook handler\n * @description Verifies, deduplicates and routes Stripe webhook events for\n * one-time payments, subscriptions (`tierWebhookEvents.ts`) and multi-line\n * orders (`orderWebhook.ts`).\n *\n * @version 0.2.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\n\nimport type Stripe from 'stripe';\n\nimport { DoNotDevError, validateStripeBackConfig } from '@donotdev/core/server';\nimport type { BillingAuthProvider, StripeBackConfig, UpdateSubscriptionFn } from '@donotdev/core/server';\n\nimport { handleError } from '../errorHandling.js';\nimport { logger } from '../logger.js';\nimport { ReservationLostError } from './idempotencyContract.js';\nimport type { IdempotencyStore } from './idempotencyContract.js';\nimport { handleOrderSessionEvent, handleTaxIdUpdated } from './orderWebhook.js';\nimport type { OrderSessionEventType } from './orderWebhook.js';\nimport {\n handleInvoicePaymentSucceeded,\n handlePaymentFailed,\n handleSubscriptionDeleted,\n handleTierCheckoutEvent,\n} from './tierWebhookEvents.js';\n\n/** Attempts to record a processed event before answering non-2xx. */\nconst MARK_PROCESSED_ATTEMPTS = 3;\n\n/** Backoff between markProcessed attempts (multiplied by the attempt number). */\nconst MARK_PROCESSED_BACKOFF_MS = 200;\n\n/**\n * Verify, deduplicate and route one Stripe webhook event.\n *\n * Idempotency (at-least-once): the event is reserved before routing.\n * - Already processed \u2192 resolves \"Event already processed\" (answer 2xx).\n * - Another delivery holds a live lease \u2192 throws `unavailable` (answer non-2xx,\n * Stripe retries later; an abandoned lease is retaken after it expires).\n * - Routing throws \u2192 the reservation is released and the error rethrown, so\n * Stripe's retry is processed.\n * - Routing succeeds \u2192 the event is marked processed, retried a bounded number\n * of times; if it still fails the error is rethrown WITHOUT releasing, so the\n * event is re-run after the lease. Hooks must therefore be idempotent.\n *\n * @param rawBody - Raw request body\n * @param signature - Stripe signature\n * @param webhookSecret - Stripe webhook secret\n * @param stripe - Stripe instance\n * @param billingConfig - Billing configuration\n * @param updateSubscription - Function to update user subscription\n * @param authProvider - Auth provider for subscription claims (null: subscription events fail)\n * @param idempotencyStore - Durable store matching the backend\n * (`createFirestoreIdempotencyStore` / `createSupabaseIdempotencyStore`). Required:\n * shared logic never picks a backend.\n * @throws Any failure: the caller must answer non-2xx so Stripe retries\n *\n * @version 0.2.1\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nexport async function processWebhook(\n rawBody: string | Buffer,\n signature: string,\n webhookSecret: string,\n stripe: Stripe,\n billingConfig: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n authProvider: BillingAuthProvider | null,\n idempotencyStore: IdempotencyStore\n): Promise<{ success: boolean; message: string }> {\n try {\n // Validate data fields only. Valibot strips unknown keys (the hooks) from its\n // output, so routing must use the original config object, never the parse result.\n validateStripeBackConfig(billingConfig);\n const config = billingConfig;\n\n // Verify webhook signature\n // Async variant: works on Node and on Web Crypto runtimes (Deno, Workers)\n const event = await stripe.webhooks.constructEventAsync(\n rawBody,\n signature,\n webhookSecret\n );\n\n logger.info('[Webhook] Processing event', {\n eventType: event.type,\n eventId: event.id,\n operation: 'webhook_processing',\n });\n\n const reservation = await idempotencyStore.reserve(event.id);\n if (reservation.state === 'processed') {\n logger.info('[Webhook] Already processed', { eventId: event.id });\n return { success: true, message: 'Event already processed' };\n }\n if (reservation.state === 'in_progress') {\n logger.warn('[Webhook] Event in progress in another delivery', {\n eventId: event.id,\n eventType: event.type,\n operation: 'webhook_in_progress',\n });\n throw new DoNotDevError(\n `Stripe event ${event.id} is being processed by another delivery; answering non-2xx so Stripe retries it`,\n 'unavailable',\n { details: { eventId: event.id, reason: 'webhook_event_in_progress' } }\n );\n }\n const { ownerToken } = reservation;\n\n // G59: Warn when authProvider is null \u2014 subscription update events will fail\n if (!authProvider) {\n logger.warn(\n '[Webhook] authProvider is null \u2014 subscription-related events will fail',\n {\n eventType: event.type,\n eventId: event.id,\n }\n );\n }\n\n // Route to handler. On failure, release the reservation so the retry runs.\n try {\n await routeEvent(event, config, updateSubscription, stripe, authProvider);\n } catch (routingError) {\n logger.error('[Webhook] Event processing failed, releasing reservation', {\n error:\n routingError instanceof Error\n ? routingError\n : new Error(String(routingError)),\n eventId: event.id,\n eventType: event.type,\n operation: 'webhook_routing',\n });\n await releaseReservation(idempotencyStore, event.id, ownerToken);\n throw routingError;\n }\n\n await markProcessedWithRetry(idempotencyStore, event.id, ownerToken);\n return { success: true, message: 'Webhook processed' };\n } catch (error) {\n throw handleError(error);\n }\n}\n\n/** Release after a routing failure. Never masks the routing error. */\nasync function releaseReservation(\n store: IdempotencyStore,\n eventId: string,\n ownerToken: string\n): Promise<void> {\n try {\n if (!(await store.release(eventId, ownerToken))) {\n logger.warn('[Webhook] Reservation not released: no longer owned', {\n eventId,\n operation: 'idempotency_release_stale',\n });\n }\n } catch (releaseError) {\n logger.error('[Webhook] Failed to release idempotency reservation', {\n error:\n releaseError instanceof Error\n ? releaseError\n : new Error(String(releaseError)),\n eventId,\n operation: 'idempotency_release',\n });\n }\n}\n\n/**\n * Record a processed event. Transient store errors are retried; a lost\n * reservation is not (another delivery owns the event). The final error is\n * rethrown without releasing: Stripe retries after the lease and the event is\n * processed again (at-least-once).\n */\nasync function markProcessedWithRetry(\n store: IdempotencyStore,\n eventId: string,\n ownerToken: string\n): Promise<void> {\n for (let attempt = 1; ; attempt++) {\n try {\n await store.markProcessed(eventId, ownerToken);\n return;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n if (error instanceof ReservationLostError) {\n logger.error(\n '[Webhook] Event processed but its reservation was retaken by another delivery; hooks may run twice',\n { error: err, eventId, operation: 'idempotency_mark_processed_lost' }\n );\n throw error;\n }\n if (attempt >= MARK_PROCESSED_ATTEMPTS) {\n logger.error(\n '[Webhook] Event processed but not recorded; answering non-2xx, Stripe will redeliver after the lease and hooks re-run',\n {\n error: err,\n eventId,\n attempts: attempt,\n operation: 'idempotency_mark_processed_failed',\n }\n );\n throw error;\n }\n logger.warn('[Webhook] markProcessed failed, retrying', {\n eventId,\n attempt,\n error: err.message,\n });\n await new Promise((resolve) =>\n setTimeout(resolve, MARK_PROCESSED_BACKOFF_MS * attempt)\n );\n }\n }\n}\n\n/**\n * Route events to appropriate handlers\n *\n * @version 0.1.0\n * @since 0.0.1\n * @author AMBROISE PARK Consulting\n */\nasync function routeEvent(\n event: Stripe.Event,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n stripe: Stripe,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n switch (event.type) {\n case 'checkout.session.completed':\n case 'checkout.session.async_payment_succeeded':\n case 'checkout.session.async_payment_failed':\n case 'checkout.session.expired':\n await handleCheckoutSessionEvent(\n event.type,\n event.id,\n event.api_version,\n event.data.object,\n config,\n updateSubscription,\n stripe,\n authProvider\n );\n break;\n\n case 'invoice.payment_succeeded':\n await handleInvoicePaymentSucceeded(\n event.data.object as Stripe.Invoice,\n config,\n updateSubscription,\n stripe,\n authProvider\n );\n break;\n\n case 'customer.subscription.deleted':\n await handleSubscriptionDeleted(\n event.data.object as Stripe.Subscription,\n config,\n updateSubscription,\n authProvider\n );\n break;\n\n case 'invoice.payment_failed':\n await handlePaymentFailed(event.data.object as Stripe.Invoice, config);\n break;\n\n case 'customer.tax_id.updated':\n await handleTaxIdUpdated(event.id, event.data.object, config);\n break;\n\n default:\n // W23: Use structured logger instead of console.log in production\n logger.debug('[Webhook] Unhandled event type', { type: event.type });\n }\n}\n\n/**\n * Route Checkout Session events: StripeOrder items go to the order hooks,\n * StripePayment / StripeSubscription items to the tier handlers.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nasync function handleCheckoutSessionEvent(\n eventType: OrderSessionEventType,\n eventId: string,\n apiVersion: string | null,\n session: Stripe.Checkout.Session,\n config: StripeBackConfig,\n updateSubscription: UpdateSubscriptionFn,\n stripe: Stripe,\n authProvider: BillingAuthProvider | null\n): Promise<void> {\n const billingConfigKey = session.metadata?.billingConfigKey;\n const billingItem = billingConfigKey ? config[billingConfigKey] : undefined;\n\n if (billingConfigKey && billingItem?.type === 'StripeOrder') {\n await handleOrderSessionEvent(\n eventType,\n eventId,\n apiVersion,\n session,\n billingConfigKey,\n billingItem,\n stripe\n );\n return;\n }\n\n await handleTierCheckoutEvent(\n eventType,\n session,\n config,\n updateSubscription,\n authProvider\n );\n}\n", "// packages/functions/src/shared/billing/supabaseIdempotency.ts\n\n/**\n * @fileoverview Postgres (Supabase) webhook idempotency store\n * @description `webhook_events` table and its RPCs. Re-exported from\n * `idempotency.ts`.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\n\nimport type { SupabaseClient } from '@supabase/supabase-js';\nimport * as v from 'valibot';\n\nimport { handleError } from '../errorHandling.js';\nimport {\n RESERVATION_LEASE_MS,\n ReservationLostError,\n newOwnerToken,\n} from './idempotencyContract.js';\nimport type {\n IdempotencyStore,\n ReservationResult,\n} from './idempotencyContract.js';\n\n/**\n * SQL required by {@link createSupabaseIdempotencyStore}: table, the\n * service_role-only RPCs `webhook_event_reserve` / `webhook_event_mark_processed`\n * / `webhook_event_release`, and a daily pg_cron cleanup (30 days). Shipped\n * verbatim as the CLI Supabase template migration `*_webhook_events.sql`.\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport const WEBHOOK_EVENTS_SQL = `\nCREATE TABLE IF NOT EXISTS public.webhook_events (\n event_id TEXT PRIMARY KEY,\n status TEXT NOT NULL CHECK (status IN ('processing', 'processed')),\n owner_token UUID NOT NULL,\n reserved_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n processed_at TIMESTAMPTZ\n);\n\n-- Only service_role accesses this table\nALTER TABLE public.webhook_events ENABLE ROW LEVEL SECURITY;\n\nCREATE INDEX IF NOT EXISTS idx_webhook_events_processed_at\n ON public.webhook_events (processed_at);\n\n-- The functions below run as the caller (SECURITY INVOKER) and refuse every\n-- role but service_role. EXECUTE is deliberately not revoked: on Supabase\n-- Postgres 17.6.1.x a permission-denied function call by anon/authenticated\n-- crashes the backend (signal 11), which restarts every connection.\nCREATE OR REPLACE FUNCTION public.webhook_events_assert_service_role()\nRETURNS VOID\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n IF current_user IS DISTINCT FROM 'service_role' THEN\n RAISE EXCEPTION 'webhook_events is reserved to service_role (current role: %)', current_user\n USING ERRCODE = 'insufficient_privilege';\n END IF;\nEND;\n$$;\n\n-- Atomic reservation. Returns:\n-- 'reserved' the caller now owns the event under p_owner_token\n-- 'processed' the event was already processed (skip, answer 2xx)\n-- 'in_progress' another worker holds a live lease (answer non-2xx, Stripe retries)\n-- A 'processing' row older than the lease is retaken (abandoned worker).\nCREATE OR REPLACE FUNCTION public.webhook_event_reserve(\n p_event_id TEXT,\n p_owner_token UUID,\n p_lease_seconds INT\n)\nRETURNS TEXT\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nDECLARE\n v_status TEXT;\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n INSERT INTO public.webhook_events (event_id, status, owner_token, reserved_at)\n VALUES (p_event_id, 'processing', p_owner_token, clock_timestamp())\n ON CONFLICT (event_id) DO UPDATE\n SET owner_token = EXCLUDED.owner_token,\n reserved_at = clock_timestamp()\n WHERE webhook_events.status = 'processing'\n AND webhook_events.reserved_at\n < clock_timestamp() - make_interval(secs => p_lease_seconds);\n IF FOUND THEN\n RETURN 'reserved';\n END IF;\n\n SELECT status INTO v_status\n FROM public.webhook_events\n WHERE event_id = p_event_id;\n IF v_status = 'processed' THEN\n RETURN 'processed';\n END IF;\n -- Live lease, or the row was released in between: Stripe retries either way\n RETURN 'in_progress';\nEND;\n$$;\n\n-- Mark a reservation processed. Returns false when p_owner_token no longer owns\n-- the row (lease retaken, released, or deleted). Repeating it for the same\n-- owner is a no-op that returns true.\nCREATE OR REPLACE FUNCTION public.webhook_event_mark_processed(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n UPDATE public.webhook_events\n SET status = 'processed',\n processed_at = COALESCE(processed_at, clock_timestamp())\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token;\n RETURN FOUND;\nEND;\n$$;\n\n-- Drop a reservation after a processing failure. Returns false when\n-- p_owner_token does not own a 'processing' row (nothing is deleted).\nCREATE OR REPLACE FUNCTION public.webhook_event_release(\n p_event_id TEXT,\n p_owner_token UUID\n)\nRETURNS BOOLEAN\nLANGUAGE plpgsql\nSET search_path = public\nAS $$\nBEGIN\n PERFORM public.webhook_events_assert_service_role();\n\n DELETE FROM public.webhook_events\n WHERE event_id = p_event_id\n AND owner_token = p_owner_token\n AND status = 'processing';\n RETURN FOUND;\nEND;\n$$;\n\n-- Enable pg_cron extension (if not already enabled)\nCREATE EXTENSION IF NOT EXISTS pg_cron;\n\n-- Cleanup webhook events older than 30 days (daily at 5 AM UTC).\n-- Stripe retries an event for up to 3 days, so older rows are never read again.\nSELECT cron.schedule(\n 'cleanup-webhook-events',\n '0 5 * * *',\n $$DELETE FROM public.webhook_events WHERE COALESCE(processed_at, reserved_at) < now() - interval '30 days'$$\n);\n`;\n\nconst ReserveResultSchema = v.picklist(['reserved', 'processed', 'in_progress']);\nconst OwnedResultSchema = v.boolean();\n\n/**\n * Postgres-backed store (Supabase). Requires {@link WEBHOOK_EVENTS_SQL}.\n *\n * @param supabaseAdmin - Supabase client created with the service role key\n *\n * @version 0.2.0\n * @since 0.2.0\n * @author AMBROISE PARK Consulting\n */\nexport function createSupabaseIdempotencyStore(\n supabaseAdmin: SupabaseClient\n): IdempotencyStore {\n const call = async <T>(\n fn: string,\n args: Record<string, unknown>,\n schema: v.GenericSchema<unknown, T>\n ): Promise<T> => {\n const { data, error } = await supabaseAdmin.rpc(fn, args);\n if (error) throw handleError(error);\n const result = v.safeParse(schema, data);\n if (!result.success) {\n throw handleError(\n new Error(`${fn} returned an unexpected result: ${JSON.stringify(data)}`)\n );\n }\n return result.output;\n };\n\n return {\n async reserve(eventId): Promise<ReservationResult> {\n const ownerToken = newOwnerToken();\n const state = await call(\n 'webhook_event_reserve',\n {\n p_event_id: eventId,\n p_owner_token: ownerToken,\n p_lease_seconds: RESERVATION_LEASE_MS / 1000,\n },\n ReserveResultSchema\n );\n return state === 'reserved' ? { state, ownerToken } : { state };\n },\n async markProcessed(eventId, ownerToken) {\n const owned = await call(\n 'webhook_event_mark_processed',\n { p_event_id: eventId, p_owner_token: ownerToken },\n OwnedResultSchema\n );\n if (!owned) throw new ReservationLostError(eventId);\n },\n async release(eventId, ownerToken) {\n return call(\n 'webhook_event_release',\n { p_event_id: eventId, p_owner_token: ownerToken },\n OwnedResultSchema\n );\n },\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;6TA6BO,SAASA,EAAYC,EAAuB,CAajD,IAAIC,EACAC,EACAC,EAEJ,GAAIH,aAAiBI,EACnBH,EAAOD,EAAM,KACbE,EAAUF,EAAM,QAChBG,EAAUH,EAAM,gBAEhBA,GACA,OAAOA,GAAU,UACjB,WAAYA,IACVA,aAAiB,OAASA,EAAM,OAAS,aACxC,SAAUA,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W7B,SAASC,GACdC,EACkB,CAClB,IAAMC,EAAOC,EAAA,MACXC,EACAC,EACAC,IACe,CACf,GAAM,CAAE,KAAAC,EAAM,MAAAC,CAAM,EAAI,MAAMP,EAAc,IAAIG,EAAIC,CAAI,EACxD,GAAIG,EAAO,MAAMC,EAAYD,CAAK,EAClC,IAAME,EAAWC,EAAUL,EAAQC,CAAI,EACvC,GAAI,CAACG,EAAO,QACV,MAAMD,EACJ,IAAI,MAAM,GAAGL,CAAE,mCAAmC,KAAK,UAAUG,CAAI,CAAC,EAAE,CAC1E,EAEF,OAAOG,EAAO,MAChB,EAda,QAgBb,MAAO,CACL,MAAM,QAAQE,EAAqC,CACjD,IAAMC,EAAaC,GAAc,EAC3BC,EAAQ,MAAMb,EAClB,wBACA,CACE,WAAYU,EACZ,cAAeC,EACf,gBAAiBG,GAAuB,GAC1C,EACApB,EACF,EACA,OAAOmB,IAAU,WAAa,CAAE,MAAAA,EAAO,WAAAF,CAAW,EAAI,CAAE,MAAAE,CAAM,CAChE,EACA,MAAM,cAAcH,EAASC,EAAY,CAMvC,GAAI,CALU,MAAMX,EAClB,+BACA,CAAE,WAAYU,EAAS,cAAeC,CAAW,EACjDf,EACF,EACY,MAAM,IAAImB,EAAqBL,CAAO,CACpD,EACA,MAAM,QAAQA,EAASC,EAAY,CACjC,OAAOX,EACL,wBACA,CAAE,WAAYU,EAAS,cAAeC,CAAW,EACjDf,EACF,CACF,CACF,CACF,CAjDgBK,EAAAH,GAAA",
6
+ "names": ["handleError", "error", "code", "message", "details", "DoNotDevError", "entityError", "__name", "createMetadata", "userId", "now", "__name", "updateMetadata", "writtenOf", "result", "collection", "locator", "messages", "issue", "p", "DoNotDevError", "__name", "EMPTY_BULK_RESPONSE", "executeBulk", "params", "collection", "ops", "createSchema", "draftCreateSchema", "updateSchema", "access", "uid", "userRole", "transact", "readStored", "mintInsertId", "stampInsertMetadata", "stampUpdateMetadata", "audit", "parsed", "safeParse", "BulkRequestSchema", "messages", "issue", "p", "DoNotDevError", "request", "inserts", "updates", "deletes", "collision", "detectBulkCollisions", "BulkCollisionError", "hasRoleAccess", "noDraftSchema", "__name", "locator", "schemas", "insertRows", "i", "rowObj", "statusCan", "createStatus", "row", "writtenOf", "prepareCreate", "stored", "u", "updatePatches", "id", "patch", "storedRow", "updateCheck", "prepareUpdate", "preparedInserts", "clientId", "withId", "stamped", "preparedUpdates", "raw", "responseParse", "BulkResponseSchema", "calculateCost", "usage", "model", "markup", "DEFAULT_AI_MARKUP", "pricing", "AI_TOKEN_PRICING", "promptCost", "completionCost", "providerCost", "__name", "getDenoEnv", "__name", "resolveModel", "provider", "model", "factory", "__name", "createAnthropic", "apiKey", "createOpenAI", "createGoogle", "getAIApiKey", "DEFAULT_RATE_LIMIT", "rateLimiter", "getRateLimiter", "redisUrl", "getEnv", "redisToken", "Ratelimit", "Redis", "redis", "limiters", "userId", "config", "key", "rl", "err", "resolveTools", "sdk", "requestTools", "configTools", "merged", "sdkTools", "name", "def", "toAIUsage", "usage", "promptTokens", "completionTokens", "handleAIRequest", "request", "options", "validation", "validateAIChatRequest", "jsonError", "i", "providerModels", "AI_MODELS", "allowed", "languageModel", "systemMessages", "m", "systemPrompt", "messages", "maxTokens", "temperature", "requestId", "streamText", "generateText", "toUIMessageStream", "createUIMessageStreamResponse", "tools", "recordCost", "markup", "cost", "calculateCost", "record", "result", "part", "toolCalls", "tc", "message", "status", "getDenoEnv", "providerKey", "getEnv", "name", "getDenoEnv", "__name", "resolveModelForTier", "tier", "functionName", "perFn", "perTier", "AI_TIERS", "t", "classifyAIError", "err", "status", "extractStatus", "message", "extractMessage", "extractRetryAfter", "__name", "mapClassifiedToHTTP", "code", "headers", "retryAfter", "seconds", "STRIPE_API_VERSION_PIN", "MIN_ORDER_API_VERSION", "STRIPE_API_VERSION_PIN", "ORDER_ID_METADATA_KEY", "PRODUCT_ID_METADATA_KEY", "idOf", "value", "__name", "toAddress", "address", "toCheckoutSessionSnapshot", "session", "details", "shipping", "taxId", "listPaidLineItems", "stripe", "sessionId", "lines", "item", "product", "productId", "handleOrderSessionEvent", "eventType", "eventId", "apiVersion", "billingConfigKey", "orderItem", "metadata", "userId", "orderId", "ctx", "snapshot", "lineItems", "logger", "toTaxIdSnapshot", "handleTaxIdUpdated", "config", "ran", "resolvePricePlan", "item", "request", "key", "priceId", "line", "mode", "__name", "toStripeSessionParams", "params", "STRIPE_METADATA_LIMITS", "validateCheckoutUrl", "url", "name", "parsed", "error", "__name", "sanitizeMetadata", "metadata", "sanitized", "key", "value", "assertStripeMetadata", "target", "maxKeys", "maxKeyLength", "maxValueLength", "entries", "assertCheckoutSessionMetadata", "params", "targets", "line", "i", "assertResolvedOrder", "order", "configKey", "assertResolvedOrderSession", "STRIPE_TAX_CODE", "CHECKOUT_EXPIRY_WINDOW", "MAX_INVOICE_FOOTER_LENGTH", "ORDER_PAYMENT_METHOD_TYPES", "STRIPE_CUSTOMER_ID", "session", "nowSeconds", "taxRateIds", "paymentMethodTypes", "expiresAt", "invoiceFooter", "customerId", "id", "type", "minSeconds", "maxSeconds", "taxRateInclusiveCache", "assertExclusiveTaxRates", "retrieveTaxRate", "inclusive", "rate", "isSessionProvider", "provider", "__name", "resolveRedirectUrl", "url", "path", "frontendUrl", "customerUpdate", "item", "taxIdCollectionEnabled", "update", "buildOrderSessionParams", "order", "base", "options", "taxRates", "metadata", "ORDER_ID_METADATA_KEY", "customerParams", "line", "PRODUCT_ID_METADATA_KEY", "id", "createCheckoutAlgorithm", "input", "args", "legacyCall", "userId", "stripeProvider", "authProvider", "billingConfig", "billingConfigKey", "request", "billingItem", "isOrder", "plan", "resolvePricePlan", "clientMetadata", "sanitizeMetadata", "assertStripeMetadata", "allowPromotionCodes", "hookResult", "successUrl", "cancelUrl", "validateCheckoutUrl", "session", "assertExclusiveTaxRates", "assertResolvedOrder", "sessionOptions", "params", "assertCheckoutSessionMetadata", "stripeParams", "toStripeSessionParams", "updateUserSubscription", "userId", "subscriptionData", "authProvider", "currentClaims", "subscriptionClaims", "parse", "SubscriptionClaimsSchema", "updatedClaims", "__name", "ReservationLostError", "__name", "eventId", "RESERVATION_LEASE_MS", "WEBHOOK_EVENT_RETENTION_MS", "newOwnerToken", "pinnedInvoiceSubscriptionId", "invoice", "__name", "isOneOf", "values", "value", "handleTierCheckoutEvent", "eventType", "session", "config", "updateSubscription", "authProvider", "logContext", "logger", "handleError", "grantCheckoutPurchase", "__name", "userId", "billingConfigKey", "billingItem", "SUBSCRIPTION_STATUS", "calculateSubscriptionEndDate", "error", "handleInvoicePaymentSucceeded", "invoice", "stripe", "subscriptionId", "pinnedInvoiceSubscriptionId", "subscription", "handleSubscriptionDeleted", "SUBSCRIPTION_TIERS", "handlePaymentFailed", "MARK_PROCESSED_ATTEMPTS", "MARK_PROCESSED_BACKOFF_MS", "processWebhook", "rawBody", "signature", "webhookSecret", "stripe", "billingConfig", "updateSubscription", "authProvider", "idempotencyStore", "validateStripeBackConfig", "config", "event", "logger", "reservation", "DoNotDevError", "ownerToken", "routeEvent", "routingError", "releaseReservation", "markProcessedWithRetry", "error", "handleError", "__name", "store", "eventId", "releaseError", "attempt", "err", "ReservationLostError", "resolve", "handleCheckoutSessionEvent", "handleInvoicePaymentSucceeded", "handleSubscriptionDeleted", "handlePaymentFailed", "handleTaxIdUpdated", "eventType", "apiVersion", "session", "billingConfigKey", "billingItem", "handleOrderSessionEvent", "handleTierCheckoutEvent", "WEBHOOK_EVENTS_SQL", "ReserveResultSchema", "picklist", "OwnedResultSchema", "boolean", "createSupabaseIdempotencyStore", "supabaseAdmin", "call", "__name", "fn", "args", "schema", "data", "error", "handleError", "result", "safeParse", "eventId", "ownerToken", "newOwnerToken", "state", "RESERVATION_LEASE_MS", "ReservationLostError"]
7
+ }
@@ -0,0 +1,22 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname } from 'node:path';
4
+ import { Buffer } from 'node:buffer';
5
+ import process from 'node:process';
6
+
7
+ const require = __createRequire(import.meta.url);
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ if (typeof globalThis !== 'undefined') {
12
+ globalThis.require = require;
13
+ globalThis.__filename = __filename;
14
+ globalThis.__dirname = __dirname;
15
+ globalThis.Buffer = Buffer;
16
+ globalThis.process = process;
17
+ if (typeof global === 'undefined') {
18
+ globalThis.global = globalThis;
19
+ }
20
+ }
21
+ import{b as D,c as b,d as p}from"./chunk-WJUL2W7Y.js";import{E as x,F as a,G as f,V as g,e as w,f as k,h as u,i as y,j as I,m as A,u as T,v as m,w as d,z as c}from"./chunk-Y6BR2QOV.js";import{a as s}from"./chunk-AYY7UXNI.js";import{logger as B}from"firebase-functions/v2";var E={webhookEvent:m({id:a(c(),u(1,"Event ID is required")),type:a(c(),u(1,"Event type is required")),data:m({object:A()}),created:a(T(),y(0,"Valid timestamp required"))}),purchaseRequest:m({userId:a(c(),u(1,"User ID is required")),productType:a(c(),u(1,"Product type is required")),githubUsername:d(a(c(),I(/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/,"Invalid GitHub username"))),sessionId:a(c(),u(1,"Session ID is required")),amount:d(a(T(),y(0,"Amount must be positive"))),currency:d(a(c(),k(3,"Currency must be 3 characters")))})};function j(e){try{return{isValid:!0,data:x(E.webhookEvent,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Webhook event validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(j,"validateWebhookEvent");function _(e){try{return{isValid:!0,data:x(E.purchaseRequest,e),errors:[]}}catch(r){if(w(r)){let t=r.issues.map(n=>`${n.path?.map(o=>o.key).join(".")||""}: ${n.message}`);return B.warn("Purchase request validation failed",{errors:t,data:e}),{isValid:!1,errors:t}}return{isValid:!1,errors:["Unknown validation error"]}}}s(_,"validatePurchaseRequest");function M(e){return/^[a-zA-Z0-9]([a-zA-Z0-9]|-(?=[a-zA-Z0-9])){0,38}$/.test(e)}s(M,"validateGitHubUsername");function z(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}s(z,"validateEmail");function L(e){return e.startsWith("price_")&&e.length>6}s(L,"validateStripePriceId");function Z(e){return e.startsWith("cs_")&&e.length>3}s(Z,"validateStripeSessionId");function H(e,r="URL"){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid protocol: ${t.protocol}`);return e}catch(t){throw new Error(`Invalid ${r}: ${e}. ${t instanceof Error?t.message:"Invalid URL format"}`)}}s(H,"validateUrl");function W(e){let r={};for(let[t,n]of Object.entries(e)){if(typeof n!="string")throw new Error(`Metadata value for key '${t}' must be a string, got ${typeof n}`);let o=n.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");if(o.length>1e3)throw new Error(`Metadata value for key '${t}' is too long (max 1000 characters)`);if(t.length>100)throw new Error(`Metadata key '${t}' is too long (max 100 characters)`);r[t]=o}return r}s(W,"validateMetadata");function v(e,r,t){let o=f(t||r,e);return o.success?{success:!0,data:o.output}:{success:!1,error:`Validation failed: ${o.issues.map(i=>i.message).join(", ")}`}}s(v,"validateRequestData");function q(e,r){return async(t,n)=>{let o=v(t.data,e,n);if(!o.success)throw new Error(o.error);return await r(t,o.data)}}s(q,"withSchemaValidation");function S(e,r){return async(t,n,o)=>{let i=v(t.body,e,o);return i.success?await r(t,n,i.data):n.status(400).json({error:i.error})}}s(S,"withVercelSchemaValidation");function J(e,r){let t=q(e,r);return{standard:s(n=>t(n),"standard"),withSchema:s((n,o)=>t(n,o),"withSchema")}}s(J,"createFirebaseFunction");function K(e,r){return S(e,r)}s(K,"createVercelFunction");import{onCall as V}from"firebase-functions/v2/https";function C(e,r,t){let n=q(r,t);return{onCall:V(e,async o=>await n(o)),withSchema:s(async(o,i)=>await n(o,i),"withSchema")}}s(C,"createFirebaseCallable");function re(e,r,t){let{onCall:n,withSchema:o}=C(e,r,t);return{[t.name||"mainFunction"]:n,[`${t.name||"mainFunction"}WithSchema`]:o}}s(re,"createFirebaseFunctionExports");function ie(e,r){return S(e,r)}s(ie,"createVercelHandler");function ae(e,r,t){return async(n,o,i)=>{if(n.method!==e)return o.status(405).json({error:"Method not allowed"});let l=v(n.body,r,i);return l.success?await t(n,o,l.data):o.status(400).json({error:l.error})}}s(ae,"createVercelApiHandler");function me(e){if(e instanceof Date)return e.toISOString();if(typeof e=="object"&&e!==null&&"toDate"in e&&typeof e.toDate=="function")return e.toDate().toISOString();if(typeof e=="string"){let t=new Date(e);if(isNaN(t.getTime()))throw new Error("Invalid date format");return t.toISOString()}let r=new Date(e);if(isNaN(r.getTime()))throw new Error("Invalid date format");return r.toISOString()}s(me,"toISOString");function R(e,r){let t=new Date(e),n=t.getDate();return t.setMonth(t.getMonth()+r),t.getDate()!==n&&t.setDate(0),t}s(R,"addMonths");function F(e,r){let t=new Date(e),n=t.getDate();return t.setFullYear(t.getFullYear()+r),t.getDate()!==n&&t.setDate(0),t}s(F,"addYears");function de(e,r=new Date){if(e==="lifetime")return"2099-12-31T23:59:59.000Z";let t;return e==="1month"?t=R(r,1):e==="3months"?t=R(r,3):e==="6months"?t=R(r,6):e==="1year"?t=F(r,1):e==="2years"?t=F(r,2):t=R(r,1),t.toISOString()}s(de,"calculateSubscriptionEndDate");async function he(e,r){return[]}s(he,"findReferences");function $(e){return{price_pro_monthly:"pro",price_ai_monthly:"ai",price_pro_yearly:"pro",price_ai_yearly:"ai"}[e]||"free"}s($,"getTierFromPriceId");async function N(e,r){if(!e)throw new Error("Firebase UID is required to cancel subscription");let t={tier:"free",subscriptionId:null,customerId:r.customer,status:"canceled",subscriptionEnd:null,cancelAtPeriodEnd:!1,updatedAt:new Date().toISOString()};try{let n=b(),o=p(),l=(await n.getUser(e)).customClaims||{};await n.setCustomUserClaims(e,{...l,subscription:t}),await o.collection("subscriptions").doc(e).update({...t,updatedAt:new Date().toISOString()}),console.log(`Subscription canceled for user ${e}:`,{subscriptionId:r.id})}catch(n){throw console.error("Failed to cancel user subscription:",n),new Error("Failed to cancel user subscription")}}s(N,"cancelUserSubscription");async function U(e){try{return(await b().getUser(e)).customClaims?.subscription||null}catch(r){return console.error("Failed to get user subscription:",r),null}}s(U,"getUserSubscription");async function De(){return await D()}s(De,"initializeFirebaseAdmin");import{logger as h}from"firebase-functions/v2";async function Ve(e,r){let t=p();try{let o=await t.collection("idempotency").doc(`${r}_${e}`).get();if(o.exists){let i=o.data();return h.info("Operation already processed (idempotency)",{key:e,operation:r,processedAt:i.processedAt,processedBy:i.processedBy}),i.result}return null}catch(n){throw h.error("Idempotency check failed",{key:e,operation:r,error:n instanceof Error?n.message:String(n)}),new Error(`Idempotency check failed for ${r}/${e}: ${n instanceof Error?n.message:String(n)}`)}}s(Ve,"checkIdempotency");async function Ce(e,r,t,n){try{await p().collection("idempotency").doc(`${r}_${e}`).set({result:t,processedAt:new Date().toISOString(),processedBy:n}),h.info("Idempotency result stored",{key:e,operation:r,processedBy:n})}catch(o){h.error("Failed to store idempotency result",{key:e,operation:r,processedBy:n,error:o instanceof Error?o.message:String(o)})}}s(Ce,"storeIdempotencyResult");function Oe(e){try{return JSON.parse(e)}catch{return null}}s(Oe,"safeJsonParse");function je(e){if(!e||typeof e!="string")throw new Error("Collection name is required");if(e.includes("/")||e.includes("..")||e.startsWith("_"))throw new Error('Invalid collection name: must not contain "/", "..", or start with "_"')}s(je,"validateCollectionName");function _e(e,r){if(!e||typeof e!="object")throw new g("Invalid document data","invalid-argument");if(Array.isArray(e))throw new g("Document data cannot be an array","invalid-argument");if(r){let t=f(r,e);if(!t.success){let n=t.issues.map(o=>`${o.path?.map(i=>i.key).join(".")||"root"}: ${o.message}`).join("; ");throw new g(`Validation failed: ${n}`,"invalid-argument",{details:{validationErrors:t.issues}})}}}s(_e,"validateDocument");async function Ye(e,r){let{code:t,redirectUri:n,codeVerifier:o}=e;return await r.exchangeCodeForToken({code:t,redirectUri:n,codeVerifier:o})}s(Ye,"exchangeTokenAlgorithm");async function Qe(e,r,t,n,o){return await o.grantAccess({userId:e,provider:r,accessToken:t,refreshToken:n})}s(Qe,"grantAccessAlgorithm");export{E as a,j as b,_ as c,M as d,z as e,L as f,Z as g,H as h,W as i,v as j,q as k,S as l,J as m,K as n,C as o,re as p,ie as q,ae as r,me as s,de as t,he as u,$ as v,N as w,U as x,De as y,Ve as z,Ce as A,Oe as B,je as C,_e as D,Ye as E,Qe as F};
22
+ //# sourceMappingURL=chunk-MJ5VZTLM.js.map