@lunora/server 1.0.0-alpha.27 → 1.0.0-alpha.270

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE.md +213 -0
  2. package/README.md +18 -12
  3. package/dist/data-model.d.mts +415 -170
  4. package/dist/data-model.d.ts +415 -170
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/in-process.d.mts +115 -0
  8. package/dist/in-process.d.ts +115 -0
  9. package/dist/in-process.mjs +1 -0
  10. package/dist/index.d.mts +3800 -1405
  11. package/dist/index.d.ts +3800 -1405
  12. package/dist/index.mjs +1 -29
  13. package/dist/otel.d.mts +597 -0
  14. package/dist/otel.d.ts +597 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DMYtb827.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
  18. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-MUPXbAHR.mjs +1 -0
  19. package/dist/packem_shared/LunoraEnvError-bkdMu_-N.mjs +4 -0
  20. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CKPKoWy_.mjs +1 -0
  21. package/dist/packem_shared/PROCEDURE_META-DVzrXpfa.mjs +1 -0
  22. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  23. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  24. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  25. package/dist/packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs +1 -0
  26. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  27. package/dist/packem_shared/beginDeferredSchedules--FVDtp-M.mjs +1 -0
  28. package/dist/packem_shared/bindOrm-D5mVDvbi.mjs +1 -0
  29. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  30. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  31. package/dist/packem_shared/composePluginMiddleware-Cvl_EFSm.mjs +1 -0
  32. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  33. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  34. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  35. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  36. package/dist/packem_shared/defineAggregateIndex-Ds7prVoi.mjs +1 -0
  37. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  38. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  39. package/dist/packem_shared/defineLiveStream-CmmPtMBt.mjs +1 -0
  40. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  41. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  42. package/dist/packem_shared/defineMutator-DlLFSWbO.mjs +1 -0
  43. package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
  44. package/dist/packem_shared/defineShape-CAIsX21I.mjs +1 -0
  45. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  46. package/dist/packem_shared/defineWebSocket-BHoy6_ox.mjs +1 -0
  47. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  48. package/dist/packem_shared/functions-QFoBUe9t.mjs +1 -0
  49. package/dist/packem_shared/httpAction-CVo4_CSy.mjs +1 -0
  50. package/dist/packem_shared/initLunora-DcvCGLL_.mjs +1 -0
  51. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  52. package/dist/packem_shared/isSafeHeaderValue-DswDADFy.mjs +6 -0
  53. package/dist/packem_shared/mask--ZXtzCj7.mjs +1 -0
  54. package/dist/packem_shared/middleware-CdoC33P7.mjs +1 -0
  55. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  56. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  57. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  58. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  59. package/dist/packem_shared/plugin-D0ogWCbA.mjs +1 -0
  60. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  61. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  62. package/dist/packem_shared/rls-C74k6tmE.mjs +1 -0
  63. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  64. package/dist/packem_shared/serveStorageObject-CLz3qhNI.mjs +1 -0
  65. package/dist/packem_shared/storageRules-BZgB67oS.mjs +1 -0
  66. package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
  67. package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
  68. package/dist/packem_shared/types.d-D0mb6QC3.d.mts +3004 -0
  69. package/dist/packem_shared/types.d-D0mb6QC3.d.ts +3004 -0
  70. package/dist/rls/testing.d.mts +42 -34
  71. package/dist/rls/testing.d.ts +42 -34
  72. package/dist/rls/testing.mjs +1 -49
  73. package/dist/types.d.mts +2 -1335
  74. package/dist/types.d.ts +2 -1335
  75. package/dist/types.mjs +0 -31
  76. package/package.json +27 -7
  77. package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
  78. package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
  79. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-Cv1UPaJj.mjs +0 -114
  80. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  81. package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
  82. package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
  83. package/dist/packem_shared/composePluginMiddleware-z62dttBo.mjs +0 -103
  84. package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
  85. package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
  86. package/dist/packem_shared/defineAggregateIndex-DTULzh09.mjs +0 -333
  87. package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
  88. package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
  89. package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
  90. package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
  91. package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
  92. package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
  93. package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
  94. package/dist/packem_shared/initLunora-CmMVk4i7.mjs +0 -107
  95. package/dist/packem_shared/mask-CZuu9WAF.mjs +0 -331
  96. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  97. package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
  98. package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
  99. package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
  100. package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
  101. package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
  102. package/dist/packem_shared/types.d-BB3pjV0m.d.mts +0 -141
  103. package/dist/packem_shared/types.d-Cxl6ndhm.d.ts +0 -141
@@ -1,25 +1,25 @@
1
1
  /**
2
- * Schema-independent type machinery for the generated data model.
3
- *
4
- * `@lunora/codegen` emits `lunora/_generated/dataModel.ts` with the
5
- * schema-specific pieces (the per-table `Doc_*` / `Insert_*` interfaces, the
6
- * `DataModel` / `Relations` / index-name maps) and then binds the generics
7
- * below to them. Everything here is identical for every project, so it lives
8
- * in the shipped package rather than in generated output — evolving the query
9
- * DSL or the table-facade API no longer regenerates a single line of a user's
10
- * `_generated` directory.
11
- *
12
- * The generics are parameterized over the generated maps:
13
- * - `DM` — `DataModel`: table name → document type
14
- * - `IM` — `InsertModel`: table name → insert shape
15
- * - `REL` — `Relations`: table name → relation-descriptor map
16
- * - `RANK` — `RankIndexNamesByTable`: table name → declared rank-index names
17
- * - `SEARCH` — `SearchIndexNamesByTable`: table name → declared search-index names
18
- *
19
- * Relation descriptors are matched structurally (`{ __relationKind; __target }`)
20
- * so this module needs no reference to the project-local `OneRelation` /
21
- * `ManyRelation` aliases the codegen still emits.
22
- */
2
+ * Schema-independent type machinery for the generated data model.
3
+ *
4
+ * `@lunora/codegen` emits `lunora/_generated/dataModel.ts` with the
5
+ * schema-specific pieces (the per-table `Doc_*` / `Insert_*` interfaces, the
6
+ * `DataModel` / `Relations` / index-name maps) and then binds the generics
7
+ * below to them. Everything here is identical for every project, so it lives
8
+ * in the shipped package rather than in generated output — evolving the query
9
+ * DSL or the table-facade API no longer regenerates a single line of a user's
10
+ * `_generated` directory.
11
+ *
12
+ * The generics are parameterized over the generated maps:
13
+ * - `DM` — `DataModel`: table name → document type
14
+ * - `IM` — `InsertModel`: table name → insert shape
15
+ * - `REL` — `Relations`: table name → relation-descriptor map
16
+ * - `RANK` — `RankIndexNamesByTable`: table name → declared rank-index names
17
+ * - `SEARCH` — `SearchIndexNamesByTable`: table name → declared search-index names
18
+ *
19
+ * Relation descriptors are matched structurally (`{ __relationKind; __target }`)
20
+ * so this module needs no reference to the project-local `OneRelation` /
21
+ * `ManyRelation` aliases the codegen still emits.
22
+ */
23
23
  /** A branded id for table `TName`. Structurally a `string` at runtime. */
