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