primitive-functions 0.3.0-alpha.17 → 0.3.0-alpha.19

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/index.d.ts CHANGED
@@ -1126,7 +1126,6 @@ export interface FunctionApi {
1126
1126
  description?: unknown;
1127
1127
  name?: unknown;
1128
1128
  preset?: unknown;
1129
- ruleSetId?: unknown;
1130
1129
  ttlTier?: unknown;
1131
1130
  };
1132
1131
  }): Promise<{
@@ -1137,7 +1136,7 @@ export interface FunctionApi {
1137
1136
  description?: string | null;
1138
1137
  ttlTier: string;
1139
1138
  preset: string | null;
1140
- ruleSetId: string | null;
1139
+ convertedFromRuleSet: boolean;
1141
1140
  createdBy?: string | null;
1142
1141
  createdAt?: string | null;
1143
1142
  modifiedAt?: string | null;
@@ -1166,18 +1165,44 @@ export interface FunctionApi {
1166
1165
  }): Promise<{
1167
1166
  deleted: boolean;
1168
1167
  }>;
1169
- /** `blobBuckets.download` — GET /blob-buckets/{bucketId}/blobs/{blobId}. Download a blob (anonymous allowed for public buckets) */
1168
+ /** `blobBuckets.download` — GET /blob-buckets/{bucketId}/blobs/{blobId}/download. Download a blob's bytes (anonymous allowed for public buckets) */
1170
1169
  "download"(args: {
1171
1170
  "bucketId": string | number;
1172
1171
  "blobId": string | number;
1173
1172
  "disposition"?: string | number | boolean;
1174
1173
  }): Promise<Uint8Array>;
1174
+ /** `blobBuckets.downloadHeaders` — HEAD /blob-buckets/{bucketId}/blobs/{blobId}/download. Get a blob's download headers (anonymous allowed for public buckets) */
1175
+ "downloadHeaders"(args: {
1176
+ "bucketId": string | number;
1177
+ "blobId": string | number;
1178
+ "disposition"?: string | number | boolean;
1179
+ }): Promise<HeaderResult>;
1175
1180
  /** `blobBuckets.downloadSigned` — GET /blob-buckets/{bucketId}/blobs/{blobId}/signed. Download a blob via a signed URL token */
1176
1181
  "downloadSigned"(args: {
1177
1182
  "bucketId": string | number;
1178
1183
  "blobId": string | number;
1179
1184
  "token"?: string | number | boolean;
1185
+ "disposition"?: string | number | boolean;
1180
1186
  }): Promise<Uint8Array>;
1187
+ /** `blobBuckets.get` — GET /blob-buckets/{bucketId}/blobs/{blobId}. Get a blob's metadata (anonymous allowed for public buckets) */
1188
+ "get"(args: {
1189
+ "bucketId": string | number;
1190
+ "blobId": string | number;
1191
+ }): Promise<{
1192
+ blobId: string | null;
1193
+ bucketId: string;
1194
+ filename: string | null;
1195
+ contentType: string | null;
1196
+ numBytes: number;
1197
+ sha256: string | null;
1198
+ tags: string[];
1199
+ /** The member who uploaded the blob; null when the app (a server function) did */
1200
+ createdBy: string | null;
1201
+ /** When the blob was stored, ISO 8601 */
1202
+ createdAt: string | null;
1203
+ /** The entity tag the download answers */
1204
+ etag: string | null;
1205
+ }>;
1181
1206
  /** `blobBuckets.getBucket` — GET /blob-buckets/{bucketId}. Get a blob bucket by id */
1182
1207
  "getBucket"(args: {
1183
1208
  "bucketId": string | number;
@@ -1189,27 +1214,11 @@ export interface FunctionApi {
1189
1214
  description?: string | null;
1190
1215
  ttlTier: string;
1191
1216
  preset: string | null;
1192
- ruleSetId: string | null;
1217
+ convertedFromRuleSet: boolean;
1193
1218
  createdBy?: string | null;
1194
1219
  createdAt?: string | null;
1195
1220
  modifiedAt?: string | null;
1196
1221
  }>;
1197
- /** `blobBuckets.getMetadata` — GET /blob-buckets/{bucketId}/blobs/{blobId}/metadata. Get blob metadata (anonymous allowed for public buckets) */
1198
- "getMetadata"(args: {
1199
- "bucketId": string | number;
1200
- "blobId": string | number;
1201
- }): Promise<{
1202
- blobId: string | null;
1203
- bucketId: string;
1204
- filename: string | null;
1205
- contentType: string | null;
1206
- numBytes: number;
1207
- sha256?: string | null;
1208
- tags?: string[];
1209
- createdBy?: string | null;
1210
- uploaded?: string | null;
1211
- etag?: string | null;
1212
- }>;
1213
1222
  /** `blobBuckets.getSignedUrl` — POST /blob-buckets/{bucketId}/blobs/{blobId}/signed-url. Create a signed download URL for a blob */
1214
1223
  "getSignedUrl"(args: {
1215
1224
  "bucketId": string | number;
@@ -1232,7 +1241,7 @@ export interface FunctionApi {
1232
1241
  body: {
1233
1242
  /** The blobs to sign, 0 to 100 non-empty ids */
1234
1243
  blobIds: string[];
1235
- /** How long every URL works, in seconds: 30 to 86,400; 300 when absent */
1244
+ /** How long every URL works, in seconds: 30 to 86,400 (3,600 in a signed-out run); 300 when absent */
1236
1245
  expiresInSeconds?: number;
1237
1246
  };
1238
1247
  }): Promise<{
@@ -1260,11 +1269,14 @@ export interface FunctionApi {
1260
1269
  filename: string | null;
1261
1270
  contentType: string | null;
1262
1271
  numBytes: number;
1263
- sha256?: string | null;
1264
- tags?: string[];
1265
- createdBy?: string | null;
1266
- uploaded?: string | null;
1267
- etag?: string | null;
1272
+ sha256: string | null;
1273
+ tags: string[];
1274
+ /** The member who uploaded the blob; null when the app (a server function) did */
1275
+ createdBy: string | null;
1276
+ /** When the blob was stored, ISO 8601 */
1277
+ createdAt: string | null;
1278
+ /** The entity tag the download answers */
1279
+ etag: string | null;
1268
1280
  }[];
1269
1281
  hasMore: boolean;
1270
1282
  nextCursor?: string;
@@ -1280,7 +1292,7 @@ export interface FunctionApi {
1280
1292
  description?: string | null;
1281
1293
  ttlTier: string;
1282
1294
  preset: string | null;
1283
- ruleSetId: string | null;
1295
+ convertedFromRuleSet: boolean;
1284
1296
  createdBy?: string | null;
1285
1297
  createdAt?: string | null;
1286
1298
  modifiedAt?: string | null;
@@ -1294,7 +1306,6 @@ export interface FunctionApi {
1294
1306
  expectedModifiedAt?: unknown;
1295
1307
  name?: unknown;
1296
1308
  preset?: unknown;
1297
- ruleSetId?: unknown;
1298
1309
  };
1299
1310
  }): Promise<{
1300
1311
  bucketId: string;
@@ -1304,27 +1315,37 @@ export interface FunctionApi {
1304
1315
  description?: string | null;
1305
1316
  ttlTier: string;
1306
1317
  preset: string | null;
1307
- ruleSetId: string | null;
1318
+ convertedFromRuleSet: boolean;
1308
1319
  createdBy?: string | null;
1309
1320
  createdAt?: string | null;
1310
1321
  modifiedAt?: string | null;
1311
1322
  }>;
1312
- /** `blobBuckets.upload` — POST /blob-buckets/{bucketId}/blobs. Upload a blob to a bucket */
1323
+ /** `blobBuckets.upload` — PUT /blob-buckets/{bucketId}/blobs/{blobId}. Upload a blob to a bucket under a caller-chosen id (immutable + idempotent) */
1313
1324
  "upload"(args: {
1314
1325
  "bucketId": string | number;
1326
+ "blobId": string | number;
1315
1327
  "X-Blob-Filename": string | number;
1328
+ "X-Blob-Size": string | number;
1329
+ "X-Blob-Sha256": string | number;
1316
1330
  "X-Blob-Tags"?: string | number;
1317
1331
  "Content-Type"?: string | number;
1318
1332
  body: ArrayBuffer | Uint8Array | string;
1319
1333
  }): Promise<{
1320
- blobId: string;
1334
+ blobId: string | null;
1321
1335
  bucketId: string;
1322
- filename: string;
1323
- contentType: string;
1336
+ filename: string | null;
1337
+ contentType: string | null;
1324
1338
  numBytes: number;
1325
- sha256?: string | null;
1326
- tags?: string[];
1327
- createdBy?: string | null;
1339
+ sha256: string | null;
1340
+ tags: string[];
1341
+ /** The member who uploaded the blob; null when the app (a server function) did */
1342
+ createdBy: string | null;
1343
+ /** When the blob was stored, ISO 8601 */
1344
+ createdAt: string | null;
1345
+ /** The entity tag the download answers */
1346
+ etag: string | null;
1347
+ /** 0 on the idempotent 200; the stored length on a 201 */
1348
+ bytesTransferred: number;
1328
1349
  }>;
1329
1350
  };
1330
1351
  "channels": {
@@ -10816,16 +10837,24 @@ export type Db3QueriesOf<K extends string> = Db3FilterTyping extends { enforced:
10816
10837
  : {}
10817
10838
  : {};
10818
10839
 
10840
+ /**
10841
+ * Each model's filter type in `TQueries` (a `Db3QueriesOf`), by model name,
10842
+ * and `Record<string, unknown>` for a name it has no entry for.
10843
+ */
10844
+ export type Db3FilterMap<TQueries> = {
10845
+ [N in keyof TQueries]: TQueries[N] extends { filter: infer F } ? F : Record<string, unknown>;
10846
+ } & { [name: string]: Record<string, unknown> };
10847
+
10819
10848
  /**
10820
10849
  * Model `M`'s filter type when `TQueries` (a `Db3QueriesOf`) types it,
10821
10850
  * `Record<string, unknown>` otherwise. Only the `filter` members read it,
10822
10851
  * so a model name a generic helper passes on leaves every other option open.
10852
+ * For a generic `M`, a literal filter is checked against every model `M`
10853
+ * may be: it compiles when each of them takes it.
10823
10854
  */
10824
- export type Db3ModelFilterOf<TQueries, M extends string> = M extends keyof TQueries
10825
- ? TQueries[M] extends { filter: infer F }
10826
- ? F
10827
- : Record<string, unknown>
10828
- : Record<string, unknown>;
10855
+ export type Db3ModelFilterOf<TQueries, M extends string> = [keyof TQueries] extends [never]
10856
+ ? Record<string, unknown>
10857
+ : Db3FilterMap<TQueries>[M];
10829
10858
 
10830
10859
  /**
10831
10860
  * The names an upsert of model `M` takes when `TQueries` types them (its
@@ -10847,12 +10876,22 @@ export type Db3ModelUniqueOf<TQueries, M extends string> = M extends keyof TQuer
10847
10876
  */
10848
10877
  export type Db3UpsertName<TName extends string, TUnique> = string extends TName ? TName : TUnique;
10849
10878
 
10850
- /** Model `M`'s sort type when `TQueries` types it, `Record<string, 1 | -1>` otherwise. */
10851
- export type Db3ModelSortOf<TQueries, M extends string> = M extends keyof TQueries
10852
- ? TQueries[M] extends { sort: infer S }
10853
- ? S
10854
- : Record<string, 1 | -1>
10855
- : Record<string, 1 | -1>;
10879
+ /**
10880
+ * Each model's sort type in `TQueries`, by model name, and
10881
+ * `Record<string, 1 | -1>` for a name it has no entry for.
10882
+ */
10883
+ export type Db3SortMap<TQueries> = {
10884
+ [N in keyof TQueries]: TQueries[N] extends { sort: infer S } ? S : Record<string, 1 | -1>;
10885
+ } & { [name: string]: Record<string, 1 | -1> };
10886
+
10887
+ /**
10888
+ * Model `M`'s sort type when `TQueries` types it, `Record<string, 1 | -1>`
10889
+ * otherwise. For a generic `M`, a literal sort is checked against every
10890
+ * model `M` may be.
10891
+ */
10892
+ export type Db3ModelSortOf<TQueries, M extends string> = [keyof TQueries] extends [never]
10893
+ ? Record<string, 1 | -1>
10894
+ : Db3SortMap<TQueries>[M];
10856
10895
 
10857
10896
  /**
10858
10897
  * What a db3 model handle's `query` takes: `DocumentQueryOptions`, with model
@@ -10959,11 +10998,26 @@ export interface Db3MemberOperators {
10959
10998
  $contains?: string;
10960
10999
  }
10961
11000
 
11001
+ /**
11002
+ * What marks a condition as operators: a plain object, never a string, a
11003
+ * number, a boolean, a list or a `Date`. A filter checked against several
11004
+ * models at once (a generic model name's) then never reads a value one
11005
+ * model's field takes as another model's operators.
11006
+ */
11007
+ export interface Db3OperatorsObject {
11008
+ length?: never;
11009
+ getTime?: never;
11010
+ toFixed?: never;
11011
+ charAt?: never;
11012
+ valueOf?: () => object;
11013
+ }
11014
+
10962
11015
  /** The operators a field of kind `K` takes. */
10963
11016
  export type Db3FieldOperators<K extends Db3FieldKind> = Db3CommonOperators<Db3FieldValue<K>> &
10964
11017
  (K extends "id" | "string" | "number" | "date" ? Db3RangeOperators<Db3FieldValue<K>> : {}) &
10965
11018
  (K extends "string" | "stringset" ? Db3SubstringOperators : {}) &
10966
- (K extends "stringset" ? Db3MemberOperators : {});
11019
+ (K extends "stringset" ? Db3MemberOperators : {}) &
11020
+ Db3OperatorsObject;
10967
11021
 
10968
11022
  /** A condition on a field of kind `K`: a value (equality), a list (`$in`), or operators. */
10969
11023
  export type Db3Condition<K extends Db3FieldKind> =
@@ -11129,15 +11183,141 @@ export type Db3BatchReadOp =
11129
11183
  /** One read of a handle-level `batch` or `batchRead`: it names its `model`. */
11130
11184
  export type Db3HandleBatchReadOp<TModels> = Db3BatchReadOp & { model: Db3ModelNames<TModels> };
11131
11185
 
11186
+ /** What a read of a db3 batch does: `query`, `count` or `aggregate`. */
11187
+ export type Db3BatchReadAction = Db3BatchReadOp["action"];
11188
+
11189
+ /** A read of a db3 batch the db3 refused, answered in its place with `atomic: false`. */
11190
+ export interface Db3BatchReadRefusal<TModel extends string = string> {
11191
+ index: number;
11192
+ model: TModel;
11193
+ action: string;
11194
+ ok: false;
11195
+ code: string;
11196
+ status: number;
11197
+ error: string;
11198
+ details?: Record<string, unknown>;
11199
+ }
11200
+
11201
+ /**
11202
+ * One read's result in a db3 batch, at its `index`: a query's page of
11203
+ * `TRow` rows, a count or an aggregate's rows, for each action in
11204
+ * `TAction`, or, with `atomic: false`, the read's refusal. Narrowing on
11205
+ * `ok` reaches the answered shape. Written with no type arguments it is
11206
+ * any read's result.
11207
+ *
11208
+ * ```ts
11209
+ * const { results } = await ctx.db3(id, "household").batchRead([{ model: "account", action: "query" }]);
11210
+ * const accounts = results[0];
11211
+ * if (accounts.ok) for (const row of accounts.items) console.log(row.name);
11212
+ * else console.warn(accounts.code);
11213
+ * ```
11214
+ */
11215
+ export type Db3BatchReadResult<TRow = Record<string, any>, TAction extends string = Db3BatchReadAction, TModel extends string = string> =
11216
+ | ("query" extends TAction ? { index: number; model: TModel; action: "query"; ok: true; items: Array<TRow & { _related?: Record<string, any> }>; hasMore: boolean; nextCursor?: string; prevCursor?: string } : never)
11217
+ | ("count" extends TAction ? { index: number; model: TModel; action: "count"; ok: true; count: number } : never)
11218
+ | ("aggregate" extends TAction ? { index: number; model: TModel; action: "aggregate"; ok: true; result: any[] } : never)
11219
+ | Db3BatchReadRefusal<TModel>;
11220
+
11221
+ /** The read actions a position's `action` names: every one when it names none of them. */
11222
+ export type Db3BatchReadActionOf<TAction> = Extract<TAction, Db3BatchReadAction> extends never ? Db3BatchReadAction : Extract<TAction, Db3BatchReadAction>;
11223
+
11224
+ /**
11225
+ * The result of one handle-level read of model `TModel` with `TAction`:
11226
+ * the row is the one `model(m).query()` gives. A union of models gives the
11227
+ * union of their results.
11228
+ */
11229
+ export type Db3HandleBatchReadResultOf<TModels, TModel, TAction> = [TModel] extends [string]
11230
+ ? TModel extends string
11231
+ ? Db3BatchReadResult<Db3ModelRow<TModels, TModel>, Db3BatchReadActionOf<TAction>, TModel>
11232
+ : never
11233
+ : Db3HandleBatchReadResultOf<TModels, Db3ModelNames<TModels>, TAction>;
11234
+
11132
11235
  /**
11133
- * One read's result in a db3 batch, at its `index`: a query's page, a count or
11134
- * an aggregate's rows, or, with `atomic: false`, the read's refusal.
11236
+ * What an op's `action` makes of its position in a batch's reads: `"read"`
11237
+ * when it names only reads, `"write"` when it names none, `"either"` when
11238
+ * it may be one or the other. A union of reads is one position, its result
11239
+ * the union of theirs.
11135
11240
  */
11136
- export type Db3BatchReadResult =
11137
- | { index: number; model: string; action: "query"; ok: true; items: Array<Record<string, any>>; hasMore: boolean; nextCursor?: string; prevCursor?: string }
11138
- | { index: number; model: string; action: "count"; ok: true; count: number }
11139
- | { index: number; model: string; action: "aggregate"; ok: true; result: any[] }
11140
- | { index: number; model: string; action: string; ok: false; code: string; status: number; error: string; details?: Record<string, unknown> };
11241
+ export type Db3BatchReadPosition<TAction> = [Extract<TAction, Db3BatchReadAction>] extends [never]
11242
+ ? "write"
11243
+ : [Exclude<TAction, Db3BatchReadAction>] extends [never]
11244
+ ? "read"
11245
+ : "either";
11246
+
11247
+ /**
11248
+ * The result one op of a non-literal handle-level op list can give, its
11249
+ * `model` kept with its `action`: a write gives none.
11250
+ */
11251
+ export type Db3HandleBatchOpReadResultOf<TModels, TOp> = TOp extends { model: infer M; action: infer A }
11252
+ ? string extends A
11253
+ ? Db3HandleBatchReadResultOf<TModels, M, Db3BatchReadAction>
11254
+ : [Extract<A, Db3BatchReadAction>] extends [never]
11255
+ ? never
11256
+ : Db3HandleBatchReadResultOf<TModels, M, Extract<A, Db3BatchReadAction>>
11257
+ : never;
11258
+
11259
+ /**
11260
+ * The results of a handle-level batch's reads, in op order: `TModelsAt` and
11261
+ * `TActionsAt` hold each op's `model` and `action`, and a write's
11262
+ * position is skipped. A list that is not a literal is answered by `TOp`,
11263
+ * its element, so each read keeps its own model and action. Once an op may be
11264
+ * a read or a write, the positions after it are not known and the reads are
11265
+ * an array.
11266
+ */
11267
+ export type Db3HandleBatchReadsOf<TModels, TModelsAt extends readonly unknown[], TActionsAt extends readonly unknown[], TOp = unknown, TDone extends unknown[] = [], TOpen extends boolean = false> =
11268
+ number extends TActionsAt["length"]
11269
+ ? unknown extends TOp
11270
+ ? Array<Db3HandleBatchReadResultOf<TModels, TModelsAt[number], TActionsAt[number]>>
11271
+ : Array<Db3HandleBatchOpReadResultOf<TModels, TOp>>
11272
+ : TActionsAt extends readonly [infer A, ...infer RestA]
11273
+ ? Db3HandleBatchReadsOf<
11274
+ TModels,
11275
+ TModelsAt extends readonly [unknown, ...infer RestM] ? RestM : [],
11276
+ RestA,
11277
+ TOp,
11278
+ Db3BatchReadPosition<A> extends "write"
11279
+ ? TDone
11280
+ : [...TDone, Db3HandleBatchReadResultOf<TModels, TModelsAt extends readonly [infer M, ...unknown[]] ? M : unknown, Extract<A, Db3BatchReadAction>>],
11281
+ Db3BatchReadPosition<A> extends "either" ? true : TOpen
11282
+ >
11283
+ : TOpen extends true
11284
+ ? Array<TDone[number]>
11285
+ : TDone;
11286
+
11287
+ /**
11288
+ * The results of a model's batch reads, in op order, typed to the model's
11289
+ * `TRow`: `TActionsAt` holds each op's `action`, and a write's position
11290
+ * is skipped. Once an op may be a read or a write, the reads are an array.
11291
+ */
11292
+ export type Db3BatchReadsOf<TRow, TActionsAt extends readonly unknown[], TDone extends unknown[] = [], TOpen extends boolean = false> =
11293
+ number extends TActionsAt["length"]
11294
+ ? Array<Db3BatchReadResult<TRow, Db3BatchReadActionOf<TActionsAt[number]>>>
11295
+ : TActionsAt extends readonly [infer A, ...infer RestA]
11296
+ ? Db3BatchReadsOf<
11297
+ TRow,
11298
+ RestA,
11299
+ Db3BatchReadPosition<A> extends "write" ? TDone : [...TDone, Db3BatchReadResult<TRow, Extract<A, Db3BatchReadAction>>],
11300
+ Db3BatchReadPosition<A> extends "either" ? true : TOpen
11301
+ >
11302
+ : TOpen extends true
11303
+ ? Array<TDone[number]>
11304
+ : TDone;
11305
+
11306
+ /**
11307
+ * The element of a handle-level op list that is not a literal, inferred so
11308
+ * each op's `model` stays with its `action`; a literal list, whose
11309
+ * positions are known, adds nothing here.
11310
+ */
11311
+ export type Db3BatchOpsElement<TActionsAt extends readonly unknown[], TOp> = number extends TActionsAt["length"] ? readonly TOp[] : unknown;
11312
+
11313
+ /** Each op's `action`, by position, as a batch call infers them. */
11314
+ export type Db3BatchActionsAt<TActionsAt extends readonly unknown[]> = { [K in keyof TActionsAt]: { action: TActionsAt[K] } };
11315
+
11316
+ /** Each op's `model`, by position, as a handle-level batch call infers them. */
11317
+ export type Db3BatchModelsAt<TModelsAt extends readonly unknown[]> = { [K in keyof TModelsAt]: { model: TModelsAt[K] } };
11318
+
11319
+ /** The reads of a handle-level `batchRead`, each checked as `Db3HandleBatchReadOp` is, its `model` inferred by position. */
11320
+ export type Db3HandleBatchReadsAt<TModels, TModelsAt extends readonly unknown[]> = { [K in keyof TModelsAt]: Db3HandleBatchReadOp<TModels> & { model: TModelsAt[K] } };
11141
11321
 
11142
11322
  /**
11143
11323
  * What a db3 call cost on the server, in SQLite rows. Each figure is `null`
@@ -11153,8 +11333,8 @@ export interface Db3Cost {
11153
11333
  }
11154
11334
 
11155
11335
  /** What `db3.records.batchRead` answers: one result per read, in order, and what reading them cost. */
11156
- export interface Db3BatchReadResponse {
11157
- results: Db3BatchReadResult[];
11336
+ export interface Db3BatchReadResponse<TResults extends readonly unknown[] = Db3BatchReadResult[]> {
11337
+ results: TResults;
11158
11338
  cost?: Db3Cost;
11159
11339
  }
11160
11340
 
@@ -11163,7 +11343,7 @@ export interface Db3BatchReadResponse {
11163
11343
  * its own and `results` names each write, a refused one carrying its `code`;
11164
11344
  * `reads` answers each read, against the writes before it.
11165
11345
  */
11166
- export interface Db3BatchResult {
11346
+ export interface Db3BatchResult<TReads extends readonly unknown[] = Db3BatchReadResult[]> {
11167
11347
  applied: number;
11168
11348
  added: Array<{ model: string; id: string; appliedFields?: Record<string, unknown> }>;
11169
11349
  updated: Array<{ model: string; id: string; appliedFields?: Record<string, unknown> }>;
@@ -11175,7 +11355,7 @@ export interface Db3BatchResult {
11175
11355
  | { index: number; model: string; id: string; ok: true; kind: string; values?: Record<string, number>; appliedFields?: Record<string, unknown>; requestId?: string }
11176
11356
  | { index: number; model: string; id?: string; ok: false; code: string; status: number; error: string; reason?: string; requestId?: string }
11177
11357
  >;
11178
- reads?: Db3BatchReadResult[];
11358
+ reads?: TReads;
11179
11359
  requestId?: string;
11180
11360
  cost?: Db3Cost;
11181
11361
  }
@@ -11255,15 +11435,125 @@ export interface Db3ModelHandle<TRow, TQuery = DocumentQueryOptions, TCount = {
11255
11435
  * or each on its own with `atomic: false`.
11256
11436
  * @beta
11257
11437
  */
11258
- batch<TConstraints extends readonly unknown[] = unknown[]>(
11259
- ops: [...Db3BatchOps<TRow, TUnique, TConstraints>],
11438
+ batch<TConstraints extends readonly unknown[] = unknown[], const TActionsAt extends readonly unknown[] = unknown[]>(
11439
+ ops: [...Db3BatchOps<TRow, TUnique, TConstraints>] & [...Db3BatchActionsAt<TActionsAt>],
11260
11440
  options?: { atomic?: boolean; requestId?: string }
11261
- ): Promise<Db3BatchResult>;
11441
+ ): Promise<Db3BatchResult<Db3BatchReadsOf<TRow, TActionsAt>>>;
11262
11442
  /**
11263
- * Several reads of this model in one request, answered from one state of the db3.
11443
+ * Several reads of this model in one request, answered from one state of
11444
+ * the db3: one result per read, in order, typed by the read's action.
11264
11445
  * @beta
11265
11446
  */
11266
- batchRead(reads: Db3BatchReadOp[], options?: { atomic?: boolean }): Promise<Db3BatchReadResponse>;
11447
+ batchRead<const TActionsAt extends readonly Db3BatchReadAction[] = Db3BatchReadAction[]>(
11448
+ reads: readonly [...{ [K in keyof TActionsAt]: Db3BatchReadOp & { action: TActionsAt[K] } }],
11449
+ options?: { atomic?: boolean }
11450
+ ): Promise<Db3BatchReadResponse<Db3BatchReadsOf<TRow, TActionsAt>>>;
11451
+ }
11452
+
11453
+ /**
11454
+ * Where a db3 bulk load's session is: `uploading` until committed, then the
11455
+ * room's apply states, and one of `complete`, `failed` or `aborted` once
11456
+ * it has ended.
11457
+ */
11458
+ export type Db3LoadState =
11459
+ | "uploading"
11460
+ | "committed"
11461
+ | "validating"
11462
+ | "staging"
11463
+ | "applying"
11464
+ | "finalizing"
11465
+ | "registering"
11466
+ | "complete"
11467
+ | "failed"
11468
+ | "aborted";
11469
+
11470
+ /**
11471
+ * A row a db3 bulk load refused: its model and id, and why (`code`, and the
11472
+ * unique `constraint` and `conflicting` record of a unique-key refusal).
11473
+ */
11474
+ export interface Db3LoadRefusedRow {
11475
+ model: string;
11476
+ id: string;
11477
+ code: string;
11478
+ constraint?: string;
11479
+ conflicting?: { model: string; id: string };
11480
+ /** The room's own words, where it gave them. */
11481
+ reason?: string;
11482
+ }
11483
+
11484
+ /**
11485
+ * What `load` and `loadStatus` answer: the session and its figures so far.
11486
+ * `done` is true once `state` is `complete`, `failed` or `aborted`; a
11487
+ * load whose wait ended first answers `done: false`, and `loadStatus` reads
11488
+ * it again. On a merge that is `complete`, `applied + refusedRows` is
11489
+ * `rows`.
11490
+ */
11491
+ export interface Db3LoadResult {
11492
+ /** The session's id; null only for a load with nothing to send. */
11493
+ sessionId: string | null;
11494
+ state: Db3LoadState;
11495
+ done: boolean;
11496
+ mode: "merge" | "refresh";
11497
+ /** Rows sent. */
11498
+ rows: number;
11499
+ chunks: number;
11500
+ /** Rows the db3 took so far. */
11501
+ applied: number;
11502
+ /** Rows the db3 refused so far. */
11503
+ refusedRows: number;
11504
+ /** The first 20 refused rows; `loadRefused` pages them all. */
11505
+ refused: Db3LoadRefusedRow[];
11506
+ /** Why a `failed` session failed; null otherwise. */
11507
+ failure: { code: string; reason: string; rows?: { model: string; id: string }[] } | null;
11508
+ }
11509
+
11510
+ /**
11511
+ * A load row's fields: any of the model's fields, each optional, an optional
11512
+ * one also taking `null`, and no `_deleted`.
11513
+ */
11514
+ export type Db3LoadPatch<TRow> = {
11515
+ [K in Exclude<keyof TRow, "id">]?: TRow[K] | (undefined extends TRow[K] ? null : never);
11516
+ } & { _deleted?: never };
11517
+
11518
+ /** A load row that deletes its record: exactly `{ _deleted: true }`. */
11519
+ export type Db3LoadDelete<TRow> = { _deleted: true } & { [K in Exclude<keyof TRow, "id">]?: never };
11520
+
11521
+ /**
11522
+ * One row of a db3 bulk load: a model the type declares, the record's id, and
11523
+ * either a patch of that model's fields or a delete. Open on a db3 type that
11524
+ * declares no models.
11525
+ */
11526
+ export type Db3LoadRow<TModels> = string extends Db3ModelNames<TModels>
11527
+ ? { model: string; id: string; patch: Record<string, unknown> }
11528
+ : {
11529
+ [M in Db3ModelNames<TModels>]: {
11530
+ model: M;
11531
+ id: string;
11532
+ patch: Db3LoadPatch<Db3ModelRow<TModels, M>> | Db3LoadDelete<Db3ModelRow<TModels, M>>;
11533
+ };
11534
+ }[Db3ModelNames<TModels>];
11535
+
11536
+ /** How a db3 bulk load runs. */
11537
+ export interface Db3LoadOptions<TModelName extends string = string> {
11538
+ /** `merge` (the default) writes each row over its record; `refresh` also removes the records of a covered model that no row names. */
11539
+ mode?: "merge" | "refresh";
11540
+ /** The models a refresh covers, beside the ones its rows name. */
11541
+ models?: TModelName[];
11542
+ /** When the load's epoch is reserved: `open` (the default) or `commit`. */
11543
+ reserveEpoch?: "open" | "commit";
11544
+ /**
11545
+ * The longest the call waits after its commit for the load to finish, in
11546
+ * milliseconds: an integer from 0 to 600,000, 20,000 by default. The wait
11547
+ * also ends 1,000 ms before the invocation's own deadline.
11548
+ */
11549
+ waitMs?: number;
11550
+ }
11551
+
11552
+ /** One page of a load's refused rows. */
11553
+ export interface Db3LoadRefusedPage {
11554
+ items: Db3LoadRefusedRow[];
11555
+ hasMore: boolean;
11556
+ nextCursor?: string;
11267
11557
  }
11268
11558
 
11269
11559
  /**
@@ -11284,15 +11574,59 @@ export interface Db3Handle<TModels, TQueries = {}> {
11284
11574
  * Writes and reads across models in one request (at most 100); each op names its `model`.
11285
11575
  * @beta
11286
11576
  */
11287
- batch<TConstraints extends readonly unknown[] = unknown[]>(
11288
- ops: [...Db3HandleBatchOps<TModels, TQueries, TConstraints>],
11577
+ batch<TConstraints extends readonly unknown[] = unknown[], const TModelsAt extends readonly unknown[] = unknown[], const TActionsAt extends readonly unknown[] = unknown[], TOp = unknown>(
11578
+ ops: [...Db3HandleBatchOps<TModels, TQueries, TConstraints>] & [...Db3BatchModelsAt<TModelsAt>] & [...Db3BatchActionsAt<TActionsAt>] & Db3BatchOpsElement<TActionsAt, TOp>,
11289
11579
  options?: { atomic?: boolean; requestId?: string }
11290
- ): Promise<Db3BatchResult>;
11580
+ ): Promise<Db3BatchResult<Db3HandleBatchReadsOf<TModels, TModelsAt, TActionsAt, TOp>>>;
11581
+ /**
11582
+ * Several reads across models in one request, answered from one state of
11583
+ * the db3: one result per read, in order, typed by the read's model and
11584
+ * action.
11585
+ *
11586
+ * ```ts
11587
+ * const { results: [accounts, count] } = await household.batchRead([
11588
+ * { model: "account", action: "query", filter: {} },
11589
+ * { model: "transaction", action: "count" },
11590
+ * ]);
11591
+ * if (accounts.ok) accounts.items.forEach((row) => console.log(row.name));
11592
+ * if (count.ok) console.log(count.count);
11593
+ * ```
11594
+ * @beta
11595
+ */
11596
+ batchRead<const TModelsAt extends readonly Db3ModelNames<TModels>[] = Db3ModelNames<TModels>[], const TActionsAt extends readonly Db3BatchReadAction[] = Db3BatchReadAction[], TOp = unknown>(
11597
+ reads:
11598
+ | ([...Db3HandleBatchReadsAt<TModels, TModelsAt>] & [...Db3BatchActionsAt<TActionsAt>] & Db3BatchOpsElement<TActionsAt, TOp>)
11599
+ | (readonly [...Db3HandleBatchReadsAt<TModels, TModelsAt>] & readonly [...Db3BatchActionsAt<TActionsAt>] & Db3BatchOpsElement<TActionsAt, TOp>),
11600
+ options?: { atomic?: boolean }
11601
+ ): Promise<Db3BatchReadResponse<Db3HandleBatchReadsOf<TModels, TModelsAt, TActionsAt, TOp>>>;
11291
11602
  /**
11292
- * Several reads across models in one request, answered from one state of the db3.
11603
+ * Bulk-load rows into this db3 in one call, however many there are: the
11604
+ * call cuts them into chunks, opens one load, uploads, commits and waits
11605
+ * for the db3 to apply it.
11606
+ *
11607
+ * ```ts
11608
+ * const result = await ctx.db3(input.db3Id, "ledger").load(rows);
11609
+ * if (!result.done) return { pending: result.sessionId };
11610
+ * ```
11611
+ *
11612
+ * Rows may come in any order and span models, naming each record once. One
11613
+ * load runs on a db3 at a time (`DOCUMENT_INGEST_ACTIVE` otherwise). A row
11614
+ * or option the SDK refuses rejects before any request, with `code`
11615
+ * `DB3_LOAD_INVALID`; a row the db3 refuses is counted in `refusedRows`.
11616
+ * Not available on a handle opened with `asUser`.
11293
11617
  * @beta
11294
11618
  */
11295
- batchRead(reads: Array<Db3HandleBatchReadOp<TModels>>, options?: { atomic?: boolean }): Promise<Db3BatchReadResponse>;
11619
+ load(rows: ReadonlyArray<Db3LoadRow<TModels>>, options?: Db3LoadOptions<Db3ModelNames<TModels>>): Promise<Db3LoadResult>;
11620
+ /**
11621
+ * A load's session as `load` answers it, read again.
11622
+ * @beta
11623
+ */
11624
+ loadStatus(sessionId: string): Promise<Db3LoadResult>;
11625
+ /**
11626
+ * One page of the rows a load refused, oldest first.
11627
+ * @beta
11628
+ */
11629
+ loadRefused(sessionId: string, options?: { limit?: number; cursor?: string }): Promise<Db3LoadRefusedPage>;
11296
11630
  }
11297
11631
 
11298
11632
  /**
@@ -11315,6 +11649,70 @@ export interface Db3HandleOptions {
11315
11649
  asUser?: string;
11316
11650
  }
11317
11651
 
11652
+ /**
11653
+ * The model names db3 type `K` declares: what a helper generic over the
11654
+ * model is bounded by. `string` before the tree has pushed a db3 type.
11655
+ *
11656
+ * ```ts
11657
+ * async function firstRow<M extends Db3TypeModelName<"household">>(ctx: FunctionContext, id: string, model: M) {
11658
+ * const page = await ctx.db3(id, "household").model(model).query({ filter: {}, sort: { id: 1 }, limit: 1 });
11659
+ * return page.items[0];
11660
+ * }
11661
+ * ```
11662
+ */
11663
+ export type Db3TypeModelName<K extends Db3TypeKeys> = Db3ModelNames<Db3Models<K>>;
11664
+
11665
+ /**
11666
+ * One row of model `M` of db3 type `K`, as `query` and `get` answer it.
11667
+ *
11668
+ * ```ts
11669
+ * async function readAll<M extends Db3TypeModelName<"household">>(ctx: FunctionContext, id: string, model: M) {
11670
+ * const rows: Array<Db3TypeRow<"household", M>> = [];
11671
+ * let cursor: string | undefined;
11672
+ * do {
11673
+ * const page = await ctx.db3(id, "household").model(model).query({ limit: 100, cursor });
11674
+ * rows.push(...page.items);
11675
+ * cursor = page.hasMore ? page.nextCursor : undefined;
11676
+ * } while (cursor);
11677
+ * return rows;
11678
+ * }
11679
+ * ```
11680
+ */
11681
+ export type Db3TypeRow<K extends Db3TypeKeys, M extends Db3TypeModelName<K>> = Db3ModelRow<Db3Models<K>, M>;
11682
+
11683
+ /**
11684
+ * The filter model `M` of db3 type `K` takes, for a helper that takes a
11685
+ * caller's filter and passes it on: the call site's filter is checked against
11686
+ * the model it names.
11687
+ *
11688
+ * ```ts
11689
+ * async function countWhere<M extends Db3TypeModelName<"household">>(ctx: FunctionContext, id: string, model: M, filter: Db3TypeFilter<"household", M>) {
11690
+ * return (await ctx.db3(id, "household").model(model).count({ filter })).count;
11691
+ * }
11692
+ * ```
11693
+ */
11694
+ export type Db3TypeFilter<K extends Db3TypeKeys, M extends Db3TypeModelName<K>> = Db3ModelFilterOf<Db3QueriesOf<K>, M>;
11695
+
11696
+ /** The sort model `M` of db3 type `K` takes, for a helper that passes a caller's sort on. */
11697
+ export type Db3TypeSort<K extends Db3TypeKeys, M extends Db3TypeModelName<K>> = Db3ModelSortOf<Db3QueriesOf<K>, M>;
11698
+
11699
+ /**
11700
+ * One write of a `batch` on a db3 of type `K`, for a model `M` of it (any
11701
+ * of its models by default): its `model` picks the row its `data` is checked
11702
+ * against. An `upsert`'s `constraint` is a `string` here, as a computed name
11703
+ * is; an op written inline in the `batch` call has its literal name checked.
11704
+ *
11705
+ * ```ts
11706
+ * async function writeInChunks(ctx: FunctionContext, id: string, ops: Array<Db3TypeBatchOp<"household">>) {
11707
+ * const household = ctx.db3(id, "household");
11708
+ * for (let at = 0; at < ops.length; at += 100) await household.batch(ops.slice(at, at + 100));
11709
+ * }
11710
+ * ```
11711
+ */
11712
+ export type Db3TypeBatchOp<K extends Db3TypeKeys, M extends Db3TypeModelName<K> = Db3TypeModelName<K>> = {
11713
+ [N in M]: Db3BatchOp<Db3TypeRow<K, N>> & { model: N };
11714
+ }[M];
11715
+
11318
11716
  /** A db3 opened with no type: the model API over open record shapes, and no `type`. */
11319
11717
  export type Db3UntypedHandle = Omit<Db3Handle<Record<string, Record<string, unknown>>>, "type">;
11320
11718
 
@@ -11703,6 +12101,25 @@ export type PromptRunErrorCode =
11703
12101
  | "PROMPT_STRICT_OUTPUT_SCHEMA_MISSING"
11704
12102
  | "PROMPT_SCHEMA_NOT_TRANSLATABLE";
11705
12103
 
12104
+ /**
12105
+ * What a prompt run measured. Each field is absent when the provider did not
12106
+ * report it.
12107
+ */
12108
+ export interface PromptRunMetrics {
12109
+ /** How long the run took, in milliseconds. */
12110
+ durationMs?: number;
12111
+ /** Tokens the provider counted in the request. */
12112
+ inputTokens?: number;
12113
+ /** Tokens the provider counted in the answer. */
12114
+ outputTokens?: number;
12115
+ /** `inputTokens` and `outputTokens` together. */
12116
+ totalTokens?: number;
12117
+ /** Reasoning tokens, reported separately from `outputTokens`. */
12118
+ reasoningTokens?: number;
12119
+ /** The price of the call in USD, as the provider reported it. */
12120
+ cost?: number;
12121
+ }
12122
+
11706
12123
  /** A prompt that declares an output shape, when the answer matched it. */
11707
12124
  export interface PromptRunSuccess<TParsed> {
11708
12125
  success: true;
@@ -11711,7 +12128,7 @@ export interface PromptRunSuccess<TParsed> {
11711
12128
  parsed: TParsed;
11712
12129
  error?: null;
11713
12130
  errorCode?: null;
11714
- metrics?: Record<string, unknown>;
12131
+ metrics?: PromptRunMetrics;
11715
12132
  configId: string;
11716
12133
  /**
11717
12134
  * `true` when the provider stopped at the output token limit
@@ -11734,7 +12151,7 @@ export interface PromptRunFailure {
11734
12151
  error: string | null;
11735
12152
  errorCode?: PromptRunErrorCode | null;
11736
12153
  parsed?: undefined;
11737
- metrics?: Record<string, unknown>;
12154
+ metrics?: PromptRunMetrics;
11738
12155
  configId: string;
11739
12156
  /**
11740
12157
  * The upstream provider's HTTP status, when the call reached a provider and
@@ -11766,7 +12183,7 @@ export interface PromptRunOpenResult {
11766
12183
  parsed?: unknown;
11767
12184
  error?: string | null;
11768
12185
  errorCode?: PromptRunErrorCode | null;
11769
- metrics?: Record<string, unknown>;
12186
+ metrics?: PromptRunMetrics;
11770
12187
  configId: string;
11771
12188
  /** The upstream provider's HTTP status on a provider failure. */
11772
12189
  upstreamStatus?: number;
@@ -13095,6 +13512,7 @@ export type AuthorizeHelper<TInput, TAuth> = [TInput] extends [unknown]
13095
13512
  * import { allow, defineFunction, deny } from "primitive-functions";
13096
13513
  *
13097
13514
  * export default defineFunction({
13515
+ * input: [],
13098
13516
  * authorize: async (input: { orgId: string }, auth) =>
13099
13517
  * auth.user ? allow({ orgId: input.orgId }) : deny("FORBIDDEN"),
13100
13518
  * handler: async (input, ctx) => ({ orgId: ctx.auth.orgId }),
@@ -13171,6 +13589,7 @@ export declare function requireRole(
13171
13589
  * import { defineFunction, requireMember } from "primitive-functions";
13172
13590
  *
13173
13591
  * export default defineFunction("team-report", {
13592
+ * input: [],
13174
13593
  * authorize: requireMember((input) => input.teamId, "manager"),
13175
13594
  * handler: async (input, ctx) => ({ team: ctx.auth.groupId, as: ctx.auth.role }),
13176
13595
  * });
@@ -13212,6 +13631,7 @@ export declare function requireDocumentOwner<TInput = any>(
13212
13631
  * import { defineFunction, requirePublicDb3 } from "primitive-functions";
13213
13632
  *
13214
13633
  * export default defineFunction({
13634
+ * input: [],
13215
13635
  * authorize: requirePublicDb3((input: { db3Id: string }) => input.db3Id),
13216
13636
  * handler: async (input, ctx) => ctx.api.db3.get({ db3Id: ctx.auth.db3Id }),
13217
13637
  * });
@@ -13294,6 +13714,7 @@ export interface InvitationAuth {
13294
13714
  * import { defineFunction, requireInvitation } from "primitive-functions";
13295
13715
  *
13296
13716
  * export default defineFunction({
13717
+ * input: [],
13297
13718
  * authorize: requireInvitation((input: { inviteToken: string }) => input.inviteToken),
13298
13719
  * handler: async (input, ctx) => ({ shared: ctx.auth.shared.map((item) => item.title) }),
13299
13720
  * });
@@ -13320,6 +13741,7 @@ export declare function requireInvitation<TInput = any>(
13320
13741
  * import { defineFunction, requireToken } from "primitive-functions";
13321
13742
  *
13322
13743
  * export default defineFunction({
13744
+ * input: [],
13323
13745
  * authorize: requireToken((input: { token: string }) => input.token),
13324
13746
  * handler: async (input, ctx) => ({ orderId: ctx.auth.args.orderId }),
13325
13747
  * });
@@ -13366,6 +13788,7 @@ export interface CallerRules<TInput = any, TAuth = unknown, TAgentAuth = TAuth>
13366
13788
  * import { allowCallers, defineFunction, requireRole } from "primitive-functions";
13367
13789
  *
13368
13790
  * export default defineFunction({
13791
+ * input: [],
13369
13792
  * authorize: allowCallers({ cron: true, manual: true, users: requireRole("admin") }),
13370
13793
  * handler: async () => ({ swept: true }),
13371
13794
  * });
@@ -13435,6 +13858,7 @@ export interface FunctionAuthorizedContext<TAuth> {
13435
13858
  *
13436
13859
  * ```ts
13437
13860
  * export default defineFunction("get-class", {
13861
+ * input: [],
13438
13862
  * authorize: async (input, auth) => allow({ classId: input.classId }),
13439
13863
  * handler: async (input, ctx) => ctx.auth.classId,
13440
13864
  * });
@@ -13635,11 +14059,13 @@ export type AuthorizedFunctionHandler<TInput, TOutput, TAuth> = FunctionHandler<
13635
14059
  * adds an `authorize` method that decides who may run the handler; what its
13636
14060
  * `allow` resolves is the handler's `ctx.auth`. `input` lists the
13637
14061
  * top-level input keys the handler may read, and its `input` is typed as
13638
- * the declared input picked to them. With no list the handler's `input` is
13639
- * `{}`, and an annotation on the handler's parameter never adds a key the
13640
- * list does not name. With explicit type arguments the list is the fourth,
13641
- * as a tuple (`<In, Out, Auth, ["classId"]>`), and is still written on the
13642
- * definition. `authorize` always reads the whole input:
14062
+ * the declared input picked to them; `input: []` says the handler reads
14063
+ * none. With no list the handler's `input` is typed `{}`, push refuses the
14064
+ * function unless its TOML declares a trigger, and a caller's call is refused
14065
+ * `FUNCTION_INPUT_LIST_MISSING`. An annotation on the handler's parameter
14066
+ * never adds a key the list does not name. With explicit type arguments the
14067
+ * list is the fourth, as a tuple (`<In, Out, Auth, ["classId"]>`), and is
14068
+ * still written on the definition. `authorize` always reads the whole input:
13643
14069
  *
13644
14070
  * ```ts
13645
14071
  * export default defineFunction("get-class", {