24
24
  type Id<TName extends string> = string & {
25
25
  readonly __table: TName;
@@ -37,78 +37,130 @@ interface WhereOperators<T> {
37
37
  ne?: T;
38
38
  notIn?: T[];
39
39
  }
40
+ /**
41
+ * A value stored as a plain JS object: not a scalar (an `Id<T>` is a branded string, which is an `object` to
42
+ * TypeScript but has no keys worth offering), an array, a date, bytes, a bigint or a function.
43
+ */
44
+ type IsPlainObject<V> = V extends string | number | boolean | bigint | symbol ? false : V extends ReadonlyArray<unknown> ? false : V extends Date | Uint8Array | ArrayBuffer | bigint | ((...arguments_: never[]) => unknown) ? false : V extends object ? true : false;
45
+ /** The dotted paths below an object, to three steps. */
46
+ type SubPaths<V, Depth extends unknown[]> = Depth["length"] extends 3 ? never : [IsPlainObject<V>] extends [true] ? { [K in keyof V & string]-?: K | `${K}.${SubPaths<NonNullable<V[K]>, [...Depth, 0]>}`; }[keyof V & string] : never;
47
+ /** The type at the end of dotted path `P` below `V`. */
48
+ type PathValue<V, P extends string> = P extends `${infer Head}.${infer Rest}` ? Head extends keyof V ? PathValue<NonNullable<V[Head]>, Rest> : never : P extends keyof V ? V[P] : never;
49
+ /**
50
+ * Every dotted path into an object-valued column of `Doc` (`"profile.address.city"`), at most four segments
51
+ * counting the column. A column that is not a plain object contributes none.
52
+ */
53
+ type ColumnPaths<Doc> = { [K in keyof Doc & string]-?: [IsPlainObject<NonNullable<Doc[K]>>] extends [true] ? `${K}.${SubPaths<NonNullable<Doc[K]>, []>}` : never; }[keyof Doc & string];
54
+ /** The type at the end of a {@link ColumnPaths} path. */
55
+ type DocPathValue<Doc, P extends string> = P extends `${infer Column}.${infer Rest}` ? Column extends keyof Doc ? PathValue<NonNullable<Doc[Column]>, Rest> : never : never;
56
+ type ScalarLeaf = boolean | number | string | null | undefined;
57
+ /** The dotted paths into an object column that end at a string, number or boolean. */
58
+ type ScalarPaths<Doc> = { [P in ColumnPaths<Doc>]: [DocPathValue<Doc, P>] extends [ScalarLeaf] ? P : never; }[ColumnPaths<Doc>];
59
+ /**
60
+ * `where` keys that reach into an object column: `{ "profile.plan": "pro" }`. Only paths that end at a string,
61
+ * number or boolean are offered — an object, array, date, bigint or bytes leaf has no single SQL comparison.
62
+ *
63
+ * `unknown` (the identity for `&`) when there are none, never `{}`: intersecting with an empty object type
64
+ * switches off the weak-type check that rejects a `where` key naming nothing.
65
+ */
66
+ type PathWhere<Doc, Paths extends string = ScalarPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P> | WhereOperators<DocPathValue<Doc, P>>; };
67
+ /** `patch` keys that set one value inside an object column, keeping its siblings: `{ "profile.plan": "pro" }`. */
68
+ type PathPatch<Doc, Paths extends string = ColumnPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P>; };
40
69
  /** A typed `where` tree over a document's columns. */
