@prisma-idb/client-idb 0.9.1 → 0.10.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/README.md +2 -0
- package/dist/client-auto.d.mts +3 -19
- package/dist/client-auto.d.mts.map +1 -1
- package/dist/client-auto.mjs +2 -2
- package/dist/client.d.mts +1 -1
- package/dist/client.mjs +1 -1
- package/dist/{idb-orm-MOH1S3ES.d.mts → executor-CevtdBfz.d.mts} +3 -396
- package/dist/executor-CevtdBfz.d.mts.map +1 -0
- package/dist/idb-orm-DsfllvzD.mjs +1256 -0
- package/dist/idb-orm-DsfllvzD.mjs.map +1 -0
- package/dist/idb-orm-gEKHfG4H.d.mts +399 -0
- package/dist/idb-orm-gEKHfG4H.d.mts.map +1 -0
- package/dist/internal.d.mts +39 -0
- package/dist/internal.d.mts.map +1 -0
- package/dist/internal.mjs +2 -0
- package/dist/{managed-client-CJD9lBx5.d.mts → managed-client-B_xGXdjz.d.mts} +3 -2
- package/dist/managed-client-B_xGXdjz.d.mts.map +1 -0
- package/dist/{managed-client-CA1_fthM.mjs → managed-client-Cp01irrm.mjs} +3 -2
- package/dist/{managed-client-CA1_fthM.mjs.map → managed-client-Cp01irrm.mjs.map} +1 -1
- package/dist/{idb-orm-kDKFzR3S.mjs → mutation-executor-CD5n_kKT.mjs} +4 -1247
- package/dist/mutation-executor-CD5n_kKT.mjs.map +1 -0
- package/dist/mutation-scope-pOn0QzvV.d.mts +33 -0
- package/dist/mutation-scope-pOn0QzvV.d.mts.map +1 -0
- package/dist/orm.d.mts +4 -75
- package/dist/orm.d.mts.map +1 -1
- package/dist/orm.mjs +3 -2
- package/dist/orm.mjs.map +1 -1
- package/package.json +7 -6
- package/dist/idb-orm-MOH1S3ES.d.mts.map +0 -1
- package/dist/idb-orm-kDKFzR3S.mjs.map +0 -1
- package/dist/managed-client-CJD9lBx5.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idb-orm-DsfllvzD.mjs","names":["#contract","#modelName","#executor","#storeName","#state","#newGroupingKey","#includeRefinementMode","#clone","#resolveIncludeEntry","#buildScanPlan","#executeOrRows","#applyIncludes","#projectRows","#combinedFilterExpr","#executeNativeCount","#materialize","#planMeta","#countTerminal"],"sources":["../src/core/model-accessor.ts","../src/core/store-state.ts","../src/core/query-shaping.ts","../src/core/aggregate-builder.ts","../src/core/grouped-accessor.ts","../src/core/relation-loader.ts","../src/core/store-accessor.ts","../src/core/idb-orm.ts"],"sourcesContent":["/**\n * Proxy-based typed accessor handed to `where(fn)` callbacks.\n *\n * Mirrors `createModelAccessor()` from\n * Prisma ORM's SQL client, but without\n * the codec-trait gating — IDB stores native JS values, so every operator\n * is available on every field. The runtime accessor object is a Proxy\n * that materialises an `IdbFieldAccessor` on demand for whichever field\n * name is read; the type-level surface narrows that to the model's\n * actual field set so callbacks get autocomplete.\n */\n\nimport {\n type IdbFieldFilter,\n type IdbNullCheckExpr,\n fieldFilter,\n nullCheckExpr,\n} from \"@prisma-idb/adapter-idb/runtime\";\nimport type { DefaultModelRow, IdbContract } from \"./types\";\n\n// ── Typed surface ─────────────────────────────────────────────────────────────\n\n/**\n * Operator surface available on every field. All return frozen AST nodes\n * — they are values, not statements, so chaining and logical combinators\n * compose naturally.\n */\nexport interface IdbFieldAccessor<T> {\n eq(value: T): IdbFieldFilter;\n neq(value: T): IdbFieldFilter;\n gt(value: T): IdbFieldFilter;\n lt(value: T): IdbFieldFilter;\n gte(value: T): IdbFieldFilter;\n lte(value: T): IdbFieldFilter;\n in(values: ReadonlyArray<T>): IdbFieldFilter;\n notIn(values: ReadonlyArray<T>): IdbFieldFilter;\n contains(sub: string): IdbFieldFilter;\n startsWith(sub: string): IdbFieldFilter;\n endsWith(sub: string): IdbFieldFilter;\n isNull(): IdbNullCheckExpr;\n isNotNull(): IdbNullCheckExpr;\n}\n\n/**\n * The accessor object handed to a `where(fn)` callback. Each key resolves\n * to an {@link IdbFieldAccessor} typed against the field's output type.\n *\n * The Proxy makes every string key resolve to an accessor at runtime; the\n * type narrows the visible surface to the model's declared fields so the\n * developer gets autocomplete.\n */\nexport type IdbModelAccessor<TContract, ModelName extends string> = {\n readonly [K in keyof DefaultModelRow<TContract, ModelName>]-?: IdbFieldAccessor<\n DefaultModelRow<TContract, ModelName>[K]\n >;\n};\n\n// ── Runtime construction ──────────────────────────────────────────────────────\n\n/**\n * Build an {@link IdbFieldAccessor} for a single field. The accessor is\n * shared via the proxy below, but each accessor instance is bound to its\n * own field name so the produced AST nodes carry the right field.\n */\nfunction createFieldAccessor(field: string): IdbFieldAccessor<unknown> {\n return {\n eq: (value) => fieldFilter(field, \"eq\", value),\n neq: (value) => fieldFilter(field, \"neq\", value),\n gt: (value) => fieldFilter(field, \"gt\", value),\n lt: (value) => fieldFilter(field, \"lt\", value),\n gte: (value) => fieldFilter(field, \"gte\", value),\n lte: (value) => fieldFilter(field, \"lte\", value),\n in: (values) => fieldFilter(field, \"in\", values),\n notIn: (values) => fieldFilter(field, \"notIn\", values),\n contains: (sub) => fieldFilter(field, \"contains\", sub),\n startsWith: (sub) => fieldFilter(field, \"startsWith\", sub),\n endsWith: (sub) => fieldFilter(field, \"endsWith\", sub),\n isNull: () => nullCheckExpr(field, true),\n isNotNull: () => nullCheckExpr(field, false),\n };\n}\n\n/**\n * Create the typed model accessor used by `where(fn)` callbacks.\n *\n * Implemented as a Proxy keyed on field names — every read returns an\n * {@link IdbFieldAccessor} bound to that field. The accessor cache means\n * `m.name.eq(...)` and `m.name.startsWith(...)` reuse the same per-field\n * accessor object across the same `where()` invocation.\n *\n * The type parameter is structural — no contract is consulted at\n * runtime, because TS already gates the visible field set at compile\n * time. (Misspelled fields surface as accessor calls on names that\n * don't exist in stored rows, which is consistent with how the\n * shorthand form behaves today.)\n */\nexport function createModelAccessor<TContract extends IdbContract, ModelName extends string>(): IdbModelAccessor<\n TContract,\n ModelName\n> {\n const cache = new Map<string, IdbFieldAccessor<unknown>>();\n return new Proxy(\n {},\n {\n get(_target, prop: string | symbol) {\n if (typeof prop !== \"string\") return undefined;\n let acc = cache.get(prop);\n if (acc === undefined) {\n acc = createFieldAccessor(prop);\n cache.set(prop, acc);\n }\n return acc;\n },\n }\n ) as IdbModelAccessor<TContract, ModelName>;\n}\n","import type { IdbFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\n\n/**\n * One entry in {@link IdbAccessorState.includes} — describes how a single\n * `.include()`d relation should be materialised.\n *\n * - `collection`: load the related rows, applying the refined `state`\n * (its `filters` / `orderBy` / `skip` / `take`) to the child scan.\n * `state` is `emptyAccessorState()` for an unrefined `.include(rel)`.\n * - `scalar`: reduce the related rows to a single number (Phase 6.5 supports\n * `count`). The `state.filters` still constrain which children are counted.\n *\n * Mirrors the `IncludeExpr` / `IncludeScalar` split from\n * Prisma ORM's SQL client, collapsed to the two shapes IDB\n * needs (no SQL column mapping, no `combine()` branches).\n */\nexport type IncludeEntry =\n | { readonly kind: \"collection\"; readonly state: IdbAccessorState }\n | { readonly kind: \"scalar\"; readonly fn: \"count\"; readonly state: IdbAccessorState };\n\n/**\n * Marker returned by the child accessor's `.count()` terminal when it is\n * called inside an `include()` refinement callback. Carries the refined\n * child `state` so the relation loader counts only the matching children.\n *\n * Detected by {@link isIncludeScalar}; mirrors `IncludeScalar` from the\n * vendor `sql-orm-client/include-descriptors.ts`.\n */\nexport interface IdbIncludeScalar {\n readonly kind: \"includeScalar\";\n readonly fn: \"count\";\n readonly state: IdbAccessorState;\n}\n\n/** Build an {@link IdbIncludeScalar} marker for a `count()` reducer. */\nexport function createIncludeScalar(state: IdbAccessorState): IdbIncludeScalar {\n return { kind: \"includeScalar\", fn: \"count\", state };\n}\n\n/** Type guard: is `value` an {@link IdbIncludeScalar} marker? */\nexport function isIncludeScalar(value: unknown): value is IdbIncludeScalar {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { kind?: unknown; fn?: unknown };\n return candidate.kind === \"includeScalar\" && candidate.fn === \"count\";\n}\n\n/**\n * Immutable state carried by each {@link IdbStoreAccessorImpl} node in the\n * builder chain.\n *\n * Every mutating method (`.where()`, `.take()`, etc.) returns a cloned\n * instance with an updated state rather than mutating in place, making the\n * accessor safe to reuse across multiple query branches.\n */\nexport interface IdbAccessorState {\n /**\n * Accumulated filter expressions. Multiple `.where()` calls compose\n * with AND semantics — the planner wraps them in an `andExpr` when\n * lowering. Each entry is already either an `IdbFieldFilter`, a\n * combinator, or a `null-check` node — never raw shorthand records.\n */\n readonly filters: ReadonlyArray<IdbFilterExpr>;\n /** Sort spec: field → direction. Applied as an in-memory comparator. */\n readonly orderBy?: Record<string, \"asc\" | \"desc\">;\n /** OFFSET (number of rows to skip). */\n readonly skip?: number;\n /** LIMIT (maximum number of rows to return). */\n readonly take?: number;\n /**\n * Relations that have been `.include()`d — keys are relation names, values\n * describe how to materialise each (collection vs scalar count, plus any\n * refinement state). See {@link IncludeEntry}.\n */\n readonly includes: Record<string, IncludeEntry>;\n /**\n * Fields kept by `.select()`. `undefined` means \"all fields\". When set,\n * the materialised rows are projected down to these fields (plus any\n * included relation keys) after the scan and relation loads complete.\n */\n readonly selectedFields?: ReadonlyArray<string>;\n}\n\n/** Create a fresh, empty accessor state (no filters, no ordering, no includes). */\nexport function emptyAccessorState(): IdbAccessorState {\n return {\n filters: [],\n includes: {},\n };\n}\n\n/** Return a shallow-merged copy of `state` with the given overrides applied. */\nexport function mergeAccessorState(state: IdbAccessorState, overrides: Partial<IdbAccessorState>): IdbAccessorState {\n return { ...state, ...overrides };\n}\n","import type { IdbFilterExpr, IdbOrExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport { andExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbCountPlan, IdbCursorScanPlan, IdbRowComparator } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbKeyPath } from \"@prisma-idb/target-idb/pack\";\nimport { compareFieldValues } from \"@prisma-idb/target-idb/runtime\";\nimport { isValidIdbKey } from \"./types\";\n\n/** Describes an extractable indexed equality that can narrow a cursor scan. */\nexport interface IndexEqualityHint {\n /**\n * The IDB index name (e.g. `\"byEmail\"`), or `undefined` when the condition\n * is on the store's own primary key — a store's keyPath is always\n * point-range-queryable directly (`IDBObjectStore.openCursor(range)`),\n * without a named `IDBIndex`.\n */\n readonly indexName: string | undefined;\n /** The equality value to pass to `IDBKeyRange.only()`. */\n readonly value: unknown;\n /** The remainder of the filter after the indexed condition is peeled off. */\n readonly remainingFilter: IdbFilterExpr | undefined;\n}\n\n/**\n * Describes an OR filter where every branch can be satisfied by an indexed\n * equality lookup. Each branch maps to one `IDBKeyRange.only()` cursor scan;\n * the caller unions the results and deduplicates before applying\n * `remainingFilter`.\n */\nexport interface IndexOrHint {\n /** `indexName` is `undefined` for a branch on the store's own primary key — see {@link IndexEqualityHint}. */\n readonly branches: ReadonlyArray<{ readonly indexName: string | undefined; readonly value: unknown }>;\n /** AND conditions that wrapped the OR — applied in-memory after the union. */\n readonly remainingFilter: IdbFilterExpr | undefined;\n}\n\n/**\n * Combine accumulated filter expressions with AND.\n *\n * Returns `undefined` when no filter is present so callers can skip building a\n * row-filter closure. Shared by {@link IdbStoreAccessorImpl} (top-level scans)\n * and the relation loader (refined `include()` child scans).\n */\nexport function combineFilterExprs(filters: ReadonlyArray<IdbFilterExpr>): IdbFilterExpr | undefined {\n if (filters.length === 0) return undefined;\n if (filters.length === 1) return filters[0];\n return andExpr(filters);\n}\n\n/** Recursively flatten nested AND nodes into a single array of children. */\nfunction flattenAnd(filter: IdbFilterExpr): IdbFilterExpr[] {\n if (filter.kind !== \"and\") return [filter];\n return filter.exprs.flatMap(flattenAnd);\n}\n\n/**\n * `true` when `field` is a *single-field* primary key that a lone `eq`\n * condition can directly point-range-query (`store.get`/`openCursor(range)`\n * against the store's own keyPath, no named index required).\n *\n * Deliberately `false` for a compound (array) `keyPath`, even if `field`\n * happens to be one of its member fields — a single `eq` condition can only\n * pin one member, not the whole compound key, so it can't drive a PK\n * point-range scan on its own. Accelerating that case needs *all* member\n * fields ANDed together, which is a cost-based multi-field planner decision\n * (Phase 10 §3.2), not this peephole optimizer's job.\n */\nfunction isPrimaryKeyField(field: string, keyPath: IdbKeyPath): boolean {\n return typeof keyPath === \"string\" && field === keyPath;\n}\n\n/**\n * Scan the combined filter expression for the first `eq` field condition whose\n * field either has a matching IDB index (`fieldToIndexName[field]` is set) or\n * *is* the store's own primary key (`keyPath`) — a store's keyPath is always\n * point-range-queryable directly, no named index required.\n *\n * When found, the indexed condition is peeled off and returned as an\n * {@link IndexEqualityHint}; any remaining conditions are preserved in\n * `remainingFilter`. Returns `null` when no usable index can be found.\n *\n * Nested AND nodes are flattened before scanning, so deeply-composed filters\n * are handled correctly. Only `eq` conditions are considered — range operators\n * (`gt`, `lt`, etc.) could also use an index range but that optimization is\n * not yet implemented.\n */\nexport function extractIndexEqualityHint(\n filter: IdbFilterExpr | undefined,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath\n): IndexEqualityHint | null {\n if (filter === undefined) return null;\n\n if (filter.kind === \"field\" && filter.op === \"eq\") {\n const indexName = fieldToIndexName[filter.field];\n if ((indexName !== undefined || isPrimaryKeyField(filter.field, keyPath)) && isValidIdbKey(filter.value)) {\n return { indexName, value: filter.value, remainingFilter: undefined };\n }\n return null;\n }\n\n if (filter.kind === \"and\") {\n const flat = flattenAnd(filter);\n for (let i = 0; i < flat.length; i++) {\n const expr = flat[i]!;\n if (expr.kind === \"field\" && expr.op === \"eq\") {\n const indexName = fieldToIndexName[expr.field];\n if ((indexName !== undefined || isPrimaryKeyField(expr.field, keyPath)) && isValidIdbKey(expr.value)) {\n const rest = flat.filter((_, j) => j !== i);\n return { indexName, value: expr.value, remainingFilter: combineFilterExprs(rest) };\n }\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check whether every branch of an OR node is a single `field eq value`\n * condition whose field has a matching index. Returns an {@link IndexOrHint}\n * when the whole OR can be satisfied by N point-range cursor scans, `null`\n * otherwise.\n */\nfunction tryExtractOrBranches(\n orNode: IdbOrExpr,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath,\n remainingFilter: IdbFilterExpr | undefined\n): IndexOrHint | null {\n if (orNode.exprs.length === 0) return null;\n const branches: { indexName: string | undefined; value: unknown }[] = [];\n for (const expr of orNode.exprs) {\n if (expr.kind !== \"field\" || expr.op !== \"eq\") return null;\n const indexName = fieldToIndexName[expr.field];\n if ((indexName === undefined && !isPrimaryKeyField(expr.field, keyPath)) || !isValidIdbKey(expr.value)) return null;\n branches.push({ indexName, value: expr.value });\n }\n return { branches, remainingFilter };\n}\n\n/**\n * Attempt to extract an {@link IndexOrHint} from `filter`.\n *\n * Handles two shapes:\n * - Top-level `or` where every branch is `field eq value` on an indexed field.\n * - Top-level `and` (with nested ANDs flattened) that contains exactly one `or`\n * child fitting the above pattern; the remaining AND children become\n * `remainingFilter` applied in-memory after the union.\n *\n * Returns `null` when the filter cannot be accelerated via OR index scans.\n */\nexport function extractIndexOrHint(\n filter: IdbFilterExpr | undefined,\n fieldToIndexName: Record<string, string>,\n keyPath: IdbKeyPath\n): IndexOrHint | null {\n if (filter === undefined) return null;\n\n if (filter.kind === \"or\") {\n return tryExtractOrBranches(filter, fieldToIndexName, keyPath, undefined);\n }\n\n if (filter.kind === \"and\") {\n const flat = flattenAnd(filter);\n const orIndices: number[] = [];\n for (let i = 0; i < flat.length; i++) {\n if (flat[i]!.kind === \"or\") orIndices.push(i);\n }\n if (orIndices.length !== 1) return null;\n const orIdx = orIndices[0]!;\n const orNode = flat[orIdx]! as IdbOrExpr;\n const rest = flat.filter((_, j) => j !== orIdx);\n return tryExtractOrBranches(orNode, fieldToIndexName, keyPath, combineFilterExprs(rest));\n }\n\n return null;\n}\n\n/**\n * Build an in-memory comparator from an `orderBy` spec (field → direction).\n *\n * Returns `undefined` when there is nothing to sort by. Compares fields in\n * declaration order, with {@link compareFieldValues}: the same order an\n * IndexedDB index uses, so equal `Date`s tie and fall through to the next\n * field, and `null`s sort last (first when descending).\n */\nexport function buildRowComparator(orderBy: Record<string, \"asc\" | \"desc\"> | undefined): IdbRowComparator | undefined {\n if (orderBy === undefined) return undefined;\n return (a: Record<string, unknown>, b: Record<string, unknown>): number => {\n for (const [field, dir] of Object.entries(orderBy)) {\n const cmp = compareFieldValues(a[field], b[field]);\n if (cmp === 0) continue;\n return dir === \"desc\" ? -cmp : cmp;\n }\n return 0;\n };\n}\n\n// ── Native count ──────────────────────────────────────────────────────────────\n\n/**\n * `true` when a `cursor-scan` plan's result *cardinality* is fully determined\n * by its store/index + key range — i.e. there is no in-memory `filter` that\n * would need each row's value. Only then can `count()` be answered natively\n * (`store.count(range)` / `index.count(range)`) without deserializing rows.\n *\n * `comparator` (ORDER BY), `direction`, `skip` and `take` don't change *which*\n * rows match, so they don't disqualify a plan — `skip`/`take` are applied to\n * the native total afterwards via {@link clampCount}.\n *\n * Safe for index scans because the equality hint that builds `range` never\n * selects a `multiEntry` (or compound) index — `buildFieldToIndexMap` excludes\n * them — so one record maps to at most one index entry and entries == rows.\n */\nexport function isNativelyCountable(plan: IdbCursorScanPlan): boolean {\n return plan.filter === undefined;\n}\n\n/** Rewrites a natively-countable `cursor-scan` as the equivalent native `count` plan. */\nexport function toCountPlan(plan: IdbCursorScanPlan): IdbCountPlan {\n return {\n meta: plan.meta,\n kind: \"count\",\n storeName: plan.storeName,\n ...(plan.indexName !== undefined ? { indexName: plan.indexName } : {}),\n ...(plan.range !== undefined ? { range: plan.range } : {}),\n };\n}\n\n/**\n * Applies `skip`/`take` to an *unpaginated* total. A paginated count is pure\n * arithmetic on the unpaginated count — `max(0, total - skip)`, capped at\n * `take` — so this is exact, not an approximation.\n */\nexport function clampCount(total: number, skip: number | undefined, take: number | undefined): number {\n let n = total;\n if (skip !== undefined) n = Math.max(0, n - skip);\n if (take !== undefined) n = Math.min(take, n);\n return n;\n}\n","import type { AggregateFn, IdbAggregateBuilder, IdbAggregateSelector } from \"./types\";\n\n/**\n * Build the aggregate selector factory handed to `.aggregate(agg => …)` and\n * `groupBy(...).aggregate(agg => …)`.\n *\n * Each method returns an {@link IdbAggregateSelector} marker; the actual\n * reduction happens in {@link reduceAggregate} once the matching rows are\n * materialised in memory. Mirrors `createAggregateBuilder` from the vendor\n * `sql-orm-client/aggregate-builder.ts`, minus the field→column mapping (IDB\n * stores native field names).\n */\nexport function createAggregateBuilder<TContract, ModelName extends string>(): IdbAggregateBuilder<\n TContract,\n ModelName\n> {\n return {\n count: () => ({ kind: \"aggregate\", fn: \"count\" }),\n sum: (field) => ({ kind: \"aggregate\", fn: \"sum\", field: field as string }),\n avg: (field) => ({ kind: \"aggregate\", fn: \"avg\", field: field as string }),\n min: (field) => ({ kind: \"aggregate\", fn: \"min\", field: field as string }),\n max: (field) => ({ kind: \"aggregate\", fn: \"max\", field: field as string }),\n };\n}\n\n/** Type guard: is `value` an {@link IdbAggregateSelector}? */\nfunction isAggregateSelector(value: unknown): value is IdbAggregateSelector<unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as { kind?: unknown; fn?: unknown };\n return (\n candidate.kind === \"aggregate\" &&\n (candidate.fn === \"count\" ||\n candidate.fn === \"sum\" ||\n candidate.fn === \"avg\" ||\n candidate.fn === \"min\" ||\n candidate.fn === \"max\")\n );\n}\n\n/**\n * Reduce a set of materialised rows to a single aggregate value.\n *\n * - `count` → the number of rows (always a number, never null).\n * - `sum`/`avg`/`min`/`max` → computed over the non-null numeric values of\n * `field`; `null` when no row has a non-null value (matching Prisma's\n * \"aggregate of an empty set is null\" and the vendor `coerceAggregateValue`\n * null handling). String-encoded numbers are coerced via `Number()`.\n */\nfunction reduceAggregate(\n fn: AggregateFn,\n field: string | undefined,\n rows: readonly Record<string, unknown>[]\n): number | null {\n if (fn === \"count\") return rows.length;\n if (field === undefined) return null;\n\n const values: number[] = [];\n for (const row of rows) {\n const raw = row[field];\n if (raw === null || raw === undefined) continue;\n const n = typeof raw === \"bigint\" ? Number(raw) : Number(raw as number);\n if (!Number.isNaN(n)) values.push(n);\n }\n\n if (values.length === 0) return null;\n\n switch (fn) {\n case \"sum\":\n return values.reduce((acc, n) => acc + n, 0);\n case \"avg\":\n return values.reduce((acc, n) => acc + n, 0) / values.length;\n case \"min\":\n return Math.min(...values);\n case \"max\":\n return Math.max(...values);\n }\n}\n\n/**\n * Run every selector in an aggregate spec against `rows`, producing the\n * result object keyed by the spec's aliases.\n */\nexport function computeAggregateSpec(\n spec: Record<string, IdbAggregateSelector<unknown>>,\n rows: readonly Record<string, unknown>[]\n): Record<string, number | null> {\n const result: Record<string, number | null> = {};\n for (const [alias, selector] of Object.entries(spec)) {\n result[alias] = reduceAggregate(selector.fn, selector.field, rows);\n }\n return result;\n}\n\n/**\n * Project an aggregate spec down to the plain `{ fn, field? }` shape carried by\n * the query AST (`IdbAggregateAst.aggregates` / `IdbGroupByAst.aggregates`), so\n * middleware can observe the requested aggregations.\n */\nexport function toAggregateRequests(\n spec: Record<string, IdbAggregateSelector<unknown>>\n): Record<string, { readonly fn: string; readonly field?: string }> {\n const out: Record<string, { fn: string; field?: string }> = {};\n for (const [alias, selector] of Object.entries(spec)) {\n out[alias] = selector.field !== undefined ? { fn: selector.fn, field: selector.field } : { fn: selector.fn };\n }\n return out;\n}\n\n/**\n * Validate a user-supplied aggregate spec: it must be non-empty and every\n * value must be a real selector. Throws a descriptive error otherwise, so a\n * typo (e.g. returning a plain object) fails loudly rather than silently\n * producing `NaN`/`undefined` results.\n */\nexport function assertValidAggregateSpec(\n spec: Record<string, unknown>,\n context: \"aggregate()\" | \"groupBy().aggregate()\"\n): void {\n const entries = Object.entries(spec);\n if (entries.length === 0) {\n throw new Error(`${context} requires at least one aggregation selector`);\n }\n for (const [alias, selector] of entries) {\n if (!isAggregateSelector(selector)) {\n throw new Error(`${context} selector \"${alias}\" is invalid`);\n }\n }\n}\n","import type { IdbFilterExpr, IdbGroupByAst, IdbQueryAst } from \"@prisma-idb/adapter-idb/runtime\";\nimport {\n assertValidAggregateSpec,\n computeAggregateSpec,\n createAggregateBuilder,\n toAggregateRequests,\n} from \"./aggregate-builder\";\nimport { fieldValueToken } from \"./types\";\nimport type { DefaultModelRow, IdbAggregateBuilder, IdbAggregateResult, IdbAggregateSpec } from \"./types\";\n\n/**\n * One grouped-aggregate result row: the group-key fields picked from the model\n * row, intersected with the aggregate aliases.\n */\nexport type GroupedResultRow<\n TContract,\n ModelName extends string,\n Fields extends readonly string[],\n Spec extends IdbAggregateSpec,\n> = Pick<DefaultModelRow<TContract, ModelName>, Fields[number] & keyof DefaultModelRow<TContract, ModelName>> &\n IdbAggregateResult<Spec>;\n\n/**\n * Grouped-aggregate builder returned by `accessor.groupBy(...)`.\n *\n * Port of the vendor `GroupedCollection` (`sql-orm-client/grouped-collection.ts`),\n * but purely in-memory: there is no SQL compilation, so `aggregate()`\n * materialises the matching rows, partitions them by the group-key fields, and\n * reduces each partition with the requested selectors.\n */\nexport interface IdbGroupedAccessor<TContract, ModelName extends string, Fields extends readonly string[]> {\n /**\n * Reduce each group to one row of `{ ...groupKeyFields, ...aggregates }`.\n *\n * @example\n * ```ts\n * const byUser = await db.posts\n * .where({ published: true })\n * .groupBy(\"authorId\")\n * .aggregate((agg) => ({ count: agg.count(), totalViews: agg.sum(\"views\") }));\n * // [{ authorId: \"u1\", count: 3, totalViews: 120 }, ...]\n * ```\n */\n aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<Array<GroupedResultRow<TContract, ModelName, Fields, Spec>>>;\n}\n\n/** Runtime wiring handed to {@link createGroupedAccessor} by the store accessor. */\ninterface GroupedAccessorInit {\n readonly modelName: string;\n /** Group-key fields, in declaration order. */\n readonly by: readonly string[];\n /** Combined `where` expression carried over from the source accessor, if any. */\n readonly where: IdbFilterExpr | undefined;\n /**\n * Materialise all rows matching the source filters. The store accessor owns\n * plan-building; the grouped accessor only supplies the AST it wants attached\n * (for middleware visibility) and does the in-memory grouping.\n */\n readonly materialize: (ast: IdbQueryAst) => Promise<Record<string, unknown>[]>;\n}\n\n/**\n * Build a composite group key from type-tagged field tokens. Equal Date, binary,\n * array and JSON object values share a group; null and undefined also share a group.\n */\nfunction groupKeyOf(by: readonly string[], row: Record<string, unknown>): string {\n return JSON.stringify(by.map((field) => groupToken(row[field])));\n}\n\n/** Keep `1n`, `1` and `\"1\"` apart while preserving structural grouping for JSON objects. */\nfunction groupToken(value: unknown): readonly [string, unknown] {\n // Invalid Dates serialize as null, so give them a separate token.\n if (value instanceof Date && Number.isNaN(value.getTime())) return [\"date\", \"invalid\"];\n const token = fieldValueToken(value ?? null);\n return [typeof token, typeof token === \"object\" ? token : String(token)];\n}\n\n/** Build a grouped accessor that reduces materialized rows from the source accessor. */\nexport function createGroupedAccessor<TContract, ModelName extends string, Fields extends readonly string[]>(\n init: GroupedAccessorInit\n): IdbGroupedAccessor<TContract, ModelName, Fields> {\n return {\n async aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<Array<GroupedResultRow<TContract, ModelName, Fields, Spec>>> {\n const spec = fn(createAggregateBuilder<TContract, ModelName>());\n assertValidAggregateSpec(spec, \"groupBy().aggregate()\");\n\n const ast: IdbGroupByAst = {\n kind: \"groupBy\",\n modelName: init.modelName,\n by: init.by,\n aggregates: toAggregateRequests(spec),\n ...(init.where !== undefined ? { where: init.where } : {}),\n };\n\n const rows = await init.materialize(ast);\n\n // Partition rows by their composite group key, preserving first-seen order.\n const groups = new Map<string, { key: Record<string, unknown>; rows: Record<string, unknown>[] }>();\n for (const row of rows) {\n const gk = groupKeyOf(init.by, row);\n let group = groups.get(gk);\n if (group === undefined) {\n const key: Record<string, unknown> = {};\n for (const field of init.by) key[field] = row[field];\n group = { key, rows: [] };\n groups.set(gk, group);\n }\n group.rows.push(row);\n }\n\n return Array.from(groups.values()).map(\n (group) =>\n ({ ...group.key, ...computeAggregateSpec(spec, group.rows) }) as GroupedResultRow<\n TContract,\n ModelName,\n Fields,\n Spec\n >\n );\n },\n };\n}\n","import type { ContractReferenceRelation } from \"@prisma/orm-framework/contract/types\";\nimport { domainModelsAtDefaultNamespace } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbQueryPlan } from \"@prisma-idb/adapter-idb/runtime\";\nimport { evaluateFilter } from \"@prisma-idb/adapter-idb/runtime\";\nimport type { IdbRowFilter } from \"@prisma-idb/driver-idb/runtime\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { buildRowComparator, combineFilterExprs } from \"./query-shaping\";\nimport type { IncludeEntry } from \"./store-state\";\nimport { keyPathFields, type IdbKeyPath } from \"@prisma-idb/target-idb/pack\";\nimport { fieldValueToken, getKeyPath, getStoreName, isValidIdbKey } from \"./types\";\nimport type { IdbContract } from \"./types\";\n\n/**\n * Batch-load a single named relation for all rows in `rows` and attach the\n * result to each row under the `relName` key.\n *\n * The join matches every field of the relation, so compound foreign keys join\n * on the whole tuple. It uses one key-range scan per distinct tuple when an\n * index or the related primary key covers the target fields, and otherwise\n * one full scan with an in-memory filter. Rows are then grouped in memory,\n * which avoids N+1 queries.\n *\n * The `entry` carries any `include()` refinement:\n *\n * - `collection` — the refined `where` further filters the child scan;\n * `orderBy` / `skip` / `take` are applied **per parent group** for `1:N`\n * relations (each parent's children are independently sorted and paginated).\n * - `scalar` — the relation field becomes the `count` of matching children\n * (to-many only; `include()` rejects scalar refinements on to-one relations).\n *\n * @param relName - The relation key to load (e.g. `\"posts\"`, `\"author\"`).\n * @param entry - How to materialise the relation (collection vs scalar + refinement state).\n * @param rows - The parent rows to attach related data to.\n * @param contract - The resolved IDB contract.\n * @param modelName - The source model name (owner of the relation).\n * @param executor - The query executor used to run the related-store scan.\n */\nexport async function loadRelation(\n relName: string,\n entry: IncludeEntry,\n rows: Record<string, unknown>[],\n contract: IdbContract,\n modelName: string,\n executor: IdbQueryExecutor,\n groupingKey: string\n): Promise<Record<string, unknown>[]> {\n if (rows.length === 0) return rows;\n\n const models = domainModelsAtDefaultNamespace(contract.domain);\n const model = models[modelName];\n if (model === undefined) return rows;\n\n const rawRelation = model.relations[relName];\n if (rawRelation === undefined) return rows;\n\n // Only handle reference relations (cross-store joins). Embed relations don't\n // have an `on` block and are stored inline — nothing to load.\n if (!(\"on\" in rawRelation)) return rows;\n\n const relation = rawRelation as ContractReferenceRelation;\n const { cardinality, on } = relation;\n // `relation.to` is a CrossReference `{ namespace, model }`.\n const relatedModelName = relation.to.model;\n\n const localFields = on.localFields;\n const targetFields = on.targetFields;\n if (localFields.length === 0 || localFields.length !== targetFields.length) return rows;\n\n const relatedModel = models[relatedModelName];\n if (relatedModel === undefined) return rows;\n\n // Resolve the related object store name from the model's storage metadata.\n const relatedStoreName = getStoreName(contract, relatedModelName);\n\n const isScalar = entry.kind === \"scalar\";\n\n // Collect the distinct local tuples to drive the related-store lookup. A\n // tuple is keyed by `tupleToken`, so equal Date/binary values collapse and\n // match the related rows' freshly-deserialized values below. A row with a\n // null in any local field has no related rows.\n const localTuples = new Map<string, unknown[]>();\n for (const row of rows) {\n const token = tupleToken(row, localFields);\n if (token !== null)\n localTuples.set(\n token,\n localFields.map((f) => row[f])\n );\n }\n\n // Short-circuit: if every local tuple has a null, attach empties.\n // (Scalar counts are 0; to-many is [], to-one is null.)\n if (localTuples.size === 0) {\n return rows.map((row) => ({\n ...row,\n [relName]: isScalar ? 0 : cardinality === \"1:N\" ? [] : null,\n }));\n }\n\n const refinedWhere = combineFilterExprs(entry.state.filters);\n\n const storageHash = contract.storage.storageHash;\n const planMeta = { target: \"idb\", storageHash, lane: \"idb-orm\", annotations: { groupingKey } } as const;\n\n // When an index or the related store's own primary key covers exactly the\n // target fields, run one IDBKeyRange.only() point-range scan per distinct\n // tuple. Each scan visits only matching records, so only the refined\n // `where` is applied as a row filter. Otherwise, scan the whole store.\n const rangeSource = findRangeSource(contract, relatedStoreName, relatedModelName, targetFields);\n\n let relatedRows: Record<string, unknown>[];\n if (rangeSource !== undefined) {\n const refinedFilter: IdbRowFilter | undefined =\n refinedWhere !== undefined ? (row: Record<string, unknown>) => evaluateFilter(refinedWhere, row) : undefined;\n\n // IDBKeyRange.only() throws DataError for invalid keys (boolean, NaN,\n // plain objects, etc.). Such values cannot be stored as IndexedDB keys,\n // so no related rows can match — skip them before building plans.\n const ranges: IDBKeyRange[] = [];\n for (const values of localTuples.values()) {\n const ordered = keyPathFields(rangeSource.keyPath).map((f) => values[targetFields.indexOf(f)]);\n if (!ordered.every((v) => isValidIdbKey(v))) continue;\n ranges.push(\n IDBKeyRange.only(\n typeof rangeSource.keyPath === \"string\" ? (ordered[0] as IDBValidKey) : (ordered as IDBValidKey[])\n )\n );\n }\n\n // One scan per distinct tuple — independent, so run concurrently.\n const rangeResults = await Promise.all(\n ranges.map(async (range) => {\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta: planMeta,\n idbPlan: {\n meta: planMeta,\n kind: \"cursor-scan\",\n storeName: relatedStoreName,\n ...(rangeSource.indexName !== undefined ? { indexName: rangeSource.indexName } : {}),\n range,\n ...(refinedFilter !== undefined ? { filter: refinedFilter } : {}),\n },\n };\n const rows: Record<string, unknown>[] = [];\n for await (const row of executor.query(plan)) {\n rows.push(row);\n }\n return rows;\n })\n );\n relatedRows = rangeResults.flat();\n } else {\n relatedRows = [];\n // Full store scan with an in-memory FK membership + refined-where filter.\n const filter: IdbRowFilter = (row: Record<string, unknown>): boolean => {\n const token = tupleToken(row, targetFields);\n return (\n token !== null && localTuples.has(token) && (refinedWhere === undefined || evaluateFilter(refinedWhere, row))\n );\n };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta: planMeta,\n idbPlan: { meta: planMeta, kind: \"cursor-scan\", storeName: relatedStoreName, filter },\n };\n for await (const row of executor.query(plan)) {\n relatedRows.push(row);\n }\n }\n\n return attachRelatedRows(relName, entry, rows, relatedRows, relation);\n}\n\n/** Attach related rows by their join tuple, shaping each parent's collection independently. */\nfunction attachRelatedRows(\n relName: string,\n entry: IncludeEntry,\n rows: Record<string, unknown>[],\n relatedRows: Record<string, unknown>[],\n relation: ContractReferenceRelation\n): Record<string, unknown>[] {\n const {\n cardinality,\n on: { localFields, targetFields },\n } = relation;\n if (cardinality === \"1:N\") {\n // Group related rows by their target tuple.\n const grouped = new Map<string, Record<string, unknown>[]>();\n for (const rrow of relatedRows) {\n const gk = tupleToken(rrow, targetFields);\n if (gk === null) continue;\n const group = grouped.get(gk) ?? [];\n group.push(rrow);\n grouped.set(gk, group);\n }\n const groupFor = (row: Record<string, unknown>): Record<string, unknown>[] => {\n const token = tupleToken(row, localFields);\n return token === null ? [] : (grouped.get(token) ?? []);\n };\n\n if (entry.kind === \"scalar\") {\n // Counts include all filtered children, without collection pagination.\n return rows.map((row) => ({\n ...row,\n [relName]: groupFor(row).length,\n }));\n }\n\n // Collection: apply refined orderBy / skip / take per parent group.\n const comparator = buildRowComparator(entry.state.orderBy);\n const skip = entry.state.skip ?? 0;\n const take = entry.state.take;\n return rows.map((row) => {\n let group = groupFor(row);\n if (comparator !== undefined) group = [...group].sort(comparator);\n if (skip > 0 || take !== undefined) {\n group = group.slice(skip, take !== undefined ? skip + take : undefined);\n }\n return { ...row, [relName]: group };\n });\n }\n\n // N:1 / 1:1: index related rows by their target tuple, attach singles.\n // A refined `where` that excludes the related row yields `null` here.\n const indexed = new Map<string, Record<string, unknown>>();\n for (const rrow of relatedRows) {\n const token = tupleToken(rrow, targetFields);\n if (token !== null) indexed.set(token, rrow);\n }\n return rows.map((row) => {\n const token = tupleToken(row, localFields);\n return { ...row, [relName]: (token === null ? undefined : indexed.get(token)) ?? null };\n });\n}\n\n/**\n * A `Map` key for the values of `fields` in `row`, or `null` when any of them\n * is null or undefined. Equal `Date`s and binary values give equal tokens.\n */\nfunction tupleToken(row: Record<string, unknown>, fields: readonly string[]): string | null {\n const parts: unknown[] = [];\n for (const field of fields) {\n const value = row[field];\n if (value === null || value === undefined) return null;\n const token = fieldValueToken(value);\n parts.push([typeof token, String(token)]);\n }\n return JSON.stringify(parts);\n}\n\n/**\n * Finds an index, or else the store's primary key, whose key path has exactly\n * `fields` (in any order), so a lookup on those fields can use a key range.\n * Returns `undefined` when there is none, or when `IDBKeyRange` isn't available.\n */\nfunction findRangeSource(\n contract: IdbContract,\n storeName: string,\n modelName: string,\n fields: readonly string[]\n): { readonly indexName?: string; readonly keyPath: IdbKeyPath } | undefined {\n if (typeof IDBKeyRange === \"undefined\") return undefined;\n const coversFields = (keyPath: IdbKeyPath): boolean => {\n const keyFields = keyPathFields(keyPath);\n return keyFields.length === fields.length && keyFields.every((f) => fields.includes(f));\n };\n const indexes = contract.storage.stores[storeName]?.indexes ?? {};\n for (const [indexName, indexDef] of Object.entries(indexes)) {\n if (indexDef.multiEntry !== true && coversFields(indexDef.keyPath)) return { indexName, keyPath: indexDef.keyPath };\n }\n const primaryKey = getKeyPath(contract, modelName);\n return coversFields(primaryKey) ? { keyPath: primaryKey } : undefined;\n}\n","import { AsyncIterableResult } from \"@prisma/orm-framework/components/runtime\";\nimport type { PlanMeta } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbFilterExpr, IdbQueryPlan } from \"@prisma-idb/adapter-idb/runtime\";\nimport type {\n IdbAggregateAst,\n IdbCountAst,\n IdbCreateAst,\n IdbCreateAllAst,\n IdbDeleteAst,\n IdbFindManyAst,\n IdbFindUniqueAst,\n IdbQueryAst,\n} from \"@prisma-idb/adapter-idb/runtime\";\nimport { evaluateFilter, shorthandToFilterExpr } from \"@prisma-idb/adapter-idb/runtime\";\nimport {\n type CreateInput,\n type DefaultModelRow,\n type IdbAggregateBuilder,\n type IdbAggregateResult,\n type IdbAggregateSpec,\n type IdbContract,\n type IncludeSpec,\n type KeyType,\n type MutationCreateInput,\n type MutationUpdateInput,\n type NoIncludes,\n type OrderBySpec,\n type PatchInput,\n type ReferenceRelKeys,\n type RelatedModelOf,\n type SelectedRow,\n type WhereFilter,\n buildFieldToIndexMap,\n extractKeyFromRow,\n getKeyPath,\n getRelation,\n getStoreName,\n keyToken,\n} from \"./types\";\nimport { createModelAccessor, type IdbModelAccessor } from \"./model-accessor\";\nimport {\n type IdbAccessorState,\n type IdbIncludeScalar,\n type IncludeEntry,\n createIncludeScalar,\n emptyAccessorState,\n isIncludeScalar,\n mergeAccessorState,\n} from \"./store-state\";\nimport {\n buildRowComparator,\n combineFilterExprs,\n clampCount,\n extractIndexEqualityHint,\n extractIndexOrHint,\n isNativelyCountable,\n toCountPlan,\n type IndexEqualityHint,\n type IndexOrHint,\n} from \"./query-shaping\";\nimport {\n assertValidAggregateSpec,\n computeAggregateSpec,\n createAggregateBuilder,\n toAggregateRequests,\n} from \"./aggregate-builder\";\nimport { type IdbGroupedAccessor, createGroupedAccessor } from \"./grouped-accessor\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { assertEnumValues } from \"./enum-validation\";\nimport { applyCreateDefaults, applyUpdateDefaults, createMutationDefaultsCache } from \"./mutation-defaults\";\nimport { loadRelation } from \"./relation-loader\";\nimport {\n applyReferentialActionsForRowOnUpdate,\n collectOnUpdateEnforcementStoreNames,\n collectScalarFkStoreNames,\n executeBulkUpdateWithFkValidation,\n executeDeleteAllWithReferentialActions,\n executeDeleteWithReferentialActions,\n executeNestedCreateMutation,\n executeNestedUpdateMutation,\n executeScalarCreateAllWithFkValidation,\n executeScalarCreateWithFkValidation,\n executeScalarUpdateWithFkValidation,\n hasEnforceableChildRelations,\n hasNestedMutationCallbacks,\n hasScalarFkFields,\n requireTransactionExecutor,\n validateScalarFks,\n} from \"./mutation-executor\";\nimport { withMutationScope } from \"./mutation-scope\";\n\n/** Callback form of `.where(fn)` — receives the typed model accessor proxy. */\nexport type WhereCallback<TContract, ModelName extends string> = (\n m: IdbModelAccessor<TContract, ModelName>\n) => IdbFilterExpr;\n\n/** Tuple of one-or-more field names of a model (for `select()` / `groupBy()`). */\ntype FieldTuple<TContract, ModelName extends string> = readonly [\n keyof DefaultModelRow<TContract, ModelName> & string,\n ...(keyof DefaultModelRow<TContract, ModelName> & string)[],\n];\n\n/**\n * The child accessor handed to an `include()` refinement callback.\n *\n * Exposes the chainable narrowing methods (`where` / `orderBy` / `take` /\n * `skip`) plus the scalar `count()` reducer. Mirrors the vendor\n * `IncludeRefinementCollection`: chainable methods return the same refinement\n * surface so `count()` stays reachable after a `where()`, and `count()` returns\n * an {@link IdbIncludeScalar} marker rather than the async terminal `count()`\n * found on the top-level accessor.\n */\nexport interface IdbIncludeRefinementAccessor<TContract, ModelName extends string> {\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbIncludeRefinementAccessor<TContract, ModelName>;\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbIncludeRefinementAccessor<TContract, ModelName>;\n take(n: number): IdbIncludeRefinementAccessor<TContract, ModelName>;\n skip(n: number): IdbIncludeRefinementAccessor<TContract, ModelName>;\n count(): IdbIncludeScalar;\n}\n\n/** Refinement callback type for a given relation key `K`. */\ntype IncludeRefineFn<TContract, ModelName extends string, K extends string, R> = (\n collection: IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n) => R;\n\n// ── Interface ─────────────────────────────────────────────────────────────────\n\n/**\n * Immutable query-builder for a single IDB object store.\n *\n * Each method that narrows the query (`.where()`, `.take()`, etc.) returns a\n * new, independent accessor instance — the original is never mutated. This\n * mirrors the `MongoCollection` pattern from Prisma ORM's Mongo family.\n *\n * @template TContract - The full IDB contract (with or without type maps).\n * @template ModelName - The model (store) this accessor targets.\n * @template TIncludes - Tracks which relations have been included via\n * `.include()` calls, so the return type widens progressively.\n * @template TSelected - Field names kept by `.select()`. `never` (the\n * default) means \"all fields\"; otherwise the row narrows to these fields\n * (plus any included relations).\n */\nexport interface IdbStoreAccessor<\n TContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName> = NoIncludes,\n TSelected extends string = never,\n> {\n /**\n * Add a filter (ANDed with any previous `.where()` calls).\n *\n * Two forms:\n *\n * - **Shorthand**: `where({ field: value })` — multi-key shorthand\n * objects compose as AND. `null` values become null-checks rather\n * than literal-null equalities so absent fields match.\n * - **Callback**: `where((m) => m.field.op(value))` — receives the\n * typed model accessor proxy and returns an `IdbFilterExpr` built\n * via the operator surface. Combinators (`and`, `or`, `not` from\n * `@prisma-idb/client-idb/orm`) compose nodes.\n */\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Set the sort order. Replaces any previous `.orderBy()` call. */\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Limit the number of rows returned. */\n take(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /** Skip the first `n` rows (OFFSET). */\n skip(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected>;\n\n /**\n * Include a reference relation in the returned rows.\n *\n * The relation is loaded via a single batch cursor scan after the main\n * query — O(1) round trips to IDB per included relation regardless of\n * the number of parent rows. The return type gains the relation field\n * automatically.\n *\n * An optional refinement callback narrows the loaded relation:\n *\n * - return the (chained) collection to apply `where` / `orderBy` /\n * `take` / `skip` to the related rows (per-parent for `1:N`);\n * - return `collection.count()` to reduce a to-many relation to the\n * number of matching children (the field becomes a `number`).\n *\n * @example\n * ```ts\n * db.users.include(\"posts\", (posts) => posts.where({ published: true }).take(5))\n * db.users.include(\"posts\", (posts) => posts.count())\n * ```\n */\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n >\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, true>, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn: IncludeRefineFn<TContract, ModelName, K, IdbIncludeScalar>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, \"scalar\">, TSelected>;\n\n /**\n * Project the row down to a subset of scalar fields. Any previously\n * `.include()`d relations are preserved on the result; only the scalar\n * fields are narrowed.\n *\n * @example\n * ```ts\n * const summaries = await db.users.select(\"id\", \"email\").all();\n * // typeof summaries[number] === { id: string; email: string }\n * ```\n */\n select<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, Fields[number]>;\n\n /** Return all matching rows as an async iterable (also awaitable as `Row[]`). */\n all(): AsyncIterableResult<SelectedRow<TContract, ModelName, TIncludes, TSelected>>;\n\n /** Return the first matching row, or `null` if none match. */\n first(): Promise<SelectedRow<TContract, ModelName, TIncludes, TSelected> | null>;\n\n /**\n * Run an in-memory aggregate (count/sum/avg/min/max) over the rows matching\n * the accumulated `.where()` filter. Returns one result object keyed by the\n * aliases supplied in the spec.\n *\n * @example\n * ```ts\n * const stats = await db.posts.where({ published: true }).aggregate((agg) => ({\n * total: agg.count(),\n * avgViews: agg.avg(\"views\"),\n * }));\n * ```\n */\n aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<IdbAggregateResult<Spec>>;\n\n /**\n * Switch to grouped-aggregate mode. The returned {@link IdbGroupedAccessor}'s\n * `.aggregate(...)` terminal produces one row per group with the chosen key\n * fields plus the requested aggregates.\n *\n * @example\n * ```ts\n * const byUser = await db.posts\n * .where({ published: true })\n * .groupBy(\"authorId\")\n * .aggregate((agg) => ({ count: agg.count(), totalViews: agg.sum(\"views\") }));\n * ```\n */\n groupBy<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbGroupedAccessor<TContract, ModelName, Fields>;\n\n /**\n * Insert a record into the store and return the stored row.\n *\n * The primary key field is optional in `data` — pass it to use a\n * client-generated ID (`cuid`, `uuid`) or omit it for auto-increment stores.\n *\n * Relation fields accept a mutation callback:\n * `posts: (rel) => rel.create([...])` or `author: (rel) => rel.connect({ id })`.\n * When any relation callback is present, all writes are wrapped in a single\n * multi-store IDB transaction (requires IdbRuntime, not a plain executor).\n */\n create(data: MutationCreateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName>>;\n\n /** Look up a single row by primary key. Returns `null` if not found. */\n findUnique(key: KeyType<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null>;\n\n /** Delete the row with the given primary key. */\n delete(key: KeyType<TContract, ModelName>): Promise<void>;\n\n /**\n * Update the first row matching the accumulated `.where()` filter.\n * Returns the merged row, or `null` if no row matches.\n *\n * Relation fields accept `connect` or `disconnect` callbacks. When any\n * relation callback is present, all writes run in a single multi-store\n * IDB transaction (requires IdbRuntime).\n */\n update(patch: MutationUpdateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null>;\n\n /**\n * Update all rows matching the accumulated `.where()` filter and return\n * them as an `AsyncIterableResult` (also awaitable as `Row[]`).\n */\n updateAll(patch: PatchInput<TContract, ModelName>): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Update all rows matching the accumulated `.where()` filter.\n * Returns the count of updated rows.\n */\n updateCount(patch: PatchInput<TContract, ModelName>): Promise<number>;\n\n /**\n * Insert or update a single record.\n *\n * - If a row matching `where` exists: shallow-merge `update` onto it and\n * return the merged row.\n * - If no matching row exists: insert `create` and return it.\n */\n upsert(args: {\n create: CreateInput<TContract, ModelName>;\n update: PatchInput<TContract, ModelName>;\n where: WhereFilter<TContract, ModelName>;\n }): Promise<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Insert multiple records in a single atomic transaction.\n * Returns all inserted rows as an `AsyncIterableResult`.\n */\n createAll(data: CreateInput<TContract, ModelName>[]): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Insert multiple records in a single atomic transaction.\n * Returns the count of inserted rows.\n */\n createCount(data: CreateInput<TContract, ModelName>[]): Promise<number>;\n\n /**\n * Delete all rows matching the accumulated `.where()` filter.\n * Returns the deleted rows as an `AsyncIterableResult`.\n */\n deleteAll(): AsyncIterableResult<DefaultModelRow<TContract, ModelName>>;\n\n /**\n * Delete all rows matching the accumulated `.where()` filter.\n * Returns the count of deleted rows.\n */\n deleteCount(): Promise<number>;\n\n /**\n * Count all rows matching the accumulated `.where()` filter.\n * With no filter, counts all rows in the store.\n *\n * **Note — `skip`/`take` are respected**: unlike Prisma's SQL `count()`,\n * which ignores pagination, this implementation reuses the same cursor-scan\n * plan as `all()`. That means `where(...).take(5).count()` returns at most 5,\n * not the total number of matching rows. Use `where(...).count()` without\n * `take`/`skip` when you need an unbounded total.\n */\n count(): Promise<number>;\n}\n\n// ── Implementation ────────────────────────────────────────────────────────────\n\n/**\n * Concrete immutable query builder.\n *\n * Internal details:\n * - All state is in `#state` (filters, orderBy, skip, take, includes, selectedFields).\n * - Builder methods clone via `#clone()` — O(1) copies since state is\n * structurally shared.\n * - `all()` materialises the main rows first, then batch-loads each included\n * relation, then applies any `.select()` projection before yielding.\n * - `#includeRefinementMode` flips `count()` from an async terminal to an\n * {@link IdbIncludeScalar} marker so it can be used inside `include()`.\n */\nexport class IdbStoreAccessorImpl<\n TContract extends IdbContract,\n ModelName extends string,\n TIncludes extends IncludeSpec<TContract, ModelName> = NoIncludes,\n TSelected extends string = never,\n> implements IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n readonly #contract: TContract;\n readonly #modelName: ModelName;\n readonly #executor: IdbQueryExecutor;\n readonly #storeName: string;\n readonly #state: IdbAccessorState;\n readonly #newGroupingKey: () => string;\n readonly #includeRefinementMode: boolean;\n\n constructor(\n contract: TContract,\n modelName: ModelName,\n executor: IdbQueryExecutor,\n state?: IdbAccessorState,\n newGroupingKey?: () => string,\n includeRefinementMode = false\n ) {\n this.#contract = contract;\n this.#modelName = modelName;\n this.#executor = executor;\n this.#storeName = getStoreName(contract, modelName);\n this.#state = state ?? emptyAccessorState();\n // Default: per-instance counter (single client; avoids module-level interleaving).\n let _key = 0;\n this.#newGroupingKey = newGroupingKey ?? (() => `idb-op-${++_key}`);\n this.#includeRefinementMode = includeRefinementMode;\n }\n\n // ── Builder methods ───────────────────────────────────────────────────────\n\n where(\n filter: WhereFilter<TContract, ModelName> | WhereCallback<TContract, ModelName>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n const expr =\n typeof filter === \"function\"\n ? filter(createModelAccessor<TContract, ModelName>())\n : shorthandToFilterExpr(filter as Record<string, unknown>);\n // An empty shorthand object (or one with only undefined values) lifts\n // to `undefined` — keep the existing filter list untouched so chained\n // `.where({})` calls don't produce noisy AND nodes.\n if (expr === undefined) return this.#clone({});\n return this.#clone({ filters: [...this.#state.filters, expr] });\n }\n\n orderBy(spec: OrderBySpec<TContract, ModelName>): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ orderBy: spec as Record<string, \"asc\" | \"desc\"> });\n }\n\n take(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ take: n });\n }\n\n skip(n: number): IdbStoreAccessor<TContract, ModelName, TIncludes, TSelected> {\n return this.#clone({ skip: n });\n }\n\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>>\n >\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, true>, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn: IncludeRefineFn<TContract, ModelName, K, IdbIncludeScalar>\n ): IdbStoreAccessor<TContract, ModelName, TIncludes & Record<K, \"scalar\">, TSelected>;\n include<K extends ReferenceRelKeys<TContract, ModelName>>(\n relation: K,\n refineFn?: IncludeRefineFn<\n TContract,\n ModelName,\n K,\n IdbIncludeRefinementAccessor<TContract, RelatedModelOf<TContract, ModelName, K>> | IdbIncludeScalar\n >\n ): IdbStoreAccessor<TContract, ModelName, IncludeSpec<TContract, ModelName>, TSelected> {\n const entry = this.#resolveIncludeEntry(relation, refineFn);\n const newState = mergeAccessorState(this.#state, {\n includes: { ...this.#state.includes, [relation]: entry },\n });\n // The new instance is identical at runtime; the narrowed TIncludes type is\n // only a compile-time distinction — so an `as unknown as` cast is safe.\n return new IdbStoreAccessorImpl(\n this.#contract,\n this.#modelName,\n this.#executor,\n newState,\n this.#newGroupingKey,\n this.#includeRefinementMode\n ) as unknown as IdbStoreAccessor<TContract, ModelName, IncludeSpec<TContract, ModelName>, TSelected>;\n }\n\n select<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbStoreAccessor<TContract, ModelName, TIncludes, Fields[number]> {\n // Runtime is identical; only TSelected narrows. Cast bridges the type-level\n // projection (the clone preserves TIncludes / contract / executor).\n return this.#clone({ selectedFields: fields as readonly string[] }) as unknown as IdbStoreAccessor<\n TContract,\n ModelName,\n TIncludes,\n Fields[number]\n >;\n }\n\n // ── Execution methods ─────────────────────────────────────────────────────\n\n all(): AsyncIterableResult<SelectedRow<TContract, ModelName, TIncludes, TSelected>> {\n const groupingKey = this.#newGroupingKey();\n // Capture the private fields needed inside the generator. Private names\n // must be accessed on `this`, so we bind the methods to keep them callable\n // without aliasing `this` (no-this-alias).\n const buildScanPlan = this.#buildScanPlan.bind(this);\n const executeOrRows = this.#executeOrRows.bind(this);\n const executorQuery = this.#executor.query.bind(this.#executor);\n const applyIncludes = this.#applyIncludes.bind(this);\n const projectRows = this.#projectRows.bind(this);\n const combined = this.#combinedFilterExpr();\n const fieldToIndexMap =\n typeof IDBKeyRange !== \"undefined\" ? buildFieldToIndexMap(this.#contract, this.#storeName) : undefined;\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const comparator = buildRowComparator(this.#state.orderBy);\n const skip = this.#state.skip;\n const take = this.#state.take;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<SelectedRow<TContract, ModelName, TIncludes, TSelected>, void, unknown> {\n let rows: Record<string, unknown>[];\n\n // OR multi-scan path: union N index point-range scans, deduplicate,\n // re-apply orderBy (the union has no overall ordering), then apply\n // skip/take in-memory (pagination must happen after the union).\n const orHint = fieldToIndexMap !== undefined ? extractIndexOrHint(combined, fieldToIndexMap, keyPath) : null;\n if (orHint !== null) {\n rows = await executeOrRows(orHint, groupingKey, combined);\n if (comparator !== undefined) rows.sort(comparator);\n if (skip !== undefined) rows = rows.slice(skip);\n if (take !== undefined) rows = rows.slice(0, take);\n } else {\n // AND single-index path (or full scan — decided inside buildScanPlan).\n const scanPlan = buildScanPlan<Record<string, unknown>>(groupingKey, fieldToIndexMap);\n rows = [];\n for await (const row of executorQuery(scanPlan)) {\n rows.push(row);\n }\n }\n\n // Batch-load any included relations (uses full rows — FK fields intact).\n const withIncludes = await applyIncludes(rows, groupingKey);\n\n // Apply any `.select()` projection, then yield.\n for (const row of projectRows(withIncludes)) {\n yield row as SelectedRow<TContract, ModelName, TIncludes, TSelected>;\n }\n })()\n );\n }\n\n async first(): Promise<SelectedRow<TContract, ModelName, TIncludes, TSelected> | null> {\n return this.take(1).all().first();\n }\n\n async aggregate<Spec extends IdbAggregateSpec>(\n fn: (agg: IdbAggregateBuilder<TContract, ModelName>) => Spec\n ): Promise<IdbAggregateResult<Spec>> {\n const spec = fn(createAggregateBuilder<TContract, ModelName>());\n assertValidAggregateSpec(spec, \"aggregate()\");\n const combined = this.#combinedFilterExpr();\n const ast: IdbAggregateAst = {\n kind: \"aggregate\",\n modelName: this.#modelName,\n aggregates: toAggregateRequests(spec),\n ...(combined !== undefined ? { where: combined } : {}),\n };\n const groupingKey = this.#newGroupingKey();\n\n // When `count` is the ONLY selector no row value is ever read, so the\n // total can come from a native count. A mixed spec (count alongside\n // sum/avg/min/max) needs the rows regardless, so it materializes. Like\n // the materialized path, aggregate() ignores skip/take.\n if (Object.values(spec).every((selector) => selector.fn === \"count\")) {\n const scanPlan = this.#buildScanPlan<Record<string, unknown>>(groupingKey);\n const total = await this.#executeNativeCount(scanPlan, ast);\n if (total !== null) {\n const result: Record<string, number | null> = {};\n for (const alias of Object.keys(spec)) result[alias] = total;\n return result as IdbAggregateResult<Spec>;\n }\n }\n\n const rows = await this.#materialize(groupingKey, ast);\n return computeAggregateSpec(spec, rows) as IdbAggregateResult<Spec>;\n }\n\n groupBy<Fields extends FieldTuple<TContract, ModelName>>(\n ...fields: Fields\n ): IdbGroupedAccessor<TContract, ModelName, Fields> {\n const combined = this.#combinedFilterExpr();\n const materialize = (ast: IdbQueryAst): Promise<Record<string, unknown>[]> =>\n this.#materialize(this.#newGroupingKey(), ast);\n return createGroupedAccessor<TContract, ModelName, Fields>({\n modelName: this.#modelName,\n by: fields as readonly string[],\n where: combined,\n materialize,\n });\n }\n\n async create(data: MutationCreateInput<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName>> {\n const record = data as Record<string, unknown>;\n\n if (hasNestedMutationCallbacks(this.#contract, this.#modelName, record)) {\n const row = await executeNestedCreateMutation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n data: record,\n });\n return row as DefaultModelRow<TContract, ModelName>;\n }\n\n // Apply defaults before deciding whether foreign keys need checking: a\n // default can fill in a foreign key the caller left out.\n const withDefaults = applyCreateDefaults(\n this.#contract.execution?.mutations.defaults,\n this.#storeName,\n record,\n createMutationDefaultsCache()\n );\n assertEnumValues(this.#contract, this.#modelName, withDefaults);\n if (hasScalarFkFields(this.#contract, this.#modelName, withDefaults)) {\n const row = await executeScalarCreateWithFkValidation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n data: withDefaults,\n });\n return row as DefaultModelRow<TContract, ModelName>;\n }\n\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbCreateAst = { kind: \"create\", modelName: this.#modelName, data: withDefaults };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"add\", storeName: this.#storeName, record: withDefaults },\n };\n // The IDB driver echoes the stored record back as the single result row.\n for await (const row of this.#executor.query(plan)) {\n return row as DefaultModelRow<TContract, ModelName>;\n }\n return withDefaults as DefaultModelRow<TContract, ModelName>;\n }\n\n async findUnique(key: KeyType<TContract, ModelName>): Promise<DefaultModelRow<TContract, ModelName> | null> {\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbFindUniqueAst = { kind: \"findUnique\", modelName: this.#modelName, key };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"key-get\", storeName: this.#storeName, key: key as IDBValidKey },\n };\n for await (const row of this.#executor.query(plan)) {\n return row as DefaultModelRow<TContract, ModelName>;\n }\n return null;\n }\n\n async delete(key: KeyType<TContract, ModelName>): Promise<void> {\n if (hasEnforceableChildRelations(this.#contract, this.#modelName)) {\n await executeDeleteWithReferentialActions({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n key: key as IDBValidKey,\n });\n return;\n }\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbDeleteAst = { kind: \"delete\", modelName: this.#modelName, key };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: { meta, kind: \"delete\", storeName: this.#storeName, key: key as IDBValidKey },\n };\n // The driver echoes the deleted row, but this API returns void — drain\n // via toArray() just to execute the plan and discard the result.\n await this.#executor.query(plan).toArray();\n }\n\n async update(\n patch: MutationUpdateInput<TContract, ModelName>\n ): Promise<DefaultModelRow<TContract, ModelName> | null> {\n const patchRecord = patch as Record<string, unknown>;\n\n if (hasNestedMutationCallbacks(this.#contract, this.#modelName, patchRecord)) {\n const row = await executeNestedUpdateMutation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n filters: this.#state.filters,\n data: patchRecord,\n });\n return row as DefaultModelRow<TContract, ModelName> | null;\n }\n\n // Always routes through the transaction scope, whether or not the patch\n // touches a scalar FK field — same reasoning as `updateAll()` below: the\n // matched row isn't known until the scan-write actually runs (`.where()`\n // filters on ANY field, not just the primary key), and only the\n // transaction-scope path lets the sync interceptor observe that REAL row\n // and key it correctly (`SyncInterceptingTransactionScope#maybeTrack`'s\n // `update`/`scan-write` cases), atomically with the write itself.\n //\n // The previous plan-level fallback here (for patches with no FK field)\n // tried to recover the key by statically inspecting the filter AST\n // instead — which only worked for the narrow case of an equality filter\n // directly on the primary key (`.where({ id })`). Any other filter\n // (`.where({ name: \"...\" })`, a range, an OR) left the key unresolved,\n // and the outbox event synced with a raw filter tree the server\n // couldn't apply — or, after an earlier fix, was rejected outright with\n // `Unsupported update: filter does not pin \"id\" by equality`. Routing\n // through the transaction scope unconditionally removes the whole\n // category: the row (and therefore its key) comes from what actually\n // matched, not from re-deriving it from the filter that found it.\n const row = await executeScalarUpdateWithFkValidation({\n executor: requireTransactionExecutor(this.#executor),\n contract: this.#contract,\n modelName: this.#modelName,\n filters: this.#state.filters,\n data: patchRecord,\n });\n return row as DefaultModelRow<TContract, ModelName> | null;\n }\n\n /**\n * Always routes through the transaction scope (`executeBulkUpdateWithFkValidation`),\n * unlike single-row `update()`'s plan-level fallback for the no-FK-field\n * case. A bulk scan-write's affected row set isn't knowable until it\n * actually runs — going through the transaction scope is what lets the\n * sync interceptor observe the real affected rows and write one outbox\n * event per row (see `SyncInterceptingTransactionScope#maybeTrack`'s\n * `scan-write` case), atomically with the write itself, instead of one\n * event for the whole batch with no way to recover which rows it covered.\n */\n updateAll(patch: PatchInput<TContract, ModelName>): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n const contract = this.#contract;\n const modelName = this.#modelName;\n const filters = this.#state.filters;\n const patchRecord = patch as Record<string, unknown>;\n const executor = requireTransactionExecutor(this.#executor);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeBulkUpdateWithFkValidation({\n executor,\n contract,\n modelName,\n filters,\n data: patchRecord,\n });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n\n async updateCount(patch: PatchInput<TContract, ModelName>): Promise<number> {\n return (await this.updateAll(patch).toArray()).length;\n }\n\n async upsert(args: {\n create: CreateInput<TContract, ModelName>;\n update: PatchInput<TContract, ModelName>;\n where: WhereFilter<TContract, ModelName>;\n }): Promise<DefaultModelRow<TContract, ModelName>> {\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const whereExpr = shorthandToFilterExpr(args.where as Record<string, unknown>);\n const matches = (row: Record<string, unknown>): boolean =>\n whereExpr === undefined || evaluateFilter(whereExpr, row);\n const meta = this.#planMeta(this.#newGroupingKey());\n const createRecord = args.create as Record<string, unknown>;\n const patchRecord = args.update as Record<string, unknown>;\n const storeName = this.#storeName;\n const executionDefaults = this.#contract.execution?.mutations.defaults;\n\n // Runs the find-then-write in a single readwrite transaction so there is\n // no check-then-act race window — atomicity is needed both for that and\n // for `onUpdate` referential-action enforcement (a multi-store read +\n // write) on the update branch. Mirrors the vendor's single-statement\n // upsert.\n const exec = requireTransactionExecutor(this.#executor);\n // Defaults are applied here, before store-name collection, rather than\n // inside the transaction: a default can add a field that isn't in the\n // caller's raw data, and if that field is a foreign key or a field that\n // children reference, collecting stores from the raw data would\n // under-declare the transaction's store list. Applying defaults first (a\n // pure function of the data + static contract config, no row read needed)\n // and reusing the result throughout keeps FK checks, enforcement, store\n // collection and the actual write looking at the same values.\n const effectivePatch = applyUpdateDefaults(\n executionDefaults,\n storeName,\n patchRecord,\n createMutationDefaultsCache()\n );\n const createWithDefaults = applyCreateDefaults(\n executionDefaults,\n storeName,\n createRecord,\n createMutationDefaultsCache()\n );\n assertEnumValues(this.#contract, this.#modelName, effectivePatch);\n assertEnumValues(this.#contract, this.#modelName, createWithDefaults);\n const { storeNames: onUpdateStoreNames } = collectOnUpdateEnforcementStoreNames(\n this.#contract,\n this.#modelName,\n effectivePatch\n );\n // Either branch may set foreign keys, and which one runs isn't known until\n // the row is looked up, so declare the parent stores both would read.\n const storeNames = [\n ...new Set([\n storeName,\n ...onUpdateStoreNames,\n ...collectScalarFkStoreNames(this.#contract, this.#modelName, createWithDefaults),\n ...collectScalarFkStoreNames(this.#contract, this.#modelName, effectivePatch),\n ]),\n ];\n return withMutationScope(exec, storeNames, async (scope) => {\n const found = await scope.execute({ meta, kind: \"cursor-scan\", storeName, filter: matches, take: 1 });\n const existing = found[0];\n if (existing === undefined) {\n await validateScalarFks(scope, this.#contract, this.#modelName, createWithDefaults);\n const rows = await scope.execute({ meta, kind: \"add\", storeName, record: createWithDefaults });\n return (rows[0] ?? createWithDefaults) as DefaultModelRow<TContract, ModelName>;\n }\n await validateScalarFks(scope, this.#contract, this.#modelName, effectivePatch, existing);\n const key = extractKeyFromRow(existing, keyPath);\n await applyReferentialActionsForRowOnUpdate(scope, this.#contract, this.#modelName, existing, effectivePatch);\n const rows = await scope.execute({ meta, kind: \"update\", storeName, key, patch: effectivePatch });\n return (rows[0] ?? existing) as DefaultModelRow<TContract, ModelName>;\n });\n }\n\n createAll(data: CreateInput<TContract, ModelName>[]): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n // One shared cache for the whole batch — every row in a single createAll()\n // call gets the same generated `temporal.updatedAt()` timestamp, matching\n // SQL's 'query'-stability semantics for the same generator. Defaults are\n // applied before deciding whether foreign keys need checking, because a\n // default can fill in a foreign key.\n const defaultsCache = createMutationDefaultsCache();\n const executionDefaults = this.#contract.execution?.mutations.defaults;\n const records = data.map((d) =>\n applyCreateDefaults(executionDefaults, this.#storeName, d as Record<string, unknown>, defaultsCache)\n );\n if (records.some((row) => hasScalarFkFields(this.#contract, this.#modelName, row))) {\n const executor = requireTransactionExecutor(this.#executor);\n const contract = this.#contract;\n const modelName = this.#modelName;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeScalarCreateAllWithFkValidation({ executor, contract, modelName, data: records });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n const groupingKey = this.#newGroupingKey();\n const meta = this.#planMeta(groupingKey);\n const ast: IdbCreateAllAst = { kind: \"createAll\", modelName: this.#modelName, data: records };\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"batch\",\n storeNames: [this.#storeName],\n ops: records.map((record) => ({ meta, kind: \"add\" as const, storeName: this.#storeName, record })),\n },\n };\n const executorQuery = this.#executor.query.bind(this.#executor);\n const contract = this.#contract;\n const modelName = this.#modelName;\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n // The foreign-key path above checks enums per row in `insertSingleRow`.\n for (const record of records) assertEnumValues(contract, modelName, record);\n for await (const row of executorQuery(plan)) {\n yield row as DefaultModelRow<TContract, ModelName>;\n }\n })()\n );\n }\n\n async createCount(data: CreateInput<TContract, ModelName>[]): Promise<number> {\n return (await this.createAll(data).toArray()).length;\n }\n\n /**\n * Always routes through the transaction scope (`executeDeleteAllWithReferentialActions`),\n * not just when there are enforceable child relations to cascade — that\n * function already handles the no-relations case correctly (an empty\n * relation list is a no-op loop), and going through it unconditionally is\n * what lets the sync interceptor's transaction-scope tracking write one\n * outbox event per actually-deleted row instead of one lump event for\n * the whole batch with no way to know which rows it covered. See\n * `updateAll()`'s doc comment for the same reasoning.\n */\n deleteAll(): AsyncIterableResult<DefaultModelRow<TContract, ModelName>> {\n const combined = this.#combinedFilterExpr();\n const filter = combined !== undefined ? (row: Record<string, unknown>) => evaluateFilter(combined, row) : undefined;\n const contract = this.#contract;\n const modelName = this.#modelName;\n const executor = requireTransactionExecutor(this.#executor);\n return new AsyncIterableResult(\n (async function* (): AsyncGenerator<DefaultModelRow<TContract, ModelName>, void, unknown> {\n const rows = await executeDeleteAllWithReferentialActions({\n executor,\n contract,\n modelName,\n ...(filter !== undefined ? { filter } : {}),\n });\n for (const row of rows) yield row as DefaultModelRow<TContract, ModelName>;\n })()\n );\n }\n\n async deleteCount(): Promise<number> {\n return (await this.deleteAll().toArray()).length;\n }\n\n count(): Promise<number> {\n if (this.#includeRefinementMode) {\n // Inside an include() refinement, count() is a scalar-include marker that\n // include() consumes synchronously — not the async terminal below. The\n // IdbIncludeRefinementAccessor type surfaces the IdbIncludeScalar return;\n // this cast bridges count()'s dual runtime role.\n return createIncludeScalar(this.#state) as unknown as Promise<number>;\n }\n return this.#countTerminal();\n }\n\n // ── Private helpers ───────────────────────────────────────────────────────\n\n async #countTerminal(): Promise<number> {\n const groupingKey = this.#newGroupingKey();\n const combined = this.#combinedFilterExpr();\n const fieldToIndexMap =\n typeof IDBKeyRange !== \"undefined\" ? buildFieldToIndexMap(this.#contract, this.#storeName) : undefined;\n\n // OR multi-scan path: count the deduped+filtered union, applying\n // skip/take pagination so count() is consistent with the non-OR path.\n // Never native: a per-branch count() double-counts a row that matches two\n // branches, and deduplication needs the actual primary keys.\n if (fieldToIndexMap !== undefined) {\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const orHint = extractIndexOrHint(combined, fieldToIndexMap, keyPath);\n if (orHint !== null) {\n const rows = await this.#executeOrRows(orHint, groupingKey, combined);\n return clampCount(rows.length, this.#state.skip, this.#state.take);\n }\n }\n\n const scanPlan = this.#buildScanPlan<Record<string, unknown>>(groupingKey, fieldToIndexMap);\n // Middleware sees a `count` AST regardless of which physical plan runs.\n const scanAst = scanPlan.ast;\n const ast: IdbCountAst = {\n kind: \"count\",\n modelName: this.#modelName,\n ...(scanAst?.kind === \"findMany\" && scanAst.where !== undefined ? { where: scanAst.where } : {}),\n };\n\n // Native path: when the whole `where` is captured by a key range (or\n // there is none), ask IndexedDB to count directly — no row is\n // deserialized. skip/take are applied to the native (unpaginated) total.\n const nativeTotal = await this.#executeNativeCount(scanPlan, ast);\n if (nativeTotal !== null) return clampCount(nativeTotal, this.#state.skip, this.#state.take);\n\n // Fallback: a residual in-memory filter needs each row's value, so the\n // rows must be materialized and counted.\n const plan: IdbQueryPlan<Record<string, unknown>> = { ...scanPlan, ast };\n let n = 0;\n for await (const _ of this.#executor.query(plan)) {\n n++;\n }\n return n;\n }\n\n /**\n * Resolve an `include()` argument pair into an {@link IncludeEntry}: run the\n * optional refinement against a fresh refinement-mode child accessor, then\n * classify the result as a scalar count or a refined collection.\n */\n #resolveIncludeEntry(relation: string, refineFn: ((collection: never) => unknown) | undefined): IncludeEntry {\n if (refineFn === undefined) {\n return { kind: \"collection\", state: emptyAccessorState() };\n }\n\n const rel = getRelation(this.#contract, this.#modelName, relation);\n // v0.12.0: `relation.to` is a CrossReference `{ namespace, model }`.\n const relatedModelName = rel?.to.model ?? relation;\n const child = new IdbStoreAccessorImpl(\n this.#contract,\n relatedModelName,\n this.#executor,\n emptyAccessorState(),\n this.#newGroupingKey,\n /* includeRefinementMode */ true\n );\n\n const refined = (refineFn as (c: unknown) => unknown)(child);\n\n if (isIncludeScalar(refined)) {\n if (rel !== undefined && rel.cardinality !== \"1:N\") {\n throw new Error(`include('${relation}'): count() is only supported for to-many (1:N) relations`);\n }\n return { kind: \"scalar\", fn: refined.fn, state: refined.state };\n }\n\n // Cross-instance private access is allowed within the class body.\n if (refined instanceof IdbStoreAccessorImpl) {\n return { kind: \"collection\", state: refined.#state };\n }\n\n throw new Error(\n `include('${relation}') refinement must return the collection (for where/orderBy/take/skip) or a count() selector`\n );\n }\n\n /**\n * Runs `scanPlan` as a native `count` plan when its cardinality is fully\n * determined by a key range (no in-memory filter) — returning the\n * *unpaginated* total — or `null` when it can't (the caller then falls back\n * to materializing). `ast` is attached so middleware sees the caller's\n * intent (`count` / `aggregate`) regardless of the physical plan.\n */\n async #executeNativeCount(scanPlan: IdbQueryPlan<Record<string, unknown>>, ast: IdbQueryAst): Promise<number | null> {\n const body = scanPlan.idbPlan;\n if (body.kind !== \"cursor-scan\" || !isNativelyCountable(body)) return null;\n const nativePlan: IdbQueryPlan<Record<string, unknown>> = { ...scanPlan, ast, idbPlan: toCountPlan(body) };\n let total = 0;\n for await (const row of this.#executor.query(nativePlan)) {\n total = (row as unknown as { count: number }).count;\n }\n return total;\n }\n\n /**\n * Materialise all rows matching the accumulated filters with no pagination —\n * used by `aggregate()` / `groupBy()`. The supplied `ast` is attached to the\n * scan plan so middleware can observe the aggregate intent.\n */\n async #materialize(groupingKey: string, ast: IdbQueryAst): Promise<Record<string, unknown>[]> {\n const combined = this.#combinedFilterExpr();\n const filter = combined !== undefined ? (row: Record<string, unknown>) => evaluateFilter(combined, row) : undefined;\n const meta = this.#planMeta(groupingKey);\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\",\n storeName: this.#storeName,\n ...(filter !== undefined ? { filter } : {}),\n },\n };\n const rows: Record<string, unknown>[] = [];\n for await (const row of this.#executor.query(plan)) {\n rows.push(row);\n }\n return rows;\n }\n\n #buildScanPlan<Row>(groupingKey: string, fieldToIndexMap?: Record<string, string>): IdbQueryPlan<Row> {\n const combined = this.#combinedFilterExpr();\n const comparator = buildRowComparator(this.#state.orderBy);\n const meta = this.#planMeta(groupingKey);\n const ast: IdbFindManyAst = {\n kind: \"findMany\",\n modelName: this.#modelName,\n ...(combined !== undefined ? { where: combined } : {}),\n ...(this.#state.orderBy !== undefined ? { orderBy: this.#state.orderBy as Record<string, \"asc\" | \"desc\"> } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n };\n\n // Attempt to peel an indexed equality condition from the combined filter\n // and use a cursor-scan over the index with a point range. This avoids\n // a full store scan when IDBKeyRange is available (browser / fake-indexeddb).\n let hint: IndexEqualityHint | null = null;\n if (typeof IDBKeyRange !== \"undefined\") {\n const fieldToIndexName = fieldToIndexMap ?? buildFieldToIndexMap(this.#contract, this.#storeName);\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n hint = extractIndexEqualityHint(combined, fieldToIndexName, keyPath);\n }\n\n const remainingFilter = hint !== null ? hint.remainingFilter : combined;\n const filter =\n remainingFilter !== undefined\n ? (row: Record<string, unknown>) => evaluateFilter(remainingFilter, row)\n : undefined;\n // exactOptionalPropertyTypes: spread conditionally to avoid `undefined`\n // values in optional fields.\n return {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\" as const,\n storeName: this.#storeName,\n ...(hint?.indexName !== undefined ? { indexName: hint.indexName } : {}),\n ...(hint !== null ? { range: IDBKeyRange.only(hint.value as IDBValidKey) } : {}),\n ...(filter !== undefined ? { filter } : {}),\n ...(comparator !== undefined ? { comparator } : {}),\n ...(this.#state.skip !== undefined ? { skip: this.#state.skip } : {}),\n ...(this.#state.take !== undefined ? { take: this.#state.take } : {}),\n },\n } as IdbQueryPlan<Row>;\n }\n\n /**\n * Execute one cursor-scan per OR branch, union the results, deduplicate by\n * primary key, and apply `hint.remainingFilter` in-memory. Skip/take are\n * NOT applied here — the caller slices the array after union so pagination\n * is correct across branches.\n */\n async #executeOrRows(\n hint: IndexOrHint,\n groupingKey: string,\n combined: IdbFilterExpr | undefined\n ): Promise<Record<string, unknown>[]> {\n const meta = this.#planMeta(groupingKey);\n const storeName = this.#storeName;\n const keyPath = getKeyPath(this.#contract, this.#modelName);\n const seen = new Set<unknown>();\n const rows: Record<string, unknown>[] = [];\n const ast: IdbFindManyAst = {\n kind: \"findMany\",\n modelName: this.#modelName,\n ...(combined !== undefined ? { where: combined } : {}),\n };\n\n // Branches are independent index scans — run them concurrently, then\n // merge/dedupe sequentially (first-branch-wins) so results stay\n // deterministic regardless of completion order.\n const branchResults = await Promise.all(\n hint.branches.map(async (branch) => {\n const plan: IdbQueryPlan<Record<string, unknown>> = {\n meta,\n ast,\n idbPlan: {\n meta,\n kind: \"cursor-scan\" as const,\n storeName,\n ...(branch.indexName !== undefined ? { indexName: branch.indexName } : {}),\n range: IDBKeyRange.only(branch.value as IDBValidKey),\n },\n };\n const branchRows: Record<string, unknown>[] = [];\n for await (const row of this.#executor.query(plan)) {\n branchRows.push(row);\n }\n return branchRows;\n })\n );\n for (const branchRows of branchResults) {\n for (const row of branchRows) {\n const pk = keyToken(extractKeyFromRow(row, keyPath));\n if (!seen.has(pk)) {\n seen.add(pk);\n rows.push(row);\n }\n }\n }\n\n if (hint.remainingFilter === undefined) return rows;\n const { remainingFilter } = hint;\n return rows.filter((row) => evaluateFilter(remainingFilter, row));\n }\n\n /**\n * Combine all accumulated filter expressions with AND.\n *\n * Returns `undefined` when no filter has been installed so the driver can\n * skip building a row filter closure (a small perf and readability win on\n * `.all()` paths). Delegates to the shared {@link combineFilterExprs}.\n */\n #combinedFilterExpr(): IdbFilterExpr | undefined {\n return combineFilterExprs(this.#state.filters);\n }\n\n async #applyIncludes(rows: Record<string, unknown>[], groupingKey: string): Promise<Record<string, unknown>[]> {\n const relNames = Object.keys(this.#state.includes);\n if (relNames.length === 0) return rows;\n let result = rows;\n for (const relName of relNames) {\n const entry = this.#state.includes[relName]!;\n result = await loadRelation(relName, entry, result, this.#contract, this.#modelName, this.#executor, groupingKey);\n }\n return result;\n }\n\n /**\n * Apply a `.select()` projection (if any) to materialised rows. Keeps the\n * selected scalar fields plus every included relation key (which `include()`\n * attached during {@link #applyIncludes}); a no-op when nothing is selected.\n */\n #projectRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {\n const selected = this.#state.selectedFields;\n if (selected === undefined) return rows;\n const keep = [...selected, ...Object.keys(this.#state.includes)];\n return rows.map((row) => {\n const out: Record<string, unknown> = {};\n for (const field of keep) {\n if (field in row) out[field] = row[field];\n }\n return out;\n });\n }\n\n #planMeta(groupingKey: string): PlanMeta {\n return {\n target: \"idb\",\n storageHash: this.#contract.storage.storageHash,\n lane: \"idb-orm\",\n annotations: { groupingKey },\n };\n }\n\n #clone(overrides: Partial<IdbAccessorState>): IdbStoreAccessorImpl<TContract, ModelName, TIncludes, TSelected> {\n return new IdbStoreAccessorImpl(\n this.#contract,\n this.#modelName,\n this.#executor,\n mergeAccessorState(this.#state, overrides),\n this.#newGroupingKey,\n this.#includeRefinementMode\n );\n }\n}\n","import type { Contract } from \"@prisma/orm-framework/contract/types\";\nimport type { IdbContract, IdbStorage } from \"./types\";\nimport type { IdbQueryExecutor } from \"./executor\";\nimport { type IdbStoreAccessor, IdbStoreAccessorImpl } from \"./store-accessor\";\n\n// ── Public types ──────────────────────────────────────────────────────────────\n\n/**\n * The ORM client object returned by {@link idbOrm}.\n *\n * Keys are the root keys from `contract.roots` (e.g. `\"users\"`, `\"posts\"`).\n * Each value is an {@link IdbStoreAccessor} targeting the corresponding model.\n *\n * @example\n * ```ts\n * const db = idbOrm({ contract, executor: runtime });\n * const users = await db.users.all(); // IdbStoreAccessor<..., \"User\">\n * ```\n */\nexport type IdbOrmClient<TContract extends Contract<IdbStorage>> = {\n // v0.12.0: `roots` values are CrossReference `{ namespace, model }`, so the\n // target model name is `roots[K].model` (was a bare model-name string).\n readonly [K in string & keyof TContract[\"roots\"]]: TContract[\"roots\"][K] extends {\n model: infer ModelName extends string;\n }\n ? IdbStoreAccessor<TContract, ModelName>\n : never;\n};\n\n/**\n * Options for {@link idbOrm}.\n */\nexport interface IdbOrmOptions<TContract extends IdbContract> {\n /** The resolved IDB contract (with or without attached type maps). */\n readonly contract: TContract;\n /**\n * The query executor.\n *\n * Any object with a compatible `query()` signature satisfies this —\n * most commonly an `IdbRuntime` created via `createIdbRuntime()`.\n */\n readonly executor: IdbQueryExecutor;\n}\n\n// ── Factory function ──────────────────────────────────────────────────────────\n\n/**\n * Create a typed IDB ORM client from a contract and executor.\n *\n * The client exposes one `IdbStoreAccessor` per entry in `contract.roots`.\n * Only roots-declared stores are accessible at the top level — other stores\n * can be reached via `.include()` on any accessor.\n *\n * @example\n * ```ts\n * import { idbOrm } from \"@prisma-idb/client-idb/orm\";\n * import { createIdbRuntime } from \"@prisma-idb/runtime-idb/runtime\";\n * import contract from \"./prisma/idb-contract\";\n *\n * const runtime = createIdbRuntime({ adapter, driver });\n * const db = idbOrm({ contract, executor: runtime });\n *\n * // Typed query builder:\n * const alice = await db.users.where({ email: \"alice@example.com\" }).first();\n * const postsWithAuthor = await db.posts.include(\"author\").all();\n * ```\n */\nexport function idbOrm<TContract extends IdbContract>(options: IdbOrmOptions<TContract>): IdbOrmClient<TContract> {\n const { contract, executor } = options;\n\n // One counter per idbOrm() call — two clients in the same realm get\n // independent key sequences and can't interleave (ADR 160).\n let _key = 0;\n const newGroupingKey = () => `idb-op-${++_key}`;\n\n const client: Record<string, IdbStoreAccessor<TContract, string>> = {};\n for (const [rootKey, ref] of Object.entries(contract.roots)) {\n // v0.12.0: `roots` values are CrossReference `{ namespace, model }`.\n client[rootKey] = new IdbStoreAccessorImpl(contract, ref.model, executor, undefined, newGroupingKey);\n }\n\n return client as unknown as IdbOrmClient<TContract>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAS,oBAAoB,OAA0C;CACrE,OAAO;EACL,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,KAAK,UAAU,YAAY,OAAO,MAAM,KAAK;EAC7C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,MAAM,UAAU,YAAY,OAAO,OAAO,KAAK;EAC/C,KAAK,WAAW,YAAY,OAAO,MAAM,MAAM;EAC/C,QAAQ,WAAW,YAAY,OAAO,SAAS,MAAM;EACrD,WAAW,QAAQ,YAAY,OAAO,YAAY,GAAG;EACrD,aAAa,QAAQ,YAAY,OAAO,cAAc,GAAG;EACzD,WAAW,QAAQ,YAAY,OAAO,YAAY,GAAG;EACrD,cAAc,cAAc,OAAO,IAAI;EACvC,iBAAiB,cAAc,OAAO,KAAK;CAC7C;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,sBAGd;CACA,MAAM,wBAAQ,IAAI,IAAuC;CACzD,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAuB;EAClC,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;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