@authoric/handler-sdk 0.0.0-stage → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +25 -2
  2. package/handler-sdk.d.ts +2797 -0
  3. package/package.json +15 -6
@@ -0,0 +1,2797 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
3
+ interface JsonObject {
4
+ [key: string]: JsonValue;
5
+ }
6
+
7
+ type SortDirection = "asc" | "desc";
8
+ type DeleteStrategy = "hard" | "soft";
9
+ type ScopeType = "org" | "tenant" | "user";
10
+
11
+ type Identifier = string | number;
12
+
13
+ /**
14
+ * THE ROW SHAPE (SDK 3.0.0). Every CRUD method speaks the shape a row has outside its database:
15
+ *
16
+ * - A row is named by its `uid` (a string). It never carries `id`, and `read` / `update` /
17
+ * `delete` take a uid. Sorting by `id` is allowed (creation order); sorting by `uid` is not.
18
+ * - A foreign key travels as `<name>_uid` holding the referenced row's uid: `customer_id` is read,
19
+ * written and filtered as `customer_uid`. Sending `id`, `uid`, `org_id`, or the raw `customer_id`
20
+ * is a 400 (`ROW_FIELD_NOT_ACCEPTED`) naming the field to use; a `_uid` that names no row is a 400
21
+ * (`ROW_REFERENCE_NOT_FOUND`).
22
+ * - `org_id` / `tenant_id` and integer `created_by` / `updated_by` / `deleted_by` / `user_id`
23
+ * columns without a declared foreign key are stamped and applied by the platform and never appear.
24
+ * - A table may declare a KEY column (SDK 6.3.0): a text column, unique per org, such as a channel's
25
+ * `slug`. A row of that table then answers to its key as well as its uid wherever a row is named:
26
+ * `sdk.read("channels", "leadership")`, and a reference written or filtered on
27
+ * (`{ channel_uid: "leadership" }`). A key is never shaped like a uid (refused on write with
28
+ * `ROW_KEY_INVALID`), so a value is always one or the other. A key used in several orgs the caller
29
+ * reaches is refused rather than guessed (`ROW_REFERENCE_AMBIGUOUS`): name the row by uid there.
30
+ *
31
+ * Raw SQL (`sdk.sql`, `sdk.query`) is NOT the edge: it runs inside the database and may join on
32
+ * `id` at full speed. That is what it is for. But whatever your handler RETURNS to its caller must
33
+ * not carry an id: select the uid instead.
34
+ */
35
+ /** A row's uid, or its table's key when the table declares one (`"leadership"`). */
36
+ type RowUid = string;
37
+
38
+ type ComparableValue = JsonPrimitive | Date | Identifier;
39
+
40
+ /** Comparison operators for a column filter: `{ amount: { $gte: 100, $lt: 500 } }`. */
41
+ interface FilterComparison {
42
+ /** Equal to. `null` matches `IS NULL`. */
43
+ $eq?: ComparableValue | null;
44
+ /** Not equal to. `null` matches `IS NOT NULL`. */
45
+ $ne?: ComparableValue | null;
46
+ /** Strictly greater than. */
47
+ $gt?: ComparableValue;
48
+ /** Greater than or equal to. */
49
+ $gte?: ComparableValue;
50
+ /** Strictly less than. */
51
+ $lt?: ComparableValue;
52
+ /** Less than or equal to. */
53
+ $lte?: ComparableValue;
54
+ /** Matches any value in the list. An empty list matches nothing. */
55
+ $in?: ComparableValue[];
56
+ /** Inclusive range: `[low, high]`. */
57
+ $between?: [ComparableValue, ComparableValue];
58
+ /** The column contains this text, literally (`%` and `_` are not wildcards). Follows the column's collation. */
59
+ $contains?: string;
60
+ /** The column starts with this text, literally. */
61
+ $startsWith?: string;
62
+ }
63
+
64
+ type FilterValue =
65
+ | JsonPrimitive
66
+ | Date
67
+ | Identifier
68
+ | Array<JsonPrimitive | Date | Identifier>
69
+ | FilterComparison
70
+ | { operator?: string; value?: JsonValue | Date | Identifier | Identifier[] };
71
+
72
+ type Filters = Record<string, FilterValue>;
73
+
74
+ type ReadListPaging = {
75
+ /** Page size that was applied. */
76
+ limit: number;
77
+ /** Rows skipped before this page. */
78
+ offset: number;
79
+ /** Total matching rows, present only when `includeTotal` asked for the extra count. */
80
+ total?: number | null;
81
+ };
82
+
83
+ type ReadListEnvelope<T = Record<string, unknown>> = {
84
+ /** The rows for this page. */
85
+ items: T[];
86
+ /** How the page was cut. Absent when the call did not ask to paginate. */
87
+ paging?: ReadListPaging;
88
+ };
89
+
90
+ interface ScopeOptions {
91
+ /**
92
+ * Which scope column the query is narrowed by: org, tenant, or user. The scope always follows
93
+ * the caller's own org and user: there is no pin to another org by id (SDK 3.0.0 refuses
94
+ * `orgId` / `tenantId` / `userId` here with `ROW_FIELD_NOT_ACCEPTED`).
95
+ */
96
+ type?: ScopeType;
97
+ /** Permit tenant-scoped narrowing. Granted automatically to a caller holding a global role. */
98
+ allowTenantScope?: boolean;
99
+ /** Permit user-scoped narrowing. */
100
+ allowUserScope?: boolean;
101
+ /**
102
+ * Read across ALL org / tenant / user scopes (cross-tenant) instead of only the
103
+ * acting org (e.g. `scope: { shared: true }`). This is the ungated cross-org read
104
+ * power and is HIGH RISK: it requires the `sdk:shared_read` capability to save or
105
+ * publish, and flags the handler with the "Cross-org" badge.
106
+ */
107
+ shared?: boolean;
108
+ }
109
+
110
+ interface ReadListOptions {
111
+ /** Which rows to match. Equality, `null`, `$and`/`$or`, and the comparison operators. */
112
+ filters?: Filters;
113
+ /** Return ONLY these columns (validated identifiers) instead of every column. Redaction still applies. */
114
+ columns?: string[];
115
+ /** Page size. */
116
+ limit?: number;
117
+ /** Rows to skip. Always pair with a sort; without one, pages may overlap or skip rows. */
118
+ offset?: number;
119
+ /** Return the `{ items, paging }` envelope instead of a bare array. */
120
+ paginate?: boolean;
121
+ /** `"column"` or `"column DESC"`. An unknown column is rejected, not ignored. */
122
+ sort?: string;
123
+ /** Alias of `sort`, for callers shaped like the REST layer. `sort` wins if both are set. */
124
+ orderBy?: string;
125
+ /** Fallback ordering used only when neither `sort` nor `orderBy` was supplied. */
126
+ defaultSort?: string;
127
+ /** Restrict which columns may be sorted on. A sort outside the list throws rather than silently ordering by something else. */
128
+ allowedSortColumns?: string[];
129
+ /** Also run the COUNT that fills `paging.total`. Costs a second query, so it is opt-in. */
130
+ includeTotal?: boolean;
131
+ /** Narrow (or, with `shared`, widen) which tenant's rows are visible. */
132
+ scope?: ScopeOptions;
133
+ /**
134
+ * **readPage only.** Page in creation order with a cursor instead of an offset (keyset paging):
135
+ * `null` for the first page, then the previous page's `nextCursor`. A row added or removed
136
+ * between pages never shifts another onto a page twice or off them all, and a deep page costs
137
+ * what the first does: the way to walk a whole table. Takes no `sort` or `offset`
138
+ * (PAGE_CURSOR_INVALID). The cursor is opaque and sealed: it works only for the table it came
139
+ * from, and only as given.
140
+ */
141
+ after?: string | null;
142
+ }
143
+
144
+ interface ReadPageResult<T = Record<string, unknown>> {
145
+ /** The rows for this page. */
146
+ items: T[];
147
+ /** Page size applied, or `null` when the call was not paginated. */
148
+ limit: number | null;
149
+ /** Rows skipped, or `null` when the call was not paginated. */
150
+ offset: number | null;
151
+ /** Whether a page was actually cut, as opposed to the whole result being returned. */
152
+ paginated: boolean;
153
+ /** Total matching rows, or `null` when the total was not requested. With `after`: the rows from this page on. */
154
+ total: number | null;
155
+ /**
156
+ * With `after`: where the next page starts (pass it as `after`), or `null` after the last page.
157
+ * Absent on an offset page.
158
+ */
159
+ nextCursor?: string | null;
160
+ }
161
+
162
+ /** One aggregate measure: an allow-listed op over an (optional) column, with an output alias. */
163
+ interface AggregateMeasure {
164
+ /** The aggregate to compute. Allow-listed: arbitrary SQL functions are not accepted. */
165
+ op: "count" | "count_distinct" | "sum" | "avg" | "min" | "max";
166
+ /**
167
+ * Required for every op except `count`. Must be a real, non-redacted column. A uid column
168
+ * (`uid`, `customer_uid`) takes only `count_distinct`; `id` is never measured.
169
+ */
170
+ column?: string;
171
+ /** Output key for this measure (safe charset; falls back to a derived default otherwise). */
172
+ as?: string;
173
+ }
174
+
175
+ /** One group-by key: a column, optionally derived via a FIXED template (never model SQL). */
176
+ interface AggregateGroupBy {
177
+ /**
178
+ * The column to group on. Validated against the table's real columns. Group by a reference
179
+ * under its `<name>_uid` name and the group key comes back as the referenced row's uid (never
180
+ * truncated, bucketed or lower-cased). `id` is never a group key.
181
+ */
182
+ column: string;
183
+ /** Date truncation bucket for a date/datetime column. */
184
+ truncate?: "year" | "quarter" | "month" | "week" | "day" | "hour" | "date";
185
+ /** Numeric range bucket width, e.g. `25` groups 0-24, 25-49, … */
186
+ bucket?: number;
187
+ /** Case-fold the group key (`LOWER(col)`). */
188
+ lower?: boolean;
189
+ /** Output key for this group column (defaults to the column name). */
190
+ as?: string;
191
+ }
192
+
193
+ interface AggregateSpec {
194
+ /** Reuses the read filter DSL (equality, IS NULL, $and/$or, and the comparison operators). */
195
+ filters?: Filters;
196
+ /** Group keys, outermost first. Omit for a single total row over the whole filtered set. */
197
+ groupBy?: AggregateGroupBy[];
198
+ /** What to compute per group. Omit for a plain row count. */
199
+ measures?: AggregateMeasure[];
200
+ /** Threshold on a measure alias, e.g. `{ revenue: { $gt: 1000 } }`. */
201
+ having?: Record<string, number | { $gt?: number; $gte?: number; $lt?: number; $lte?: number; $eq?: number; $ne?: number }>;
202
+ /** `"<group-or-measure-name> ASC|DESC"`. */
203
+ sort?: string;
204
+ /** Max groups to return (clamped to MAX_GROUPS). */
205
+ limit?: number;
206
+ }
207
+
208
+ interface AggregateResult<T = Record<string, unknown>> {
209
+ /** One row per group, carrying the group keys and each measure under its output name. */
210
+ rows: T[];
211
+ /** How complete the result is. Read this before treating `rows` as the whole picture. */
212
+ meta: {
213
+ /** Groups returned in `rows`. */
214
+ groups: number;
215
+ /** Groups the filter matched in total, or `null` when that was not counted. */
216
+ matchedGroups: number | null;
217
+ /** More groups exist beyond those returned (e.g. a deliberate top-N `limit`). */
218
+ hasMore: boolean;
219
+ /** The HARD MAX_GROUPS cap cut the result (narrow with filters); not set for an intended top-N. */
220
+ truncated: boolean;
221
+ /** The group ceiling actually applied to this call. */
222
+ limit: number;
223
+ };
224
+ }
225
+
226
+ /** One column's entry in a {@link SummarizeResult}. Shape varies by the column's kind. */
227
+ interface SummarizeColumn {
228
+ /** Column name. */
229
+ column: string;
230
+ /** The column's SQL type, as declared. */
231
+ type: string;
232
+ /** Which family of statistics the fields below carry. A `reference` is a `<name>_uid` column. */
233
+ kind?: "numeric" | "date" | "categorical" | "reference" | "other";
234
+ /** Reference: the table it points at. */
235
+ references?: string;
236
+ /** The column is masked by redaction, so no values are profiled, only that it exists. */
237
+ redacted?: boolean;
238
+ /** Numeric: smallest value. */
239
+ min?: unknown;
240
+ /** Numeric: largest value. */
241
+ max?: unknown;
242
+ /** Numeric: mean, or `null` when there is nothing to average. */
243
+ avg?: number | null;
244
+ /** Numeric: count of distinct values. */
245
+ distinct?: number;
246
+ /** Date: earliest value. */
247
+ earliest?: unknown;
248
+ /** Date: latest value. */
249
+ latest?: unknown;
250
+ /** Categorical: the most common values with their counts. */
251
+ topValues?: Array<{ value: unknown; count: number }>;
252
+ /** Categorical: more distinct values exist than `topValues` shows. */
253
+ moreCategories?: boolean;
254
+ /** Why this column was profiled thinly or not at all. */
255
+ note?: string;
256
+ }
257
+
258
+ interface SummarizeResult {
259
+ /** The table profiled. */
260
+ table: string;
261
+ /** Rows in the table at the time of the call. */
262
+ rowCount: number;
263
+ /** One entry per column, in the table's own column order. */
264
+ columns: SummarizeColumn[];
265
+ }
266
+
267
+ interface CreateResult {
268
+ /**
269
+ * The new row's uid: the handle to store, link and pass around. Minted by the platform; a `uid`
270
+ * in the row you pass is refused. `null` only for a table with no uid column.
271
+ */
272
+ uid: RowUid | null;
273
+ /** Rows written: `1` for a successful single insert. */
274
+ affectedRows?: number;
275
+ }
276
+
277
+ interface BulkCreateResult {
278
+ /** Number of rows requested. */
279
+ count: number;
280
+ /** The new rows' uids, aligned to the input row order (`null` for a table with no uid column). */
281
+ uids: Array<RowUid | null>;
282
+ /** Total rows inserted. */
283
+ affectedRows: number;
284
+ }
285
+
286
+ interface GenerateResult {
287
+ /** Rows asked for. */
288
+ requested: number;
289
+ /** Rows actually generated + inserted (< `requested` only when the per-call cap clipped it). */
290
+ generated: number;
291
+ /** Total rows inserted across every batch. */
292
+ affectedRows: number;
293
+ /** Column names present on the generated rows. */
294
+ columns: string[];
295
+ /** The first generated row as written, with its `uid`, so a caller can eyeball the shape. `null` when nothing was generated. */
296
+ sample: Record<string, unknown> | null;
297
+ /** Present only when the per-call cap clipped the request; call again for `remaining`. */
298
+ capped?: true;
299
+ /** The per-call ceiling that clipped the request. */
300
+ perCallMax?: number;
301
+ /** Rows still owed after the cap. */
302
+ remaining?: number;
303
+ }
304
+
305
+ interface UpdateResult {
306
+ /** Rows changed. `0` means the filter matched nothing; it is not an error. */
307
+ affectedRows?: number;
308
+ }
309
+
310
+ interface DeleteResult {
311
+ /** Rows removed, or soft-deleted when the table's strategy is `"soft"`. */
312
+ affectedRows?: number;
313
+ }
314
+
315
+ interface WithIdempotencyPersistOptions {
316
+ /** Store ONLY these keys of the result. Everything else is dropped before it is saved. */
317
+ pick?: string[];
318
+ /** Store the result except these keys: the way to keep a secret out of the replay. */
319
+ omit?: string[];
320
+ }
321
+
322
+ interface WithIdempotencyOptions<TWorkResult = unknown> {
323
+ /** The client-supplied key that identifies this attempt. Same key = same outcome. */
324
+ key: string;
325
+ /** Route recorded alongside the key, so the same key on a different route is a different operation. */
326
+ route?: string;
327
+ /** HTTP method recorded with the key, for the same reason as `route`. */
328
+ method?: string;
329
+ /** Request body fingerprinted with the key. A retry whose body differs is rejected rather than silently replayed. */
330
+ body?: Record<string, unknown>;
331
+ /** Query fingerprinted with the key, as `body` is. */
332
+ query?: Record<string, unknown>;
333
+ /**
334
+ * What to store for replay: a function returning the value to keep, or a pick/omit
335
+ * filter over the result. Leave unset to store nothing and only guard against a
336
+ * duplicate run.
337
+ */
338
+ persistResponse?:
339
+ | ((result: TWorkResult) => unknown)
340
+ | WithIdempotencyPersistOptions;
341
+ /** How long the key stays reserved before an identical call may run again. */
342
+ ttlSeconds?: number;
343
+ /** Let a retry re-run the work after a failure, instead of replaying the failure. */
344
+ allowRetryOnFailure?: boolean;
345
+ }
346
+
347
+ interface ApprovalRecord {
348
+ /** The approval's uid: its handle, stable for the life of the request (a key is reused once the request closes). */
349
+ uid: string;
350
+ /** The stable key this approval was created under: how a resumed run finds it again. */
351
+ key: string;
352
+ /** Where the decision stands. Branch on the `approved`/`rejected`/`pending` booleans instead of string-matching. */
353
+ status: "pending" | "approved" | "rejected" | string;
354
+ /** Caller-defined label for what kind of thing is being approved, for grouping in the inbox. */
355
+ requestType: string | null;
356
+ /** The human-readable justification shown to whoever decides. */
357
+ reason: string | null;
358
+ /** What was asked for: the payload an approver reviews before deciding. */
359
+ requestData: unknown;
360
+ /** State the handler stashed so it can pick up exactly where it paused. */
361
+ resumeData: unknown;
362
+ /**
363
+ * Anything the approver attached to the decision. Who raised and who decided are not carried
364
+ * (SDK 3.0.0): they are internal principal ids. The decider is always the caller who decided,
365
+ * and never the principal that raised the request.
366
+ */
367
+ decisionData: unknown;
368
+ /** Free-text note the approver left with the decision. */
369
+ decisionNotes: string | null;
370
+ /** When the request stops being actionable, if it was given a deadline. */
371
+ expiresAt: string | null;
372
+ /** When the decision was made. */
373
+ decidedAt: string | null;
374
+ /** When the request closed: its approval used by the one gate pass it authorizes, or its rejection delivered to the next pass. */
375
+ consumedAt: string | null;
376
+ /** When the request was raised. */
377
+ createdAt: string | null;
378
+ /** When the row last changed. */
379
+ updatedAt: string | null;
380
+ /** Decided, and the answer was yes. */
381
+ approved: boolean;
382
+ /** Decided, and the answer was no. */
383
+ rejected: boolean;
384
+ /** Still waiting on a human. */
385
+ pending: boolean;
386
+ /** The request is closed (approval used, or rejection delivered), and the next call under its key raises a new one. */
387
+ consumed: boolean;
388
+ }
389
+
390
+ interface AwaitApprovalOptions {
391
+ /** Stable identifier for this gate. Reuse it to resume the same approval rather than raising a second one. Once an approval under this key has been used, the next call raises a new request. */
392
+ key?: string;
393
+ /** Caller-defined label for what kind of approval this is, used to group the inbox. */
394
+ requestType?: string;
395
+ /** Why this needs a person. Shown to the approver, so write it for them. */
396
+ reason?: string;
397
+ /** The payload under review. Show the actual arguments; an approver should not have to trust a summary. */
398
+ requestData?: unknown;
399
+ /** Alias of `requestData`. */
400
+ data?: unknown;
401
+ /** State to hand back to the handler when the run resumes, so it continues instead of restarting. */
402
+ resumeData?: Record<string, unknown>;
403
+ /** How long the request stays actionable before it expires. */
404
+ expiresInSeconds?: number;
405
+ /** How long to hold this call open waiting for a decision. On timeout the approval stays pending and the run pauses. */
406
+ waitForMs?: number;
407
+ /** How often to re-check for a decision while waiting. */
408
+ pollIntervalMs?: number;
409
+ /** Throw on rejection instead of returning the rejected record for the handler to deal with. */
410
+ throwOnReject?: boolean;
411
+ }
412
+
413
+ interface ApprovalDecisionOptions {
414
+ /** Identify the approval by its key (the OPEN request under it). Supply this or `uid`. */
415
+ key?: string;
416
+ /** Identify the approval by its uid (`ApprovalRecord.uid`). Supply this or `key`. */
417
+ uid?: string;
418
+ /** Structured payload to record with the decision. */
419
+ decisionData?: unknown;
420
+ /** Free-text note to record with the decision. */
421
+ decisionNotes?: string;
422
+ }
423
+
424
+ /**
425
+ * An email, sent as the app (`sdk.sendEmail`). Give the content as STRUCTURED fields, laid out in
426
+ * the app's branding (App settings › Branding), or as raw `html` / `text`, sent as written. Not both.
427
+ *
428
+ * Any text field (subject included) may name values from `data` by placeholder:
429
+ * - `{key}` is filled in the email and kept in the app's email log;
430
+ * - `{{key}}` is filled in the email but REDACTED (`•••`) in the log: use it for codes, tokens,
431
+ * anything secret;
432
+ * - `\{` is a literal brace. A key may be a path (`{order.number}`).
433
+ * A placeholder naming no key in `data` refuses the send (`EMAIL_PLACEHOLDER_MISSING`). Pass
434
+ * secrets through `data`: one written straight into the text cannot be told apart, and is logged.
435
+ */
436
+ interface EmailMessage {
437
+ /** Recipient address, or several (at most 50 recipients counting cc and bcc). */
438
+ to: string | string[];
439
+ cc?: string | string[];
440
+ bcc?: string | string[];
441
+ /** Subject line. Placeholders allowed. */
442
+ subject: string;
443
+ /**
444
+ * Sender address. Omitted: the connection's default sender. Must be one of the senders the
445
+ * connection may send as (`EMAIL_FROM_NOT_ALLOWED` otherwise).
446
+ */
447
+ from?: string;
448
+ /** The sender's display name. Omitted: the app's branding name, else the app's name. */
449
+ fromName?: string;
450
+ /** Where replies go. Omitted: the branding's reply-to, else the connection's. */
451
+ replyTo?: string;
452
+
453
+ // Structured content, rendered in the app's branding:
454
+ /** The big line at the top. Defaults to the subject. */
455
+ heading?: string;
456
+ /** Paragraphs of plain text (escaped for you). */
457
+ body?: string | string[];
458
+ /** A button. `url` must be http(s) or mailto. */
459
+ action?: { label: string; url: string };
460
+ /** A one-time code, shown large instead of a button. */
461
+ code?: string;
462
+ /** Small print under a rule. */
463
+ footnotes?: string | string[];
464
+ /** The inbox preview line. Defaults to the heading. */
465
+ preheader?: string;
466
+
467
+ // Or raw content, sent as written (placeholder values are HTML-escaped in `html`):
468
+ html?: string;
469
+ text?: string;
470
+
471
+ /** Values for the `{key}` / `{{key}}` placeholders. */
472
+ data?: Record<string, unknown>;
473
+ }
474
+
475
+ /** What `sdk.sendEmail` returns. */
476
+ interface SendEmailResult {
477
+ /** The message in the app's email log (App › Email). */
478
+ uid: string;
479
+ status: "sent" | "sending" | "failed";
480
+ /**
481
+ * True when a retried job item sent this already (the same item, connection, recipients, sender
482
+ * and subject): nothing was sent this time.
483
+ */
484
+ duplicate: boolean;
485
+ /** The provider's message id, when it gave one. */
486
+ messageId: string | null;
487
+ from: string;
488
+ to: string[];
489
+ /** The connection's alias in this app. */
490
+ alias: string;
491
+ /** True when `{{key}}` values were masked in the logged copy. */
492
+ redacted: boolean;
493
+ }
494
+
495
+ /** The app's branding, as `sdk.app.branding()` returns it. Every field may be null. */
496
+ interface AppBranding {
497
+ displayName: string | null;
498
+ /** Public URLs of the logo, its dark-mode variant and the square icon. */
499
+ logoUrl: string | null;
500
+ logoDarkUrl: string | null;
501
+ iconUrl: string | null;
502
+ /** `#rrggbb` colors, for light and dark mode. */
503
+ colors: {
504
+ light: { primary: string | null; accent: string | null; background: string | null };
505
+ dark: { primary: string | null; accent: string | null; background: string | null };
506
+ };
507
+ footer: {
508
+ company: string | null;
509
+ address: string | null;
510
+ supportEmail: string | null;
511
+ website: string | null;
512
+ social: { label: string; url: string }[];
513
+ };
514
+ email: { replyTo: string | null; footerNote: string | null };
515
+ }
516
+
517
+ /** The app itself. */
518
+ interface HandlerApp {
519
+ /**
520
+ * The app's branding (App settings › Branding), with images as public URLs: for a handler that
521
+ * renders something of its own (a PDF, a page) in the app's look. Email from `sendEmail` wears
522
+ * it already.
523
+ */
524
+ branding(): Promise<AppBranding>;
525
+ }
526
+
527
+ interface ImportCsvOptions {
528
+ /** Destination table. */
529
+ table: string;
530
+ /** The CSV itself, as text. Supply this or `csvBase64`. */
531
+ csv?: string;
532
+ /** The CSV base64-encoded, for content that does not survive being passed as text. */
533
+ csvBase64?: string;
534
+ /** Rename incoming headers to real columns: `{ "Email Address": "email" }`. */
535
+ mapping?: Record<string, string>;
536
+ /**
537
+ * Values written to every row for columns the CSV does not carry. This is the answer to a
538
+ * column the table REQUIRES (NOT NULL, no default) that no header maps onto; without one the
539
+ * import is refused, because there is no row it could succeed for. Each value is coerced and
540
+ * checked against its column exactly like a cell from the file.
541
+ */
542
+ defaults?: Record<string, unknown>;
543
+ /** Rows per insert batch. */
544
+ batchSize?: number;
545
+ /** Reject the import if the payload exceeds this many bytes. */
546
+ maxBytes?: number;
547
+ /** Reject the import if it carries more than this many rows. */
548
+ maxRows?: number;
549
+ /** Parse and validate everything, report what WOULD happen, write nothing. */
550
+ dryRun?: boolean;
551
+ /** Treat an empty cell as `NULL` rather than an empty string. */
552
+ emptyAsNull?: boolean;
553
+ /** Skip CSV columns with no matching table column instead of failing the import. */
554
+ ignoreUnknownColumns?: boolean;
555
+ /**
556
+ * What to do with a row holding a value the table cannot store (bad enum member, over-long
557
+ * string, non-numeric number, out-of-range integer).
558
+ * - `"abort"` (default): import nothing and throw with the offending rows listed.
559
+ * - `"skip"`: import the clean rows and report the rest in `skippedRows` / `errors`.
560
+ * A bad value is never silently repaired or replaced under either setting. Neither setting
561
+ * rescues a required column with nothing mapped onto it: that fails every row identically, so
562
+ * it is refused outright rather than skipped row by row.
563
+ */
564
+ onError?: "abort" | "skip";
565
+ /** Narrow (or, with `shared`, widen) the tenant scope stamped on every imported row. */
566
+ scope?: ScopeOptions;
567
+ /** Character encoding of the incoming CSV. */
568
+ encoding?: string;
569
+ /**
570
+ * Upsert: a UNIQUE column each file row is matched on, typically the id the rows had in the
571
+ * system they come from (`"shopify_id"`). A row whose value matches an existing row updates it;
572
+ * the rest are created; so running the same file twice changes nothing the second time. The
573
+ * column must be unique (alone or per org) and mapped from the file. Two file rows with the same
574
+ * value are refused (`CSV_DUPLICATE_MATCH`, 422) with their lines. A dry run reports
575
+ * `match: { inserts, updates, skipped }`.
576
+ */
577
+ matchOn?: string;
578
+ /** With `matchOn`: `"update"` (default) updates a matched row, `"skip"` leaves it as it is. */
579
+ onMatch?: "update" | "skip";
580
+ /**
581
+ * External keys: resolve a reference column by a unique column of the table it points at, instead
582
+ * of by uid. `{ customer_uid: "shopify_id" }` reads the file's `customer_uid` column as
583
+ * customers' `shopify_id` (`"C-1042"`), so orders from another system link to the customers
584
+ * imported before them. Without it, a reference takes a uid or the parent's key.
585
+ */
586
+ references?: Record<string, string>;
587
+ }
588
+
589
+ interface ReadOptions {
590
+ /**
591
+ * Rows are addressed by `uid` only (SDK 3.0.0): any other value is refused. To find a row by
592
+ * another column, use {@link HandlerSdk.readList} with a filter.
593
+ */
594
+ idColumn?: "uid";
595
+ /** Narrow (or, with `shared`, widen) which tenant's rows are visible. */
596
+ scope?: ScopeOptions;
597
+ /**
598
+ * `read` only, on the `tx` inside {@link HandlerSdk.withTransaction}: hold the row until the
599
+ * transaction ends (`SELECT ... FOR UPDATE`), so a check made on it still holds when you write.
600
+ * Without it two callers can both read "1 seat left" and both book it: a transaction makes the
601
+ * writes all-or-nothing, it does not stop another caller reading the same row meanwhile. Outside a
602
+ * transaction it is refused (READ_LOCK_NEEDS_TRANSACTION).
603
+ *
604
+ * For a rule over OTHER rows (no two bookings of one practitioner overlap, a class holds 20), lock
605
+ * the one row every such write goes through first (the practitioner, the class), then read the
606
+ * others: a handler's transaction reads what has been committed by then, so the second caller,
607
+ * once the first commits, sees its booking. Lock first, read after.
608
+ */
609
+ lock?: boolean;
610
+ }
611
+
612
+ interface UpdateOptions extends Omit<ReadOptions, "lock"> {}
613
+
614
+ interface DeleteOptions extends Omit<ReadOptions, "lock"> {
615
+ /** Override the table's configured strategy for this call: remove the row, or mark it deleted. */
616
+ deleteStrategy?: DeleteStrategy;
617
+ }
618
+
619
+ interface CreateOptions {
620
+ /** Which tenant the new row is attributed to. Defaults to the acting scope. */
621
+ scope?: ScopeOptions;
622
+ }
623
+
624
+ interface BulkCreateOptions extends CreateOptions {
625
+ /**
626
+ * Max rows per INSERT statement (batches larger than this are split). Defaults to 500;
627
+ * clamped to 1..1000. Lower it for very wide rows; it never caps the total row count.
628
+ */
629
+ chunkSize?: number;
630
+ }
631
+
632
+ /**
633
+ * One column's generation recipe. `kind` picks the generator; the remaining keys are that kind's
634
+ * options. Omit a column entirely and its kind is inferred from the live schema (enum → a real
635
+ * member, varchar → text clamped to length, int → a number, date → a recent date), so a bare
636
+ * `generateRecords(table, 100)` still produces valid rows.
637
+ */
638
+ interface GenerateColumnSpec {
639
+ /** Which generator to use. Omit to infer one from the column's real type in the live schema. */
640
+ kind?:
641
+ | "oneOf"
642
+ | "weighted"
643
+ | "int"
644
+ | "float"
645
+ | "bool"
646
+ | "date"
647
+ | "datetime"
648
+ | "name"
649
+ | "firstName"
650
+ | "lastName"
651
+ | "email"
652
+ | "phone"
653
+ | "company"
654
+ | "city"
655
+ | "country"
656
+ | "url"
657
+ | "uuid"
658
+ | "title"
659
+ | "sentence"
660
+ | "paragraph"
661
+ | "words"
662
+ | "streetAddress"
663
+ | "template"
664
+ | "sequence"
665
+ | "sample"
666
+ | "constant"
667
+ | "enum"
668
+ | "set"
669
+ | "json";
670
+ /** `oneOf` / `sample`: the pool to draw from. `weighted`: `{ value: weight }`. */
671
+ values?: unknown[] | Record<string, number>;
672
+ /** `int` / `float` / `sample` / `sentence` / `paragraph`: lower bound. */
673
+ min?: number;
674
+ /** `int` / `float` / `sample` / `sentence` / `paragraph`: upper bound. */
675
+ max?: number;
676
+ /** `float`: decimal places. */
677
+ precision?: number;
678
+ /** `bool`: probability of `true` (0..1). */
679
+ trueRate?: number;
680
+ /** `date` / `datetime`: a relative window like `"90d"`, counted back from now. */
681
+ within?: string;
682
+ /** `date` / `datetime`: explicit range start, as an alternative to `within`. */
683
+ from?: string | number | Date;
684
+ /** `date` / `datetime`: explicit range end. */
685
+ to?: string | number | Date;
686
+ /** `template`: `"Order {i}"`, where `{i}` is the row number, `{col}` another column in the same row. */
687
+ template?: string;
688
+ /** `sequence`: the first number in the run. */
689
+ start?: number;
690
+ /** `sequence`: how much each row advances the counter. */
691
+ step?: number;
692
+ /** `sequence`: zero-pad the number to this width. */
693
+ pad?: number;
694
+ /** `sequence`: text placed before the number. */
695
+ prefix?: string;
696
+ /** `sequence`: text placed after the number. */
697
+ suffix?: string;
698
+ /** `words`: how many words. */
699
+ count?: number;
700
+ /** `constant`: the fixed value to write. */
701
+ value?: unknown;
702
+ /** Fraction of rows (0..1) that get NULL instead of a generated value. */
703
+ nullRate?: number;
704
+ }
705
+
706
+ /** Column name → its generation recipe (or a bare kind string, e.g. `{ status: "oneOf" }`). */
707
+ type GenerateSpec = Record<string, GenerateColumnSpec | string>;
708
+
709
+ interface GenerateOptions extends BulkCreateOptions {
710
+ /** Seed the PRNG for reproducible output. Omit for varied data. */
711
+ seed?: number;
712
+ /**
713
+ * Rows generated + inserted per slice, so memory stays bounded for very large counts.
714
+ * Defaults to 2000; clamped to 1..5000. Independent of `chunkSize` (rows per INSERT).
715
+ */
716
+ batchSize?: number;
717
+ }
718
+
719
+ interface BulkUpdateOptions {
720
+ /** Narrow which tenant's rows the statement may touch. */
721
+ scope?: ScopeOptions;
722
+ /**
723
+ * Required to run with NO filter. Without it an unfiltered call is rejected
724
+ * (`BULK_WRITE_UNFILTERED`, 400) so a whole table is never rewritten by accident.
725
+ */
726
+ all?: boolean;
727
+ }
728
+
729
+ interface BulkDeleteOptions extends BulkUpdateOptions {
730
+ /**
731
+ * `"soft"` (default) sets `deleted_at` when the table has that column; `"hard"` (or any table
732
+ * without `deleted_at`) issues a real DELETE. Note this is the OPPOSITE default from
733
+ * {@link HandlerSdk.delete}, which is hard by default.
734
+ */
735
+ deleteStrategy?: DeleteStrategy;
736
+ }
737
+
738
+ // --- Safe SQL builder (sdk.sql``) -------------------------------------------
739
+ /** A validated dynamic identifier (table/column name) produced by `sdk.sql.id(name)`. */
740
+ interface SqlIdentifier {
741
+ /** The validated identifier text, safe to splice into SQL because it was checked, not escaped. */
742
+ readonly name: string;
743
+ }
744
+
745
+ /**
746
+ * A composable SQL fragment produced by the `sdk.sql`` tagged template. Await it to RUN the
747
+ * query (it resolves to the result rows); or interpolate it into another `sdk.sql`` to compose
748
+ * (e.g. build a conditional WHERE). Carries the compiled `text` + bound `values`.
749
+ */
750
+ interface SqlFragment<TRow = Record<string, unknown>> extends PromiseLike<TRow[]> {
751
+ /** The compiled SQL, with every interpolation replaced by a `?` placeholder. */
752
+ readonly text: string;
753
+ /** The values bound to those placeholders, in order. */
754
+ readonly values: unknown[];
755
+ }
756
+
757
+ /** Values you may interpolate into a `sdk.sql`` template (everything is bound as a `?` param). */
758
+ type SqlInterpolation =
759
+ | JsonPrimitive
760
+ | Date
761
+ | Identifier
762
+ | Array<JsonPrimitive | Date | Identifier>
763
+ | SqlIdentifier
764
+ | SqlFragment;
765
+
766
+ interface SqlBuilder {
767
+ /** Tagged template: `sdk.sql`SELECT ... WHERE col = ${value}``. Interpolations auto-bind. */
768
+ <TRow = Record<string, unknown>>(
769
+ strings: TemplateStringsArray,
770
+ ...values: SqlInterpolation[]
771
+ ): SqlFragment<TRow>;
772
+ /** Wrap a dynamic table/column NAME (validated: letters/numbers/underscore) for interpolation. */
773
+ id(name: string): SqlIdentifier;
774
+ /** Stitch a list of fragments/values together with a separator (default `", "`). */
775
+ join(items: SqlInterpolation[], separator?: string): SqlFragment;
776
+ }
777
+
778
+ // The handler-facing SDK.
779
+ //
780
+ // Members are grouped by WHAT THEY DO, in `// ── Section ──` blocks, and the docs generator
781
+ // (docs-site/scripts/generate-sdk-reference.mjs) turns each block into a heading in that
782
+ // order. The reference used to group by capability instead, which split siblings apart:
783
+ // `update` sat under "Write data" while `updateWhere` fell into a leftover bucket several
784
+ // screens away, because one needs a grant and the other does not. Capability is now shown
785
+ // per method as a badge, which is where a grant belongs; it is not a taxonomy.
786
+ //
787
+ // Adding a method: put it inside the section it belongs to, next to its siblings, and give
788
+ // an alias the slot directly after the method it aliases. Deciding where it goes is part of
789
+ // adding it; do not append to the bottom and leave it. A member declared before the first
790
+ // marker fails the build; one appended after the last marker inherits that last section
791
+ // silently, so `npm run generate` prints the full roster for exactly that reason. Read it.
792
+ //
793
+ // Plain `//` rather than JSDoc on purpose: this is a note for whoever edits the contract,
794
+ // and JSDoc here would surface in the console editor's hover for every handler author.
795
+ interface HandlerSdk {
796
+ // ── Reading data ────────────────────────────────────────────────────────
797
+
798
+ /**
799
+ * Read a single row by its uid, or by its key when the table declares one. Resolves to `null`
800
+ * when no row matches (a value that is neither matches nothing). The row carries `uid` and no
801
+ * `id`; each foreign key appears as `<name>_uid` holding the referenced row's uid.
802
+ *
803
+ * @param table - Table name.
804
+ * @param uid - The row's uid, or its key (`sdk.read("channels", "leadership")`).
805
+ * @param options - Restrict scope.
806
+ * @returns The row, or `null` if not found.
807
+ * @example
808
+ * const order = await sdk.read("orders", ctx.reqParams.orderUid);
809
+ * // order.customer_uid is the customer's uid, ready to pass to sdk.read("customers", …)
810
+ */
811
+ read<T = Record<string, unknown>>(
812
+ table: string,
813
+ uid: RowUid,
814
+ options?: ReadOptions,
815
+ ): Promise<T | null>;
816
+
817
+ /**
818
+ * Read a filtered list of rows.
819
+ *
820
+ * ## ALWAYS NORMALIZE THE RESULT
821
+ *
822
+ * ```js
823
+ * const result = await sdk.readList("orders", { filters: { status: "open" }, limit: 50 });
824
+ * const rows = Array.isArray(result) ? result : result.items;
825
+ * ```
826
+ *
827
+ * This returns a plain array **only when you pass no `limit`, no `offset`, and no
828
+ * `paginate`**. Any one of those three switches it to an `{ items, paging }` envelope,
829
+ * and `limit` is on nearly every real call, so in practice the envelope is what you get.
830
+ *
831
+ * Treating the envelope as an array does not throw; it silently misbehaves.
832
+ * `result.length` is `undefined`, `result.map` is not a function, and
833
+ * `result.length ? result[0] : null` yields `null`, so a row that EXISTS reads as absent.
834
+ * The failure surfaces much later as a duplicate-key error on the insert you only made
835
+ * because the lookup "found nothing".
836
+ *
837
+ * Use `readPage` instead when you always want the envelope and never want to branch.
838
+ *
839
+ * @param table - Table name, e.g. `"orders"`.
840
+ * @param options - Filters, paging, sorting, and scope. Set `scope: { shared: true }`
841
+ * to read across ALL orgs (cross-tenant; needs the `sdk:shared_read` capability).
842
+ * @returns A plain array with no limit/offset/paginate; otherwise `{ items, paging }`.
843
+ * @example
844
+ * // `limit` means this resolves to an ENVELOPE; normalize before using it.
845
+ * // A reference is filtered by uid under its `_uid` name; rows carry `uid`, never `id`.
846
+ * const result = await sdk.readList("orders", {
847
+ * filters: { status: "open", customer_uid: data.customerUid, deleted_at: null },
848
+ * limit: 50,
849
+ * sort: "created_at desc",
850
+ * });
851
+ * const rows = Array.isArray(result) ? result : result.items;
852
+ * @example
853
+ * // Cross-org read (requires the sdk:shared_read capability):
854
+ * const all = await sdk.readList("orders", { scope: { shared: true } });
855
+ */
856
+ readList<T = Record<string, unknown>>(
857
+ table: string,
858
+ options?: ReadListOptions,
859
+ ): Promise<T[] | ReadListEnvelope<T>>;
860
+
861
+ /**
862
+ * Read a paginated list and always get back a normalized page result,
863
+ * including `total` when `includeTotal` is set.
864
+ *
865
+ * @param table - Table name.
866
+ * @param options - Filters, paging, sorting, and `includeTotal`.
867
+ * @returns `{ items, limit, offset, total, paginated }`.
868
+ * @example
869
+ * const page = await sdk.readPage("orders", {
870
+ * filters: { deleted_at: null },
871
+ * limit: 25,
872
+ * includeTotal: true,
873
+ * });
874
+ * @example
875
+ * // Every row, a page at a time, in creation order (keyset paging).
876
+ * let after = null;
877
+ * do {
878
+ * const page = await sdk.readPage("orders", { filters: { status: "open" }, limit: 200, after });
879
+ * for (const order of page.items) { … }
880
+ * after = page.nextCursor;
881
+ * } while (after);
882
+ */
883
+ readPage<T = Record<string, unknown>>(
884
+ table: string,
885
+ options?: ReadListOptions,
886
+ ): Promise<ReadPageResult<T>>;
887
+
888
+ // ── Analyzing data ──────────────────────────────────────────────────────
889
+
890
+ /**
891
+ * Aggregate rows in the DATABASE: COUNT/SUM/AVG/MIN/MAX/COUNT_DISTINCT, optionally grouped
892
+ * (with date-truncation / numeric-bucket / lower derivations), filtered, HAVING, and sorted,
893
+ * returning only the compact grouped result. Token/compute cost scales with the ANSWER, not the
894
+ * dataset. Runs the SAME read governance as {@link readList} (read_list policy + tenancy scope +
895
+ * redaction) and compiles an allow-listed structured spec to one safe, parameterized SELECT:
896
+ * every column is validated against the live, non-redacted catalog (unknown/redacted → 422) and
897
+ * all values are bound params. Results are bounded by `MAX_GROUPS` with honest `truncated` meta.
898
+ *
899
+ * @param table - Table name.
900
+ * @param spec - The structured aggregate spec (measures / groupBy / filters / having / sort / limit).
901
+ * @returns `{ rows, meta: { groups, matchedGroups, truncated, limit } }`.
902
+ * @example
903
+ * const byMonth = await sdk.aggregate("orders", {
904
+ * groupBy: [{ column: "created_at", truncate: "month" }, { column: "status" }],
905
+ * measures: [{ op: "count" }, { op: "sum", column: "total", as: "revenue" }],
906
+ * filters: { total: { $gte: 100 } },
907
+ * sort: "revenue DESC",
908
+ * });
909
+ * // Grouping by a reference answers with uids: rows are { customer_uid, revenue }.
910
+ * const byCustomer = await sdk.aggregate("orders", {
911
+ * groupBy: [{ column: "customer_uid" }],
912
+ * measures: [{ op: "sum", column: "total", as: "revenue" }],
913
+ * });
914
+ */
915
+ aggregate<T = Record<string, unknown>>(
916
+ table: string,
917
+ spec: AggregateSpec,
918
+ ): Promise<AggregateResult<T>>;
919
+
920
+ /**
921
+ * Profile a resource in ONE call: a first-class, DETERMINISTIC recipe that composes
922
+ * {@link aggregate}: returns the total row count plus a per-column summary (numeric
923
+ * min/max/avg/distinct, date earliest/latest, categorical top-N with counts). Runs the same
924
+ * read_list governance; redacted columns are omitted. Zero improvisation, no model tokens.
925
+ *
926
+ * @param table - Table name.
927
+ * @param options - `topN` controls how many top categories to return per categorical column.
928
+ * @returns `{ table, rowCount, columns }`, one summary entry per non-redacted column.
929
+ * @example
930
+ * const profile = await sdk.summarize("orders", { topN: 10 });
931
+ */
932
+ summarize(
933
+ table: string,
934
+ options?: { topN?: number },
935
+ ): Promise<SummarizeResult>;
936
+
937
+ // ── Writing data ────────────────────────────────────────────────────────
938
+
939
+ /**
940
+ * Insert one row into a table and return its uid. A foreign key is written by uid under its
941
+ * `<name>_uid` name; `id`, `uid`, `org_id` and the raw foreign-key column are refused.
942
+ *
943
+ * @param table - Table name.
944
+ * @param data - Column → value object to insert.
945
+ * @param options - Narrow the scope the row is attributed to.
946
+ * @returns `{ uid, affectedRows }`.
947
+ * @example
948
+ * const { uid } = await sdk.create("orders", {
949
+ * customer_uid: data.customerUid,
950
+ * total: 42.0,
951
+ * });
952
+ */
953
+ create(
954
+ table: string,
955
+ data: Record<string, unknown>,
956
+ options?: CreateOptions,
957
+ ): Promise<CreateResult>;
958
+
959
+ /**
960
+ * Insert MANY rows in one atomic, guarded batch. Runs the create authorization + scope once
961
+ * (create policy is row-independent) and issues a single multi-row INSERT per distinct column
962
+ * set, far fewer round-trips than looping `create`, with identical governance (same
963
+ * `${table}:create` policy, per-row scope/owner injection, and change-events). Rolls the whole
964
+ * batch back if any row fails.
965
+ *
966
+ * @param table - Table name.
967
+ * @param rows - Array of column → value objects to insert.
968
+ * @param options - Write into a specific org / tenant / user scope.
969
+ * Every row's `<name>_uid` references are resolved together, one lookup per referenced column.
970
+ *
971
+ * @returns `{ count, uids, affectedRows }`, with `uids` aligned to the input order.
972
+ * @example
973
+ * const { count, uids } = await sdk.createMany("tickets", [
974
+ * { subject: "A", status: "open" },
975
+ * { subject: "B", status: "open" },
976
+ * ]);
977
+ */
978
+ createMany(
979
+ table: string,
980
+ rows: Array<Record<string, unknown>>,
981
+ options?: BulkCreateOptions,
982
+ ): Promise<BulkCreateResult>;
983
+
984
+ /**
985
+ * Update one row, named by its uid, with partial column values.
986
+ *
987
+ * @param table - Table name.
988
+ * @param uid - The row's uid.
989
+ * @param data - Column → new value object (a reference by uid, as `<name>_uid`).
990
+ * @param options - Restrict scope.
991
+ * @returns `{ affectedRows }`.
992
+ * @example
993
+ * await sdk.update("orders", order.uid, { status: "fulfilled" });
994
+ */
995
+ update(
996
+ table: string,
997
+ uid: RowUid,
998
+ data: Record<string, unknown>,
999
+ options?: UpdateOptions,
1000
+ ): Promise<UpdateResult>;
1001
+
1002
+ /**
1003
+ * Update EVERY row matching a filter in ONE governed UPDATE: the set-based counterpart to
1004
+ * {@link update}. Use it instead of reading rows and looping: one statement, one policy check
1005
+ * (`${table}:update`), scope clauses always ANDed in, and soft-deleted rows excluded when the
1006
+ * table has `deleted_at`.
1007
+ *
1008
+ * SAFETY: an unfiltered call is REJECTED (`BULK_WRITE_UNFILTERED`, 400) unless you explicitly
1009
+ * pass `{ all: true }`, so a whole table is never rewritten by accident.
1010
+ *
1011
+ * @param table - Table name.
1012
+ * @param filters - Filter object (same DSL as {@link readList}) selecting the rows to update.
1013
+ * @param changes - Column → new value object applied to every matching row.
1014
+ * @param options - `all` to permit an unfiltered update, plus scope.
1015
+ * @returns `{ affectedRows }`.
1016
+ * @example
1017
+ * const { affectedRows } = await sdk.updateWhere(
1018
+ * "tickets",
1019
+ * { status: "open", priority: "low" },
1020
+ * { status: "archived" },
1021
+ * );
1022
+ */
1023
+ updateWhere(
1024
+ table: string,
1025
+ filters: Filters,
1026
+ changes: Record<string, unknown>,
1027
+ options?: BulkUpdateOptions,
1028
+ ): Promise<UpdateResult>;
1029
+
1030
+ // ── Deleting data ───────────────────────────────────────────────────────
1031
+
1032
+ /**
1033
+ * Delete one row, named by its uid. Honors soft-delete when `deleteStrategy: "soft"`.
1034
+ *
1035
+ * @param table - Table name.
1036
+ * @param uid - The row's uid.
1037
+ * @param options - `deleteStrategy` (`"hard"` | `"soft"`) and scope.
1038
+ * @returns `{ affectedRows }`.
1039
+ * @example
1040
+ * await sdk.delete("orders", order.uid, { deleteStrategy: "soft" });
1041
+ */
1042
+ delete(
1043
+ table: string,
1044
+ uid: RowUid,
1045
+ options?: DeleteOptions,
1046
+ ): Promise<DeleteResult>;
1047
+
1048
+ /**
1049
+ * Delete EVERY row matching a filter in ONE governed statement: the set-based counterpart to
1050
+ * {@link delete}. One policy check (`${table}:delete`) with scope clauses always ANDed in.
1051
+ * Defaults to SOFT delete (sets `deleted_at`) when the table has that column; pass
1052
+ * `deleteStrategy: "hard"` for a real DELETE.
1053
+ *
1054
+ * SAFETY: an unfiltered call is REJECTED (`BULK_WRITE_UNFILTERED`, 400) unless you explicitly
1055
+ * pass `{ all: true }`, so a whole table is never wiped by accident.
1056
+ *
1057
+ * @param table - Table name.
1058
+ * @param filters - Filter object (same DSL as {@link readList}) selecting the rows to delete.
1059
+ * @param options - `deleteStrategy`, `all` to permit an unfiltered delete, plus scope.
1060
+ * @returns `{ affectedRows }`.
1061
+ * @example
1062
+ * await sdk.deleteWhere("sessions", { expires_at: { $lt: new Date() } });
1063
+ */
1064
+ deleteWhere(
1065
+ table: string,
1066
+ filters: Filters,
1067
+ options?: BulkDeleteOptions,
1068
+ ): Promise<DeleteResult>;
1069
+
1070
+ // ── Bulk and synthetic data ─────────────────────────────────────────────
1071
+
1072
+ /**
1073
+ * Bulk-import rows from a CSV into a table: parse, map headers to columns, coerce and validate
1074
+ * every cell against the live schema, then insert.
1075
+ *
1076
+ * Every cell is checked against the column that will hold it BEFORE anything is written (enum
1077
+ * membership, string length, integer range and signedness, numeric scale, JSON validity), so a
1078
+ * bad spreadsheet fails with `row 412, column status: 'Pending' is not one of open, closed`
1079
+ * rather than an opaque MySQL error part-way through the batch. A value that cannot be stored is
1080
+ * always an error; it is never silently coerced to a default or a substitute.
1081
+ *
1082
+ * Rows go through {@link createMany}, so an import is an ordinary governed write: create policy,
1083
+ * table lock, db-size gate, scope stamping, and one change-event per row. The file speaks the row
1084
+ * shape whichever runtime imports it: a reference is a `<name>_uid` column of uids, and `id`,
1085
+ * `uid` and the scope columns (`org_id` / `tenant_id`) are not importable (the write path mints
1086
+ * and stamps them; pass `ignoreUnknownColumns` to skip them in an export you re-import).
1087
+ * Inside {@link withTransaction} the whole import rolls back with everything else.
1088
+ *
1089
+ * A column the table REQUIRES (NOT NULL, no default) that the mapping does not answer is
1090
+ * refused before anything is written, and reported as `missingRequiredColumns`. That is a
1091
+ * property of the mapping rather than of any row, so no `onError` setting skips past it: supply
1092
+ * a header, a `defaults` entry, or a column default.
1093
+ *
1094
+ * Start with `dryRun: true`: it returns the resolved mapping, the coerced preview rows, and any
1095
+ * validation errors without writing, which is exactly what an import confirmation screen needs.
1096
+ *
1097
+ * @param options - Source (`csv` or `csvBase64`), `mapping`, `defaults`, `dryRun`, `onError`.
1098
+ * @returns `{ imported, affectedRows, columns, mapping, totalRows, skippedRows, errors }`, or the
1099
+ * dry-run shape `{ dryRun: true, headers, mapping, columns, previewRows, errors,
1100
+ * missingRequiredColumns, ... }`.
1101
+ * @example
1102
+ * const preview = await sdk.importCsv({ table: "contacts", csv, dryRun: true });
1103
+ * // Both checks: clean cells are not the same thing as a committable mapping.
1104
+ * if (!preview.errorRowCount && !preview.missingRequiredColumns.length) {
1105
+ * await sdk.importCsv({ table: "contacts", csv });
1106
+ * }
1107
+ */
1108
+ importCsv(options: ImportCsvOptions): Promise<unknown>;
1109
+
1110
+ /**
1111
+ * Generate + insert N synthetic rows from a compact per-column spec: you supply INTENT, the
1112
+ * runtime produces the VOLUME. This is the correct way to seed sample/demo/test data at scale:
1113
+ * never write a loop that emits rows by hand, which does not scale past a few hundred.
1114
+ *
1115
+ * Fully schema-driven, so it seeds ANY table: the row shape comes from the live column catalog
1116
+ * (types, enum members, lengths, nullability, defaults). Enum membership and column lengths are
1117
+ * enforced for you, and a bad or partial spec degrades to a type-aware default rather than a
1118
+ * failed INSERT. Columns the scope owns (`org_id` / `tenant_id`) are never generated (the write
1119
+ * path stamps them), and neither is `uid` (minted on insert). A reference is generated only when
1120
+ * the spec names it by `<name>_uid` with uids to pick from. Rows go through {@link createMany}, so every governance invariant (create
1121
+ * policy, scope injection, table lock, db-size gate, change-events) still applies.
1122
+ *
1123
+ * @param table - Table name.
1124
+ * @param count - How many rows to generate. Clipped by a per-call ceiling; the result reports
1125
+ * `capped` + `remaining` so you can loop rather than be silently truncated.
1126
+ * @param spec - Column → generation recipe. Omitted columns are inferred from the schema.
1127
+ * @param options - `seed` for reproducible data, `batchSize` / `chunkSize` to tune batching, `scope`.
1128
+ * @returns `{ requested, generated, affectedRows, columns, sample }` (+ `capped` / `remaining`).
1129
+ * @example
1130
+ * const { generated, sample } = await sdk.generateRecords("tickets", 500, {
1131
+ * status: { kind: "weighted", values: { open: 3, closed: 1 } },
1132
+ * subject: { kind: "title" },
1133
+ * opened_at: { kind: "datetime", within: "90d" },
1134
+ * });
1135
+ */
1136
+ generateRecords(
1137
+ table: string,
1138
+ count: number,
1139
+ spec?: GenerateSpec,
1140
+ options?: GenerateOptions,
1141
+ ): Promise<GenerateResult>;
1142
+
1143
+ // ── Raw SQL ─────────────────────────────────────────────────────────────
1144
+
1145
+ /**
1146
+ * Safe SQL builder: the injection-proof way to write DYNAMIC raw SQL. Used as a tagged
1147
+ * template, every `${...}` interpolation is bound as a `?` parameter automatically, so user
1148
+ * input can NEVER inject. This is the sanctioned alternative to string-interpolated
1149
+ * `query(...)` (which is rejected at save).
1150
+ *
1151
+ * RAW SQL IS INSIDE THE DATABASE. It sees storage rows (`id`, raw foreign keys, `org_id`)
1152
+ * and may JOIN on `id` at full speed; that is the fast path. It is also outside the typed
1153
+ * helpers' scope wall, so scope it yourself. Whatever you RETURN to your caller must not carry an
1154
+ * id: select `uid` (and the referenced row's `uid` through the join) instead.
1155
+ *
1156
+ * @example
1157
+ * // Values auto-bind, safe even with raw user input. Join on ids; return uids.
1158
+ * const rows = await sdk.sql`
1159
+ * SELECT o.uid, o.status, c.uid AS customer_uid
1160
+ * FROM orders o JOIN customers c ON c.id = o.customer_id
1161
+ * WHERE o.status = ${data.status}
1162
+ * `;
1163
+ * @example
1164
+ * // Dynamic identifier (a value can't be a column name), IN-list, and composition:
1165
+ * const sortCol = sdk.sql.id(data.sortColumn); // whitelist-validated
1166
+ * const uids = data.orderUids; // array → `?, ?, ?`
1167
+ * const openOnly = data.openOnly ? sdk.sql`AND status = ${"open"}` : sdk.sql``;
1168
+ * const rows = await sdk.sql`
1169
+ * SELECT uid, status FROM orders WHERE uid IN (${uids}) ${openOnly} ORDER BY ${sortCol}
1170
+ * `;
1171
+ *
1172
+ * Runs raw SQL, so it needs the `sdk:query` capability and bypasses the typed helpers'
1173
+ * scope/redaction/lock walls, exactly like {@link HandlerSdk.query}.
1174
+ */
1175
+ sql: SqlBuilder;
1176
+
1177
+ /**
1178
+ * Run a raw parameterized SQL query. Prefer the typed helpers above when
1179
+ * possible; use this for joins or aggregates they can't express. Like {@link HandlerSdk.sql}
1180
+ * it runs inside the database on storage rows (ids included): never return an id to a caller.
1181
+ *
1182
+ * SECURITY (enforced at save): the `sql` argument MUST be a STATIC string literal with `?`
1183
+ * placeholders. Interpolating or concatenating into it (`` sdk.query(`... ${x}`) ``,
1184
+ * `sdk.query("..." + x)`) or passing a variable / request field (`sdk.query(data.sql)`) is a
1185
+ * SQL-injection hole and is REJECTED at save. For ANY dynamic SQL, use the injection-proof
1186
+ * {@link HandlerSdk.sql} tagged template instead (await it directly).
1187
+ *
1188
+ * @param sql - A STATIC SQL string literal with `?` placeholders.
1189
+ * @param params - Values bound to the placeholders, in order.
1190
+ * @returns The result rows.
1191
+ * @example
1192
+ * const rows = await sdk.query(
1193
+ * "SELECT status, COUNT(*) AS n FROM orders WHERE created_at >= ? GROUP BY status",
1194
+ * [data.since],
1195
+ * );
1196
+ */
1197
+ query<TRow = Record<string, unknown>>(
1198
+ sql: string,
1199
+ params?: unknown[],
1200
+ ): Promise<TRow[]>;
1201
+
1202
+ // ── Transactions and idempotency ────────────────────────────────────────
1203
+
1204
+ /**
1205
+ * Run multiple SDK calls atomically. The callback receives a transactional
1206
+ * `tx` SDK; throwing rolls everything back, returning commits.
1207
+ *
1208
+ * All-or-nothing is not the same as alone: another caller can read the same row while your
1209
+ * transaction runs. When a write depends on what you read (stock, seats, a balance, a status),
1210
+ * read that row with `{ lock: true }` so the next caller waits for your commit.
1211
+ *
1212
+ * @param work - Async callback given a `tx` SDK. Return to commit, throw to roll back.
1213
+ * @returns Whatever the callback returns.
1214
+ * @example
1215
+ * const orderUid = await sdk.withTransaction(async (tx) => {
1216
+ * const type = await tx.read("ticket_types", data.ticketTypeUid, { lock: true });
1217
+ * if (!type || type.sold + data.quantity > type.capacity) throw new Error("Sold out");
1218
+ * await tx.update("ticket_types", type.uid, { sold: type.sold + data.quantity });
1219
+ * const { uid } = await tx.create("orders", { ticket_type_uid: type.uid, quantity: data.quantity });
1220
+ * return uid;
1221
+ * });
1222
+ */
1223
+ withTransaction<T>(work: (txSdk: HandlerSdk) => Promise<T>): Promise<T>;
1224
+
1225
+ /** Alias of {@link HandlerSdk.withTransaction}. */
1226
+ transaction<T>(work: (txSdk: HandlerSdk) => Promise<T>): Promise<T>;
1227
+
1228
+ /**
1229
+ * Guard a block with an idempotency key so retries with the same key return
1230
+ * the stored result instead of running the work twice.
1231
+ *
1232
+ * @param options - Idempotency `key` (required), plus `route`/`method`/`ttlSeconds`.
1233
+ * @param work - Async work to run at most once per key.
1234
+ * @returns The work result, fresh or replayed.
1235
+ * @example
1236
+ * const result = await sdk.withIdempotency(
1237
+ * { key: data.idempotencyKey, route: "create-order", method: "POST" },
1238
+ * async () => sdk.create("orders", data),
1239
+ * );
1240
+ */
1241
+ withIdempotency<T>(
1242
+ options: WithIdempotencyOptions<T>,
1243
+ work: () => Promise<T>,
1244
+ ): Promise<T>;
1245
+
1246
+ /** Alias of {@link HandlerSdk.withIdempotency}. */
1247
+ idempotent<T>(
1248
+ options: WithIdempotencyOptions<T>,
1249
+ work: () => Promise<T>,
1250
+ ): Promise<T>;
1251
+
1252
+ // ── Human approvals ─────────────────────────────────────────────────────
1253
+
1254
+ /**
1255
+ * Create (or resume) a human-approval gate and wait up to `waitForMs` for a
1256
+ * decision. Use with a stable `key` so retries attach to the same request.
1257
+ *
1258
+ * An approval is single-use: the call that passes the gate uses it up, so the approved
1259
+ * work runs once. A rejection is delivered once: the next call gets APPROVAL_REJECTED and
1260
+ * the request closes. Either way, a later call with the same key raises a new request for
1261
+ * a human to decide. If the work fails after the gate opened, the approval is still spent.
1262
+ * Requests belong to the caller's organization and are never visible to another.
1263
+ *
1264
+ * @returns The approval record (`approved` / `rejected` / `pending`).
1265
+ */
1266
+ awaitApproval(options?: AwaitApprovalOptions): Promise<ApprovalRecord>;
1267
+
1268
+ /** Look up an existing approval by `uid` or `key` without waiting. */
1269
+ getApprovalStatus(options?: { uid?: string; key?: string }): Promise<ApprovalRecord | null>;
1270
+
1271
+ /**
1272
+ * Approve a pending approval, optionally attaching `decisionData`/notes.
1273
+ *
1274
+ * Authorized against the CALLER (the person or agent who invoked this handler), not the
1275
+ * handler: the caller's role must hold "Approve paused work" (`approval_requests:decide`), and
1276
+ * listing that action on the handler's endpoint does not substitute for it. The decision is
1277
+ * recorded as the caller's, and a caller cannot approve a request they raised
1278
+ * (`APPROVAL_SELF_APPROVAL`). In a dry run nothing is written and the paused handler is not
1279
+ * replayed.
1280
+ */
1281
+ approveApproval(options?: ApprovalDecisionOptions): Promise<ApprovalRecord | null>;
1282
+
1283
+ /**
1284
+ * Reject a pending approval, optionally attaching `decisionData`/notes. Needs the same
1285
+ * authority as `approveApproval`; the principal that raised the request may reject (withdraw) it.
1286
+ */
1287
+ rejectApproval(options?: ApprovalDecisionOptions): Promise<ApprovalRecord | null>;
1288
+
1289
+ // ── External services ───────────────────────────────────────────────────
1290
+
1291
+ /**
1292
+ * Send an email AS THE APP, through an email connection (SMTP) its owner granted it under
1293
+ * App settings › Email, in the app's branding. Every message is logged in the app (App › Email),
1294
+ * where the owner can preview it exactly as sent, with `{{secret}}` values masked.
1295
+ *
1296
+ * `sdk.sendEmail(message)` uses the app's default connection; `sdk.sendEmail("billing", message)`
1297
+ * the one granted under that alias (in any case), or the connection's uid; App settings › Email
1298
+ * shows both. An app with no such grant is refused (`EMAIL_NOT_GRANTED`). Needs `sdk:external_email` and the caller's `email:send`.
1299
+ *
1300
+ * In a scheduled job's `ctx.job.each`, an email is keyed to its row: a retried page finds the
1301
+ * logged message and sends nothing (`duplicate: true`). A dry run checks everything and sends
1302
+ * nothing.
1303
+ *
1304
+ * @example
1305
+ * await sdk.sendEmail("billing", {
1306
+ * to: invoice.billing_email,
1307
+ * subject: "Invoice {number} is overdue",
1308
+ * heading: "Your invoice is overdue",
1309
+ * body: ["Invoice {number} for {amount} was due on {due}."],
1310
+ * action: { label: "Pay now", url: invoice.pay_url },
1311
+ * data: { number: invoice.number, amount: invoice.amount, due: invoice.due_date },
1312
+ * });
1313
+ *
1314
+ * @example
1315
+ * // A secret: in the email, but "•••" in the log.
1316
+ * await sdk.sendEmail({
1317
+ * to: user.email,
1318
+ * subject: "Your sign-in code",
1319
+ * body: ["Hi {name},", "Your code is {{code}}. It expires in 10 minutes."],
1320
+ * data: { name: user.fname, code },
1321
+ * });
1322
+ */
1323
+ sendEmail(
1324
+ connectionOrMessage: string | EmailMessage,
1325
+ message?: EmailMessage,
1326
+ ): Promise<SendEmailResult>;
1327
+
1328
+
1329
+ /**
1330
+ * Your app's connected Stripe account, scoped to THIS app. Products are
1331
+ * isolated per app via `metadata.app_uid`, so you only ever see/sell your
1332
+ * own. The org must have connected Stripe (Integrations); otherwise calls
1333
+ * throw `NO_STRIPE_CONNECTION`.
1334
+ *
1335
+ * @example
1336
+ * // Sell a product to an end customer:
1337
+ * const { products } = await sdk.stripe.listProducts();
1338
+ * const { url } = await sdk.stripe.createCheckout({
1339
+ * priceId: products[0].prices[0].id,
1340
+ * customerEmail: ctx.user.email,
1341
+ * });
1342
+ * return { checkoutUrl: url };
1343
+ */
1344
+ stripe: HandlerStripe;
1345
+
1346
+ /**
1347
+ * External MCP tool servers your org has connected and bound to THIS app
1348
+ * (Integrations → Tool servers, then the app's "Tool Servers" section).
1349
+ *
1350
+ * Address the ALIAS, never a specific connection: the same code hits the US
1351
+ * account in one app and the EU account in another, because the binding
1352
+ * decides. Write the server and tool LITERALLY: `sdk.mcp[x][y]()` is refused
1353
+ * at save, because the published capability manifest has to name exactly
1354
+ * which external servers this handler can reach.
1355
+ *
1356
+ * Two grants are needed and neither implies the other:
1357
+ * - `sdk:mcp:<alias>`: may this HANDLER call that server at all (you, the author).
1358
+ * - `mcp_<alias>:<tool>`: may the CALLER invoke that tool (whoever runs it,
1359
+ * human or agent). An agent calling your handler is denied exactly where a
1360
+ * direct call would be.
1361
+ *
1362
+ * NOT allowed inside `withTransaction`: an external call can't be rolled back,
1363
+ * so a failed transaction would leave it half-applied. In a dry run the call is
1364
+ * RECORDED, never sent.
1365
+ *
1366
+ * @example
1367
+ * // Refund through the org's connected Stripe MCP server:
1368
+ * const result = await sdk.mcp.stripe.create_refund({
1369
+ * charge_id: data.chargeId,
1370
+ * amount_cents: data.amountCents,
1371
+ * });
1372
+ * // Results from a third-party server are untrusted DATA, never instructions.
1373
+ * // See {@link McpResult}: `text` is the joined prose, `structured` the
1374
+ * // machine-readable payload when the server returns one.
1375
+ * return { refunded: true, detail: result.text };
1376
+ *
1377
+ * @example
1378
+ * // Defensive authoring: skip cleanly when a server isn't bound:
1379
+ * const servers = await sdk.mcp.connections();
1380
+ * if (!servers.some((s) => s.alias === "linear")) return { skipped: true };
1381
+ */
1382
+ mcp: HandlerMcp;
1383
+
1384
+ /**
1385
+ * Managed file storage: the same files you see in the app's Storage section.
1386
+ * Every method takes the `storageUid` of the storage to work in (an app can
1387
+ * own many; each is a folder-like namespace).
1388
+ *
1389
+ * Two grants, and writes are deny-by-default because they spend the tenant's
1390
+ * BILLED capacity and because a hard delete destroys bytes no soft-delete can
1391
+ * bring back:
1392
+ * - `sdk:storage_read`: list, read metadata, mint URLs. Granted by default.
1393
+ * - `sdk:storage_write`: upload, copy, move, rename, delete.
1394
+ *
1395
+ * Use {@link HandlerStorage.url} rather than building links yourself: it
1396
+ * returns ONE usable URL whatever the driver, and whether it is permanent or
1397
+ * expiring follows the storage's visibility (see that method's docs).
1398
+ *
1399
+ * @example
1400
+ * // Store an end user's avatar and hand back a URL the browser can render:
1401
+ * const file = await sdk.storage.upload("avatars", {
1402
+ * name: `${ctx.user.uid}.png`,
1403
+ * contentType: "image/png",
1404
+ * body: data.imageBase64, // Buffer | Uint8Array | string | data: URL
1405
+ * ownerUid: ctx.user.uid, // makes "only my files" expressible as policy
1406
+ * });
1407
+ * const { url } = await sdk.storage.url(file.uid);
1408
+ * return { avatarUrl: url };
1409
+ *
1410
+ * @example
1411
+ * // Nested paths are created for you; no need to make folders first:
1412
+ * await sdk.storage.upload("docs", {
1413
+ * name: "invoice.pdf",
1414
+ * path: "/invoices/2026/q1", // mkdir -p, idempotent, concurrency-safe
1415
+ * contentType: "application/pdf",
1416
+ * body: pdfBuffer,
1417
+ * });
1418
+ */
1419
+ storage: HandlerStorage;
1420
+
1421
+ /**
1422
+ * Scheduled jobs: run a PUBLISHED handler on an interval or a cron expression.
1423
+ *
1424
+ * The thing to understand before using this: a job runs as its OWN principal, not as you
1425
+ * and not as whoever created it. A newly created job holds NO roles, so it can do nothing
1426
+ * at all until a person arms it in the console. That is deliberate: a schedule outlives the
1427
+ * people who set it up, so its access has to be a standing decision somebody made on
1428
+ * purpose, not an inheritance from whoever happened to run this handler.
1429
+ *
1430
+ * Two grants, and writes are HIGH risk rather than medium:
1431
+ * - `sdk:crons_read`: list jobs, read run history, preview a schedule. Granted by default.
1432
+ * - `sdk:crons_write`: create, change, pause, delete, trigger. Deny-by-default, because
1433
+ * changing an EXISTING job decides what code runs under a principal someone else armed,
1434
+ * and {@link HandlerCrons.runNow} fires a job as that principal rather than as the caller.
1435
+ *
1436
+ * Binding roles to a job is deliberately NOT here. Arming a job stays on the governed action
1437
+ * surface (`crons:assign_cron_role`), so handler code can create a schedule but can never
1438
+ * grant it power, which keeps those two decisions separate.
1439
+ *
1440
+ * Missed windows are SKIPPED, never replayed: an outage owes one run, not six. And a job
1441
+ * fires at or after its due time, within about the scheduler tick (30s by default). If you
1442
+ * need sub-minute precision, you want a queue, not a schedule.
1443
+ *
1444
+ * @example
1445
+ * // Give a new customer their own nightly digest, in THEIR timezone:
1446
+ * const job = await sdk.crons.create({
1447
+ * name: `Nightly digest for ${data.customerName}`,
1448
+ * targetHandlerUid: data.digestHandlerUid, // must already exist; publish it to run it
1449
+ * payload: { customerId: data.customerId },
1450
+ * scheduleKind: "cron",
1451
+ * cronExpression: "0 7 * * *", // 7am local, correct across DST
1452
+ * timezone: data.timezone,
1453
+ * });
1454
+ * // It is PAUSED and powerless until someone arms it in the console.
1455
+ * return { jobUid: job.uid, status: job.status };
1456
+ *
1457
+ * @example
1458
+ * // Check a schedule before saving it: real fire times, not a restatement:
1459
+ * const runs = await sdk.crons.preview({
1460
+ * scheduleKind: "cron",
1461
+ * cronExpression: "0 0 1 * mon", // the 1st AND every Monday, not the overlap
1462
+ * timezone: "America/New_York",
1463
+ * });
1464
+ *
1465
+ * @example
1466
+ * // Report which jobs are failing, and what they were allowed to do when they failed:
1467
+ * const failures = await sdk.crons.listRuns({ status: "failed", limit: 20 });
1468
+ * return failures.map((run) => ({
1469
+ * job: run.cronName,
1470
+ * when: run.startedAt,
1471
+ * why: run.errorText,
1472
+ * couldDo: run.principalRoles, // the roles held AT THE TIME it ran
1473
+ * }));
1474
+ */
1475
+ crons: HandlerCrons;
1476
+
1477
+ /**
1478
+ * Give a PERSON a role in one of this app's orgs: the roster flow, from your own handler.
1479
+ *
1480
+ * Three walls, and you need all three:
1481
+ * - `sdk:roles_read` (granted by default) to read; `sdk:roles_write` (deny-by-default, HIGH)
1482
+ * to assign or unassign, so "this handler hands out roles" is visible when it is published.
1483
+ * - the CALLER's own policy (`users:bind-role`), evaluated as whoever called the handler.
1484
+ * - the grant ceiling: you may only hand out a role carrying what you hold yourself. A handler
1485
+ * is never a way around it.
1486
+ *
1487
+ * PEOPLE ONLY. Roles for agents and scheduled jobs are granted through their own governed
1488
+ * actions, which halt for a human; creating a principal and giving it power stay two decisions.
1489
+ *
1490
+ * @example
1491
+ * // Someone joined a customer's org: give them the role your app decided on.
1492
+ * await sdk.roles.assign({ userUid: member.uid, roleKey: "dispatcher" });
1493
+ *
1494
+ * const held = await sdk.roles.list({ userUid: member.uid });
1495
+ */
1496
+ roles: HandlerRoles;
1497
+
1498
+ /**
1499
+ * Semantic verbs over your own rows: the questions SQL cannot answer because they need the
1500
+ * model to read row CONTENT ("what are these tickets about", "pull the vendor and amount out
1501
+ * of this email body", "which of these complaints are about shipping").
1502
+ *
1503
+ * Reads go through the SAME governed read as {@link readList}: policy gate, tenancy scope,
1504
+ * and redaction are applied before anything reaches a provider. There is no privileged read
1505
+ * path here.
1506
+ *
1507
+ * Every mode reads a BOUNDED sample (default 100 rows, hard cap 500), so cost is predictable
1508
+ * and the result carries `sampled` when the table had more matching rows than were analyzed.
1509
+ * Runs on your organization's **fast** model by default. Pass `tier: "default"` for a harder
1510
+ * one-off question. Handlers never name a model; the AI connection decides which model each
1511
+ * tier uses, so changing it is one edit, not one per handler.
1512
+ *
1513
+ * In a handler dry run these make NO provider call: the intent is recorded in the test
1514
+ * ledger and an empty result is returned, so testing a handler never bills the org.
1515
+ *
1516
+ * @example
1517
+ * // What are the open tickets about?
1518
+ * const { text } = await sdk.ai.digest("tickets", { filters: { status: "open" } });
1519
+ *
1520
+ * // Group them, with a closed label set
1521
+ * const { byLabel } = await sdk.ai.classify("tickets", {
1522
+ * instruction: "Classify the support theme.",
1523
+ * labels: ["billing", "shipping", "bug", "other"],
1524
+ * });
1525
+ */
1526
+ ai: HandlerAi;
1527
+
1528
+
1529
+ // ── Utilities ───────────────────────────────────────────────────────────
1530
+
1531
+ /** Hash a plaintext password (bcrypt-style) for safe storage. */
1532
+ hashPassword(password: string): Promise<string>;
1533
+
1534
+ /**
1535
+ * The app itself: its branding (App settings › Branding), for what a handler renders in the
1536
+ * app's look. Read-only.
1537
+ *
1538
+ * @example
1539
+ * const brand = await sdk.app.branding();
1540
+ * return { logo: brand.logoUrl, primary: brand.colors.light.primary ?? "#111111" };
1541
+ */
1542
+ app: HandlerApp;
1543
+ }
1544
+
1545
+ /**
1546
+ * The external-MCP namespace. Any property is a bound server ALIAS, whose
1547
+ * properties are that server's tools: `sdk.mcp.<alias>.<tool>(args)`. Arguments
1548
+ * are validated against the server's OWN JSON Schema, so they must match what it
1549
+ * advertises (see `sdk.mcp.tools(alias)`).
1550
+ */
1551
+ interface HandlerMcp {
1552
+ /** External servers bound to this app (alias, label, status, exposed tools). No secrets, ever. */
1553
+ connections(): Promise<
1554
+ Array<{
1555
+ alias: string;
1556
+ label: string | null;
1557
+ provider: string | null;
1558
+ status: string | null;
1559
+ tools: string[];
1560
+ }>
1561
+ >;
1562
+ /**
1563
+ * The tools this app may surface on `alias`, with each one's JSON Schema, reviewed risk, and
1564
+ * the standard MCP tool annotations. The annotations are the server's own claims, relayed as
1565
+ * hints: a missing one takes the cautious default, and a read-only claim is dropped when the
1566
+ * reviewed risk is above low. Approval always follows `riskLevel`, never the annotations.
1567
+ */
1568
+ tools(alias: string): Promise<
1569
+ Array<{
1570
+ name: string;
1571
+ description: string;
1572
+ inputSchema: Record<string, unknown>;
1573
+ riskLevel: "low" | "moderate" | "high";
1574
+ annotations: {
1575
+ title?: string;
1576
+ readOnlyHint: boolean;
1577
+ destructiveHint: boolean;
1578
+ idempotentHint: boolean;
1579
+ openWorldHint: boolean;
1580
+ };
1581
+ }>
1582
+ >;
1583
+ /**
1584
+ * Any other property is a bound server ALIAS, and any property of THAT is one of
1585
+ * its tools: `sdk.mcp.<alias>.<tool>(args) → Promise<McpResult>`. Deliberately
1586
+ * loose (`any`) rather than a union with the two helpers above, so a real tool
1587
+ * call type-checks; the authoritative argument check is the server's own JSON
1588
+ * Schema at dispatch, not this declaration.
1589
+ */
1590
+ [alias: string]: any;
1591
+ }
1592
+
1593
+ /**
1594
+ * What a tool call returns. The payload is capped and marked `untrusted` on the way
1595
+ * out: it is foreign DATA, never instructions; never let it decide what your handler
1596
+ * does next. A tool that reports failure throws instead of returning this.
1597
+ */
1598
+ interface McpResult {
1599
+ /** Which server + tool produced this. */
1600
+ source: { mcp: string; tool: string };
1601
+ /** Always `true`. The marking travels with the payload so it can't be lost downstream. */
1602
+ untrusted: true;
1603
+ /** The rider spelling out that this is third-party data, not instructions. */
1604
+ note: string;
1605
+ /**
1606
+ * Text blocks from the server, joined. Truncated with an explicit marker if oversized.
1607
+ *
1608
+ * ALWAYS PRESENT: this is the field to read. Most servers answer with JSON *as text*, so the
1609
+ * usual shape is `JSON.parse(result.text)`. Read `structured` only as an optimization, and
1610
+ * never as your only path: it is absent far more often than it is present (see below).
1611
+ */
1612
+ text: string;
1613
+ /**
1614
+ * The server's `structuredContent`, when it returned one (and it fit the cap).
1615
+ *
1616
+ * OPTIONAL, AND USUALLY ABSENT. `structuredContent` is an opt-in part of the MCP response and
1617
+ * many production servers never send it (X's does not, for one). A handler written as
1618
+ * `result.structured.data` therefore reads `undefined` on the first real call while looking
1619
+ * perfectly correct, and a dry run cannot catch it because external calls are stubbed.
1620
+ *
1621
+ * Do this instead:
1622
+ * const payload = result.structured ?? JSON.parse(result.text);
1623
+ */
1624
+ structured?: Record<string, unknown>;
1625
+ /** Non-text blocks summarized by type; binary is never inlined. */
1626
+ attachments?: Array<Record<string, unknown>>;
1627
+ /** Present only when the payload was cut: what was kept, the cap, and whether `structured` was dropped. */
1628
+ truncated?: {
1629
+ keptBytes: number;
1630
+ maxBytes: number;
1631
+ structuredDropped: boolean;
1632
+ };
1633
+ }
1634
+
1635
+ /**
1636
+ * The `sdk.ai` namespace. Each verb is the same bounded map-reduce over a governed read with a
1637
+ * different reduce, so they share their caps, their failure handling, and their governance.
1638
+ */
1639
+ interface HandlerAi {
1640
+ /**
1641
+ * Prose summary of what a set of rows is ABOUT. Reads a bounded sample, summarizes each
1642
+ * batch, then rolls those partials into one set of points.
1643
+ *
1644
+ * @returns `{ text, points, analyzed, matched, sampled, batches, model }`.
1645
+ */
1646
+ digest(
1647
+ table: string,
1648
+ options?: AiCommonOptions & { instruction?: string },
1649
+ ): Promise<AiDigestResult>;
1650
+
1651
+ /**
1652
+ * Label each row and return COMPACT counts per label, not a row-proportional payload.
1653
+ * Supply `labels` to close the set; omit it to let the model choose consistent labels.
1654
+ *
1655
+ * @returns `{ byLabel, perRow, analyzed, unmapped, matched, sampled, model }`.
1656
+ */
1657
+ classify(
1658
+ table: string,
1659
+ options: AiCommonOptions & { instruction: string; labels?: string[] },
1660
+ ): Promise<AiClassifyResult>;
1661
+
1662
+ /**
1663
+ * Pull structured fields out of free text. The one deliberately row-proportional verb
1664
+ * (that IS the product), bounded by the sample cap. A field the row does not state comes
1665
+ * back `null` rather than guessed.
1666
+ *
1667
+ * @returns `{ rows: [{ uid, fields }], analyzed, unmapped, matched, sampled, model }`.
1668
+ */
1669
+ extract(
1670
+ table: string,
1671
+ options: AiCommonOptions & { instruction: string; fields: string[] },
1672
+ ): Promise<AiExtractResult>;
1673
+
1674
+ /**
1675
+ * Semantic predicate: the uids of rows that satisfy `instruction`. Returns uids rather than
1676
+ * rows so you fetch what you need through the governed read path.
1677
+ *
1678
+ * @returns `{ uids, analyzed, unmapped, matched, sampled, model }`.
1679
+ */
1680
+ filter(
1681
+ table: string,
1682
+ options: AiCommonOptions & { instruction: string },
1683
+ ): Promise<AiFilterResult>;
1684
+
1685
+ /**
1686
+ * Label rows and STORE the label in a real column. The one verb that writes.
1687
+ *
1688
+ * This is what makes AI affordable at scale: the model runs once per row, and every later
1689
+ * question about that column is a free indexed SQL aggregate instead of another model call.
1690
+ * Rows whose source text has not changed since they were labeled are skipped, so calling
1691
+ * this repeatedly costs nothing for rows that already settled.
1692
+ *
1693
+ * A value a person edited by hand is never overwritten: not by a re-run, not by a model
1694
+ * change. Editing a SOURCE column clears that protection, because that is the person asking
1695
+ * for a fresh read.
1696
+ *
1697
+ * Always runs on the fast tier and refuses `model` / `tier`: a stored value keeps one model per
1698
+ * column so the column never mixes provenance. Change the fast model on your AI connection to
1699
+ * move it.
1700
+ *
1701
+ * @param options.into the column to write into, an ordinary column you created normally.
1702
+ * @param options.from the columns the model may read. Redacted columns are refused.
1703
+ * @returns `{ column, examined, enriched, settledEmpty, skippedOverride, fresh }`.
1704
+ * @example
1705
+ * await sdk.ai.annotate("tickets", {
1706
+ * into: "theme",
1707
+ * from: ["subject", "body"],
1708
+ * instruction: "Classify the support theme.",
1709
+ * labels: ["billing", "shipping", "bug", "other"],
1710
+ * });
1711
+ * // From here on it is just SQL:
1712
+ * await sdk.aggregate("tickets", { groupBy: [{ column: "theme" }], measures: [{ op: "count" }] });
1713
+ */
1714
+ annotate(
1715
+ table: string,
1716
+ options: {
1717
+ into: string;
1718
+ from: string[];
1719
+ instruction: string;
1720
+ labels?: string[];
1721
+ filters?: Record<string, unknown>;
1722
+ /** Rows examined per call. Default 200, hard cap 500. */
1723
+ batchSize?: number;
1724
+ },
1725
+ ): Promise<AiAnnotateResult>;
1726
+
1727
+ /**
1728
+ * Mask personal details inside stored text.
1729
+ *
1730
+ * The other write verb, and the only destructive one: it overwrites the column it read
1731
+ * unless `into` names somewhere else. That is deliberate: a redaction that leaves the
1732
+ * original sitting in the next column has not redacted anything. Because of that, it only
1733
+ * ever touches the column you name, and a row the model returns nothing usable for keeps
1734
+ * its original text rather than being blanked.
1735
+ *
1736
+ * `of` is required. Masking everything by default would be a guess about which parts of the
1737
+ * customer's data matter, made destructively.
1738
+ *
1739
+ * @param options.column the text column to read.
1740
+ * @param options.into where to write the masked text. Defaults to `column` (in place).
1741
+ * @param options.of kinds to mask, e.g. `["person_name", "phone", "email"]`.
1742
+ * @returns `{ column, into, examined, rewritten, unmapped, model }`.
1743
+ * @example
1744
+ * // Mask in place
1745
+ * await sdk.ai.redact("support_notes", {
1746
+ * column: "body",
1747
+ * of: ["person_name", "phone", "email"],
1748
+ * });
1749
+ *
1750
+ * // Or keep the original and write the masked copy elsewhere
1751
+ * await sdk.ai.redact("support_notes", {
1752
+ * column: "body",
1753
+ * into: "body_public",
1754
+ * of: ["person_name", "phone"],
1755
+ * });
1756
+ */
1757
+ redact(
1758
+ table: string,
1759
+ options: {
1760
+ column: string;
1761
+ of: string[];
1762
+ into?: string;
1763
+ instruction?: string;
1764
+ filters?: Record<string, unknown>;
1765
+ sampleSize?: number;
1766
+ },
1767
+ ): Promise<AiRedactResult>;
1768
+
1769
+ /**
1770
+ * Compute and store embeddings for a set of rows, so they can be searched by meaning.
1771
+ *
1772
+ * Requires a provider that offers embeddings. Anthropic does not; OpenAI does. You get
1773
+ * `AI_EMBEDDINGS_UNSUPPORTED` rather than a confusing failure if the org's provider cannot.
1774
+ *
1775
+ * Re-running is safe: an existing embedding for a row is replaced, not duplicated.
1776
+ *
1777
+ * @returns `{ table, embedded, skipped, model, dimensions }`.
1778
+ */
1779
+ embed(
1780
+ table: string,
1781
+ options?: {
1782
+ columns?: string[];
1783
+ filters?: Record<string, unknown>;
1784
+ sampleSize?: number;
1785
+ dimensions?: number;
1786
+ },
1787
+ ): Promise<AiEmbedResult>;
1788
+
1789
+ /**
1790
+ * Find rows that mean something similar: for "related items", dedupe, and semantic search.
1791
+ *
1792
+ * Give it either `to` (an existing row's uid, which reuses that row's stored vector) or `text`
1793
+ * (free text, which is embedded on the fly). The row you searched from is never returned as
1794
+ * its own match.
1795
+ *
1796
+ * `minScore` (default 0.3) drops weak matches. A nearest-neighbor search always returns
1797
+ * *something*; without a floor the least-unrelated row comes back looking like a match.
1798
+ *
1799
+ * **Scale:** this is a scan over the rows of one table, not an index lookup; MySQL has no
1800
+ * approximate-nearest-neighbor index. Comfortable to roughly 100k embedded rows per table;
1801
+ * beyond that you want a dedicated vector store behind this same call.
1802
+ *
1803
+ * @returns `{ table, matches: [{ uid, score }], scanned }`, best score first.
1804
+ */
1805
+ similar(
1806
+ table: string,
1807
+ options: {
1808
+ to?: RowUid;
1809
+ text?: string;
1810
+ limit?: number;
1811
+ minScore?: number;
1812
+ },
1813
+ ): Promise<AiSimilarResult>;
1814
+ }
1815
+
1816
+ interface AiEmbedResult {
1817
+ table: string;
1818
+ embedded: number;
1819
+ /** Rows with no usable text, or that the provider returned no vector for. */
1820
+ skipped: number;
1821
+ model?: string | null;
1822
+ dimensions?: number;
1823
+ testMode?: boolean;
1824
+ }
1825
+
1826
+ interface AiSimilarResult {
1827
+ table: string;
1828
+ /** Best first. `score` is cosine similarity in [-1, 1]. */
1829
+ matches: Array<{ uid: RowUid | null; score: number }>;
1830
+ /** Embedded rows compared: the honest size of the scan. */
1831
+ scanned?: number;
1832
+ testMode?: boolean;
1833
+ }
1834
+
1835
+ /** What one `redact` pass did. */
1836
+ interface AiRedactResult {
1837
+ column: string;
1838
+ /** Where the masked text was written. Equal to `column` for an in-place run. */
1839
+ into: string;
1840
+ examined: number;
1841
+ /** Rows actually rewritten. Rows the model skipped keep their original text. */
1842
+ rewritten: number;
1843
+ unmapped?: number;
1844
+ model?: string;
1845
+ testMode?: boolean;
1846
+ }
1847
+
1848
+ /** What one `annotate` pass did. Every field is a count, so it reports honestly. */
1849
+ interface AiAnnotateResult {
1850
+ column: string;
1851
+ /** Rows looked at. */
1852
+ examined: number;
1853
+ /** Rows the model labeled and that were written. */
1854
+ enriched: number;
1855
+ /** Rows with no source content, settled to null without spending tokens. */
1856
+ settledEmpty: number;
1857
+ /** Rows a human owns. Never touched. */
1858
+ skippedOverride: number;
1859
+ /** Rows already up to date. */
1860
+ fresh: number;
1861
+ /** Present only in a handler dry run, where no provider call was made. */
1862
+ testMode?: boolean;
1863
+ }
1864
+
1865
+ /**
1866
+ * The kind of model a `sdk.ai` call runs on. `"fast"` is low-cost and the default; `"default"` is
1867
+ * your organization's more capable model. The models behind both are chosen on the AI connection.
1868
+ */
1869
+ type AiTier = "fast" | "default";
1870
+
1871
+ /** Options shared by every `sdk.ai` verb. */
1872
+ interface AiCommonOptions {
1873
+ /** Narrow the rows analyzed. Same filter DSL as {@link readList}. */
1874
+ filters?: Record<string, unknown>;
1875
+ /** Which columns the model may read. Defaults to all non-redacted, non-audit columns. */
1876
+ columns?: string[];
1877
+ /** Rows to analyze. Default 100, hard cap 500. */
1878
+ sampleSize?: number;
1879
+ /**
1880
+ * Which kind of model answers: `"fast"` (the default: low-cost, right for most work) or
1881
+ * `"default"` (your organization's more capable model). You never name a model: which model
1882
+ * each tier uses is set once on your organization's AI connection, so every handler keeps
1883
+ * working when that choice changes. Passing `model` is refused with `AI_TIER_INVALID`.
1884
+ */
1885
+ tier?: AiTier;
1886
+ }
1887
+
1888
+ /** Fields every `sdk.ai` verb returns. */
1889
+ interface AiResultBase {
1890
+ mode: "digest" | "classify" | "extract" | "filter";
1891
+ /** Rows actually analyzed by the model. */
1892
+ analyzed: number;
1893
+ /** Rows the read matched in total; compare with `analyzed` to see what was left out. */
1894
+ matched: number;
1895
+ /** True when `matched` exceeded the sample: the answer describes a sample, not the table. */
1896
+ sampled: boolean;
1897
+ /** The model that produced this answer. */
1898
+ model?: string;
1899
+ /** Present only in a handler dry run, where no provider call was made. */
1900
+ testMode?: boolean;
1901
+ }
1902
+
1903
+ interface AiDigestResult extends AiResultBase {
1904
+ /** The points joined as a bulleted block, ready to show. */
1905
+ text: string;
1906
+ points: string[];
1907
+ batches: number;
1908
+ }
1909
+
1910
+ interface AiClassifyResult extends AiResultBase {
1911
+ /** Compact count table, highest first. */
1912
+ byLabel: Array<{ label: string; count: number }>;
1913
+ /** Per-row assignments, in the order the rows were read. */
1914
+ perRow: Array<{ uid: RowUid; label: string }>;
1915
+ /** Rows the model returned no usable answer for (a failed batch never sinks the run). */
1916
+ unmapped: number;
1917
+ batches: number;
1918
+ }
1919
+
1920
+ interface AiExtractResult extends AiResultBase {
1921
+ rows: Array<{ uid: RowUid; fields: Record<string, string | null> }>;
1922
+ unmapped: number;
1923
+ batches: number;
1924
+ }
1925
+
1926
+ interface AiFilterResult extends AiResultBase {
1927
+ /** Uids of the rows that satisfied the predicate. */
1928
+ uids: RowUid[];
1929
+ unmapped: number;
1930
+ batches: number;
1931
+ }
1932
+
1933
+ /** A stored file's metadata row. Named by `uid`, like everything it references. */
1934
+ interface StorageFile {
1935
+ /** The file's handle: every other storage method names a file by this. */
1936
+ uid: string;
1937
+ /** File name within its folder. Duplicates are auto-deduped (`a.pdf` → `a (1).pdf`). */
1938
+ name: string;
1939
+ /** Containing folder's uid, or `null` at the storage root. */
1940
+ folder_uid: string | null;
1941
+ storage_uid: string | null;
1942
+ mime_type: string | null;
1943
+ size: number | null;
1944
+ /**
1945
+ * The END USER this file belongs to, in your app's own user space. Distinct
1946
+ * from `created_by` (whoever performed the write: an admin, a handler, an
1947
+ * agent). Set it on upload (`ownerUid`) so ownership can be enforced by policy.
1948
+ */
1949
+ owner_uid: string | null;
1950
+ /** Your own data travelling with the file (alt text, caption, status …). */
1951
+ metadata: Record<string, unknown> | null;
1952
+ created_at: string;
1953
+ updated_at: string;
1954
+ /**
1955
+ * Present only on the app owner's own items (no org), and only to the owner's side (the
1956
+ * owner's agents and jobs): which of the app's organizations see this item, and whether that
1957
+ * is its own setting or inherited from a folder above it.
1958
+ */
1959
+ sharing?: StorageSharing | null;
1960
+ /**
1961
+ * `true` on the app owner's items that were shared with the caller's org. They can be read and
1962
+ * downloaded, never renamed, moved, changed or deleted (`STORAGE_SHARED_READ_ONLY`).
1963
+ */
1964
+ sharedByOwner?: true;
1965
+ }
1966
+
1967
+ /** A folder node. `path` is materialized (e.g. `/invoices/2026`). */
1968
+ interface StorageFolder {
1969
+ /** The folder's handle (`folderUid` / `parentUid` elsewhere). */
1970
+ uid: string;
1971
+ name: string;
1972
+ /** Parent folder's uid, or `null` directly under the storage root. */
1973
+ parent_uid: string | null;
1974
+ path: string;
1975
+ depth: number;
1976
+ storage_uid: string | null;
1977
+ /**
1978
+ * Present only on the app owner's own items (no org), and only to the owner's side (the
1979
+ * owner's agents and jobs): which of the app's organizations see this item, and whether that
1980
+ * is its own setting or inherited from a folder above it.
1981
+ */
1982
+ sharing?: StorageSharing | null;
1983
+ /**
1984
+ * `true` on the app owner's items that were shared with the caller's org. They can be read and
1985
+ * downloaded, never renamed, moved, changed or deleted (`STORAGE_SHARED_READ_ONLY`).
1986
+ */
1987
+ sharedByOwner?: true;
1988
+ }
1989
+
1990
+ /**
1991
+ * Which of the app's organizations see one of the owner's folders or files. Only me (`only_me`,
1992
+ * the default), every organization including later ones (`all`), or the listed ones (`orgs`).
1993
+ * An item without its own setting takes its nearest folder's; an organization's own uploads are
1994
+ * never shared by it. Set from the console.
1995
+ */
1996
+ interface StorageSharing {
1997
+ mode: "only_me" | "all" | "orgs";
1998
+ orgs: { uid: string; name: string }[];
1999
+ inherited: boolean;
2000
+ /** The folder an inherited setting comes from; null when it is the item's own, or the default. */
2001
+ from: { uid: string; name: string; path: string } | null;
2002
+ }
2003
+
2004
+ /** One step of {@link HandlerStorage.breadcrumb}. The root crumb's `uid` is `null`. */
2005
+ interface StorageCrumb {
2006
+ uid: string | null;
2007
+ name: string;
2008
+ path: string;
2009
+ depth: number;
2010
+ }
2011
+
2012
+ /** What {@link HandlerStorage.url} returns. */
2013
+ interface StorageUrl {
2014
+ /** Use directly as an `<a href>`, `<img src>`, or fetch target. */
2015
+ url: string;
2016
+ /**
2017
+ * `"public"`: permanent and cacheable (public storages).
2018
+ * `"signed"`: expires; see `expiresAt`.
2019
+ */
2020
+ kind: "public" | "signed";
2021
+ /** ISO timestamp when a signed URL dies, or `null` when it never does. */
2022
+ expiresAt: string | null;
2023
+ }
2024
+
2025
+ interface StorageUploadInput {
2026
+ /** File name (one path segment, no `/`). */
2027
+ name: string;
2028
+ /** Bytes. A `string` is decoded per `encoding`; `data:` URLs are understood. */
2029
+ body: Buffer | Uint8Array | string;
2030
+ /** How to read a string `body`. Default `"utf8"`; use `"base64"` for binary. */
2031
+ encoding?: "utf8" | "base64";
2032
+ contentType?: string;
2033
+ /** Destination folder's uid. Takes precedence over `path` when both are given. */
2034
+ folderUid?: string | null;
2035
+ /** Destination path (`/a/b/c`). Missing folders are created; see `ensureFolder`. */
2036
+ path?: string;
2037
+ /** Uid of the end user (a `users` row) who owns the file. */
2038
+ ownerUid?: string | null;
2039
+ metadata?: Record<string, unknown>;
2040
+ }
2041
+
2042
+ /**
2043
+ * Managed file storage, scoped to this app. See {@link HandlerSdk.storage}.
2044
+ */
2045
+ interface HandlerStorage {
2046
+ /** Every storage this app owns, with byte/file counts. */
2047
+ listStorages(): Promise<{ storages: unknown[] }>;
2048
+
2049
+ /**
2050
+ * List one folder's contents. Pass `folderUid`, or `path` to address it by
2051
+ * name. Unlike on the write methods, `path` here does NOT create anything
2052
+ * and throws 404 if it doesn't exist. Omit both for the storage root.
2053
+ */
2054
+ list(
2055
+ storageUid: string,
2056
+ options?: {
2057
+ folderUid?: string | null;
2058
+ path?: string;
2059
+ limit?: number;
2060
+ offset?: number;
2061
+ },
2062
+ ): Promise<{ folder: StorageFolder | StorageCrumb; folders: StorageFolder[]; files: StorageFile[] }>;
2063
+
2064
+ /** One file's metadata. Throws 404 (`FILE_NOT_FOUND`) when it doesn't exist. */
2065
+ get(fileUid: string): Promise<StorageFile>;
2066
+
2067
+ /** Substring search over file and folder names within one storage. */
2068
+ search(
2069
+ storageUid: string,
2070
+ query: string,
2071
+ options?: { limit?: number; offset?: number },
2072
+ ): Promise<{ files: StorageFile[]; folders: StorageFolder[] }>;
2073
+
2074
+ /** The trail from the storage root down to `folderUid`, root first. */
2075
+ breadcrumb(folderUid: string): Promise<StorageCrumb[]>;
2076
+
2077
+ /**
2078
+ * ONE usable URL for a file; never branch on the driver.
2079
+ *
2080
+ * What you get follows the STORAGE's visibility, not this call:
2081
+ * - public storage → a permanent, cacheable URL (`kind: "public"`,
2082
+ * `expiresAt: null`). Right for avatars, logos, and anything an `<img>`
2083
+ * re-requests or a CDN should cache.
2084
+ * - private storage → a short-lived signed URL (`kind: "signed"`). If you
2085
+ * show it to a human, say when it expires: a link pasted into a document
2086
+ * will be dead within the hour.
2087
+ *
2088
+ * Don't email a signed link: 15 minutes is gone before the mail is opened.
2089
+ * Put the file in a public storage, or email a link to your own page that
2090
+ * mints a fresh URL on load.
2091
+ */
2092
+ url(
2093
+ fileUid: string,
2094
+ options?: {
2095
+ /** Signed-URL lifetime in seconds. Ignored for public storages. */
2096
+ expiresIn?: number;
2097
+ /** Force a download (`Content-Disposition: attachment`) over inline display. */
2098
+ download?: boolean;
2099
+ },
2100
+ ): Promise<StorageUrl>;
2101
+
2102
+ /** Read a file's bytes into memory. For large files prefer handing out a `url`. */
2103
+ download(fileUid: string): Promise<{ file: StorageFile; body: Buffer }>;
2104
+
2105
+ /**
2106
+ * Store bytes. Consumes the tenant's billed capacity, and is refused (413
2107
+ * `FILE_TOO_LARGE`, 415 `MIME_NOT_ALLOWED`) by the storage's own per-file
2108
+ * limit and MIME allow-list before anything is written.
2109
+ *
2110
+ * In a dry run this is RECORDED, not performed: an object write can't be
2111
+ * rolled back with the transaction.
2112
+ */
2113
+ upload(storageUid: string, file: StorageUploadInput): Promise<StorageFile>;
2114
+
2115
+ /** Fetch an http(s) URL and store the response. Same limits as `upload`. */
2116
+ uploadFromUrl(
2117
+ storageUid: string,
2118
+ options: {
2119
+ url: string;
2120
+ name?: string;
2121
+ contentType?: string;
2122
+ folderUid?: string | null;
2123
+ path?: string;
2124
+ ownerUid?: string | null;
2125
+ metadata?: Record<string, unknown>;
2126
+ },
2127
+ ): Promise<StorageFile>;
2128
+
2129
+ /**
2130
+ * Mint direct-to-bucket upload targets for YOUR caller, so large files never
2131
+ * round-trip through the API. The client PUTs to `upload.url`, then you call
2132
+ * {@link HandlerStorage.confirmUpload} with the returned `key`.
2133
+ *
2134
+ * `proxyUpload: true` means the driver can't presign; send the bytes to
2135
+ * {@link HandlerStorage.upload} instead.
2136
+ */
2137
+ presignUpload(
2138
+ storageUid: string,
2139
+ options: {
2140
+ files: Array<{ name: string; mimeType?: string; size?: number }>;
2141
+ folderUid?: string | null;
2142
+ path?: string;
2143
+ expiresIn?: number;
2144
+ },
2145
+ ): Promise<{
2146
+ driver: string;
2147
+ targets: Array<{
2148
+ name: string;
2149
+ key: string;
2150
+ /** The resolved destination: hand it straight back to `confirmUpload`. */
2151
+ folderUid: string | null;
2152
+ contentType: string;
2153
+ proxyUpload: boolean;
2154
+ upload: {
2155
+ url: string;
2156
+ method: string;
2157
+ headers: Record<string, string>;
2158
+ expiresIn: number;
2159
+ } | null;
2160
+ /**
2161
+ * Hand it back to `confirmUpload` with the key. It binds the target to the caller it was made
2162
+ * for: another caller, another key, or an expired token is refused (`UPLOAD_NOT_CONFIRMABLE`).
2163
+ */
2164
+ confirmToken: string;
2165
+ }>;
2166
+ }>;
2167
+
2168
+ /** Persist metadata for objects uploaded via `presignUpload`. Verifies each exists. */
2169
+ confirmUpload(
2170
+ storageUid: string,
2171
+ options: {
2172
+ files: Array<{
2173
+ key: string;
2174
+ /** The target's `confirmToken`, from `presignUpload`. Required. */
2175
+ confirmToken: string;
2176
+ name: string;
2177
+ mimeType?: string;
2178
+ ownerUid?: string | null;
2179
+ metadata?: Record<string, unknown>;
2180
+ }>;
2181
+ folderUid?: string | null;
2182
+ path?: string;
2183
+ ownerUid?: string | null;
2184
+ },
2185
+ ): Promise<{ confirmed: number; files: StorageFile[] }>;
2186
+
2187
+ /** Create ONE folder under `parentUid` (omit for the root). `name` is a single segment. */
2188
+ createFolder(
2189
+ storageUid: string,
2190
+ options: { name: string; parentUid?: string | null },
2191
+ ): Promise<StorageFolder>;
2192
+
2193
+ /**
2194
+ * `mkdir -p`: resolve `/a/b/c`, creating whatever is missing, and return the
2195
+ * leaf. Idempotent and safe when several callers race the same path, so call
2196
+ * it unconditionally rather than checking first.
2197
+ */
2198
+ ensureFolder(storageUid: string, path: string): Promise<StorageFolder | null>;
2199
+
2200
+ /** Duplicate a file, bytes and all. Defaults to the source's own folder. */
2201
+ copy(
2202
+ fileUid: string,
2203
+ options?: {
2204
+ folderUid?: string | null;
2205
+ path?: string;
2206
+ name?: string;
2207
+ ownerUid?: string | null;
2208
+ },
2209
+ ): Promise<StorageFile>;
2210
+
2211
+ /**
2212
+ * Move a file (or folder, with `type`) to another folder, named by `folderUid` or `path`
2213
+ * (neither = the storage root). Metadata only: bytes stay put.
2214
+ */
2215
+ move(
2216
+ uid: string,
2217
+ options?: {
2218
+ folderUid?: string | null;
2219
+ path?: string;
2220
+ type?: "file" | "folder";
2221
+ },
2222
+ ): Promise<StorageFile | StorageFolder>;
2223
+
2224
+ /** Rename in place. Name collisions in the destination are auto-deduped. */
2225
+ rename(
2226
+ uid: string,
2227
+ newName: string,
2228
+ options?: { type?: "file" | "folder" },
2229
+ ): Promise<StorageFile | StorageFolder>;
2230
+
2231
+ /** Update a file's `metadata` and/or `ownerUid` (`null` clears it). Use `rename` for the name. */
2232
+ update(
2233
+ fileUid: string,
2234
+ changes: { metadata?: Record<string, unknown>; ownerUid?: string | null },
2235
+ ): Promise<StorageFile>;
2236
+
2237
+ /**
2238
+ * Delete a file, or a folder with `type: "folder"`.
2239
+ *
2240
+ * Soft by default (recoverable). `hard: true` also removes the underlying
2241
+ * object; that frees billed bytes and CANNOT be undone. A non-empty folder
2242
+ * needs `recursive: true`.
2243
+ */
2244
+ delete(
2245
+ uid: string,
2246
+ options?: {
2247
+ type?: "file" | "folder";
2248
+ recursive?: boolean;
2249
+ hard?: boolean;
2250
+ },
2251
+ ): Promise<{ freedBytes: number; removedFiles: number }>;
2252
+ }
2253
+
2254
+ /** One scheduled job. `principalUserUid` is the identity it runs as, never its creator. */
2255
+ interface CronJob {
2256
+ /** The job's handle: every other crons method names a job by this. */
2257
+ uid: string;
2258
+ name: string;
2259
+ description: string | null;
2260
+ /** `active` = eligible to fire. `paused` = held, schedule and history intact. */
2261
+ status: "active" | "paused";
2262
+ targetKind: string;
2263
+ /** The uid of the handler it runs (the `uid` the handler registry gives it). */
2264
+ targetHandlerUid: string | null;
2265
+ handlerName: string | null;
2266
+ /** The fixed request body handed to the handler on every run. */
2267
+ payload: Record<string, unknown>;
2268
+ scheduleKind: "interval" | "cron";
2269
+ intervalSeconds: number | null;
2270
+ cronExpression: string | null;
2271
+ timezone: string;
2272
+ timeoutSeconds: number;
2273
+ /** `null` while paused; a paused job holds no claim on the scheduler. */
2274
+ nextRunAt: string | null;
2275
+ lastRunAt: string | null;
2276
+ lastStatus: string | null;
2277
+ /** Pass to {@link HandlerCrons.getRun}. */
2278
+ lastRunUid: string | null;
2279
+ /** A counter, never an auto-disable: a broken job is surfaced, not silently switched off. */
2280
+ consecutiveFailures: number;
2281
+ /** The job's own principal. What it may do is the roles bound to THIS user. */
2282
+ principalUserUid: string | null;
2283
+ /** The app org the job belongs to, by uid and name. Null for the app owner's own jobs. */
2284
+ orgUid: string | null;
2285
+ orgName: string | null;
2286
+ /**
2287
+ * The occurrence this job has unfinished, or `null`. A firing is carried over TURNS (a page each)
2288
+ * until it completes. `running`: it carries on by itself. `retrying`: a turn failed and is retried
2289
+ * shortly from the same place. `stopped`: it failed after its retries (or was paused part-way);
2290
+ * `runNow` (Resume), or its next scheduled time, carries on from where it stopped.
2291
+ */
2292
+ firing: {
2293
+ state: "running" | "retrying" | "stopped";
2294
+ /** Which occurrence: the time it was scheduled for, or when a Run now started. */
2295
+ windowStart: string | null;
2296
+ runUid: string | null;
2297
+ turns: number;
2298
+ attempts: number;
2299
+ doneCount: number | null;
2300
+ failedCount: number | null;
2301
+ lastError: string | null;
2302
+ } | null;
2303
+ createdAt: string | null;
2304
+ updatedAt: string | null;
2305
+ }
2306
+
2307
+ /** One attempt to run one job, including the attempts that were refused. */
2308
+ interface CronRun {
2309
+ /** The run's handle: pass to {@link HandlerCrons.getRun}. */
2310
+ uid: string;
2311
+ /** The job it belongs to. Still set after that job is deleted: run history is kept. */
2312
+ cronUid: string | null;
2313
+ cronName: string | null;
2314
+ /**
2315
+ * `schedule`, `manual` (Run now) or `resume` (Run now carrying on a stopped firing). A person's
2316
+ * run never moves the schedule's health (last status, failure count).
2317
+ */
2318
+ triggerSource: string;
2319
+ principalUserUid: string | null;
2320
+ /** The roles the principal held AT THE MOMENT IT RAN, not what it holds now. */
2321
+ principalRoles: string[];
2322
+ handlerName: string | null;
2323
+ /** The handler version that executed (its uid). */
2324
+ handlerVersionUid: string | null;
2325
+ payload: Record<string, unknown>;
2326
+ /** What the schedule said, as opposed to when the sweep got to it. */
2327
+ scheduledFor: string | null;
2328
+ startedAt: string | null;
2329
+ finishedAt: string | null;
2330
+ durationMs: number | null;
2331
+ /**
2332
+ * `partial`: every item was visited and some failed (listed in `failures`). `stopped`: the job
2333
+ * was paused with work left; Resume carries on. `failed`: it failed after its retries; Resume
2334
+ * carries on from the last page that succeeded. `running` is a LEASED state; a run abandoned by a
2335
+ * dead process is carried on by the next turn, never lost.
2336
+ */
2337
+ status: "running" | "succeeded" | "partial" | "failed" | "stopped" | "denied" | "skipped";
2338
+ httpStatus: number | null;
2339
+ result?: unknown;
2340
+ errorText: string | null;
2341
+ /** Scheduled instants passed over to get here. Skipped, never replayed. */
2342
+ missedWindows: number;
2343
+ runner: string | null;
2344
+ /** The occurrence this run belongs to. Runs of one firing (stopped, then resumed) share it. */
2345
+ windowStart: string | null;
2346
+ /** Turns taken (a page each), and failed turns retried. */
2347
+ turns: number;
2348
+ attempts: number;
2349
+ /** Items done and failed: "197 done, 3 failed". */
2350
+ doneCount: number;
2351
+ failedCount: number;
2352
+ /** The first 100 failed items (getRun only): the row's uid and what went wrong. */
2353
+ failures?: Array<{ uid: string | null; message: string; code?: string }>;
2354
+ /** The app org the run belongs to, by uid and name. Null for the app owner's own. */
2355
+ orgUid: string | null;
2356
+ orgName: string | null;
2357
+ }
2358
+
2359
+ interface CronScheduleInput {
2360
+ scheduleKind: "interval" | "cron";
2361
+ /** Minimum 60: the scheduler tick bounds resolution, so shorter is REFUSED, not rounded. */
2362
+ intervalSeconds?: number | null;
2363
+ /** Five fields: minute hour day-of-month month day-of-week. Macros like `@daily` work too. */
2364
+ cronExpression?: string | null;
2365
+ /** IANA name. `0 2 * * *` then means 2am THERE, correct across daylight saving. */
2366
+ timezone?: string;
2367
+ }
2368
+
2369
+ interface HandlerRoles {
2370
+ /**
2371
+ * Give a person a role in the org THIS RUN belongs to. Needs `sdk:roles_write`.
2372
+ *
2373
+ * Everything is named by uid: the person (`userUid`), the role (`roleUid`, or its `roleKey`)
2374
+ * and the org. `orgUid` may only restate the caller's own org; a run never reaches into
2375
+ * another org's roster, however the handler got the uid (`ROLE_ORG_MISMATCH`). To change another
2376
+ * org's roster, run as a principal of that org. The person must already belong to the org, and
2377
+ * must be a PERSON: agents and scheduled jobs are armed through their own governed actions
2378
+ * (`PRINCIPAL_NOT_HUMAN`). An unknown or malformed uid is a 404.
2379
+ */
2380
+ assign(input: { userUid: string; roleUid?: string; roleKey?: string; orgUid?: string | null }): Promise<{
2381
+ assigned: boolean;
2382
+ userUid: string;
2383
+ roleUid: string;
2384
+ /** Null only when the caller's org is not a row of this app's database. */
2385
+ orgUid: string | null;
2386
+ }>;
2387
+ /** Take a role away, in the caller's own org. Needs `sdk:roles_write`; removing needs no ceiling. */
2388
+ unassign(input: { userUid: string; roleUid?: string; roleKey?: string; orgUid?: string | null }): Promise<{
2389
+ unassigned: boolean;
2390
+ removed: number;
2391
+ }>;
2392
+ /**
2393
+ * The roles a person holds in the caller's org (plus any global binding, whose `org_uid` is
2394
+ * null). Needs `sdk:roles_read`.
2395
+ */
2396
+ list(input: { userUid: string; orgUid?: string | null }): Promise<
2397
+ Array<{ uid: string; key_name: string; display: string | null; org_uid: string | null }>
2398
+ >;
2399
+ }
2400
+
2401
+ interface HandlerCrons {
2402
+ /**
2403
+ * Scheduled jobs the caller reaches, newest first: its own org's inside the app; every org's for
2404
+ * the app's owner reaching it from outside (each job names its org). Needs `sdk:crons_read`.
2405
+ */
2406
+ list(options?: {
2407
+ status?: "active" | "paused";
2408
+ limit?: number;
2409
+ offset?: number;
2410
+ }): Promise<CronJob[]>;
2411
+
2412
+ /** One job by uid. Needs `sdk:crons_read`. An unknown or malformed uid is a 404. */
2413
+ get(cronUid: string): Promise<CronJob>;
2414
+
2415
+ /** Past runs, newest first. Omit `cronUid` for every job in the org. Needs `sdk:crons_read`. */
2416
+ listRuns(options?: {
2417
+ cronUid?: string;
2418
+ status?: CronRun["status"];
2419
+ limit?: number;
2420
+ offset?: number;
2421
+ }): Promise<CronRun[]>;
2422
+
2423
+ /** One run in full, with its result and the roles its principal held. Needs `sdk:crons_read`. */
2424
+ getRun(runUid: string): Promise<CronRun>;
2425
+
2426
+ /**
2427
+ * The roles bound to a job's principal: exactly what it may do when it runs.
2428
+ * Needs `sdk:crons_read`.
2429
+ */
2430
+ listRoles(cronUid: string): Promise<{ uid: string; keyName: string; display: string }[]>;
2431
+
2432
+ /**
2433
+ * Validate a schedule and get back the instants it would fire at, as ISO strings.
2434
+ * Reads and writes nothing. Real timestamps PROVE what a schedule does where a description
2435
+ * of it only restates what you typed, and prose cannot show you a wrong DST assumption.
2436
+ * Needs `sdk:crons_read`.
2437
+ */
2438
+ preview(input: CronScheduleInput & { count?: number }): Promise<string[]>;
2439
+
2440
+ /**
2441
+ * Create a job. It is created PAUSED with a principal holding NO roles, so it can do nothing
2442
+ * until a person arms it in the console. Needs `sdk:crons_write`.
2443
+ */
2444
+ create(
2445
+ input: CronScheduleInput & {
2446
+ name: string;
2447
+ description?: string | null;
2448
+ /**
2449
+ * The uid of the handler to run. It runs the PUBLISHED version, so publish one before
2450
+ * arming.
2451
+ */
2452
+ targetHandlerUid: string;
2453
+ payload?: Record<string, unknown>;
2454
+ timeoutSeconds?: number;
2455
+ },
2456
+ ): Promise<CronJob>;
2457
+
2458
+ /**
2459
+ * Change a job. `nextRunAt` is recomputed only when the SCHEDULE changes or the job is armed,
2460
+ * so a rename never silently pushes a running job's next fire.
2461
+ *
2462
+ * HIGH risk: if the job is already armed, changing `targetHandlerUid` changes what code runs
2463
+ * under a principal someone else granted. Needs `sdk:crons_write`.
2464
+ */
2465
+ update(
2466
+ cronUid: string,
2467
+ patch: Partial<CronScheduleInput> & {
2468
+ name?: string;
2469
+ description?: string | null;
2470
+ targetHandlerUid?: string;
2471
+ payload?: Record<string, unknown>;
2472
+ timeoutSeconds?: number;
2473
+ status?: "active" | "paused";
2474
+ },
2475
+ ): Promise<CronJob>;
2476
+
2477
+ /** Arm a job: it starts firing on its schedule. Needs `sdk:crons_write`. */
2478
+ resume(cronUid: string): Promise<CronJob>;
2479
+
2480
+ /** Hold a job without losing its schedule or history. Needs `sdk:crons_write`. */
2481
+ pause(cronUid: string): Promise<CronJob>;
2482
+
2483
+ /**
2484
+ * Delete a job and RETIRE its principal, removing that principal's role bindings so nothing
2485
+ * is left holding standing access. The run history is kept. Needs `sdk:crons_write`.
2486
+ */
2487
+ remove(cronUid: string): Promise<{ deleted: boolean; cronUid: string }>;
2488
+
2489
+ /**
2490
+ * Fire a job now, FOR REAL, as that job's OWN principal, not as the caller. Rows written and
2491
+ * mail sent are permanent. It is also RESUME: a job whose firing stopped or is still going
2492
+ * carries on from where it is (`resumed`), never from the beginning. It takes a few turns while
2493
+ * you wait; if work remains, an active job carries on in the background (`continues:
2494
+ * "background"`) and a paused one stops for the next Resume (`"resume"`). It never moves the
2495
+ * schedule's health. Refused with CRON_BUSY while a turn of the job is running. Needs
2496
+ * `sdk:crons_write`.
2497
+ */
2498
+ runNow(cronUid: string): Promise<{
2499
+ status: string;
2500
+ resumed: boolean;
2501
+ continues: "background" | "resume" | null;
2502
+ run: CronRun | null;
2503
+ }>;
2504
+ }
2505
+
2506
+ interface HandlerStripe {
2507
+ /** Raw Stripe SDK client for your connected account (full API access). */
2508
+ client(): Promise<unknown>;
2509
+ /** Connection status/metadata for your account (no secrets). */
2510
+ connection(): Promise<unknown>;
2511
+ /** List this app's products (filtered by metadata.app_uid), with prices. */
2512
+ listProducts(): Promise<{ products: StripeProductSummary[] }>;
2513
+ /** Create a product + price tagged to this app. `unitAmount` is in cents. */
2514
+ createProduct(input: {
2515
+ name: string;
2516
+ description?: string;
2517
+ unitAmount: number;
2518
+ currency?: string;
2519
+ interval?: "month" | "year" | "one_time";
2520
+ }): Promise<{ product: StripeProductSummary }>;
2521
+ /** Create a Checkout session for one of this app's prices. Returns `{ url }`. */
2522
+ createCheckout(input: {
2523
+ priceId: string;
2524
+ mode?: "payment" | "subscription";
2525
+ successUrl?: string;
2526
+ cancelUrl?: string;
2527
+ customerEmail?: string;
2528
+ quantity?: number;
2529
+ }): Promise<{ url: string; sessionId: string }>;
2530
+ }
2531
+
2532
+ interface StripeProductSummary {
2533
+ /** Stripe's product id. */
2534
+ id: string;
2535
+ /** Product name as it appears in Stripe. */
2536
+ name: string;
2537
+ /** Product description, when one was set. */
2538
+ description: string | null;
2539
+ /** Whether the product is currently sellable. */
2540
+ active: boolean;
2541
+ /** The app this product is tagged to, from its Stripe `metadata.app_uid`. */
2542
+ appUid: string | null;
2543
+ /** The price used when a checkout does not name one. */
2544
+ defaultPriceId: string | null;
2545
+ /** Every price attached to this product. */
2546
+ prices: Array<{
2547
+ id: string;
2548
+ unitAmount: number | null;
2549
+ currency: string | null;
2550
+ interval: string | null;
2551
+ recurring: boolean;
2552
+ active: boolean;
2553
+ }>;
2554
+ }
2555
+
2556
+ // The second argument every handler receives.
2557
+ //
2558
+ // Handlers run in Deno. A few members below exist only on the Node runtime, which is
2559
+ // internal; write against the ones marked "Both runtimes" unless you know you are on Node.
2560
+ // Availability here was verified against the two places a handler ctx is actually built:
2561
+ // buildHandlerCtx in endpoints/autoCrud/actionRouting.js (Node) and handlerCtx in
2562
+ // handler_worker/server.ts (Deno).
2563
+ interface HandlerCtx {
2564
+ /**
2565
+ * The same SDK object handed to the handler as its first argument, already scoped to
2566
+ * this app and the calling principal. Both runtimes.
2567
+ */
2568
+ sdk: HandlerSdk;
2569
+
2570
+ /**
2571
+ * The raw Express request.
2572
+ *
2573
+ * **Node runtime only**: the Deno worker never receives one. Use `reqParams` and
2574
+ * `reqQuery`, which both runtimes populate, and take the request payload from the
2575
+ * handler's first argument.
2576
+ */
2577
+ req?: {
2578
+ appUid?: string;
2579
+ body?: Record<string, unknown>;
2580
+ query?: Record<string, unknown>;
2581
+ params?: Record<string, string>;
2582
+ headers?: Record<string, string | string[] | undefined>;
2583
+ method?: string;
2584
+ path?: string;
2585
+ originalUrl?: string;
2586
+ };
2587
+ /**
2588
+ * The raw Express response.
2589
+ *
2590
+ * **Node runtime only.** Writing to it directly bypasses the normal response envelope;
2591
+ * return a value from the handler instead and let the platform serialize it.
2592
+ */
2593
+ res?: unknown;
2594
+
2595
+ /** The parsed query string of the request that reached this handler. Both runtimes. */
2596
+ reqQuery?: Record<string, unknown>;
2597
+
2598
+ /** Route path parameters: `/orders/:orderUid` arrives as `{ orderUid: "…" }`. Both runtimes. */
2599
+ reqParams?: Record<string, string>;
2600
+
2601
+ /**
2602
+ * This app's configuration object: the JSON held in the `app_config` row of the app's
2603
+ * own database. Both runtimes.
2604
+ *
2605
+ * This is the channel for app-level configuration, because a handler has no environment
2606
+ * of its own to read. The Deno sandbox grants `--allow-env` for a fixed allowlist of
2607
+ * platform-internal variables only, so there is no `process.env` / `Deno.env` holding
2608
+ * values you set.
2609
+ */
2610
+ appConfig?: Record<string, unknown> | null;
2611
+
2612
+ /**
2613
+ * The end user this request is acting as, with password fields stripped. `null` for a
2614
+ * caller that is not a user. Both runtimes.
2615
+ */
2616
+ user?: {
2617
+ /** The user's handle outside this database (e.g. `sdk.storage` `ownerUid`). */
2618
+ uid?: string;
2619
+ email?: string;
2620
+ fname?: string;
2621
+ lname?: string;
2622
+ /** The acting organization's uid. */
2623
+ orgUid?: string | null;
2624
+ [key: string]: unknown;
2625
+ } | null;
2626
+
2627
+ /**
2628
+ * The caller in handles, and its roles/scopes. No ids (SDK 3.0.0).
2629
+ *
2630
+ * **Node runtime only.** The Deno worker forwards the caller into the SDK's own scoping (so
2631
+ * it governs what your `sdk.*` calls may do) but does not place it on `ctx`.
2632
+ */
2633
+ userContext?: {
2634
+ /** The calling principal's uid. */
2635
+ actorUid?: string | null;
2636
+ actorType?: string | null;
2637
+ /** The acting organization's uid. */
2638
+ orgUid?: string | null;
2639
+ roles?: string[];
2640
+ scopes?: string[];
2641
+ } | null;
2642
+
2643
+ /**
2644
+ * Correlation id for this request, matching the `requestId` on any error envelope it
2645
+ * produces. **Node runtime only**: on Deno it is carried in the SDK context and shows
2646
+ * up in logs, but is not placed on `ctx`.
2647
+ */
2648
+ requestId?: string | null;
2649
+
2650
+ /**
2651
+ * What kind of principal is calling: `"user"`, an agent, or another identity type.
2652
+ * **Node runtime only.**
2653
+ */
2654
+ identityType?: string;
2655
+
2656
+ /**
2657
+ * Set when this handler was reached BY ANOTHER HANDLER rather than directly, describing
2658
+ * the delegated authority it inherited: the action that entered the chain and the
2659
+ * actions allowed or denied within it. Both runtimes.
2660
+ *
2661
+ * Read-only bookkeeping; narrowing happens in the platform, not by editing this.
2662
+ */
2663
+ handlerDelegation?: {
2664
+ entryAction?: string;
2665
+ allowedActions?: string[];
2666
+ deniedActions?: string[];
2667
+ enabled?: boolean;
2668
+ } | null;
2669
+
2670
+ /**
2671
+ * Which of the app's organizations this run reaches, so code can check it rather than infer it.
2672
+ * Both runtimes.
2673
+ *
2674
+ * - `org`: one org. A caller inside the app (its own org), or a job whose org reach is one org,
2675
+ * which runs AS that org: rows carry no org column, and new rows are that org's.
2676
+ * - `all`: every org, including ones created later (`orgUids` is empty). Acting for the app's
2677
+ * owner.
2678
+ * - `orgs`: the listed orgs. Acting for the app's owner within an org reach.
2679
+ * - `none`: no org's data, only the owner's own rows.
2680
+ *
2681
+ * In the last three modes the run acts for the app's owner and reaches the owner's own rows too:
2682
+ * every row it reads says which org it belongs to as `org_uid` (`null` for the owner's own), a
2683
+ * new row in an org's table names one with `org_uid` (ROW_ORG_REQUIRED without it, and
2684
+ * ROW_ORG_NOT_FOUND for one outside the reach), and filters and `aggregate` groupings take
2685
+ * `org_uid` too. A row's `org_uid` cannot be changed by an update.
2686
+ *
2687
+ * `null` on the platform's own plane.
2688
+ */
2689
+ audience?: {
2690
+ mode: "org" | "all" | "orgs" | "none";
2691
+ orgUids: string[];
2692
+ } | null;
2693
+
2694
+ /**
2695
+ * Present when the handler runs as a scheduled job (and when its owner tries a job-only handler
2696
+ * from the console). Deno.
2697
+ */
2698
+ job?: HandlerJob;
2699
+
2700
+ [key: string]: unknown;
2701
+ }
2702
+
2703
+ /** `ctx.job`: a scheduled run, told about itself. */
2704
+ interface HandlerJob {
2705
+ /** The job's uid. `null` when its owner is trying the handler from the console. */
2706
+ cronUid: string | null;
2707
+ /** This run's uid. `null` when its owner is trying the handler from the console. */
2708
+ runUid: string | null;
2709
+ /**
2710
+ * Which firing this is: the time it was scheduled for, or when a Run now started (ISO 8601). Use
2711
+ * it in idempotency keys, so a retried firing repeats nothing: `${ctx.job.windowStart}:${row.uid}`.
2712
+ */
2713
+ windowStart: string | null;
2714
+ /**
2715
+ * Where a hand-written loop stopped: the value it last gave `next()`. `null` at the beginning.
2716
+ * (`each` keeps its own place; this is only for loops it cannot express.)
2717
+ */
2718
+ position: unknown;
2719
+ /** Failed turns of this firing so far: 0 on a first try, so a retried turn can be told apart. */
2720
+ attempt: number;
2721
+ /**
2722
+ * THE way to write a job that loops: say which rows, and what to do with one.
2723
+ *
2724
+ * The platform pages through the matching rows within the job's own reach, in creation order,
2725
+ * and calls `fn` once per row. ONE PAGE A TURN: when the page is done and rows remain, the run
2726
+ * ends there, the platform saves where it stopped, and runs the handler again FROM THE TOP to
2727
+ * carry on, interleaved with every other app's work. So code before `each` runs on every turn
2728
+ * (keep it cheap, with no side effects) and code after it runs once, after the last row. A
2729
+ * crash or a deploy costs at most the page in hand: a failed turn is retried from the same
2730
+ * place after 1, 5 and 15 minutes, then the job stops for Resume, and the owner is told.
2731
+ *
2732
+ * A row whose `fn` throws (or runs past 60 seconds) is recorded and skipped, and the rest carry
2733
+ * on, so one bad row (a bad address) never stops the job: it ends `partial`. Every email or
2734
+ * Stripe call `fn` makes is keyed to its row, so a retried page never sends one twice. Several
2735
+ * loops in one job each keep their place.
2736
+ *
2737
+ * @param table - Table name.
2738
+ * @param filters - Which rows (the same filters as `readList`).
2739
+ * @param fn - What to do with one row.
2740
+ * @param options - `pageSize` (default 200, at most 1000) and `columns` (a projection).
2741
+ * @example
2742
+ * await ctx.job.each("invoices", { status: "overdue" }, async (invoice) => {
2743
+ * await sdk.sendEmail({
2744
+ * to: invoice.billing_email,
2745
+ * subject: `Invoice ${invoice.invoice_number} is overdue`,
2746
+ * text: `Your invoice for ${invoice.amount} ${invoice.currency} is past due.`,
2747
+ * });
2748
+ * });
2749
+ */
2750
+ each<T = Record<string, unknown>>(
2751
+ table: string,
2752
+ filters: Filters,
2753
+ fn: (row: T) => unknown | Promise<unknown>,
2754
+ options?: { pageSize?: number; columns?: string[] },
2755
+ ): Promise<HandlerJobEachResult>;
2756
+ /**
2757
+ * The lower-level shape, for a loop `each` cannot express: `return ctx.job.next(position)` ends
2758
+ * this turn, and the handler runs again with `ctx.job.position` set to `position` (any
2759
+ * JSON-serializable value). Return without it when the work is finished.
2760
+ * @example
2761
+ * const page = ctx.job.position ?? 1;
2762
+ * const done = await syncPage(page);
2763
+ * if (!done) return ctx.job.next(page + 1);
2764
+ */
2765
+ next(position: unknown): unknown;
2766
+ }
2767
+
2768
+ /** What `ctx.job.each` returns. */
2769
+ interface HandlerJobEachResult {
2770
+ /** Rows whose `fn` finished. */
2771
+ done: number;
2772
+ /** Rows whose `fn` threw. */
2773
+ failed: number;
2774
+ /** Pages read. */
2775
+ pages: number;
2776
+ /** The first 100 failures: the row's uid and what went wrong. */
2777
+ failures: Array<{ uid: string | null; message: string; code?: string }>;
2778
+ /** True when more rows failed than `failures` lists. */
2779
+ failuresTruncated: boolean;
2780
+ /** True when an earlier turn already finished this loop (a job with several). */
2781
+ skipped?: boolean;
2782
+ }
2783
+
2784
+ // ---------------------------------------------------------------------------
2785
+ // Ambient handler globals: an editor authoring aid so completion is type-aware
2786
+ // however you reference these. At runtime they arrive as the handler's function
2787
+ // parameters (`export default async function (data, ctx) { … }`), and `sdk` is
2788
+ // destructured from ctx (`const { sdk } = ctx;`) as in the starter template.
2789
+ // ---------------------------------------------------------------------------
2790
+
2791
+ /** The typed SDK for this handler. In code, obtain it via `const { sdk } = ctx;`. */
2792
+ declare const sdk: HandlerSdk;
2793
+ /** Request context: the SDK, request data, authenticated user, config, etc. */
2794
+ declare const ctx: HandlerCtx;
2795
+ /** The request body passed to the handler. */
2796
+ declare const data: Record<string, unknown>;
2797
+