41
- type Where<TDocument> = { [K in keyof TDocument]?: TDocument[K] | WhereOperators<TDocument[K]> } & {
70
+ type Where<TDocument> = PathWhere<TDocument> & { [K in keyof TDocument]?: TDocument[K] | WhereOperators<TDocument[K]>; } & {
42
71
  AND?: Where<TDocument>[];
43
72
  NOT?: Where<TDocument>;
44
73
  OR?: Where<TDocument>[];
45
74
  };
46
- /** One `{ field: "asc" | "desc" }` ordering entry; `orderBy` is an ordered list. */
47
- type OrderBy<TDocument> = Partial<Record<keyof TDocument, "asc" | "desc">>;
75
+ /**
76
+ * One ordering entry; `orderBy` is an ordered list. `{ field: "asc" | "desc" }` sorts NULLs first
77
+ * ascending and last descending. `{ field: { sort: "desc", nulls: "first" } }` places them yourself.
78
+ *
79
+ * A placement other than the default can change the query plan (see Pagination in the docs), so
80
+ * measure a hot read. It has no effect on a column that cannot hold NULL. Keep the same `orderBy` for every page of a
81
+ * paginated read, as a cursor is only valid against the ordering that minted it.
82
+ */
83
+ type OrderBy<TDocument> = Partial<Record<keyof TDocument | ScalarPaths<TDocument>, "asc" | "desc" | {
84
+ nulls: "first" | "last";
85
+ sort: "asc" | "desc";
86
+ }>>;
48
87
  interface QueryArgs<TDocument> {
49
88
  cursor?: null | string;
50
89
  limit?: number;
51
90
  orderBy?: OrderBy<TDocument>[];
52
91
  /**
53
- * Project each returned row down to these columns (plus the system fields
54
- * `_id`/`_creationTime`, always retained). Trims wire payload for wide rows;
55
- * relations requested via `with` are still attached. Reactivity is unaffected —
56
- * the engine still reads the whole row to track dependencies.
57
- */
92
+ * Project each returned row down to these columns (plus the system fields
93
+ * `_id`/`_creationTime`, always retained). Trims wire payload for wide rows;
94
+ * relations requested via `with` are still attached. Reactivity is unaffected —
95
+ * the engine still reads the whole row to track dependencies.
96
+ */
58
97
  select?: ReadonlyArray<keyof TDocument & string>;
59
98
  where?: Where<TDocument>;
60
99
  }
61
100
  /**
62
- * A to-one relation predicate node. `is` matches rows whose related record
63
- * satisfies `W`; `isNot` matches rows whose related record fails `W` *or* has
64
- * no related record at all (a null/dangling FK) — Prisma's semantics.
65
- */
101
+ * A to-one relation predicate node. `is` matches rows whose related record
102
+ * satisfies `W`; `isNot` matches rows whose related record fails `W` *or* has
103
+ * no related record at all (a null/dangling FK) — Prisma's semantics.
104
+ */
66
105
  interface OneRelationWhere<W> {
67
106
  is?: W;
68
107
  isNot?: W;
69
108
  }
70
109
  /**
71
- * A to-many relation predicate node. `some` ⇒ at least one related row matches
72
- * `W`; `none` ⇒ no related row matches (childless parents included); `every` ⇒
73
- * every *readable* related row matches (vacuously true for childless parents).
74
- */
110
+ * A to-many relation predicate node. `some` ⇒ at least one related row matches
111
+ * `W`; `none` ⇒ no related row matches (childless parents included); `every` ⇒
112
+ * every *readable* related row matches (vacuously true for childless parents).
113
+ */
75
114
  interface ManyRelationWhere<W> {
76
115
  every?: W;
77
116
  none?: W;
78
117
  some?: W;
79
118
  }
80
119
  /**
81
- * The relation-predicate portion of {@link WhereOf}: each declared relation on
82
- * `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
83
- * `{ some?; none?; every? }` — whose inner type is the target table's own
84
- * relation-aware `where` (so multi-hop predicates type-check inside-out).
85
- */
120
+ * The relation-predicate portion of {@link WhereOf}: each declared relation on
121
+ * `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
122
+ * `{ some?; none?; every? }` — whose inner type is the target table's own
123
+ * relation-aware `where` (so multi-hop predicates type-check inside-out).
124
+ */
86
125
  type RelationWhere<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
87
126
  __relationKind: "one";
88
127
  __target: infer Target extends keyof DM;
89
128
  } ? OneRelationWhere<WhereOf<DM, REL, Target>> : REL[T][K] extends {
90
129
  __relationKind: "many";
91
130
  __target: infer Target extends keyof DM;
92
- } ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never };
131
+ } ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never; };
93
132
  /**
94
- * Relation-aware `where` tree — the column predicates of {@link Where} plus
95
- * Prisma-style relation predicates resolved by the `@lunora/do` pre-resolver.
96
- * `Where&lt;DM[T]>` stays the column-only structural mirror for back-compat; the
97
- * table facade threads `REL` through this richer form.
98
- */
99
- type WhereOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = RelationWhere<DM, REL, T> & { [K in keyof DM[T]]?: DM[T][K] | WhereOperators<DM[T][K]> } & {
133
+ * Relation-aware `where` tree — the column predicates of {@link Where} plus
134
+ * Prisma-style relation predicates resolved by the `@lunora/do` pre-resolver.
135
+ * `Where<DM[T]>` stays the column-only structural mirror for back-compat; the
136
+ * table facade threads `REL` through this richer form.
137
+ */
138
+ type WhereOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = PathWhere<DM[T]> & RelationWhere<DM, REL, T> & { [K in keyof DM[T]]?: DM[T][K] | WhereOperators<DM[T][K]>; } & {
100
139
  AND?: WhereOf<DM, REL, T>[];
101
140
  NOT?: WhereOf<DM, REL, T>;
102
141
  OR?: WhereOf<DM, REL, T>[];
103
142
  };
104
143
  /** {@link QueryArgs} with the relation-aware {@link WhereOf} `where` typing. */
105
144
  interface QueryArgsOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> {
145
+ /** Read the authoritative copy, not a replica. Only a `.global()` D1 table can lag; shard-local reads are already authoritative. */
146
+ consistency?: "primary";
106
147
  cursor?: null | string;
107
148
  /**
108
- * Include soft-deleted rows (`.softDelete()` tables only). Default hides them;
109
- * `true` returns deleted rows alongside live ones. No effect on a table
110
- * without `.softDelete()`.
111
- */
149
+ * Pin the page's end to an earlier page's `continueCursor`, for reactive pagination: the read is
150
+ * the fixed range `(cursor, endCursor]` under this call's `orderBy`, so a row inserted inside it
151
+ * grows this page and the next page (starting at `endCursor`) is unchanged. The result is
152
+ * `isDone: true`, echoes `endCursor` as `continueCursor`, and carries `splitCursor`.
153
+ *
154
+ * `limit` still caps the read. A range it cuts short answers `splitRequired: true`, and the
155
+ * client splits it at `splitCursor`, so the rows past the cap come back in the second half. On
156
+ * a `.global()` table a read with no `limit` is capped at 4096 rows the same way.
157
+ */
158
+ endCursor?: null | string;
159
+ /**
160
+ * Include soft-deleted rows (`.softDelete()` tables only). Default hides them;
161
+ * `true` returns deleted rows alongside live ones. No effect on a table
162
+ * without `.softDelete()`.
163
+ */
112
164
  includeDeleted?: boolean;
113
165
  limit?: number;
114
166
  orderBy?: OrderBy<DM[T]>[];
@@ -118,6 +170,16 @@ interface QueryPage<TDocument> {
118
170
  continueCursor: null | string;
119
171
  isDone: boolean;
120
172
  page: TDocument[];
173
+ /**
174
+ * Only on an `endCursor` read: the cursor of the page's midpoint row, `null` under two rows. Paging
175
+ * `(cursor, splitCursor]` and `(splitCursor, endCursor]` reproduces the range in two halves.
176
+ */
177
+ splitCursor?: null | string;
178
+ /**
179
+ * Only on an `endCursor` read that `limit` (or the global read cap) cut short: the page holds
180
+ * the first rows of its range, and splitting at `splitCursor` is the way to reach the rest.
181
+ */
182
+ splitRequired?: boolean;
121
183
  }
122
184
  /** The nested `with` sub-argument inside a relation's with-value, or `{}`. */
123
185
  type NestedWithArgument<WK> = WK extends {
@@ -128,11 +190,11 @@ type NestedSelectArgument<WK> = WK extends {
128
190
  select: infer S;
129
191
  } ? S : undefined;
130
192
  /**
131
- * The `with` argument for table `T`: each relation can be `true` (load with no
132
- * refinements) or an object. `many` relations accept `where`/`orderBy`/`limit`/
133
- * `select` plus a nested `with`; `one` relations accept `select` + a nested
134
- * `with`. The reserved `_count` key requests per-relation aggregate counts.
135
- */
193
+ * The `with` argument for table `T`: each relation can be `true` (load with no
194
+ * refinements) or an object. `many` relations accept `where`/`orderBy`/`limit`/
195
+ * `select` plus a nested `with`; `one` relations accept `select` + a nested
196
+ * `with`. The reserved `_count` key requests per-relation aggregate counts.
197
+ */
136
198
  type WithArg<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
137
199
  __relationKind: "many";
138
200
  __target: infer Target extends keyof DM;
@@ -144,15 +206,15 @@ type WithArg<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [
144
206
  } ? boolean | {
145
207
  select?: ReadonlyArray<keyof DM[Target] & string>;
146
208
  with?: WithArg<DM, REL, Target>;
147
- } : never } & {
148
- _count?: { [K in keyof REL[T]]?: true };
209
+ } : never; } & {
210
+ _count?: { [K in keyof REL[T]]?: true; };
149
211
  };
150
212
  /**
151
- * Resolve a single relation descriptor + its with-value to the loaded type,
152
- * threading the nested `select` tuple into the projected child shape (the 5th
153
- * `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
154
- * `author` to the selected columns + system fields.
155
- */
213
+ * Resolve a single relation descriptor + its with-value to the loaded type,
214
+ * threading the nested `select` tuple into the projected child shape (the 5th
215
+ * `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
216
+ * `author` to the selected columns + system fields.
217
+ */
156
218
  type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
157
219
  __relationKind: "one";
158
220
  __target: infer Target extends keyof DM;
@@ -161,53 +223,53 @@ type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
161
223
  __target: infer Target extends keyof DM;
162
224
  } ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>>[] : never;
163
225
  /** The relation keys of `W` that were actually requested (not `false`/`undefined`). */
164
- type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never };
226
+ type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never; };
165
227
  /** The `_count` projection of `W`, if any. */
166
228
  type LoadedCount<W> = W extends {
167
229
  _count: infer C;
168
230
  } ? {
169
- _count: { [K in keyof C]: number };
231
+ _count: { [K in keyof C]: number; };
170
232
  } : {};
171
233
  /** System columns a `select` projection always retains, so cursors and by-id reuse keep working. */
172
234
  type SelectAlwaysKeep<DM, T extends keyof DM> = ("_creationTime" | "_id") & keyof DM[T];
173
235
  /**
174
- * `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
175
- * fields). `undefined` (the default — no `select`) keeps the full document.
176
- */
236
+ * `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
237
+ * fields). `undefined` (the default — no `select`) keeps the full document.
238
+ */
177
239
  type ProjectDoc<DM, T extends keyof DM, S> = S extends ReadonlyArray<infer K> ? (K extends keyof DM[T] ? Pick<DM[T], (K & keyof DM[T]) | SelectAlwaysKeep<DM, T>> : DM[T]) : DM[T];
178
240
  /**
179
- * `Doc&lt;T>` narrowed to exactly the relations requested in the with-arg `W` and,
180
- * when a `select` tuple `S` is supplied, to its projected columns. `S` defaults
181
- * to `undefined` so the 4-argument form (the codegen-emitted callers) keeps the
182
- * full document.
183
- */
241
+ * `Doc<T>` narrowed to exactly the relations requested in the with-arg `W` and,
242
+ * when a `select` tuple `S` is supplied, to its projected columns. `S` defaults
243
+ * to `undefined` so the 4-argument form (the codegen-emitted callers) keeps the
244
+ * full document.
245
+ */
184
246
  type LoadWith<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W, S = undefined> = LoadedCount<W> & LoadedRelations<DM, REL, T, W> & ProjectDoc<DM, T, S>;
185
247
  /** Reducer applied by an aggregate (`avg`/`count`/`max`/`min`/`sum`). */
186
248
  type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
187
249
  /**
188
- * Query-options shape shared by every aggregate reader. The RLS-aware ctx
189
- * populates `baseWhere` so it composes here without a hard import.
190
- * `restrictsCounts: true` flips `count()` into a thrown `COUNT_RLS_UNSUPPORTED`
191
- * `LunoraError` rather than silently undercount.
192
- */
250
+ * Query-options shape shared by every aggregate reader. The RLS-aware ctx
251
+ * populates `baseWhere` so it composes here without a hard import.
252
+ * `restrictsCounts: true` flips `count()` into a thrown `COUNT_RLS_UNSUPPORTED`
253
+ * `LunoraError` rather than silently undercount.
254
+ */
193
255
  interface RestrictableQueryOptions<TDocument> {
194
256
  baseWhere?: Where<TDocument>;
195
257
  restrictsCounts?: boolean;
196
258
  where?: Where<TDocument>;
197
259
  }
198
260
  /**
199
- * Relation-aware twin of {@link RestrictableQueryOptions}. The `@lunora/do`
200
- * pre-resolver now resolves relation predicates on the `count`/`aggregate`/
201
- * `groupBy` paths too (semijoin), so the typed surface threads `REL` through
202
- * `where`/`baseWhere` to match. `rank`/`rankPage` stay column-only — they use
203
- * `where` solely to pin a partition and fail closed on a relation predicate.
204
- */
261
+ * Relation-aware twin of {@link RestrictableQueryOptions}. The `@lunora/do`
262
+ * pre-resolver now resolves relation predicates on the `count`/`aggregate`/
263
+ * `groupBy` paths too (semijoin), so the typed surface threads `REL` through
264
+ * `where`/`baseWhere` to match. `rank`/`rankPage` stay column-only — they use
265
+ * `where` solely to pin a partition and fail closed on a relation predicate.
266
+ */
205
267
  interface RestrictableQueryOptionsOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> {
206
268
  baseWhere?: WhereOf<DM, REL, T>;
207
269
  restrictsCounts?: boolean;
208
270
  where?: WhereOf<DM, REL, T>;
209
271
  }
210
- /** Args for `ctx.db.&lt;table>.aggregate({ op, field?, where? })`. */
272
+ /** Args for `ctx.db.<table>.aggregate({ op, field?, where? })`. */
211
273
  interface TableAggregateOptions<TDocument> extends RestrictableQueryOptions<TDocument> {
212
274
  field?: keyof TDocument & string;
213
275
  op: AggregateOp;
@@ -217,7 +279,7 @@ interface TableAggregateOptionsOf<DM, REL extends Record<keyof DM, object>, T ex
217
279
  field?: keyof DM[T] & string;
218
280
  op: AggregateOp;
219
281
  }
220
- /** Args for `ctx.db.&lt;table>.groupBy({ by, agg?, where? })`. */
282
+ /** Args for `ctx.db.<table>.groupBy({ by, agg?, where? })`. */
221
283
  interface TableGroupByOptions<TDocument> extends RestrictableQueryOptions<TDocument> {
222
284
  agg?: {
223
285
  field?: keyof TDocument & string;
@@ -238,7 +300,7 @@ interface GroupByEntry<TDocument> {
238
300
  key: Partial<TDocument>;
239
301
  value: null | number;
240
302
  }
241
- /** Args for `ctx.db.&lt;table>.rank(name, args)`. `row` is either an id or a row doc. */
303
+ /** Args for `ctx.db.<table>.rank(name, args)`. `row` is either an id or a row doc. */
242
304
  interface TableRankOptions<TDocument> extends RestrictableQueryOptions<TDocument> {
243
305
  row: string | TDocument;
244
306
  }
@@ -247,7 +309,7 @@ interface RankResult {
247
309
  position: number;
248
310
  total: number;
249
311
  }
250
- /** Args for `ctx.db.&lt;table>.rankPage(name, args)`. */
312
+ /** Args for `ctx.db.<table>.rankPage(name, args)`. */
251
313
  interface TableRankPageOptions<TDocument> extends RestrictableQueryOptions<TDocument> {
252
314
  cursor?: null | string;
253
315
  take?: number;
@@ -259,44 +321,109 @@ interface RankPage<TDocument> {
259
321
  page: TDocument[];
260
322
  }
261
323
  /**
262
- * Builder passed to `.withSearchIndex(name, q => …)`. `.search(field, query)`
263
- * runs the full-text match against the index's searchable field; `.eq(field,
264
- * value)` narrows by a declared filter field. Field names are constrained to
265
- * the table's columns.
266
- */
324
+ * Builder passed to `.withSearchIndex(name, q => …)`. `.search(field, query)`
325
+ * runs the full-text match against the index's searchable field; `.eq(field,
326
+ * value)` narrows by a declared filter field. Field names are constrained to
327
+ * the table's columns.
328
+ */
267
329
  interface SearchFilterBuilder<TDocument> {
268
330
  eq: <F extends keyof TDocument & string>(field: F, value: TDocument[F]) => SearchFilterBuilder<TDocument>;
269
331
  search: (field: keyof TDocument & string, query: string) => SearchFilterBuilder<TDocument>;
270
332
  }
271
333
  /**
272
- * Chainable reader returned by `.withSearchIndex()` — rows come back ordered
273
- * by relevance. `.paginate()` is intentionally absent (a relevance-ordered
274
- * search can't keyset-paginate); cap the result set with `.take(n)`.
275
- */
334
+ * Chainable reader returned by `.withSearchIndex()` — rows come back ordered
335
+ * by relevance. `.paginate()` is intentionally absent (a relevance-ordered
336
+ * search can't keyset-paginate); cap the result set with `.take(n)`.
337
+ */
276
338
  interface SearchReader<TDocument> {
277
339
  collect: () => Promise<TDocument[]>;
340
+ /**
341
+ * Like `.collect()`, but pairs each matched document with the relevance
342
+ * score the FTS engine already computed to produce the descending order —
343
+ * `.collect()` throws it away after sorting by it, this surfaces it
344
+ * instead. Ordered by `score` descending, same order as `.collect()`.
345
+ */
346
+ collectWithScores: () => Promise<{
347
+ document: TDocument;
348
+ score: number;
349
+ }[]>;
350
+ first: () => Promise<TDocument | null>;
351
+ take: (limit: number) => Promise<TDocument[]>;
352
+ unique: () => Promise<TDocument | null>;
353
+ }
354
+ /** A latitude/longitude point (WGS84 decimal degrees) accepted by geo queries. */
355
+ interface GeoPointInput {
356
+ lat: number;
357
+ lng: number;
358
+ }
359
+ /** An axis-aligned latitude/longitude bounding box (`sw`/`ne` corners). */
360
+ interface GeoBoundingBox {
361
+ ne: GeoPointInput;
362
+ sw: GeoPointInput;
363
+ }
364
+ /**
365
+ * Builder passed to `.withGeoIndex(name, q => …)`. Call exactly one of
366
+ * `.near(point, radiusMeters)` (proximity, nearest-first) or `.within(box)`
367
+ * (bounding-box).
368
+ */
369
+ interface GeoFilterBuilder {
370
+ near: (point: GeoPointInput, radiusMeters: number) => GeoFilterBuilder;
371
+ within: (box: GeoBoundingBox) => GeoFilterBuilder;
372
+ }
373
+ /**
374
+ * Chainable reader returned by `.withGeoIndex()`. `.near()` results come back
375
+ * ordered nearest-first; `.within()` results by row creation time. `.paginate()`
376
+ * is intentionally absent — cap the result set with `.take(n)`.
377
+ */
378
+ interface GeoReader<TDocument> {
379
+ collect: () => Promise<TDocument[]>;
380
+ /**
381
+ * Like `.collect()`, but pairs each matched document with the distance
382
+ * (in meters) from `.near()`'s point that the read already computed to
383
+ * produce the nearest-first order. `.within()` box matches have no
384
+ * point-distance metric, so `distanceMeters` is `null` for those rows
385
+ * rather than a misleading `0`.
386
+ */
387
+ collectWithScores: () => Promise<{
388
+ distanceMeters: null | number;
389
+ document: TDocument;
390
+ }[]>;
278
391
  first: () => Promise<TDocument | null>;
279
392
  take: (limit: number) => Promise<TDocument[]>;
280
393
  unique: () => Promise<TDocument | null>;
281
394
  }
282
- /** Read-only typed table accessor exposed on `QueryCtx.db.&lt;table>`. */
283
- interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, T extends keyof DM> {
395
+ /** Read-only typed table accessor exposed on `QueryCtx.db.<table>`. */
396
+ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, T extends keyof DM, GEO extends Record<keyof DM, string> = Record<keyof DM, never>> {
284
397
  /**
285
- * Reduce rows in this table to a scalar (`avg`/`max`/`min`/`sum` — `count`
286
- * lives on its own method). Routes through a declared `aggregateIndex` when
287
- * the planner can prove the request is answerable; otherwise scans.
288
- */
398
+ * Reduce rows in this table to a scalar (`avg`/`max`/`min`/`sum` — `count`
399
+ * lives on its own method). Routes through a declared `aggregateIndex` when
400
+ * the planner can prove the request is answerable; otherwise scans.
401
+ */
289
402
  aggregate: (options: TableAggregateOptionsOf<DM, REL, T>) => Promise<null | number>;
290
403
  /**
291
- * Count rows. The planner routes `where` keys that match a declared
292
- * `aggregateIndex.by` set to the indexed counter (no scan); otherwise
293
- * falls back to a SCAN. Accepts either a bare `where` tree or the broader
294
- * `RestrictableQueryOptions` shape; the latter is the seam the RLS layer
295
- * uses to inject `baseWhere` and `restrictsCounts`.
296
- */
404
+ * Count rows. The planner routes `where` keys that match a declared
405
+ * `aggregateIndex.by` set to the indexed counter (no scan); otherwise
406
+ * falls back to a SCAN. Accepts either a bare `where` tree or the broader
407
+ * `RestrictableQueryOptions` shape; the latter is the seam the RLS layer
408
+ * uses to inject `baseWhere` and `restrictsCounts`.
409
+ */
297
410
  count: (where?: RestrictableQueryOptionsOf<DM, REL, T> | WhereOf<DM, REL, T>) => Promise<number>;
298
411
  /** `true` when at least one row matches `where` (any row when omitted). RLS-filtered exactly like `findFirst`. */
299
412
  exists: (where?: WhereOf<DM, REL, T>) => Promise<boolean>;
413
+ /**
414
+ * Describe how this table would run `findMany(args)` without running it: the SQL, its bound
415
+ * parameters, and the database's own plan, one line per step. Use it to check that a filter is
416
+ * served by an index (`SEARCH … USING INDEX by_room`) rather than a scan (`SCAN …`).
417
+ *
418
+ * Honors RLS and soft delete exactly like the read, so the plan is the one your caller would get.
419
+ * Explaining does not subscribe a live query to this table. A relation filter in `where` is resolved
420
+ * first with an ordinary read of the related table, which does subscribe to that table, since the ids
421
+ * it matched are part of `params`. Takes no `with` or `select`: neither changes the statement.
422
+ *
423
+ * `params` carries values your RLS policies injected and, for a relation filter, the ids it matched.
424
+ * Keep the result on the server rather than returning it to a client.
425
+ */
426
+ explain: (args?: QueryArgsOf<DM, REL, T>) => Promise<QueryPlan>;
300
427
  findFirst: <W extends WithArg<DM, REL, T> = {}, S extends ReadonlyArray<keyof DM[T] & string> | undefined = undefined>(args?: QueryArgsOf<DM, REL, T> & {
301
428
  select?: S;
302
429
  with?: W;
@@ -309,47 +436,67 @@ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK exten
309
436
  select?: S;
310
437
  with?: W;
311
438
  }) => Promise<QueryPage<LoadWith<DM, REL, T, W, S>>>;
439
+ /**
440
+ * The one row matching `where`, or `null` when none does — and a `NOT_UNIQUE`
441
+ * error when a SECOND one matches, so a broken uniqueness invariant surfaces at
442
+ * the read rather than as a wrong answer downstream. `findFirst` drops that
443
+ * assertion; this is the ORM spelling of the fluent reader's `.unique()`.
444
+ *
445
+ * `limit`/`cursor`/`endCursor` are not accepted rather than silently ignored: paging a read
446
+ * that must match at most one row is the assertion being dropped again.
447
+ */
448
+ findUnique: <W extends WithArg<DM, REL, T> = {}, S extends ReadonlyArray<keyof DM[T] & string> | undefined = undefined>(args?: Omit<QueryArgsOf<DM, REL, T>, "cursor" | "endCursor" | "limit"> & {
449
+ select?: S;
450
+ with?: W;
451
+ }) => Promise<LoadWith<DM, REL, T, W, S> | null>;
312
452
  get: (id: Id<string & T>) => Promise<DM[T] | null>;
313
453
  /**
314
- * Group rows by the named keys and apply `agg` per group (defaults to
315
- * `count`). Answered from the counter table when an aggregate index's
316
- * `by` matches `options.by` exactly; otherwise scans.
317
- */
454
+ * Group rows by the named keys and apply `agg` per group (defaults to
455
+ * `count`). Answered from the counter table when an aggregate index's
456
+ * `by` matches `options.by` exactly; otherwise scans.
457
+ */
318
458
  groupBy: (options: TableGroupByOptionsOf<DM, REL, T>) => Promise<ReadonlyArray<GroupByEntry<DM[T]>>>;
319
459
  /**
320
- * Return the 1-based position of `options.row` within its partition
321
- * under the declared rankIndex `indexName`, plus the partition's total
322
- * row count. `null` when the row isn't in the index. Honors the same
323
- * `baseWhere` / `restrictsCounts` RLS seam as `count()`.
324
- */
460
+ * Return the 1-based position of `options.row` within its partition
461
+ * under the declared rankIndex `indexName`, plus the partition's total
462
+ * row count. `null` when the row isn't in the index. Honors the same
463
+ * `baseWhere` / `restrictsCounts` RLS seam as `count()`.
464
+ */
325
465
  rank: (indexName: RANK[T], options: TableRankOptions<DM[T]>) => Promise<null | RankResult>;
326
466
  /**
327
- * Walk the rank companion in declared sort order — sorted pagination
328
- * accelerator. `options.where` may pin the partition; `cursor`/`take`
329
- * follow the Convex-style keyset shape.
330
- */
467
+ * Walk the rank companion in declared sort order — sorted pagination
468
+ * accelerator. `options.where` may pin the partition; `cursor`/`take`
469
+ * follow the Convex-style keyset shape.
470
+ */
331
471
  rankPage: (indexName: RANK[T], options?: TableRankPageOptions<DM[T]>) => Promise<RankPage<DM[T]>>;
332
472
  /**
333
- * Restrict the query to a declared `.searchIndex()` and run a full-text
334
- * match. `indexName` is constrained to this table's search indexes
335
- * (`never` when it declares none). Returns a relevance-ordered reader —
336
- * finish with `.take(n)` / `.collect()`.
337
- */
473
+ * Restrict the query to a declared `.geoIndex()` and run a proximity /
474
+ * bounding-box match. `indexName` is constrained to this table's geo indexes
475
+ * (`never` when it declares none). Returns a distance-ordered reader —
476
+ * finish with `.take(n)` / `.collect()`.
477
+ */
478
+ withGeoIndex: (indexName: GEO[T], build: (q: GeoFilterBuilder) => GeoFilterBuilder) => GeoReader<DM[T]>;
479
+ /**
480
+ * Restrict the query to a declared `.searchIndex()` and run a full-text
481
+ * match. `indexName` is constrained to this table's search indexes
482
+ * (`never` when it declares none). Returns a relevance-ordered reader —
483
+ * finish with `.take(n)` / `.collect()`.
484
+ */
338
485
  withSearchIndex: (indexName: SEARCH[T], search: (q: SearchFilterBuilder<DM[T]>) => SearchFilterBuilder<DM[T]>) => SearchReader<DM[T]>;
339
486
  }
340
- /** Read-write typed table accessor exposed on `MutationCtx.db.&lt;table>` / `ActionCtx.db.&lt;table>`. */
341
- interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, T extends keyof DM> extends TableReaderFacade<DM, REL, RANK, SEARCH, T> {
487
+ /** Read-write typed table accessor exposed on `MutationCtx.db.<table>` / `ActionCtx.db.<table>`. */
488
+ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, T extends keyof DM, GEO extends Record<keyof DM, string> = Record<keyof DM, never>> extends TableReaderFacade<DM, REL, RANK, SEARCH, T, GEO> {
342
489
  /**
343
- * Delete a row by id. On a `.softDelete()` table this flips the marker column
344
- * (and cascades as a soft delete) instead of removing the row; use
345
- * {@link TableWriterFacade.hardDelete} to force physical removal.
346
- */
490
+ * Delete a row by id. On a `.softDelete()` table this flips the marker column
491
+ * (and cascades as a soft delete) instead of removing the row; use
492
+ * {@link TableWriterFacade.hardDelete} to force physical removal.
493
+ */
347
494
  delete: (id: Id<string & T>) => Promise<void>;
348
495
  /**
349
- * Delete many rows in this table. Pass an array of ids (requested count is
350
- * returned; unknown ids are no-ops) or `{ where }` to delete matching rows
351
- * (actual removed count is returned). Atomic within a mutation.
352
- */
496
+ * Delete many rows in this table. Pass an array of ids (requested count is
497
+ * returned; unknown ids are no-ops) or `{ where }` to delete matching rows
498
+ * (actual removed count is returned). Atomic within a mutation.
499
+ */
353
500
  deleteMany: {
354
501
  (ids: ReadonlyArray<Id<string & T>>, options?: {
355
502
  limit?: number;
@@ -366,23 +513,23 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
366
513
  /** Physically remove a row (and physically cascade `onDelete`), bypassing `.softDelete()`. Same as `delete()` on a non-soft table. */
367
514
  hardDelete: (id: Id<string & T>) => Promise<void>;
368
515
  /**
369
- * Insert a document, returning its minted id. With `{ skipDuplicates: true }`
370
- * a UNIQUE-constraint breach resolves to `null` (the row already exists)
371
- * instead of throwing — the return type widens to `Id | null` on that overload.
372
- */
516
+ * Insert a document, returning its minted id. With `{ skipDuplicates: true }`
517
+ * a UNIQUE-constraint breach resolves to `null` (the row already exists)
518
+ * instead of throwing — the return type widens to `Id | null` on that overload.
519
+ */
373
520
  insert: {
374
- (values: IM[T], options: {
521
+ (values: InsertValues<DM, IM, REL, T>, options: {
375
522
  skipDuplicates: true;
376
523
  }): Promise<Id<string & T> | null>;
377
- (values: IM[T], options?: {
524
+ (values: InsertValues<DM, IM, REL, T>, options?: {
378
525
  skipDuplicates?: boolean;
379
526
  }): Promise<Id<string & T>>;
380
527
  };
381
528
  /**
382
- * Insert many documents into this table in one call, returning the minted ids
383
- * in input order. With `{ skipDuplicates: true }`, UNIQUE breaches resolve to
384
- * `null` for that row instead of failing the batch. Atomic within a mutation.
385
- */
529
+ * Insert many documents into this table in one call, returning the minted ids
530
+ * in input order. With `{ skipDuplicates: true }`, UNIQUE breaches resolve to
531
+ * `null` for that row instead of failing the batch. Atomic within a mutation.
532
+ */
386
533
  insertMany: {
387
534
  (values: ReadonlyArray<IM[T]>, options: {
388
535
  limit?: number;
@@ -393,16 +540,16 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
393
540
  skipDuplicates?: boolean;
394
541
  }): Promise<Id<string & T>[]>;
395
542
  };
396
- patch: (id: Id<string & T>, values: Partial<IM[T]>) => Promise<void>;
543
+ patch: (id: Id<string & T>, values: PatchValues<IM[T]> & RelationWrites<DM, REL, T>) => Promise<void>;
397
544
  /**
398
- * Patch many rows in this table. Pass an array of `{ id, values }` or
399
- * `{ where, values }` to patch matching rows with the same values. Returns
400
- * the actual patched count. Atomic within a mutation.
401
- */
545
+ * Patch many rows in this table. Pass an array of `{ id, values }` or
546
+ * `{ where, values }` to patch matching rows with the same values. Returns
547
+ * the actual patched count. Atomic within a mutation.
548
+ */
402
549
  patchMany: {
403
550
  (patches: ReadonlyArray<{
404
551
  id: Id<string & T>;
405
- values: Partial<IM[T]>;
552
+ values: PatchValues<IM[T]>;
406
553
  }>, options?: {
407
554
  limit?: number;
408
555
  }): Promise<{
@@ -410,7 +557,7 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
410
557
  }>;
411
558
  (args: {
412
559
  limit?: number;
413
- values: Partial<IM[T]>;
560
+ values: PatchValues<IM[T]>;
414
561
  where: Partial<DM[T]>;
415
562
  }): Promise<{
416
563
  patched: number;
@@ -420,15 +567,15 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
420
567
  /** Un-soft-delete a row by id: clears the `.softDelete()` marker so list reads see it again. Throws on a non-soft table. */
421
568
  restore: (id: Id<string & T>) => Promise<void>;
422
569
  /**
423
- * Insert when no existing row matches `target`, otherwise patch the match with
424
- * `update` (defaulting to `create`). `target` names a `.unique()` column (or a
425
- * tuple) used to look it up. Returns the row id and whether it was `created`.
426
- * Composes `findFirst` + `insert`/`patch`, so RLS gates each step.
427
- */
570
+ * Insert when no existing row matches `target`, otherwise patch the match with
571
+ * `update` (defaulting to `create`). `target` names a `.unique()` column (or a
572
+ * tuple) used to look it up. Returns the row id and whether it was `created`.
573
+ * Composes `findFirst` + `insert`/`patch`, so RLS gates each step.
574
+ */
428
575
  upsert: (args: {
429
- create: IM[T];
576
+ create: InsertValues<DM, IM, REL, T>;
430
577
  target: UpsertTargetOf<DM, T>;
431
- update?: Partial<IM[T]>;
578
+ update?: PatchValues<IM[T]> & RelationWrites<DM, REL, T>;
432
579
  }) => Promise<{
433
580
  created: boolean;
434
581
  id: Id<string & T>;
@@ -436,8 +583,8 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
436
583
  /** Sequential {@link TableWriterFacade.upsert} over many rows sharing one `target`; one result per input row, in order. */
437
584
  upsertMany: (args: {
438
585
  rows: ReadonlyArray<{
439
- create: IM[T];
440
- update?: Partial<IM[T]>;
586
+ create: InsertValues<DM, IM, REL, T>;
587
+ update?: PatchValues<IM[T]> & RelationWrites<DM, REL, T>;
441
588
  }>;
442
589
  target: UpsertTargetOf<DM, T>;
443
590
  }) => Promise<{
@@ -447,8 +594,106 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
447
594
  }
448
595
  /** Conflict target for `upsert`/`upsertMany`: one column of table `T`, or a tuple of them. */
449
596
  type UpsertTargetOf<DM, T extends keyof DM> = ReadonlyArray<keyof DM[T] & string> | (keyof DM[T] & string);
450
- /** Per-table read facade — `ctx.db.&lt;table>` on a `QueryCtx`. */
451
- type DatabaseReaderFacade<DM, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>> = { readonly [T in keyof DM]: TableReaderFacade<DM, REL, RANK, SEARCH, T> };
452
- /** Per-table read-write facade — `ctx.db.&lt;table>` on a `MutationCtx` / `ActionCtx`. */
453
- type DatabaseWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>> = { readonly [T in keyof DM]: TableWriterFacade<DM, IM, REL, RANK, SEARCH, T> };
454
- export { AggregateOp, DatabaseReaderFacade, DatabaseWriterFacade, GroupByEntry, Id, LoadWith, ManyRelationWhere, OneRelationWhere, OrderBy, QueryArgs, QueryArgsOf, QueryPage, RankPage, RankResult, RestrictableQueryOptions, RestrictableQueryOptionsOf, SearchFilterBuilder, SearchReader, TableAggregateOptions, TableAggregateOptionsOf, TableGroupByOptions, TableGroupByOptionsOf, TableRankOptions, TableRankPageOptions, TableReaderFacade, TableWriterFacade, UpsertTargetOf, Where, WhereOf, WhereOperators, WithArg };
597
+ /**
598
+ * An atomic update for a number column, applied to the value the row holds when the
599
+ * write runs: `{ increment: 1 }`, `{ decrement: 1 }`, `{ multiply: 2 }`, `{ divide: 2 }`.
600
+ * The column must already hold a finite number; a result that is not finite is rejected.
601
+ */
602
+ type NumberFieldOperator = {
603
+ decrement: number;
604
+ divide?: never;
605
+ increment?: never;
606
+ multiply?: never;
607
+ } | {
608
+ decrement?: never;
609
+ divide: number;
610
+ increment?: never;
611
+ multiply?: never;
612
+ } | {
613
+ decrement?: never;
614
+ divide?: never;
615
+ increment: number;
616
+ multiply?: never;
617
+ } | {
618
+ decrement?: never;
619
+ divide?: never;
620
+ increment?: never;
621
+ multiply: number;
622
+ };
623
+ /** An atomic update for a boolean column: `{ toggle: true }` flips the stored value. */
624
+ interface BooleanFieldOperator {
625
+ toggle: true;
626
+ }
627
+ /**
628
+ * The values a `patch` accepts: any column's own type, and for a number or boolean
629
+ * column also an atomic operator ({@link NumberFieldOperator}, {@link BooleanFieldOperator}).
630
+ */
631
+ type PatchValues<Row> = PathPatch<Row> & { [K in keyof Row]?: Row[K] | OperatorFor<NonNullable<Row[K]>>; };
632
+ /**
633
+ * The operator a column of type `T` takes: arithmetic when `T` is exactly `number` (so a literal union
634
+ * such as `1 | 2` is out — the result could leave the set — and so is `number | string`, which the
635
+ * store does not treat as a number column), `{ toggle: true }` when it is exactly `boolean`.
636
+ */
637
+ type OperatorFor<T> = [T] extends [number] ? [number] extends [T] ? NumberFieldOperator : never : [T] extends [boolean] ? [boolean] extends [T] ? BooleanFieldOperator : never : never;
638
+ /** What `explain` returns: the SQL a read compiles to, its bound parameters, and the database's plan for it. */
639
+ interface QueryPlan {
640
+ /** The bound parameters, in order. */
641
+ params: unknown[];
642
+ /** One line per plan step, as the database reports it. */
643
+ plan: string[];
644
+ /** The statement the read compiles to. */
645
+ sql: string;
646
+ }
647
+ /**
648
+ * Nested write for a to-one relation: point the row at `Target` (`connect`), or clear the link (`disconnect`, which
649
+ * needs a foreign key that can be empty). One or the other, not both.
650
+ */
651
+ type ToOneRelationWrite<TargetId> = {
652
+ connect: TargetId;
653
+ disconnect?: never;
654
+ } | {
655
+ connect?: never;
656
+ disconnect: true;
657
+ };
658
+ /**
659
+ * Nested write for a to-many relation: point `Target` rows at this one (`connect`), release them (`disconnect`, which
660
+ * needs a foreign key that can be empty), or replace the whole list (`set`: rows not named are released). `set`
661
+ * cannot be combined with the other two.
662
+ */
663
+ type ToManyRelationWrite<TargetId> = {
664
+ connect?: never;
665
+ disconnect?: never;
666
+ set: ReadonlyArray<TargetId>;
667
+ } | {
668
+ connect?: ReadonlyArray<TargetId>;
669
+ disconnect?: ReadonlyArray<TargetId>;
670
+ set?: never;
671
+ };
672
+ /**
673
+ * Nested relation writes accepted by `insert`, `patch` and `upsert`, keyed by relation name:
674
+ * `{ author: { connect: userId } }`, `{ posts: { set: [a, b] } }`. A table with no relations contributes none
675
+ * (`unknown`, the identity for `&`, never `{}`: an empty object type would switch off the weak-type check).
676
+ */
677
+ type RelationWrites<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = [keyof REL[T]] extends [never] ? unknown : { [K in keyof REL[T]]?: REL[T][K] extends {
678
+ __relationKind: "one";
679
+ __target: infer Target extends keyof DM;
680
+ } ? ToOneRelationWrite<Id<string & Target>> : REL[T][K] extends {
681
+ __relationKind: "many";
682
+ __target: infer Target extends keyof DM;
683
+ } ? ToManyRelationWrite<Id<string & Target>> : never; };
684
+ /** The foreign-key columns of a table's to-one relations — the keys a nested `connect` supplies. */
685
+ type OneRelationFields<RelT> = { [K in keyof RelT]: RelT[K] extends {
686
+ __field: infer Field extends string;
687
+ __relationKind: "one";
688
+ } ? Field : never; }[keyof RelT];
689
+ /**
690
+ * What `insert` accepts: the row as it is, or the row without its to-one foreign keys plus the nested writes that
691
+ * supply them. Leaving a key out with no `connect` to supply it is not caught by the type — the store's own
692
+ * validation rejects the missing field.
693
+ */
694
+ type InsertValues<DM, IM extends Record<keyof DM, object>, REL extends Record<keyof DM, object>, T extends keyof DM> = IM[T] | (Omit<IM[T], OneRelationFields<REL[T]>> & RelationWrites<DM, REL, T>);
695
+ /** Per-table read facade — `ctx.db.<table>` on a `QueryCtx`. */
696
+ type DatabaseReaderFacade<DM, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, GEO extends Record<keyof DM, string> = Record<keyof DM, never>> = { readonly [T in keyof DM]: TableReaderFacade<DM, REL, RANK, SEARCH, T, GEO>; };
697
+ /** Per-table read-write facade — `ctx.db.<table>` on a `MutationCtx` / `ActionCtx`. */
698
+ type DatabaseWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends Record<keyof DM, object>, RANK extends Record<keyof DM, string>, SEARCH extends Record<keyof DM, string>, GEO extends Record<keyof DM, string> = Record<keyof DM, never>> = { readonly [T in keyof DM]: TableWriterFacade<DM, IM, REL, RANK, SEARCH, T, GEO>; };
699
+ export { AggregateOp, DatabaseReaderFacade, DatabaseWriterFacade, GeoBoundingBox, GeoFilterBuilder, GeoPointInput, GeoReader, GroupByEntry, Id, InsertValues, LoadWith, ManyRelationWhere, OneRelationWhere, OrderBy, PatchValues, QueryArgs, QueryArgsOf, QueryPage, QueryPlan, RankPage, RankResult, RelationWrites, RestrictableQueryOptions, RestrictableQueryOptionsOf, SearchFilterBuilder, SearchReader, TableAggregateOptions, TableAggregateOptionsOf, TableGroupByOptions, TableGroupByOptionsOf, TableRankOptions, TableRankPageOptions, TableReaderFacade, TableWriterFacade, ToManyRelationWrite, ToOneRelationWrite, UpsertTargetOf, Where, WhereOf, WhereOperators, WithArg };