payweave 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +272 -0
- package/dist/_tsup-dts-rollup.d.ts +19470 -0
- package/dist/chunk-4R5OGOCC.js +94 -0
- package/dist/chunk-4R5OGOCC.js.map +1 -0
- package/dist/chunk-535Q3GUN.js +175 -0
- package/dist/chunk-535Q3GUN.js.map +1 -0
- package/dist/chunk-67NRYGRC.js +192 -0
- package/dist/chunk-67NRYGRC.js.map +1 -0
- package/dist/chunk-CGQ73I4I.js +568 -0
- package/dist/chunk-CGQ73I4I.js.map +1 -0
- package/dist/chunk-CJEYDHY6.js +18 -0
- package/dist/chunk-CJEYDHY6.js.map +1 -0
- package/dist/chunk-CR63JAAS.js +3 -0
- package/dist/chunk-CR63JAAS.js.map +1 -0
- package/dist/chunk-E633MKVX.js +1507 -0
- package/dist/chunk-E633MKVX.js.map +1 -0
- package/dist/chunk-FBPOCXRZ.js +1135 -0
- package/dist/chunk-FBPOCXRZ.js.map +1 -0
- package/dist/chunk-HTRGMZFH.js +267 -0
- package/dist/chunk-HTRGMZFH.js.map +1 -0
- package/dist/chunk-IUVGM3K7.js +765 -0
- package/dist/chunk-IUVGM3K7.js.map +1 -0
- package/dist/chunk-JD4OZHRI.js +326 -0
- package/dist/chunk-JD4OZHRI.js.map +1 -0
- package/dist/chunk-NV3MZF7L.js +139 -0
- package/dist/chunk-NV3MZF7L.js.map +1 -0
- package/dist/chunk-NXQBP35U.js +13 -0
- package/dist/chunk-NXQBP35U.js.map +1 -0
- package/dist/chunk-QJHXDZYC.js +412 -0
- package/dist/chunk-QJHXDZYC.js.map +1 -0
- package/dist/chunk-TWZK62TZ.js +83 -0
- package/dist/chunk-TWZK62TZ.js.map +1 -0
- package/dist/cli/index.js +35381 -0
- package/dist/core/index.d.ts +85 -0
- package/dist/core/index.js +6 -0
- package/dist/core/index.js.map +1 -0
- package/dist/db/drizzle/index.d.ts +6 -0
- package/dist/db/drizzle/index.js +1532 -0
- package/dist/db/drizzle/index.js.map +1 -0
- package/dist/db/index.d.ts +43 -0
- package/dist/db/index.js +3 -0
- package/dist/db/index.js.map +1 -0
- package/dist/db/mongodb/index.d.ts +3 -0
- package/dist/db/mongodb/index.js +934 -0
- package/dist/db/mongodb/index.js.map +1 -0
- package/dist/db/mysql/index.d.ts +1 -0
- package/dist/db/mysql/index.js +12 -0
- package/dist/db/mysql/index.js.map +1 -0
- package/dist/db/postgres/index.d.ts +5 -0
- package/dist/db/postgres/index.js +791 -0
- package/dist/db/postgres/index.js.map +1 -0
- package/dist/db/prisma/index.d.ts +1 -0
- package/dist/db/prisma/index.js +12 -0
- package/dist/db/prisma/index.js.map +1 -0
- package/dist/db/sqlite/index.d.ts +5 -0
- package/dist/db/sqlite/index.js +750 -0
- package/dist/db/sqlite/index.js.map +1 -0
- package/dist/express/index.d.ts +1 -0
- package/dist/express/index.js +3 -0
- package/dist/express/index.js.map +1 -0
- package/dist/fastify/index.d.ts +1 -0
- package/dist/fastify/index.js +3 -0
- package/dist/fastify/index.js.map +1 -0
- package/dist/flutterwave/index.d.ts +27 -0
- package/dist/flutterwave/index.js +9 -0
- package/dist/flutterwave/index.js.map +1 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +3677 -0
- package/dist/index.js.map +1 -0
- package/dist/next/index.d.ts +1 -0
- package/dist/next/index.js +3 -0
- package/dist/next/index.js.map +1 -0
- package/dist/paystack/index.d.ts +33 -0
- package/dist/paystack/index.js +9 -0
- package/dist/paystack/index.js.map +1 -0
- package/dist/products/index.d.ts +22 -0
- package/dist/products/index.js +7 -0
- package/dist/products/index.js.map +1 -0
- package/dist/testing/index.d.ts +11 -0
- package/dist/testing/index.js +69 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/unified/index.d.ts +41 -0
- package/dist/unified/index.js +6 -0
- package/dist/unified/index.js.map +1 -0
- package/dist/webhooks/index.d.ts +8 -0
- package/dist/webhooks/index.js +8 -0
- package/dist/webhooks/index.js.map +1 -0
- package/package.json +164 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db/mongodb/errors.ts","../../../src/db/mongodb/id.ts","../../../src/db/mongodb/migrations.ts","../../../src/db/mongodb/period-pipeline.ts","../../../src/db/mongodb/rows.ts","../../../src/db/mongodb/topology.ts","../../../src/db/mongodb/adapter.ts","../../../src/db/mongodb/url.ts","../../../src/db/mongodb/index.ts"],"names":["client"],"mappings":";;;;;;AAeO,SAAS,iBAAiB,KAAA,EAAqC;AACpE,EAAA,OAAO,IAAI,mBAAA;AAAA,IACT,2NAAA;AAAA,IAGA,EAAE,KAAA;AAAM,GACV;AACF;AAGA,IAAM,kBAAA,GAAqB,IAAA;AASpB,SAAS,oBAAoB,KAAA,EAAyB;AAC3D,EAAA,MAAM,OAAQ,KAAA,EAAqC,IAAA;AACnD,EAAA,OAAO,IAAA,KAAS,kBAAA;AAClB;AAWO,SAAS,eAAA,CAAgB,OAAgB,OAAA,EAAgC;AAC9E,EAAA,IAAI,KAAA,YAAiB,eAAe,OAAO,KAAA;AAC3C,EAAA,IAAI,mBAAA,CAAoB,KAAK,CAAA,EAAG;AAC9B,IAAA,OAAO,IAAI,uBAAA,CAAwB,OAAA,EAAS,EAAE,KAAA,EAAO,OAAO,CAAA;AAAA,EAC9D;AACA,EAAA,OAAO,IAAI,cAAc,OAAA,EAAS,EAAE,OAAO,KAAA,EAAO,WAAA,EAAa,OAAO,CAAA;AACxE;ACnCA,IAAM,QAAA,GAAW,kCAAA;AACjB,IAAM,eAAe,QAAA,CAAS,MAAA;AAC9B,IAAM,QAAA,GAAW,EAAA;AACjB,IAAM,UAAA,GAAa,EAAA;AAEnB,SAAS,UAAA,CAAW,QAAgB,GAAA,EAAqB;AACvD,EAAA,IAAI,CAAC,MAAA,CAAO,aAAA,CAAc,MAAM,CAAA,IAAK,SAAS,CAAA,EAAG;AAC/C,IAAA,MAAM,IAAI,UAAA,CAAW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AAA,EAAQ,EAAG,WAAW,MAAA,EAAO;AAAA,MACxD,OAAO,YAAA,CAAa,MAAM,OAAA,EAAQ,EAAG,WAAW,KAAA;AAAM,KACxD;AAAA,IACA,aAAa,OAAO,EAAA,KAAA,CAAQ,MAAM,OAAA,EAAQ,EAAG,YAAY,EAAE;AAAA,GAC7D;AACF;AAUO,SAAS,eAAe,KAAA,EAA6C;AAC1E,EAAA,MAAM,MAAA,GAAS,kBAAkB,KAAK,CAAA;AACtC,EAAA,IAAI,cAAA;AACJ,EAAA,MAAM,gBAAgB,MAA+B;AACnD,IAAA,cAAA,KAAmB,QAAQ,MAAM,CAAA;AACjC,IAAA,OAAO,cAAA;AAAA,EACT,CAAA;AACA,EAAA,OAAO,iBAAiB,aAAa,CAAA;AACvC","file":"index.js","sourcesContent":["/**\n * Error helpers for the MongoDB adapter (docs/v1/database.md §7, PW-709):\n * an actionable install-hint error when the optional `mongodb` peer driver\n * is missing (mirrors `src/db/sqlite/errors.ts`'s message style: name the\n * subpath, the missing package, and an install command), and a thin wrapper\n * turning raw driver exceptions into {@link PayweaveError} subclasses\n * (AGENTS.md §2: public SDK methods only ever throw `PayweaveError`\n * subclasses).\n */\nimport { PayweaveConfigError, PayweaveError, PayweaveValidationError } from \"../../core/errors\";\n\n/**\n * The optional peer driver `mongodb` is not installed (or failed to import\n * for some other reason — the underlying error survives as `cause`).\n */\nexport function installHintError(cause: unknown): PayweaveConfigError {\n return new PayweaveConfigError(\n 'payweave/db/mongodb: connecting requires the \"mongodb\" package, which is not installed ' +\n '(it is an optional peerDependency of \"payweave\"). Run `npm install mongodb` (or your ' +\n \"package manager's equivalent) and try again.\",\n { cause },\n );\n}\n\n/** MongoDB's duplicate-key error code (E11000 — a unique/partial-unique index rejected the write). */\nconst DUPLICATE_KEY_CODE = 11000;\n\n/**\n * `true` when `error` is a MongoDB duplicate-key error (E11000). Exported\n * (not just used internally by {@link wrapDriverError}) so callers that need\n * to DECIDE whether to retry (e.g. `plans.pushVersion`'s append-only race,\n * `./adapter.ts`) can distinguish \"retry-worthy contention\" from \"give up and\n * wrap\" without duplicating this check.\n */\nexport function isDuplicateKeyError(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === DUPLICATE_KEY_CODE;\n}\n\n/**\n * Normalize a raw driver error into a {@link PayweaveError} subclass.\n * Duplicate-key errors (e.g. the partial-unique active-subscription index,\n * `pw_customers.externalId`, `pw_plans` (`planId`, `version`),\n * `pw_feature_balances` (`customerId`, `featureId`, `group`)) become\n * {@link PayweaveValidationError} — the caller supplied input that conflicts\n * with existing state; anything else becomes a generic {@link PayweaveError},\n * preserving the driver error as `cause` either way.\n */\nexport function wrapDriverError(error: unknown, message: string): PayweaveError {\n if (error instanceof PayweaveError) return error;\n if (isDuplicateKeyError(error)) {\n return new PayweaveValidationError(message, { cause: error });\n }\n return new PayweaveError(message, { cause: error, isRetryable: false });\n}\n","/**\n * `pwv_<ulid>` id generation for the MongoDB adapter (docs/v1/database.md §2,\n * PW-709). Self-contained copy of `src/db/sqlite/id.ts`'s implementation (that\n * module's own header explains why: no ULID generator exists anywhere in\n * `src/`, and pulling in a third-party `ulid` package would violate the SDK's\n * zod-only `dependencies` rule, database.md §7). Every first-party adapter\n * that needs `pwv_` ids keeps its own copy rather than reaching across\n * `src/db/<other-adapter>/` — adapter directories are disjoint by design\n * (epic-07-database.md's parallel-safety guarantee).\n *\n * `pw_customers`/`pw_plans`/`pw_subscriptions`/`pw_feature_balances` use this\n * as their MongoDB `_id` (database.md §4: \"Documents use the row schemas\n * verbatim with `id` stored as `_id`\"). `pw_webhook_events`/`pw_migrations`\n * are the documented exceptions — natural keys (`dedupeKey`/`name`) ARE their\n * `_id`, no ULID involved.\n */\nimport { randomInt } from \"node:crypto\";\n\n/** Crockford's Base32 alphabet (32 symbols; excludes I, L, O, U). */\nconst ENCODING = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst ENCODING_LEN = ENCODING.length;\nconst TIME_LEN = 10;\nconst RANDOM_LEN = 16;\n\nfunction encodeTime(timeMs: number, len: number): string {\n if (!Number.isSafeInteger(timeMs) || timeMs < 0) {\n throw new RangeError(`ulid: time must be a non-negative safe integer — got ${timeMs}`);\n }\n let remaining = timeMs;\n let out = \"\";\n for (let i = 0; i < len; i++) {\n const mod = remaining % ENCODING_LEN;\n out = ENCODING.charAt(mod) + out;\n remaining = Math.floor(remaining / ENCODING_LEN);\n }\n return out;\n}\n\nfunction encodeRandom(len: number): string {\n let out = \"\";\n for (let i = 0; i < len; i++) {\n out += ENCODING.charAt(randomInt(0, ENCODING_LEN));\n }\n return out;\n}\n\n/** A fresh ULID (26 chars: 10 time + 16 random), uppercase Crockford Base32. */\nexport function ulid(timeMs: number = Date.now()): string {\n return encodeTime(timeMs, TIME_LEN) + encodeRandom(RANDOM_LEN);\n}\n\n/**\n * A fresh Payweave row id: `pwv_` + a 26-char ULID — matches\n * `src/db/schema.ts`'s `pwIdSchema` exactly.\n */\nexport function generatePwId(timeMs: number = Date.now()): string {\n return `pwv_${ulid(timeMs)}`;\n}\n","/**\n * Idempotent collection + index setup for the MongoDB adapter\n * (docs/v1/database.md §4, PW-709). MongoDB does NOT use\n * `src/db/migrations/*` (the SQL-only engine, PW-703) — instead\n * `migrations.status()`/`apply()` directly introspect and (re)create the\n * `pw_*` collections' indexes every time they run, so there is no ledger to\n * drift out of sync with reality (database.md §4: \"`migrations.status()`\n * reports missing indexes\").\n *\n * `createIndex(...)` both creates the target collection (if it doesn't exist\n * yet — an implicit MongoDB behavior) AND the index in one idempotent call:\n * calling it again with the IDENTICAL spec/name is a documented no-op, so\n * `apply()` is safe to run any number of times (backlog AC: \"run twice, no\n * error, no duplicate indexes\"). Every index below is given an EXPLICIT,\n * stable `name` so re-running `apply()` after a partial failure, or a\n * differently-ordered driver call, can never accidentally create a SECOND\n * index with the same keys under an auto-generated name.\n *\n * Only ONE logical \"migration\" exists for mongo (`MIGRATION_NAME`, mirroring\n * the SQL adapters' `\"0001_init\"` naming purely for `migrations.status()`'s\n * shared `{ pending, applied }` shape) — it is all-or-nothing: either every\n * required index exists (`applied`) or at least one is missing (`pending`).\n */\nimport {\n PW_ACTIVE_SUBSCRIPTION_STATUSES,\n PW_TABLES,\n} from \"../schema\";\n\n/** The one logical migration mongo tracks — see the module header. */\nexport const MIGRATION_NAME = \"0001_init\";\n\n/** Minimal structural shape of a `mongodb` `Collection` this file relies on. */\nexport interface MongoIndexCollectionLike {\n createIndex(indexSpec: Record<string, 1 | -1>, options?: Record<string, unknown>): Promise<string>;\n indexes(): Promise<ReadonlyArray<{ name?: string }>>;\n}\n\n/** Minimal structural shape of a `mongodb` `Db` this file relies on. */\nexport interface MongoIndexDbLike {\n collection(name: string): MongoIndexCollectionLike;\n}\n\ninterface RequiredIndex {\n collection: string;\n name: string;\n key: Record<string, 1 | -1>;\n options?: Record<string, unknown>;\n}\n\n/**\n * Every index database.md §2/§4 requires, beyond the default `_id` index\n * (which already covers `pw_webhook_events.dedupeKey` and, conceptually,\n * every other collection's `pwv_` id — both are stored AS `_id`, database.md\n * §4).\n */\nconst REQUIRED_INDEXES: readonly RequiredIndex[] = [\n {\n collection: PW_TABLES.customers,\n name: \"pw_customers_externalId_unique\",\n key: { externalId: 1 },\n options: { unique: true },\n },\n {\n collection: PW_TABLES.plans,\n name: \"pw_plans_planId_version_unique\",\n key: { planId: 1, version: 1 },\n options: { unique: true },\n },\n {\n collection: PW_TABLES.subscriptions,\n name: \"pw_subscriptions_active_unique\",\n key: { customerId: 1, group: 1 },\n options: {\n unique: true,\n // The §2 partial-unique active-subscription rule: at most one row per\n // (customerId, group) whose status is in the active set — everything\n // else (canceled/incomplete, and any OTHER status a community fork\n // might add) falls outside the filter and never collides.\n partialFilterExpression: { status: { $in: [...PW_ACTIVE_SUBSCRIPTION_STATUSES] } },\n },\n },\n {\n collection: PW_TABLES.featureBalances,\n name: \"pw_feature_balances_unique\",\n key: { customerId: 1, featureId: 1, group: 1 },\n options: { unique: true },\n },\n];\n\n/** `true` if `error` means \"this collection/namespace does not exist yet\" (fresh db). */\nfunction isNamespaceNotFound(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return code === 26; // NamespaceNotFound\n}\n\nasync function existingIndexNames(db: MongoIndexDbLike, collectionName: string): Promise<Set<string>> {\n try {\n const infos = await db.collection(collectionName).indexes();\n return new Set(infos.map((i) => i.name).filter((n): n is string => typeof n === \"string\"));\n } catch (error) {\n if (isNamespaceNotFound(error)) return new Set();\n throw error;\n }\n}\n\nasync function missingIndexes(db: MongoIndexDbLike): Promise<RequiredIndex[]> {\n const missing: RequiredIndex[] = [];\n const byCollection = new Map<string, Set<string>>();\n for (const required of REQUIRED_INDEXES) {\n let names = byCollection.get(required.collection);\n if (!names) {\n names = await existingIndexNames(db, required.collection);\n byCollection.set(required.collection, names);\n }\n if (!names.has(required.name)) missing.push(required);\n }\n return missing;\n}\n\n/** `{ pending, applied }` reflecting whether every required index currently exists. */\nexport async function mongoMigrationStatus(\n db: MongoIndexDbLike,\n): Promise<{ pending: string[]; applied: string[] }> {\n const missing = await missingIndexes(db);\n return missing.length === 0\n ? { pending: [], applied: [MIGRATION_NAME] }\n : { pending: [MIGRATION_NAME], applied: [] };\n}\n\n/**\n * Idempotently (re)create every missing required index. Safe to call\n * repeatedly — an already-present index (same name, same spec) is a\n * documented MongoDB no-op.\n */\nexport async function mongoMigrationApply(\n db: MongoIndexDbLike,\n): Promise<{ applied: string[] }> {\n const missing = await missingIndexes(db);\n if (missing.length === 0) return { applied: [] };\n for (const required of missing) {\n await db.collection(required.collection).createIndex(required.key, {\n name: required.name,\n ...required.options,\n });\n }\n return { applied: [MIGRATION_NAME] };\n}\n","/**\n * The aggregation-pipeline expression computing the CURRENT anchor-relative\n * billing period `{ index, start, end }` for a `pw_feature_balances` document\n * — the in-pipeline analog of `src/products/period.ts`'s `currentPeriod()`\n * (metered-usage.md §5; database.md §5's mongo bullet: \"reset-if-expired +\n * decrement in one server-side operation\", \"$dateAdd by n intervals FROM THE\n * ANCHOR — never iterate on previously clamped outputs\").\n *\n * ── Why this can be a closed-form / small-bounded pipeline expression ──────\n * - `day`/`week`: fixed-width epoch-ms periods — `index = floor((now - anchor)\n * / periodMs)`, clamped to >= 0. This is EXACT, no correction pass needed:\n * `period.ts`'s own `currentPeriod()` computes the identical closed form\n * for these two intervals (its \"estimate → walk-up loop\" degenerates to a\n * single exact step here, verified by the property test in\n * `test/db/mongodb.test.ts`).\n * - `month`/`year`: `period.ts`'s `currentPeriod()` doc comment PROVES its own\n * calendar-only estimate (`(nowYear-anchorYear)*12 + (nowMonth-anchorMonth)`,\n * ignoring day-of-month/time-of-day) never overshoots the true period index\n * by more than 1 and `estimate - 1` never undershoots it by more than 2 —\n * i.e. the true index is ALWAYS one of exactly three candidates:\n * `estimate-1`, `estimate`, `estimate+1` (each clamped to >= 0). This\n * pipeline computes that SAME calendar-only estimate via `$dateToParts`\n * (mirroring `period.ts` field-for-field, not re-deriving new math) and\n * picks the smallest of those candidates whose `$dateAdd`-computed end\n * exceeds `now` — a bounded, loop-free `$switch`, never an iterative\n * correction. A 4th candidate (`estimate+2`) is checked too as a\n * documented safety margin beyond `period.ts`'s own proven bound.\n *\n * ── The one assumption only a real `mongod` can confirm ────────────────────\n * `$dateAdd` with `unit: \"month\"` must clamp an out-of-range resulting\n * day-of-month to the target month's last day, exactly like `period.ts`'s\n * `addUtcMonthsClamped` (documented MongoDB behavior — e.g. adding 1 month to\n * `2020-01-31` yields `2020-02-29`). This sandbox has no real `mongod` to\n * execute the pipeline against; PW-710's CI conformance run (both standalone\n * and replica-set topologies) is the actual proof. `test/db/mongodb.test.ts`\n * instead proves the ALGORITHM correct: {@link simulatePeriodPipeline} is a\n * pure-JS re-implementation of this exact expression tree (same estimate,\n * same bounded candidates, same `advance()` calls `period.ts` itself uses for\n * the clamped month/year arithmetic) property-tested against\n * `currentPeriod()` across hundreds of anchors/resets/`now`s including leap\n * years, end-of-month anchors, and multi-period idle jumps. The only thing\n * that test CANNOT verify is whether MongoDB's real `$dateAdd`/`$dateToParts`/\n * `$switch`/`$let` operators behave as modeled — see PW-709's report for the\n * honest accounting of what only CI-docker verifies.\n */\nimport { DAY_MS, WEEK_MS, advance, type ResetInterval } from \"../../products/period\";\n\nexport { DAY_MS, WEEK_MS };\n\n/**\n * Build the aggregation expression for `{ index, start, end }` given\n * expressions for the document's `anchor` (a Date) and `resetInterval`\n * (a string), and the caller's `now` baked in as a literal (database.md §3:\n * \"use the caller's `now` parameter... never `$$NOW`\" — this pipeline is\n * built fresh, in JS, per `consume()` call, so `now` is always a plain Date\n * literal, never the server clock).\n */\nexport function buildPeriodExpr(\n nowMs: number,\n anchorExpr: unknown,\n resetExpr: unknown,\n): Record<string, unknown> {\n const nowLiteral = new Date(nowMs);\n return {\n $let: {\n vars: { anchor: anchorExpr, reset: resetExpr },\n in: {\n $switch: {\n branches: [\n {\n case: { $in: [\"$$reset\", [\"day\", \"week\"]] },\n then: {\n $let: {\n vars: { periodMs: { $cond: [{ $eq: [\"$$reset\", \"day\"] }, DAY_MS, WEEK_MS] } },\n in: {\n $let: {\n vars: {\n idx: {\n $max: [\n 0,\n {\n $floor: {\n $divide: [{ $subtract: [nowLiteral, \"$$anchor\"] }, \"$$periodMs\"],\n },\n },\n ],\n },\n },\n in: {\n index: \"$$idx\",\n start: { $add: [\"$$anchor\", { $multiply: [\"$$idx\", \"$$periodMs\"] }] },\n end: {\n $add: [\"$$anchor\", { $multiply: [{ $add: [\"$$idx\", 1] }, \"$$periodMs\"] }],\n },\n },\n },\n },\n },\n },\n },\n ],\n default: {\n $let: {\n vars: {\n monthsPerPeriod: { $cond: [{ $eq: [\"$$reset\", \"year\"] }, 12, 1] },\n anchorParts: { $dateToParts: { date: \"$$anchor\", timezone: \"UTC\" } },\n nowParts: { $dateToParts: { date: nowLiteral, timezone: \"UTC\" } },\n },\n in: {\n $let: {\n vars: {\n monthDiff: {\n $add: [\n { $multiply: [{ $subtract: [\"$$nowParts.year\", \"$$anchorParts.year\"] }, 12] },\n { $subtract: [\"$$nowParts.month\", \"$$anchorParts.month\"] },\n ],\n },\n },\n in: {\n $let: {\n vars: {\n idx0: {\n $max: [\n 0,\n {\n $subtract: [\n { $floor: { $divide: [\"$$monthDiff\", \"$$monthsPerPeriod\"] } },\n 1,\n ],\n },\n ],\n },\n },\n in: {\n $let: {\n vars: {\n end0: {\n $dateAdd: {\n startDate: \"$$anchor\",\n unit: \"month\",\n amount: { $multiply: [{ $add: [\"$$idx0\", 1] }, \"$$monthsPerPeriod\"] },\n },\n },\n end1: {\n $dateAdd: {\n startDate: \"$$anchor\",\n unit: \"month\",\n amount: { $multiply: [{ $add: [\"$$idx0\", 2] }, \"$$monthsPerPeriod\"] },\n },\n },\n end2: {\n $dateAdd: {\n startDate: \"$$anchor\",\n unit: \"month\",\n amount: { $multiply: [{ $add: [\"$$idx0\", 3] }, \"$$monthsPerPeriod\"] },\n },\n },\n end3: {\n $dateAdd: {\n startDate: \"$$anchor\",\n unit: \"month\",\n amount: { $multiply: [{ $add: [\"$$idx0\", 4] }, \"$$monthsPerPeriod\"] },\n },\n },\n },\n in: {\n $let: {\n vars: {\n chosenIdx: {\n $switch: {\n branches: [\n { case: { $lt: [nowLiteral, \"$$end0\"] }, then: \"$$idx0\" },\n {\n case: { $lt: [nowLiteral, \"$$end1\"] },\n then: { $add: [\"$$idx0\", 1] },\n },\n {\n case: { $lt: [nowLiteral, \"$$end2\"] },\n then: { $add: [\"$$idx0\", 2] },\n },\n ],\n default: { $add: [\"$$idx0\", 3] },\n },\n },\n chosenEnd: {\n $switch: {\n branches: [\n { case: { $lt: [nowLiteral, \"$$end0\"] }, then: \"$$end0\" },\n { case: { $lt: [nowLiteral, \"$$end1\"] }, then: \"$$end1\" },\n { case: { $lt: [nowLiteral, \"$$end2\"] }, then: \"$$end2\" },\n ],\n default: \"$$end3\",\n },\n },\n },\n in: {\n index: \"$$chosenIdx\",\n start: {\n $dateAdd: {\n startDate: \"$$anchor\",\n unit: \"month\",\n amount: { $multiply: [\"$$chosenIdx\", \"$$monthsPerPeriod\"] },\n },\n },\n end: \"$$chosenEnd\",\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n },\n };\n}\n\n/**\n * Pure-JS re-implementation of {@link buildPeriodExpr}'s exact algorithm — see\n * the module header. Used ONLY by `test/db/mongodb.test.ts`'s property test\n * (cross-checked against `currentPeriod()`); never imported by the adapter\n * itself (the adapter always builds and sends the real pipeline).\n */\nexport function simulatePeriodPipeline(\n nowMs: number,\n anchorMs: number,\n reset: ResetInterval,\n): { index: number; start: number; end: number } {\n if (reset === \"day\" || reset === \"week\") {\n const periodMs = reset === \"day\" ? DAY_MS : WEEK_MS;\n const idx = Math.max(0, Math.floor((nowMs - anchorMs) / periodMs));\n return { index: idx, start: anchorMs + idx * periodMs, end: anchorMs + (idx + 1) * periodMs };\n }\n\n const monthsPerPeriod = reset === \"year\" ? 12 : 1;\n const anchorDate = new Date(anchorMs);\n const nowDate = new Date(nowMs);\n const monthDiff =\n (nowDate.getUTCFullYear() - anchorDate.getUTCFullYear()) * 12 +\n (nowDate.getUTCMonth() - anchorDate.getUTCMonth());\n const idx0 = Math.max(0, Math.floor(monthDiff / monthsPerPeriod) - 1);\n\n // `advance(anchorMs, reset, n)` already converts `n` RESET-INTERVAL counts\n // to months internally for `reset: \"year\"` (`period.ts`'s own `* 12`) — pass\n // period counts (`idx`/`idx+1`) directly, NOT pre-multiplied by\n // `monthsPerPeriod` (that pre-multiplication is only correct for\n // `buildPeriodExpr`'s `$dateAdd` calls, which take a raw MONTH count and\n // never go through `advance()` at all).\n for (const idx of [idx0, idx0 + 1, idx0 + 2]) {\n const end = advance(anchorMs, reset, idx + 1);\n if (nowMs < end) {\n return { index: idx, start: advance(anchorMs, reset, idx), end };\n }\n }\n const idx = idx0 + 3;\n return {\n index: idx,\n start: advance(anchorMs, reset, idx),\n end: advance(anchorMs, reset, idx + 1),\n };\n}\n","/**\n * Document ⇄ row mapping for the MongoDB adapter (docs/v1/database.md §2/§4,\n * PW-709). Documents are the `src/db/schema.ts` row shapes verbatim with `id`\n * stored as `_id` — mapped at the adapter boundary in both directions\n * `pw_webhook_events.dedupeKey` and (conceptually)\n * `pw_migrations.name` are the schema's own documented exceptions to the\n * `pwv_<ulid>` id rule (`src/db/schema.ts`'s `pwIdSchema` doc comment) — for\n * `pw_webhook_events` the natural key IS `_id` directly, no separate `id`\n * field exists on that row type at all.\n *\n * Every mapper reads ONLY the fields it knows about — internal bookkeeping\n * fields the adapter also persists on some documents (`_pwLastApplied` on\n * `pw_feature_balances`, `./adapter.ts`'s doc comment) are never read here,\n * so they can never leak into a `Pw*` row even though they physically live\n * alongside the modeled fields in storage.\n */\nimport type {\n PwCustomer,\n PwFeatureBalance,\n PwPlanVersion,\n PwSubscription,\n PwWebhookEvent,\n} from \"../schema\";\n\n// ── pw_customers ─────────────────────────────────────────────────────────────\n\nexport interface CustomerDoc {\n _id: string;\n externalId: string;\n providerIds: Record<string, string>;\n email: string | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function docToCustomer(doc: CustomerDoc): PwCustomer {\n return {\n id: doc._id,\n externalId: doc.externalId,\n providerIds: doc.providerIds ?? {},\n email: doc.email ?? null,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n };\n}\n\n// ── pw_plans ─────────────────────────────────────────────────────────────────\n\nexport interface PlanVersionDoc {\n _id: string;\n planId: string;\n version: number;\n group: string;\n isDefault: boolean;\n name: string | null;\n priceMinor: number | null;\n priceCurrency: string | null;\n priceInterval: string | null;\n features: Record<string, unknown>;\n providerRefs: Record<string, Record<string, string>>;\n pushedAt: Date;\n}\n\nexport function docToPlanVersion(doc: PlanVersionDoc): PwPlanVersion {\n return {\n id: doc._id,\n planId: doc.planId,\n version: doc.version,\n group: doc.group,\n isDefault: doc.isDefault,\n name: doc.name,\n priceMinor: doc.priceMinor,\n priceCurrency: doc.priceCurrency,\n priceInterval: doc.priceInterval as PwPlanVersion[\"priceInterval\"],\n features: doc.features as PwPlanVersion[\"features\"],\n providerRefs: doc.providerRefs,\n pushedAt: doc.pushedAt,\n };\n}\n\n// ── pw_subscriptions ─────────────────────────────────────────────────────────\n\nexport interface SubscriptionDoc {\n _id: string;\n customerId: string;\n planId: string;\n planVersion: number;\n group: string;\n status: string;\n provider: string | null;\n providerSubscriptionRef: string | null;\n currentPeriodStart: Date;\n currentPeriodEnd: Date;\n cancelAtPeriodEnd: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport function docToSubscription(doc: SubscriptionDoc): PwSubscription {\n return {\n id: doc._id,\n customerId: doc.customerId,\n planId: doc.planId,\n planVersion: doc.planVersion,\n group: doc.group,\n status: doc.status as PwSubscription[\"status\"],\n provider: doc.provider,\n providerSubscriptionRef: doc.providerSubscriptionRef,\n currentPeriodStart: doc.currentPeriodStart,\n currentPeriodEnd: doc.currentPeriodEnd,\n cancelAtPeriodEnd: doc.cancelAtPeriodEnd,\n createdAt: doc.createdAt,\n updatedAt: doc.updatedAt,\n };\n}\n\n// ── pw_feature_balances ──────────────────────────────────────────────────────\n\nexport interface FeatureBalanceDoc {\n _id: string;\n customerId: string;\n featureId: string;\n group: string;\n used: number;\n limit: number;\n resetInterval: string;\n anchor: Date;\n periodStart: Date;\n periodEnd: Date;\n planId: string;\n planVersion: number;\n updatedAt: Date;\n /** Internal bookkeeping only — never part of {@link PwFeatureBalance}; see `./adapter.ts`. */\n _pwLastApplied?: boolean;\n}\n\nexport function docToFeatureBalance(doc: FeatureBalanceDoc): PwFeatureBalance {\n return {\n id: doc._id,\n customerId: doc.customerId,\n featureId: doc.featureId,\n group: doc.group,\n used: doc.used,\n limit: doc.limit,\n resetInterval: doc.resetInterval as PwFeatureBalance[\"resetInterval\"],\n anchor: doc.anchor,\n periodStart: doc.periodStart,\n periodEnd: doc.periodEnd,\n planId: doc.planId,\n planVersion: doc.planVersion,\n updatedAt: doc.updatedAt,\n };\n}\n\n// ── pw_webhook_events ────────────────────────────────────────────────────────\n\nexport interface WebhookEventDoc {\n /** The natural key — `_id` IS `dedupeKey` (schema.ts's documented exception). */\n _id: string;\n provider: string;\n type: string;\n receivedAt: Date;\n claimedAt: Date | null;\n appliedAt: Date | null;\n /** Internal bookkeeping only — never part of {@link PwWebhookEvent}; see `./adapter.ts`. */\n _pwWon?: boolean;\n}\n\nexport function docToWebhookEvent(doc: WebhookEventDoc): PwWebhookEvent {\n return {\n dedupeKey: doc._id,\n provider: doc.provider,\n type: doc.type,\n receivedAt: doc.receivedAt,\n claimedAt: doc.claimedAt ?? null,\n appliedAt: doc.appliedAt ?? null,\n };\n}\n","/**\n * Replica-set vs standalone transaction handling (docs/v1/database.md §4/§5,\n * PW-709). Standalone MongoDB servers do not support multi-document\n * transactions (\"Transaction numbers are only allowed on a replica set\n * member or mongos\") — rather than pre-probing topology with an extra\n * `hello`/`isMaster` round trip (fragile across deployment shapes: replica\n * set, sharded cluster, Atlas serverless, …), {@link runTransaction} ATTEMPTS\n * a real transaction and falls back to the documented non-atomic path ONLY on\n * the specific error MongoDB raises when transactions are unsupported —\n * letting the server itself be the authority instead of guessing.\n *\n * This is safe because the very FIRST operation issued inside a session's\n * transaction on a standalone server fails immediately with that error,\n * before anything is written (transactions never partially start on\n * standalone) — so re-running the callback a second time, fully, without a\n * session, is equivalent to never having attempted a transaction at all. No\n * double-write risk from the failed attempt.\n *\n * database.md §4/§2: this fallback is safe for Payweave's purposes because\n * the two contract paths with a hard atomicity requirement —\n * `balances.consume` and `webhookEvents.claim` — are EACH already atomic\n * per-document via a single pipeline `findOneAndUpdate` regardless of\n * topology (`./period-pipeline.ts`, `./adapter.ts`); `transaction()` only\n * adds cross-document rollback on top of that, which the stale-claim timeout\n * substitutes for on standalone (never a permanently-unclaimable event,\n * database.md §2's \"never a state where an unapplied event is permanently\n * unclaimable\" design rule).\n *\n * CAVEAT inherited from MongoDB's own `withTransaction` helper (not specific\n * to this adapter): the driver may invoke the callback MULTIPLE TIMES on\n * transient transaction errors (`TransientTransactionError`/\n * `UnknownTransactionCommitResult` labels) — MongoDB's own documented\n * requirement is that the callback's operations be safe to repeat. Every\n * `DatabaseAdapter` store this adapter exposes is either a single atomic\n * pipeline operation (safe to repeat) or itself idempotent by construction\n * (`plans.pushVersion`'s content-hash no-op, `balances.resetTo`'s replace),\n * so this holds without extra bookkeeping.\n */\nimport type { MongoConnectedClientLike, MongoSessionLike } from \"./types\";\n\nexport type { MongoSessionLike } from \"./types\";\n/** Alias kept for call-site clarity — `runTransaction` only needs `.startSession()`. */\nexport type MongoClientForTransactions = Pick<MongoConnectedClientLike, \"startSession\">;\n\nconst UNSUPPORTED_MESSAGE_PATTERN =\n /transaction numbers are only allowed on a replica set member or mongos|this mongodb deployment does not support transactions|transactions are not supported|standalone/i;\n\n/**\n * `true` when `error` is the specific MongoDB error raised for attempting a\n * multi-document transaction against a deployment that does not support one\n * (standalone `mongod`). Matches on the documented error code (20 —\n * `IllegalOperation`) combined with \"transaction\" in the message, OR a set of\n * known message substrings, defensively (the exact wording is a real `mongod`\n * implementation detail this sandbox cannot execute against — see the module\n * header and PW-709's report).\n */\nexport function isTransactionsUnsupportedError(error: unknown): boolean {\n if (error === null || typeof error !== \"object\") return false;\n const record = error as { message?: unknown; code?: unknown };\n const message = typeof record.message === \"string\" ? record.message : \"\";\n if (message.length === 0) return false;\n if (record.code === 20 && /transaction/i.test(message)) return true;\n return /transaction/i.test(message) && UNSUPPORTED_MESSAGE_PATTERN.test(message);\n}\n\n/**\n * Run `fn` inside a real multi-document transaction when the deployment\n * supports one; otherwise run it once, plainly, with no session (the\n * documented standalone fallback — see the module header). `fn` receives the\n * active {@link MongoSessionLike} (to thread into every operation so writes\n * commit/roll back together) or `undefined` in the fallback path.\n */\nexport async function runTransaction<T>(\n client: MongoClientForTransactions,\n fn: (session: MongoSessionLike | undefined) => Promise<T>,\n): Promise<T> {\n const session = client.startSession();\n try {\n let result: T;\n try {\n await session.withTransaction(async () => {\n result = await fn(session);\n });\n // `withTransaction` only resolves after `fn` ran to completion at least\n // once without throwing — `result` is always assigned by then.\n return result!;\n } catch (error) {\n if (isTransactionsUnsupportedError(error)) {\n return await fn(undefined);\n }\n throw error;\n }\n } finally {\n await session.endSession();\n }\n}\n","/**\n * Builds a `DatabaseAdapter` over a connected\n * `mongodb` `Db` — the MongoDB dialect's store implementations.\n *\n * ── `_id` mapping ──────────────────────────────────────────\n * Every document IS the `src/db/schema.ts` row shape, with `id` stored as\n * `_id`: `pw_customers`/`pw_plans`/`pw_subscriptions`/`pw_feature_balances`\n * use a `pwv_<ulid>` (`./id.ts`); `pw_webhook_events`' `_id` IS `dedupeKey`\n * directly (the schema's own documented natural-key exception, `./rows.ts`).\n *\n * ── `balances.consume` / `webhookEvents.claim` atomicity ──\n * Each is EXACTLY ONE `findOneAndUpdate` with `upsert: true` and an\n * AGGREGATION-PIPELINE update (an array of stages, not a plain `$set`\n * object) — MongoDB evaluates the whole pipeline against the matched (or, on\n * upsert, the query-filter-seeded empty) document as ONE atomic\n * read-decide-write per document, on any topology, with no second round\n * trip. `consume`'s pipeline (`./period-pipeline.ts` + the stages below)\n * computes the lazy period reset and the conditional decrement server-side;\n * `claim`'s pipeline expresses \"first sight OR stale-claim steal\" as a single\n * eligibility check that also naturally handles the upsert race (MongoDB's\n * own documented \"upsert on a unique-indexed filter\" pattern: a losing\n * concurrent upsert attempt is retried by the server against the winner's\n * now-existing document, not treated as an application-level error).\n *\n * Two internal bookkeeping fields ride alongside the modeled row fields ON\n * PURPOSE (never surfaced through `./rows.ts`'s mappers, so they never leak\n * into a `Pw*` row): `pw_feature_balances._pwLastApplied` (the `consume`\n * pipeline's own computed `applied` outcome — there is no other way to learn\n * it from a single write-only round trip without a token/second read) and\n * `pw_webhook_events._pwWon` (the `claim` pipeline's computed\n * \"did-I-just-win\" outcome, same reasoning). All other `__`-prefixed fields\n * a pipeline computes along the way are transient and `$unset` before the\n * document is returned.\n *\n * ── `$literal` wrapping (a real MongoDB pipeline gotcha, not a mock artifact) ──\n * Inside an aggregation-PIPELINE expression, ANY bare string starting with\n * `$` is a field path (or, with `$$`, a variable) — never a literal, unless\n * wrapped in `$literal`. Every caller-supplied string embedded in a pipeline\n * below (dedupe keys, customer/feature/group ids, plan ids, provider/type\n * names, external ids, emails) is arbitrary data this adapter never controls\n * the shape of, so it is always `lit(...)`-wrapped before going into a\n * pipeline stage — a value that happened to start with `$` would otherwise\n * silently be misread as a field reference instead of stored verbatim. This\n * does NOT apply to the PLAIN (non-pipeline) `$set` updates elsewhere in this\n * file (`customersLinkProviderRef`, `subscriptionsUpdate`) — ordinary update\n * documents always treat their values as literals, pipeline or not is the\n * whole distinction.\n *\n * ── Transactions ────────────────────────────────────────────\n * `transaction()` delegates to `./topology.ts`'s `runTransaction`, which\n * tries a real multi-document transaction and falls back to the documented\n * non-atomic path on standalone deployments. Every store method below\n * accepts the ambient `session` (threaded through `deps.session`) so a\n * `tx`-scoped adapter's writes all belong to the same transaction.\n */\nimport { PayweaveNotFoundError } from \"../../core/errors\";\nimport { currentPeriod } from \"../../products/period\";\nimport type { DatabaseAdapter, PwConsumeInput, PwConsumeResult } from \"../index\";\nimport {\n DEFAULT_STALE_CLAIM_AFTER_MS,\n PW_ACTIVE_SUBSCRIPTION_STATUSES,\n PW_TABLES,\n type PwCustomerUpsert,\n type PwFeatureBalanceInit,\n type PwPlanVersion,\n type PwPlanVersionInput,\n type PwSubscription,\n type PwSubscriptionInput,\n type PwSubscriptionPatch,\n} from \"../schema\";\nimport { isDuplicateKeyError, wrapDriverError } from \"./errors\";\nimport { generatePwId } from \"./id\";\nimport { mongoMigrationApply, mongoMigrationStatus } from \"./migrations\";\nimport { buildPeriodExpr } from \"./period-pipeline\";\nimport {\n docToCustomer,\n docToFeatureBalance,\n docToPlanVersion,\n docToSubscription,\n docToWebhookEvent,\n type CustomerDoc,\n type FeatureBalanceDoc,\n type PlanVersionDoc,\n type SubscriptionDoc,\n type WebhookEventDoc,\n} from \"./rows\";\nimport { runTransaction, type MongoClientForTransactions, type MongoSessionLike } from \"./topology\";\nimport type { MongoCollectionLike, MongoDbLike } from \"./types\";\n\nexport interface MongoAdapterDeps {\n db: MongoDbLike;\n client: MongoClientForTransactions;\n session?: MongoSessionLike | undefined;\n}\n\nconst ACTIVE_STATUSES: readonly string[] = [...PW_ACTIVE_SUBSCRIPTION_STATUSES];\n\n/** Stable (sorted-key) JSON for order-independent structural comparison (plans.pushVersion). */\nfunction stableStringify(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(\",\")}]`;\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n return `{${entries.map(([key, val]) => `${JSON.stringify(key)}:${stableStringify(val)}`).join(\",\")}}`;\n }\n return JSON.stringify(value);\n}\n\ninterface PlanContent {\n group: string;\n isDefault: boolean;\n name: string | null;\n priceMinor: number | null;\n priceCurrency: string | null;\n priceInterval: string | null;\n features: unknown;\n providerRefs: unknown;\n}\n\nconst planContent = (p: PwPlanVersion | PwPlanVersionInput): PlanContent => ({\n group: p.group,\n isDefault: p.isDefault,\n name: p.name,\n priceMinor: p.priceMinor,\n priceCurrency: p.priceCurrency,\n priceInterval: p.priceInterval,\n features: p.features,\n providerRefs: p.providerRefs,\n});\n\nfunction planContentEquals(active: PwPlanVersion, input: PwPlanVersionInput): boolean {\n return stableStringify(planContent(active)) === stableStringify(planContent(input));\n}\n\n/**\n * Wrap a caller-supplied STRING as `$literal` before it goes into an\n * aggregation-PIPELINE stage. Inside a pipeline expression, any bare string\n * starting with `$` is a field path (`$foo`) or, with a second `$`, a\n * variable (`$$bar`) — real MongoDB behavior, not a mock artifact. Every\n * value below (dedupe keys, customer/feature/group ids, plan ids, provider\n * names, …) is arbitrary CALLER data that could — however unlikely —\n * contain a leading `$`, so it is always wrapped before being embedded in a\n * pipeline literal (never needed for the PLAIN, non-pipeline `$set` updates\n * elsewhere in this file — e.g. `customersLinkProviderRef`,\n * `subscriptionsUpdate` — where update-document values are always literal).\n */\nfunction lit(value: string): Record<string, unknown> {\n return { $literal: value };\n}\n\nconst SUBSCRIPTION_PATCH_KEYS: ReadonlyArray<keyof PwSubscriptionPatch> = [\n \"planId\",\n \"planVersion\",\n \"status\",\n \"provider\",\n \"providerSubscriptionRef\",\n \"currentPeriodStart\",\n \"currentPeriodEnd\",\n \"cancelAtPeriodEnd\",\n];\n\n/** Build a full `DatabaseAdapter` over a connected `mongodb` `Db` (mongo dialect). */\nexport function buildAdapter(deps: MongoAdapterDeps): DatabaseAdapter {\n const sessionOpt: Record<string, unknown> = deps.session ? { session: deps.session } : {};\n const customers = deps.db.collection<CustomerDoc>(PW_TABLES.customers);\n const plans = deps.db.collection<PlanVersionDoc>(PW_TABLES.plans);\n const subscriptions = deps.db.collection<SubscriptionDoc>(PW_TABLES.subscriptions);\n const balances = deps.db.collection<FeatureBalanceDoc>(PW_TABLES.featureBalances);\n const webhookEvents = deps.db.collection<WebhookEventDoc>(PW_TABLES.webhookEvents);\n\n return {\n dialect: \"mongodb\",\n customers: {\n getByExternalId: (externalId) => customersGetByExternalId(customers, externalId, sessionOpt),\n upsert: (input) => customersUpsert(customers, input, sessionOpt),\n linkProviderRef: (externalId, provider, ref) =>\n customersLinkProviderRef(customers, externalId, provider, ref, sessionOpt),\n },\n plans: {\n getActiveVersion: (planId) => plansGetActiveVersion(plans, planId, sessionOpt),\n listActive: () => plansListActive(plans, sessionOpt),\n pushVersion: (plan) => plansPushVersion(plans, plan, sessionOpt),\n },\n subscriptions: {\n getActive: (customerId, group) => subscriptionsGetActive(subscriptions, customerId, group, sessionOpt),\n create: (input) => subscriptionsCreate(subscriptions, input, sessionOpt),\n update: (id, patch) => subscriptionsUpdate(subscriptions, id, patch, sessionOpt),\n },\n balances: {\n get: (customerId, featureId, group) => balancesGet(balances, customerId, featureId, group, sessionOpt),\n consume: (input) => balancesConsume(balances, input, sessionOpt),\n resetTo: (customerId, featureId, group, init) =>\n balancesResetTo(balances, customerId, featureId, group, init, sessionOpt),\n },\n webhookEvents: {\n claim: (dedupeKey, meta) => webhookEventsClaim(webhookEvents, dedupeKey, meta, sessionOpt),\n markApplied: (dedupeKey) => webhookEventsMarkApplied(webhookEvents, dedupeKey, sessionOpt),\n },\n migrations: {\n status: () => mongoMigrationStatus(deps.db),\n apply: () => mongoMigrationApply(deps.db),\n },\n transaction: (fn) =>\n runTransaction(deps.client, (session) => fn(buildAdapter({ ...deps, session }))),\n };\n}\n\n// ── customers ────────────────────────────────────────────────────────────────\n\nasync function customersGetByExternalId(\n collection: MongoCollectionLike<CustomerDoc>,\n externalId: string,\n sessionOpt: Record<string, unknown>,\n) {\n const doc = await collection.findOne({ externalId }, sessionOpt);\n return doc ? docToCustomer(doc) : null;\n}\n\nasync function customersUpsert(\n collection: MongoCollectionLike<CustomerDoc>,\n input: PwCustomerUpsert,\n sessionOpt: Record<string, unknown>,\n) {\n const now = new Date();\n const generatedId = generatePwId(now.getTime());\n const emailExpr = input.email !== undefined ? lit(input.email) : { $ifNull: [\"$email\", null] };\n try {\n const doc = await collection.findOneAndUpdate(\n { externalId: input.externalId },\n [\n {\n $set: {\n _id: { $ifNull: [\"$_id\", lit(generatedId)] },\n externalId: lit(input.externalId),\n providerIds: { $ifNull: [\"$providerIds\", {}] },\n email: emailExpr,\n createdAt: { $ifNull: [\"$createdAt\", now] },\n updatedAt: now,\n },\n },\n ],\n { upsert: true, returnDocument: \"after\", ...sessionOpt },\n );\n if (!doc) throw new Error(\"mongodb adapter: customers.upsert returned no document\");\n return docToCustomer(doc);\n } catch (error) {\n throw wrapDriverError(\n error,\n `payweave/db/mongodb: customers.upsert(${JSON.stringify(input.externalId)}) failed.`,\n );\n }\n}\n\nasync function customersLinkProviderRef(\n collection: MongoCollectionLike<CustomerDoc>,\n externalId: string,\n provider: string,\n ref: string,\n sessionOpt: Record<string, unknown>,\n): Promise<void> {\n // Single round trip: dot-path `$set` merges ONE provider key without\n // clobbering the rest of `providerIds` — no read-modify-write needed\n // (unlike the sqlite adapter, which reads then rewrites the whole JSON\n // blob because SQL has no equivalent of a nested-field `$set`).\n const result = await collection.updateOne(\n { externalId },\n { $set: { [`providerIds.${provider}`]: ref, updatedAt: new Date() } },\n sessionOpt,\n );\n if (result.matchedCount === 0) {\n throw new PayweaveNotFoundError(\n `payweave/db/mongodb: customers.linkProviderRef: no customer with externalId ` +\n `${JSON.stringify(externalId)}.`,\n );\n }\n}\n\n// ── plans ────────────────────────────────────────────────────────────────────\n\nasync function plansGetActiveVersion(\n collection: MongoCollectionLike<PlanVersionDoc>,\n planId: string,\n sessionOpt: Record<string, unknown>,\n) {\n const doc = await collection.findOne({ planId }, { sort: { version: -1 }, ...sessionOpt });\n return doc ? docToPlanVersion(doc) : null;\n}\n\nasync function plansListActive(\n collection: MongoCollectionLike<PlanVersionDoc>,\n sessionOpt: Record<string, unknown>,\n) {\n const docs = await collection\n .aggregate(\n [\n { $sort: { planId: 1, version: -1 } },\n { $group: { _id: \"$planId\", doc: { $first: \"$$ROOT\" } } },\n { $replaceRoot: { newRoot: \"$doc\" } },\n ],\n sessionOpt,\n )\n .toArray();\n return docs.map(docToPlanVersion);\n}\n\nconst PUSH_VERSION_MAX_ATTEMPTS = 5;\n\nasync function plansPushVersion(\n collection: MongoCollectionLike<PlanVersionDoc>,\n plan: PwPlanVersionInput,\n sessionOpt: Record<string, unknown>,\n): Promise<PwPlanVersion> {\n // No injectable `now`/no atomicity race REQUIRED by the conformance suite\n // (only `balances.consume`/`webhookEvents.claim` carry that obligation)\n // — but a bounded retry loop on the (planId, version)\n // unique-index collision hardens this against real concurrent pushes\n // without needing a session transaction for every call.\n for (let attempt = 0; attempt < PUSH_VERSION_MAX_ATTEMPTS; attempt++) {\n const active = await plansGetActiveVersion(collection, plan.planId, sessionOpt);\n if (active && planContentEquals(active, plan)) return active;\n\n const now = new Date();\n const nextVersion = (active?.version ?? 0) + 1;\n const doc: PlanVersionDoc = {\n _id: generatePwId(now.getTime()),\n planId: plan.planId,\n version: nextVersion,\n group: plan.group,\n isDefault: plan.isDefault,\n name: plan.name,\n priceMinor: plan.priceMinor,\n priceCurrency: plan.priceCurrency,\n priceInterval: plan.priceInterval,\n features: plan.features,\n providerRefs: plan.providerRefs,\n pushedAt: now,\n };\n try {\n await collection.insertOne(doc, sessionOpt);\n return docToPlanVersion(doc);\n } catch (error) {\n if (isDuplicateKeyError(error) && attempt < PUSH_VERSION_MAX_ATTEMPTS - 1) continue;\n throw wrapDriverError(\n error,\n `payweave/db/mongodb: plans.pushVersion(${JSON.stringify(plan.planId)}) failed.`,\n );\n }\n }\n /* istanbul ignore next -- unreachable: the loop above always returns or throws. */\n throw new Error(\"payweave/db/mongodb: plans.pushVersion exhausted retries under contention\");\n}\n\n// ── subscriptions ────────────────────────────────────────────────────────────\n\nasync function subscriptionsGetActive(\n collection: MongoCollectionLike<SubscriptionDoc>,\n customerId: string,\n group: string,\n sessionOpt: Record<string, unknown>,\n) {\n const doc = await collection.findOne(\n { customerId, group, status: { $in: ACTIVE_STATUSES } },\n sessionOpt,\n );\n return doc ? docToSubscription(doc) : null;\n}\n\nasync function subscriptionsCreate(\n collection: MongoCollectionLike<SubscriptionDoc>,\n input: PwSubscriptionInput,\n sessionOpt: Record<string, unknown>,\n): Promise<PwSubscription> {\n const now = new Date();\n const doc: SubscriptionDoc = {\n _id: generatePwId(now.getTime()),\n customerId: input.customerId,\n planId: input.planId,\n planVersion: input.planVersion,\n group: input.group,\n status: input.status,\n provider: input.provider,\n providerSubscriptionRef: input.providerSubscriptionRef,\n currentPeriodStart: input.currentPeriodStart,\n currentPeriodEnd: input.currentPeriodEnd,\n cancelAtPeriodEnd: input.cancelAtPeriodEnd,\n createdAt: now,\n updatedAt: now,\n };\n try {\n await collection.insertOne(doc, sessionOpt);\n return docToSubscription(doc);\n } catch (error) {\n throw wrapDriverError(\n error,\n `payweave/db/mongodb: subscriptions.create for customer ${JSON.stringify(input.customerId)} ` +\n `group ${JSON.stringify(input.group)} violated a uniqueness rule (an active-set ` +\n \"subscription already exists for this customer/group, or another constraint failed).\",\n );\n }\n}\n\nasync function subscriptionsUpdate(\n collection: MongoCollectionLike<SubscriptionDoc>,\n id: string,\n patch: PwSubscriptionPatch,\n sessionOpt: Record<string, unknown>,\n) {\n const set: Record<string, unknown> = { updatedAt: new Date() };\n const patchRecord = patch as Record<string, unknown>;\n for (const key of SUBSCRIPTION_PATCH_KEYS) {\n if (!(key in patch) || patchRecord[key] === undefined) continue;\n set[key] = patchRecord[key];\n }\n try {\n const doc = await collection.findOneAndUpdate(\n { _id: id },\n { $set: set },\n { returnDocument: \"after\", ...sessionOpt },\n );\n if (!doc) {\n throw new PayweaveNotFoundError(\n `payweave/db/mongodb: subscriptions.update: no subscription with id ${JSON.stringify(id)}.`,\n );\n }\n return docToSubscription(doc);\n } catch (error) {\n if (error instanceof PayweaveNotFoundError) throw error;\n throw wrapDriverError(error, `payweave/db/mongodb: subscriptions.update(${JSON.stringify(id)}) failed.`);\n }\n}\n\n// ── balances ─────────────────────────────────────────────────────────────────\n\nasync function balancesGet(\n collection: MongoCollectionLike<FeatureBalanceDoc>,\n customerId: string,\n featureId: string,\n group: string,\n sessionOpt: Record<string, unknown>,\n) {\n const doc = await collection.findOne({ customerId, featureId, group }, sessionOpt);\n return doc ? docToFeatureBalance(doc) : null;\n}\n\n/**\n * Build `consume`'s single pipeline-update — see the module header. Every\n * stage is a plain `$set`/`$unset`; the whole array is what\n * `findOneAndUpdate` evaluates atomically.\n */\nfunction buildConsumePipeline(input: PwConsumeInput, generatedId: string): Record<string, unknown>[] {\n const nowMs = input.now.getTime();\n const nowLiteral = input.now;\n const conditional = input.conditional === true;\n const amount = input.amount;\n\n return [\n // A: fill creation defaults. Deliberately does NOT rely on MongoDB\n // auto-seeding the query filter's equality fields into a fresh upserted\n // document (that behavior is a real-server implementation detail this\n // sandbox cannot verify one way or the other) — EVERY field the document\n // needs, including customerId/featureId/group, is explicitly `$ifNull`'d\n // from this call's own inputs (the \"$ifNull defaults\" pattern),\n // so the pipeline is correct regardless of that assumption.\n {\n $set: {\n _id: { $ifNull: [\"$_id\", lit(generatedId)] },\n customerId: { $ifNull: [\"$customerId\", lit(input.customerId)] },\n featureId: { $ifNull: [\"$featureId\", lit(input.featureId)] },\n group: { $ifNull: [\"$group\", lit(input.group)] },\n anchor: { $ifNull: [\"$anchor\", input.init.anchor] },\n resetInterval: { $ifNull: [\"$resetInterval\", lit(input.init.resetInterval)] },\n limit: { $ifNull: [\"$limit\", input.init.limit] },\n planId: { $ifNull: [\"$planId\", lit(input.init.planId)] },\n planVersion: { $ifNull: [\"$planVersion\", input.init.planVersion] },\n used: { $ifNull: [\"$used\", 0] },\n },\n },\n // B: the anchor-relative current period (./period-pipeline.ts).\n {\n $set: {\n __period: buildPeriodExpr(nowMs, \"$anchor\", \"$resetInterval\"),\n },\n },\n // C: reset-due / conditional-gate arithmetic, entirely server-side.\n {\n $set: {\n __hasPeriodEnd: { $ne: [{ $ifNull: [\"$periodEnd\", null] }, null] },\n },\n },\n {\n $set: {\n __resetDue: {\n $cond: [\"$__hasPeriodEnd\", { $gte: [nowLiteral, \"$periodEnd\"] }, true],\n },\n },\n },\n {\n $set: {\n __baseUsed: { $cond: [\"$__resetDue\", 0, \"$used\"] },\n },\n },\n // Each of the following stays in its OWN `$set` stage rather than sharing\n // one with the field it depends on — deliberately conservative given this\n // sandbox cannot execute a real pipeline to confirm same-stage field\n // visibility ordering.\n {\n $set: {\n __remaining: { $subtract: [\"$limit\", \"$__baseUsed\"] },\n },\n },\n {\n $set: {\n __applied: conditional ? { $gte: [\"$__remaining\", amount] } : true,\n },\n },\n {\n $set: {\n __finalUsed: {\n $cond: [\"$__applied\", { $add: [\"$__baseUsed\", amount] }, \"$__baseUsed\"],\n },\n __shouldWrite: { $or: [\"$__applied\", \"$__resetDue\"] },\n },\n },\n // D: write the real fields — untouched (including `updatedAt`) when\n // denied AND no reset was due (leave the row untouched in that case).\n {\n $set: {\n used: { $cond: [\"$__shouldWrite\", \"$__finalUsed\", \"$used\"] },\n periodStart: { $cond: [\"$__shouldWrite\", \"$__period.start\", \"$periodStart\"] },\n periodEnd: { $cond: [\"$__shouldWrite\", \"$__period.end\", \"$periodEnd\"] },\n updatedAt: { $cond: [\"$__shouldWrite\", nowLiteral, { $ifNull: [\"$updatedAt\", nowLiteral] }] },\n _pwLastApplied: \"$__applied\",\n },\n },\n {\n $unset: [\n \"__period\",\n \"__hasPeriodEnd\",\n \"__resetDue\",\n \"__baseUsed\",\n \"__remaining\",\n \"__applied\",\n \"__finalUsed\",\n \"__shouldWrite\",\n ],\n },\n ];\n}\n\nasync function balancesConsume(\n collection: MongoCollectionLike<FeatureBalanceDoc>,\n input: PwConsumeInput,\n sessionOpt: Record<string, unknown>,\n): Promise<PwConsumeResult> {\n const generatedId = generatePwId(input.now.getTime());\n const pipeline = buildConsumePipeline(input, generatedId);\n const doc = await collection.findOneAndUpdate(\n { customerId: input.customerId, featureId: input.featureId, group: input.group },\n pipeline,\n { upsert: true, returnDocument: \"after\", ...sessionOpt },\n );\n if (!doc) throw new Error(\"mongodb adapter: balances.consume returned no document\");\n const applied = doc._pwLastApplied ?? true;\n return { ...docToFeatureBalance(doc), applied };\n}\n\nasync function balancesResetTo(\n collection: MongoCollectionLike<FeatureBalanceDoc>,\n customerId: string,\n featureId: string,\n group: string,\n init: PwFeatureBalanceInit,\n sessionOpt: Record<string, unknown>,\n): Promise<void> {\n // No injectable `now` in this contract method — a plan\n // change's anchor IS \"now\", and this is\n // an unconditional REPLACE regardless of the row's prior state, so no\n // pipeline/atomicity concern applies (unlike `consume`).\n const now = new Date();\n const period = currentPeriod(init.anchor.getTime(), init.resetInterval, now.getTime());\n const generatedId = generatePwId(now.getTime());\n await collection.findOneAndUpdate(\n { customerId, featureId, group },\n [\n {\n $set: {\n _id: { $ifNull: [\"$_id\", lit(generatedId)] },\n // Same defensive explicitness as `buildConsumePipeline` — never\n // rely on MongoDB auto-seeding the filter's equality fields, and\n // never let a caller-supplied string be misread as a field path.\n customerId: lit(customerId),\n featureId: lit(featureId),\n group: lit(group),\n used: 0,\n limit: init.limit,\n resetInterval: lit(init.resetInterval),\n anchor: init.anchor,\n periodStart: new Date(period.start),\n periodEnd: new Date(period.end),\n planId: lit(init.planId),\n planVersion: init.planVersion,\n updatedAt: now,\n },\n },\n ],\n { upsert: true, ...sessionOpt },\n );\n}\n\n// ── webhookEvents ────────────────────────────────────────────────────────────\n\n/**\n * Build `claim`'s single pipeline-update — see the module header. Expresses\n * \"first sight OR stale-claim steal\" as one eligibility check\n * (`_pwWon`) computed and written in the SAME atomic operation, then read\n * back from the returned document — no second round trip, no caller-unique\n * token needed (a single `findOneAndUpdate` is one atomic per-document\n * operation regardless of topology, so at most one concurrent caller ever\n * observes `_pwWon: true` for a given transition.\n */\nfunction buildClaimPipeline(\n dedupeKey: string,\n meta: { provider: string; type: string; now: Date; staleClaimAfterMs?: number },\n): Record<string, unknown>[] {\n const staleClaimAfterMs = meta.staleClaimAfterMs ?? DEFAULT_STALE_CLAIM_AFTER_MS;\n const staleThreshold = new Date(meta.now.getTime() - staleClaimAfterMs);\n return [\n {\n $set: {\n // Same defensive explicitness as `buildConsumePipeline` — never rely\n // on MongoDB auto-seeding the `_id` filter's equality match on\n // upsert, and never let a caller-supplied string be misread as a\n // field path.\n _id: { $ifNull: [\"$_id\", lit(dedupeKey)] },\n provider: { $ifNull: [\"$provider\", lit(meta.provider)] },\n type: { $ifNull: [\"$type\", lit(meta.type)] },\n receivedAt: { $ifNull: [\"$receivedAt\", meta.now] },\n appliedAt: { $ifNull: [\"$appliedAt\", null] },\n claimedAt: { $ifNull: [\"$claimedAt\", null] },\n },\n },\n {\n $set: {\n _pwWon: {\n $and: [\n { $eq: [\"$appliedAt\", null] },\n { $or: [{ $eq: [\"$claimedAt\", null] }, { $lte: [\"$claimedAt\", staleThreshold] }] },\n ],\n },\n },\n },\n {\n $set: {\n claimedAt: { $cond: [\"$_pwWon\", meta.now, \"$claimedAt\"] },\n },\n },\n ];\n}\n\nasync function webhookEventsClaim(\n collection: MongoCollectionLike<WebhookEventDoc>,\n dedupeKey: string,\n meta: { provider: string; type: string; now: Date; staleClaimAfterMs?: number },\n sessionOpt: Record<string, unknown>,\n): Promise<boolean> {\n const pipeline = buildClaimPipeline(dedupeKey, meta);\n const doc = await collection.findOneAndUpdate(\n { _id: dedupeKey },\n pipeline,\n { upsert: true, returnDocument: \"after\", ...sessionOpt },\n );\n return doc?._pwWon === true;\n}\n\nasync function webhookEventsMarkApplied(\n collection: MongoCollectionLike<WebhookEventDoc>,\n dedupeKey: string,\n sessionOpt: Record<string, unknown>,\n): Promise<void> {\n await collection.updateOne({ _id: dedupeKey }, { $set: { appliedAt: new Date() } }, sessionOpt);\n}\n\n// Re-exported so tests can round-trip a raw document without duplicating the\n// mapping logic.\nexport { docToWebhookEvent };\n","/**\n * Input resolution for `mongodbAdapter(...)`.\n *\n * Accepts EITHER `{ url, dbName }` — an eagerly-validated `mongodb://` /\n * `mongodb+srv://` connection string, driver imported and connected lazily —\n * OR `{ client, dbName }` wrapping an already-constructed `MongoClient` (the\n * caller owns its lifecycle; this adapter never calls `.close()` on a\n * caller-supplied client). `dbName` is REQUIRED in both shapes: a MongoDB\n * connection string MAY name a default database in its path segment, but a\n * bare `MongoClient` handed to us carries no such default we could safely\n * assume, so both branches share the same explicit-`dbName` contract.\n *\n * `client` is validated STRUCTURALLY (`MongoClientLike` below) rather than\n * via `instanceof` against the real `mongodb` package — mirrors\n * `src/db/sqlite/url.ts`'s `BetterSqlite3DatabaseLike`/`LibsqlClientLike`\n * precedent: this keeps the adapter's PUBLIC type surface resolvable for a\n * consumer who has not (yet) installed the optional `mongodb` peer, and\n * means classifying an input needs no driver import at all (adapters only\n * import their driver lazily, inside their own subpath).\n *\n * Construction is synchronous and side-effect-free: the\n * shape/scheme is validated eagerly here; the driver package is imported and\n * the connection opened lazily, on first store call (`./index.ts`).\n *\n * SECURITY: the raw connection\n * string is NEVER interpolated into a thrown error's message here — only a\n * generic description of the expected shape. `src/core/redact.ts` also scrubs\n * `mongodb://`/`mongodb+srv://` credentials from logger events and error\n * `toJSON()` as defense in depth, but \"never put it in an error message in\n * the first place\" is the stronger guarantee and costs nothing to uphold.\n */\nimport { PayweaveConfigError } from \"../../core/errors\";\n\nconst URL_SCHEMES = [\"mongodb://\", \"mongodb+srv://\"];\n\n/**\n * Minimal structural shape of a `mongodb` `MongoClient` this adapter relies\n * on — enough to validate + drive it without importing the real driver.\n */\nexport interface MongoClientLike {\n connect(): Promise<unknown>;\n close(force?: boolean): Promise<void>;\n db(name?: string): unknown;\n startSession(options?: unknown): unknown;\n}\n\n/** Where `mongodbAdapter` should connect, resolved eagerly from its input. */\nexport type MongoConnectTarget =\n | { readonly kind: \"url\"; readonly url: string; readonly dbName: string }\n | { readonly kind: \"client\"; readonly client: MongoClientLike; readonly dbName: string };\n\nfunction looksLikeMongoClient(value: object): value is MongoClientLike {\n const candidate = value as Partial<MongoClientLike>;\n return (\n typeof candidate.connect === \"function\" &&\n typeof candidate.close === \"function\" &&\n typeof candidate.db === \"function\" &&\n typeof candidate.startSession === \"function\"\n );\n}\n\n/**\n * Eagerly validate a `{ url }` string's scheme — `mongodb://` or\n * `mongodb+srv://` only. Never echoes `url` back in the\n * thrown message (see the module header's SECURITY note).\n */\nexport function validateMongoUrl(url: unknown): asserts url is string {\n if (typeof url !== \"string\" || url.length === 0) {\n throw new PayweaveConfigError(\n \"payweave/db/mongodb: mongodbAdapter({ url, dbName }) requires a non-empty string url.\",\n );\n }\n if (!URL_SCHEMES.some((scheme) => url.startsWith(scheme))) {\n throw new PayweaveConfigError(\n 'payweave/db/mongodb: mongodbAdapter({ url, ... }) requires a \"mongodb://\" or ' +\n '\"mongodb+srv://\" connection string.',\n );\n }\n}\n\nfunction validateDbName(dbName: unknown): asserts dbName is string {\n if (typeof dbName !== \"string\" || dbName.length === 0) {\n throw new PayweaveConfigError(\n \"payweave/db/mongodb: mongodbAdapter(...) requires a non-empty `dbName` — a MongoDB \" +\n \"connection string may name a default database in its path, but this adapter always \" +\n \"requires `dbName` explicitly, for both { url } and { client }.\",\n );\n }\n}\n\n/**\n * Resolve `mongodbAdapter`'s single argument into a {@link MongoConnectTarget}.\n * Synchronous and side-effect-free — no driver import, no connection opened.\n */\nexport function resolveMongoInput(input: unknown): MongoConnectTarget {\n if (input === null || typeof input !== \"object\") {\n throw new PayweaveConfigError(\n \"payweave/db/mongodb: mongodbAdapter(...) expects { url, dbName } (a mongodb://\" +\n \"/mongodb+srv:// connection string) or { client, dbName } (an existing MongoClient) — \" +\n `got ${input === null ? \"null\" : typeof input}.`,\n );\n }\n const record = input as Record<string, unknown>;\n\n if (\"url\" in record) {\n validateMongoUrl(record.url);\n validateDbName(record.dbName);\n return { kind: \"url\", url: record.url, dbName: record.dbName };\n }\n\n if (\"client\" in record) {\n const client = record.client;\n if (client === null || typeof client !== \"object\" || !looksLikeMongoClient(client)) {\n throw new PayweaveConfigError(\n \"payweave/db/mongodb: mongodbAdapter({ client, dbName }) expects `client` to be a \" +\n \"MongoClient-like instance (has .connect()/.close()/.db()/.startSession()) — got \" +\n `${client === null ? \"null\" : typeof client === \"object\" ? \"an object missing one of those methods\" : typeof client}.`,\n );\n }\n validateDbName(record.dbName);\n return { kind: \"client\", client, dbName: record.dbName };\n }\n\n throw new PayweaveConfigError(\n \"payweave/db/mongodb: mongodbAdapter(...) expects { url, dbName } (a mongodb://\" +\n \"/mongodb+srv:// connection string) or { client, dbName } (an existing MongoClient) — \" +\n \"got an object matching neither shape.\",\n );\n}\n","/**\n * `payweave/db/mongodb` — MongoDB adapter.\n * FIRST-PARTY v1: MongoDB is not a bolted-on community adapter — it ships\n * with Payweave itself.\n *\n * `mongodbAdapter(...)` accepts EITHER:\n * - `{ url, dbName }` — a `mongodb://`/`mongodb+srv://` connection string,\n * validated eagerly (`./url.ts`); `mongodb` is imported and the connection\n * opened LAZILY, on the first store call.\n * - `{ client, dbName }` — an already-constructed `MongoClient` you own; this\n * adapter never calls `.close()` on it.\n *\n * `mongodb` is an OPTIONAL peerDependency — this module\n * NEVER imports it at the top level, only dynamically inside `connect()`\n * (mirrors `src/db/sqlite/index.ts`'s `openBetterSqlite3Driver`/\n * `openLibsqlDriver` pattern), and `mongodbAdapter`'s public parameter/return\n * types are STRUCTURAL (`./url.ts`'s `MongoClientLike`, `./types.ts`'s\n * `MongoDbLike`/`MongoCollectionLike`) rather than the real driver's classes\n * — so importing `payweave/db/mongodb` (or `payweave` core, which never\n * references this subpath at all) never requires `mongodb` to be installed\n * OR its types to be resolvable, exactly mirroring the sqlite adapter's\n * `BetterSqlite3DatabaseLike`/`LibsqlClientLike` precedent.\n * The ONE place this module bridges to the real driver is `connect()` below,\n * via an explicit, localized cast — never structural inference across the\n * whole codebase.\n *\n * Construction is synchronous and side-effect-free: input\n * is validated eagerly; the driver import + connection happen lazily and are\n * memoized (a `:memory:`-style \"hold exactly one connection\" invariant isn't\n * needed here — MongoDB is never in-process — but memoizing avoids opening a\n * new connection per call, mirroring sqlite's own memoized `driverPromise`).\n */\nimport { buildAdapter, type MongoAdapterDeps } from \"./adapter\";\nimport { installHintError } from \"./errors\";\nimport { resolveMongoInput, type MongoClientLike } from \"./url\";\nimport type { MongoConnectedClientLike } from \"./types\";\nimport type { DatabaseAdapter } from \"../index\";\n\nexport type { MongoClientLike } from \"./url\";\n\n/** `mongodbAdapter(...)`'s single argument — see the module header. */\nexport type MongodbAdapterInput =\n | { url: string; dbName: string }\n | { client: MongoClientLike; dbName: string };\n\ntype ConnectedMongo = MongoAdapterDeps;\n\nasync function connect(target: ReturnType<typeof resolveMongoInput>): Promise<ConnectedMongo> {\n if (target.kind === \"client\") {\n // `MongoClient.connect()` is documented as safe to call even on an\n // already-connected client (idempotent) — this adapter never assumes the\n // caller connected it first. The cast below is the ONE place a\n // caller-supplied (structurally-validated only) client is bridged into\n // the internal `MongoConnectedClientLike` shape `./adapter.ts`/\n // `./topology.ts` rely on — see the module header.\n const client = target.client as unknown as MongoConnectedClientLike;\n await target.client.connect();\n return { client, db: client.db(target.dbName) };\n }\n\n let mod: typeof import(\"mongodb\");\n try {\n mod = await import(\"mongodb\");\n } catch (cause) {\n throw installHintError(cause);\n }\n const rawClient = new mod.MongoClient(target.url);\n await rawClient.connect();\n const client = rawClient as unknown as MongoConnectedClientLike;\n return { client, db: client.db(target.dbName) };\n}\n\n/**\n * Wrap {@link buildAdapter} behind lazy, memoized connect-on-first-use.\n * Every `DatabaseAdapter` method awaits the SAME\n * connection/adapter-build promise, so `mongodb`'s driver connects exactly\n * once regardless of how many store methods are called.\n */\nfunction buildLazyAdapter(getConnection: () => Promise<ConnectedMongo>): DatabaseAdapter {\n let builtPromise: Promise<DatabaseAdapter> | undefined;\n const getReal = (): Promise<DatabaseAdapter> => {\n builtPromise ??= getConnection().then(\n ({ client, db }): DatabaseAdapter => buildAdapter({ client, db } satisfies MongoAdapterDeps),\n );\n return builtPromise;\n };\n\n return {\n dialect: \"mongodb\",\n customers: {\n getByExternalId: async (externalId) => (await getReal()).customers.getByExternalId(externalId),\n upsert: async (input) => (await getReal()).customers.upsert(input),\n linkProviderRef: async (externalId, provider, ref) =>\n (await getReal()).customers.linkProviderRef(externalId, provider, ref),\n },\n plans: {\n getActiveVersion: async (planId) => (await getReal()).plans.getActiveVersion(planId),\n listActive: async () => (await getReal()).plans.listActive(),\n pushVersion: async (plan) => (await getReal()).plans.pushVersion(plan),\n },\n subscriptions: {\n getActive: async (customerId, group) => (await getReal()).subscriptions.getActive(customerId, group),\n create: async (input) => (await getReal()).subscriptions.create(input),\n update: async (id, patch) => (await getReal()).subscriptions.update(id, patch),\n },\n balances: {\n get: async (customerId, featureId, group) =>\n (await getReal()).balances.get(customerId, featureId, group),\n consume: async (input) => (await getReal()).balances.consume(input),\n resetTo: async (customerId, featureId, group, init) =>\n (await getReal()).balances.resetTo(customerId, featureId, group, init),\n },\n webhookEvents: {\n claim: async (dedupeKey, meta) => (await getReal()).webhookEvents.claim(dedupeKey, meta),\n markApplied: async (dedupeKey) => (await getReal()).webhookEvents.markApplied(dedupeKey),\n },\n migrations: {\n status: async () => (await getReal()).migrations.status(),\n apply: async () => (await getReal()).migrations.apply(),\n },\n transaction: async (fn) => (await getReal()).transaction(fn),\n };\n}\n\n/**\n * Create a MongoDB-backed {@link DatabaseAdapter}. See the module header for\n * the accepted input shapes and the eager-validate/lazy-connect contract.\n *\n * @throws {PayweaveConfigError} synchronously for an unrecognized input shape\n * or connection-string scheme; asynchronously (on first query) if the\n * `mongodb` package is not installed.\n */\nexport function mongodbAdapter(input: MongodbAdapterInput): DatabaseAdapter {\n const target = resolveMongoInput(input);\n let connectPromise: Promise<ConnectedMongo> | undefined;\n const getConnection = (): Promise<ConnectedMongo> => {\n connectPromise ??= connect(target);\n return connectPromise;\n };\n return buildLazyAdapter(getConnection);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { mysqlAdapter } from '../../_tsup-dts-rollup.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { PayweaveConfigError } from '../../chunk-HTRGMZFH.js';
|
|
2
|
+
|
|
3
|
+
// src/db/mysql/index.ts
|
|
4
|
+
var mysqlAdapter = () => {
|
|
5
|
+
throw new PayweaveConfigError(
|
|
6
|
+
'payweave/db/mysql is a placeholder subpath (PW-505) \u2014 the MySQL adapter ("mysql2") lands with PW-705. Until it ships, pass your own implementation of the DatabaseAdapter contract from "payweave/db" (docs/v1/database.md \xA73) as `database`, or track EPIC 7 in docs/v1/backlog.md.'
|
|
7
|
+
);
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export { mysqlAdapter };
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/db/mysql/index.ts"],"names":[],"mappings":";;;AAkBO,IAAM,eAA6D,MAAM;AAC9E,EAAA,MAAM,IAAI,mBAAA;AAAA,IACR;AAAA,GAIF;AACF","file":"index.js","sourcesContent":["/**\n * `payweave/db/mysql` — MySQL adapter (docs/v1/database.md; ships with PW-705).\n *\n * PW-505 wires this subpath into the exports map ahead of the implementation so\n * the import path is stable. Placeholder only: no driver code is imported here\n * — `mysql2` becomes an optional peerDependency in PW-705, not now\n * (database.md §7 dependency policy).\n */\nimport { PayweaveConfigError } from \"../../core/errors\";\nimport type { DatabaseAdapter } from \"../index\";\n\n/**\n * Placeholder for the `mysql2`-backed adapter factory. The real factory\n * accepts a `mysql2/promise` pool or `{ uri }` and returns a\n * {@link DatabaseAdapter}.\n *\n * @throws {PayweaveConfigError} always — the mysql adapter lands with PW-705.\n */\nexport const mysqlAdapter: (poolOrOptions?: unknown) => DatabaseAdapter = () => {\n throw new PayweaveConfigError(\n 'payweave/db/mysql is a placeholder subpath (PW-505) — the MySQL adapter (\"mysql2\") ' +\n 'lands with PW-705. Until it ships, pass your own implementation of the DatabaseAdapter ' +\n 'contract from \"payweave/db\" (docs/v1/database.md §3) as `database`, or track EPIC 7 in ' +\n \"docs/v1/backlog.md.\",\n );\n};\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { postgresAdapter } from '../../_tsup-dts-rollup.js';
|
|
2
|
+
export { PgPoolClientLike } from '../../_tsup-dts-rollup.js';
|
|
3
|
+
export { PgPoolLike } from '../../_tsup-dts-rollup.js';
|
|
4
|
+
export { PgQueryResultLike } from '../../_tsup-dts-rollup.js';
|
|
5
|
+
export { PostgresAdapterInput } from '../../_tsup-dts-rollup.js';
|