totalum-sdk 1.11.0 → 1.11.1
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/CHANGELOG.md +9 -0
- package/dist/_types/{coerce.d-BKhuaDya.d.ts → coerce.d-D_rylvPs.d.ts} +1 -1
- package/dist/_types/{errors.d-RTRkidv5.d.ts → errors.d-BPpY5QKu.d.ts} +20 -2
- package/dist/_types/{integrations.d-CzTa9T-L.d.ts → integrations.d-BTZHy48D.d.ts} +2 -2
- package/dist/_types/{ops.d-CNsrT4Ma.d.ts → ops.d-Ce5zJyX0.d.ts} +2 -2
- package/dist/ai/index.d.ts +275 -23
- package/dist/ai/index.js +305 -24
- package/dist/analytics/index.d.ts +58 -12
- package/dist/analytics/index.js +46 -3
- package/dist/browser/index.d.ts +208 -18
- package/dist/browser/index.js +122 -13
- package/dist/connections/index.d.ts +305 -23
- package/dist/connections/index.js +302 -21
- package/dist/cron/index.d.ts +147 -20
- package/dist/cron/index.js +157 -15
- package/dist/d1/errors.js +15 -0
- package/dist/d1/index.d.ts +254 -10
- package/dist/d1/index.js +24 -4
- package/dist/d1/session.js +26 -2
- package/dist/email/index.d.ts +65 -10
- package/dist/email/index.js +60 -5
- package/dist/errors.js +17 -0
- package/dist/files/index.d.ts +243 -20
- package/dist/files/index.js +247 -14
- package/dist/index.d.ts +24 -9
- package/dist/index.js +19 -5
- package/dist/logs/index.d.ts +48 -10
- package/dist/logs/index.js +39 -4
- package/dist/payments/index.d.ts +221 -23
- package/dist/payments/index.js +216 -18
- package/dist/pdf/index.d.ts +59 -9
- package/dist/pdf/index.js +54 -4
- package/dist/react/index.d.ts +78 -6
- package/dist/react/index.js +51 -5
- package/dist/realtime/index.d.ts +55 -8
- package/dist/realtime/index.js +53 -6
- package/dist/scan/index.d.ts +78 -10
- package/dist/scan/index.js +63 -3
- package/dist/seo/index.d.ts +43 -7
- package/dist/seo/index.js +39 -3
- package/dist/speech/index.d.ts +34 -10
- package/dist/speech/index.js +25 -5
- package/dist/vectors/index.d.ts +96 -9
- package/dist/vectors/index.js +93 -7
- package/dist/web/index.d.ts +168 -15
- package/dist/web/index.js +163 -10
- package/dist/webhooks/index.d.ts +122 -15
- package/dist/webhooks/index.js +119 -13
- package/package.json +2 -1
- package/totalum-sdk.md +8841 -754
- package/totalum-sdk.signatures.json +1 -1
package/dist/cron/index.js
CHANGED
|
@@ -2,31 +2,114 @@ import { isTotalumError } from '../errors.js';
|
|
|
2
2
|
import { jsonClient, query } from '../http.js';
|
|
3
3
|
export { TotalumError, isTotalumError } from '../errors.js';
|
|
4
4
|
/**
|
|
5
|
-
* `
|
|
5
|
+
* Creates the `cron` namespace (the same object as `totalum.cron`, scope `cron`): HTTP jobs against the project's own host,
|
|
6
6
|
* fired by Totalum's Scheduler; limits per plan (`429 CRON_LIMIT_REACHED {limit, plan}`, `400 INVALID_SCHEDULE
|
|
7
7
|
* {minIntervalSeconds}`). Each run costs a small fraction of a credit. `timezone` (IANA) reads the schedule on that zone's clock, daylight
|
|
8
8
|
* saving included; `pauseAfterFailures` (1–100, default 3; `null` = never) sets how many failed runs in a row pause it.
|
|
9
|
+
*
|
|
10
|
+
* @param options - The project key, API URL and environment; each falls back to its environment variable.
|
|
11
|
+
* @returns The `cron` namespace: the methods below.
|
|
12
|
+
* @example
|
|
13
|
+
* import { totalumCron } from 'totalum-sdk/cron';
|
|
14
|
+
*
|
|
15
|
+
* const cron = totalumCron();
|
|
16
|
+
* const jobs = await cron.list();
|
|
9
17
|
*/
|
|
10
18
|
export function totalumCron(options = {}) {
|
|
11
19
|
const call = jsonClient(options);
|
|
12
20
|
const job = (id) => `/v1/cron/jobs/${encodeURIComponent(id)}`;
|
|
21
|
+
/**
|
|
22
|
+
* Changes any field of a job (`schedule`, `request`, `enabled`, `timezone`, …); fields you leave out keep their
|
|
23
|
+
* value. The same checks as `create` apply.
|
|
24
|
+
*
|
|
25
|
+
* @param id - The job's `id`.
|
|
26
|
+
* @param patch - The fields to change.
|
|
27
|
+
* @returns The updated job.
|
|
28
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
29
|
+
* @throws INVALID_SCHEDULE (400) The new schedule is invalid or too frequent for the plan.
|
|
30
|
+
* @throws CRON_URL_NOT_ALLOWED (403) The new URL is not the project's own host.
|
|
31
|
+
* @example
|
|
32
|
+
* const job = await totalum.cron.update('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD', { schedule: { everyMinutes: 60 } });
|
|
33
|
+
* //=>
|
|
34
|
+
* { "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD", "name": "daily-report", "schedule": { "everyMinutes": 60 }, "status": "active", "nextRunAt": "2026-10-11T19:30:00.000Z", … }
|
|
35
|
+
*/
|
|
13
36
|
const update = (id, patch) => call('PATCH', job(id), patch);
|
|
14
37
|
return {
|
|
15
38
|
/**
|
|
16
|
-
*
|
|
39
|
+
* Creates a job that calls a route of your own app on a schedule — a cron expression (`'0 8 * * *'`) or
|
|
40
|
+
* `{ everyMinutes: 15 }`. The URL must be the project's own `https://` host: the published site for a `live` job,
|
|
41
|
+
* the preview for a `dev` one (without `env`, the URL decides). Each call is signed by Totalum (the template's cron
|
|
42
|
+
* routes check it) and recorded in `runs()`.
|
|
17
43
|
*
|
|
44
|
+
* @param input - The name, schedule, request and options.
|
|
45
|
+
* @returns The new job.
|
|
46
|
+
* @throws INVALID_SCHEDULE (400) Not a valid schedule, or it fires more often than the plan allows;
|
|
47
|
+
* `details.minIntervalSeconds`.
|
|
48
|
+
* @throws CRON_URL_NOT_ALLOWED (403) The URL is not the project's own `https://` host for that environment;
|
|
49
|
+
* `details.allowedHost`.
|
|
50
|
+
* @throws CRON_REQUIRES_PUBLISHED_PROJECT (403) A `live` job, but the project is not published yet.
|
|
51
|
+
* @throws CRON_LIMIT_REACHED (429) The plan's number of jobs per environment is reached; `details.limit`.
|
|
52
|
+
* @throws ENGINE_UNAVAILABLE (502) The scheduler is unavailable; retry shortly.
|
|
18
53
|
* @example
|
|
19
|
-
* await cron.create({
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
54
|
+
* const job = await totalum.cron.create({
|
|
55
|
+
* name: 'daily-report',
|
|
56
|
+
* schedule: '0 8 * * *', // 08:00 in Madrid all year
|
|
57
|
+
* timezone: 'Europe/Madrid',
|
|
58
|
+
* request: { method: 'POST', url: 'https://acme.totalum.app/api/cron/report' },
|
|
24
59
|
* });
|
|
60
|
+
* //=>
|
|
61
|
+
* {
|
|
62
|
+
* "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD",
|
|
63
|
+
* "name": "daily-report",
|
|
64
|
+
* "schedule": "0 8 * * *",
|
|
65
|
+
* "request": { "method": "POST", "url": "https://acme.totalum.app/api/cron/report" },
|
|
66
|
+
* "enabled": true,
|
|
67
|
+
* "status": "active",
|
|
68
|
+
* "nextRunAt": "2026-10-12T06:00:00.000Z",
|
|
69
|
+
* "createdAt": "2026-10-11T18:30:00.000Z",
|
|
70
|
+
* "env": "live",
|
|
71
|
+
* "timezone": "Europe/Madrid",
|
|
72
|
+
* "pauseAfterFailures": 3
|
|
73
|
+
* }
|
|
25
74
|
*/
|
|
26
75
|
create: (input) => call('POST', '/v1/cron/jobs', input),
|
|
27
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* Every job of the project, both environments. Free.
|
|
78
|
+
*
|
|
79
|
+
* @returns The jobs.
|
|
80
|
+
* @throws ENGINE_UNAVAILABLE (502) The scheduler is unavailable; retry shortly.
|
|
81
|
+
* @example
|
|
82
|
+
* const jobs = await totalum.cron.list();
|
|
83
|
+
* //=>
|
|
84
|
+
* [
|
|
85
|
+
* {
|
|
86
|
+
* "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD",
|
|
87
|
+
* "name": "daily-report",
|
|
88
|
+
* "schedule": "0 8 * * *",
|
|
89
|
+
* "request": { "method": "POST", "url": "https://acme.totalum.app/api/cron/report" },
|
|
90
|
+
* "enabled": true,
|
|
91
|
+
* "status": "active",
|
|
92
|
+
* "nextRunAt": "2026-10-12T06:00:00.000Z",
|
|
93
|
+
* "lastRun": { "at": "2026-10-11T06:00:00.412Z", "status": 200, "latencyMs": 812 },
|
|
94
|
+
* "createdAt": "2026-10-01T18:30:00.000Z",
|
|
95
|
+
* "env": "live",
|
|
96
|
+
* "timezone": "Europe/Madrid",
|
|
97
|
+
* "pauseAfterFailures": 3
|
|
98
|
+
* }
|
|
99
|
+
* ]
|
|
100
|
+
*/
|
|
28
101
|
list: async () => (await call('GET', '/v1/cron/jobs')).items,
|
|
29
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* One job, or `null` when the project has no job with this id. Free.
|
|
104
|
+
*
|
|
105
|
+
* @param id - The job's `id` (`cj_…`).
|
|
106
|
+
* @returns The job, or `null`.
|
|
107
|
+
* @throws ENGINE_UNAVAILABLE (502) The scheduler is unavailable; retry shortly.
|
|
108
|
+
* @example
|
|
109
|
+
* const job = await totalum.cron.get('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD');
|
|
110
|
+
* //=>
|
|
111
|
+
* { "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD", "name": "daily-report", "status": "active", "nextRunAt": "2026-10-12T06:00:00.000Z", … }
|
|
112
|
+
*/
|
|
30
113
|
get: async (id) => {
|
|
31
114
|
try {
|
|
32
115
|
return await call('GET', job(id));
|
|
@@ -37,19 +120,78 @@ export function totalumCron(options = {}) {
|
|
|
37
120
|
throw e;
|
|
38
121
|
}
|
|
39
122
|
},
|
|
40
|
-
/** Changes any field of a job (`schedule`, `request`, `enabled`, …). */
|
|
41
123
|
update,
|
|
42
|
-
/**
|
|
124
|
+
/**
|
|
125
|
+
* Deletes a job and its run history.
|
|
126
|
+
*
|
|
127
|
+
* @param id - The job's `id`.
|
|
128
|
+
* @returns Nothing once deleted.
|
|
129
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
130
|
+
* @example
|
|
131
|
+
* await totalum.cron.delete('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD');
|
|
132
|
+
*/
|
|
43
133
|
delete: async (id) => {
|
|
44
134
|
await call('DELETE', job(id));
|
|
45
135
|
},
|
|
46
|
-
/**
|
|
136
|
+
/**
|
|
137
|
+
* Stops a job from firing until `resume` (the same as `update(id, { enabled: false })`).
|
|
138
|
+
*
|
|
139
|
+
* @param id - The job's `id`.
|
|
140
|
+
* @returns The job, now `paused`.
|
|
141
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
142
|
+
* @example
|
|
143
|
+
* const job = await totalum.cron.pause('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD');
|
|
144
|
+
* //=>
|
|
145
|
+
* { "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD", "enabled": false, "status": "paused", "nextRunAt": null, … }
|
|
146
|
+
*/
|
|
47
147
|
pause: (id) => update(id, { enabled: false }),
|
|
48
|
-
/**
|
|
148
|
+
/**
|
|
149
|
+
* Lets a paused job fire again — also one paused after failing runs (`paused_failures`) once its route is fixed.
|
|
150
|
+
*
|
|
151
|
+
* @param id - The job's `id`.
|
|
152
|
+
* @returns The job, now `active`.
|
|
153
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
154
|
+
* @example
|
|
155
|
+
* const job = await totalum.cron.resume('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD');
|
|
156
|
+
* //=>
|
|
157
|
+
* { "id": "cj_01M4P1F0R7T2Y9U4I6O3P8A5SD", "enabled": true, "status": "active", "nextRunAt": "2026-10-12T06:00:00.000Z", … }
|
|
158
|
+
*/
|
|
49
159
|
resume: (id) => update(id, { enabled: true }),
|
|
50
|
-
/**
|
|
160
|
+
/**
|
|
161
|
+
* A job's executions of the last 30 days, newest first: when each ran, the HTTP status your route answered and how
|
|
162
|
+
* long it took. Free.
|
|
163
|
+
*
|
|
164
|
+
* @param id - The job's `id`.
|
|
165
|
+
* @param opts - Paging.
|
|
166
|
+
* @param opts.limit - Runs per page.
|
|
167
|
+
* @param opts.cursor - The previous page's `nextCursor`.
|
|
168
|
+
* @returns One page of runs.
|
|
169
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
170
|
+
* @example
|
|
171
|
+
* const page = await totalum.cron.runs('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD', { limit: 2 });
|
|
172
|
+
* //=>
|
|
173
|
+
* {
|
|
174
|
+
* "items": [
|
|
175
|
+
* { "id": "cr_01M4P1G2H3J4K5L6M7N8P9Q0RS", "scheduledFor": "2026-10-11T06:00:00.000Z", "startedAt": "2026-10-11T06:00:00.412Z", "status": 200, "latencyMs": 812, "responseSnippet": "{\"ok\":true}" },
|
|
176
|
+
* { "id": "cr_01M4MZ8B7V6C5X4Z3A2S1D0F9G", "scheduledFor": "2026-10-10T06:00:00.000Z", "startedAt": "2026-10-10T06:00:00.388Z", "status": "timeout", "latencyMs": 30000, "error": "The request timed out" }
|
|
177
|
+
* ],
|
|
178
|
+
* "nextCursor": "MjAyNi0xMC0xMFQwNjowMDowMC4wMDBa"
|
|
179
|
+
* }
|
|
180
|
+
*/
|
|
51
181
|
runs: (id, opts = {}) => call('GET', `${job(id)}/runs${query(opts)}`),
|
|
52
|
-
/**
|
|
182
|
+
/**
|
|
183
|
+
* Fires a job now, outside its schedule — a "Run now" button, or to test a new job. At most 10 manual runs a
|
|
184
|
+
* minute per project.
|
|
185
|
+
*
|
|
186
|
+
* @param id - The job's `id`.
|
|
187
|
+
* @returns The id of the run it started (it shows in `runs()` once done).
|
|
188
|
+
* @throws CRON_JOB_NOT_FOUND (404) No job with this id.
|
|
189
|
+
* @throws RATE_LIMITED (429) More than 10 manual runs in a minute; `details.retryAfterSeconds`.
|
|
190
|
+
* @example
|
|
191
|
+
* const { runId } = await totalum.cron.trigger('cj_01M4P1F0R7T2Y9U4I6O3P8A5SD');
|
|
192
|
+
* //=>
|
|
193
|
+
* { "runId": "cr_01M4P1H5J6K7L8M9N0P1Q2R3ST" }
|
|
194
|
+
*/
|
|
53
195
|
trigger: (id) => call('POST', `${job(id)}/trigger`),
|
|
54
196
|
};
|
|
55
197
|
}
|
package/dist/d1/errors.js
CHANGED
|
@@ -4,6 +4,7 @@ import { TotalumError } from '../errors.js';
|
|
|
4
4
|
* byte-identical to the binding's message when the failure is SQLite's.
|
|
5
5
|
*/
|
|
6
6
|
export class TotalumD1Error extends TotalumError {
|
|
7
|
+
/** `'TotalumD1Error'`, or `'Error'` for SQLite's own failures (as the native binding throws them). */
|
|
7
8
|
name = 'TotalumD1Error';
|
|
8
9
|
constructor(errorCode, message, options = {}) {
|
|
9
10
|
super(errorCode, message, options.status ?? 500, options.details, options.requestId);
|
|
@@ -43,6 +44,20 @@ export class TotalumD1Error extends TotalumError {
|
|
|
43
44
|
return new TotalumD1Error(errors.errorCode, `D1_ERROR: ${errors.errorCode}: ${errors.errorMessage}`, init);
|
|
44
45
|
}
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Whether `e` is a database error (a `TotalumD1Error`): a SQL error, a refusal of the driver, or the Totalum API's
|
|
49
|
+
* answer to a statement.
|
|
50
|
+
*
|
|
51
|
+
* @param e - Anything caught.
|
|
52
|
+
* @returns `true` for a `TotalumD1Error` (then `e.errorCode`, `e.message` are typed).
|
|
53
|
+
* @example
|
|
54
|
+
* try {
|
|
55
|
+
* await db.insert(users).values({ email });
|
|
56
|
+
* } catch (e) {
|
|
57
|
+
* if (isTotalumD1Error(e) && e.message.includes('UNIQUE constraint failed')) return { error: 'Email already used' };
|
|
58
|
+
* throw e;
|
|
59
|
+
* }
|
|
60
|
+
*/
|
|
46
61
|
export function isTotalumD1Error(e) {
|
|
47
62
|
return e instanceof TotalumD1Error;
|
|
48
63
|
}
|
package/dist/d1/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { S as SdkClientErrorCode, a as TotalumError, b as TotalumErrorCode, E as ErrorBody } from '../_types/errors.d-
|
|
1
|
+
import { S as SdkClientErrorCode, a as TotalumError, b as TotalumErrorCode, E as ErrorBody } from '../_types/errors.d-BPpY5QKu.js';
|
|
2
2
|
import { TotalumClientOptions } from '../ai/index.js';
|
|
3
|
-
export { i as isTotalumError } from '../_types/errors.d-
|
|
3
|
+
export { i as isTotalumError } from '../_types/errors.d-BPpY5QKu.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Cloudflare's `D1Database` surface, re-declared structurally so an app needs no Cloudflare types to compile
|
|
@@ -8,30 +8,113 @@ export { i as isTotalumError } from '../_types/errors.d-RTRkidv5.js';
|
|
|
8
8
|
* (`size_after` required); the contracts wire shape is looser and every value here satisfies it (type-tested).
|
|
9
9
|
*/
|
|
10
10
|
type D1Meta = {
|
|
11
|
+
/** How long the statement took in the database, in ms. */
|
|
11
12
|
duration: number;
|
|
13
|
+
/** The database's size after the statement, in bytes. */
|
|
12
14
|
size_after: number;
|
|
15
|
+
/** Rows the statement read (what makes a query slow: add an index when it is high). */
|
|
13
16
|
rows_read: number;
|
|
17
|
+
/** Rows the statement wrote. */
|
|
14
18
|
rows_written: number;
|
|
19
|
+
/** The rowid of the last inserted row (`INSERT` without `RETURNING`). */
|
|
15
20
|
last_row_id: number;
|
|
21
|
+
/** Whether the database changed. */
|
|
16
22
|
changed_db: boolean;
|
|
23
|
+
/** Rows inserted, updated or deleted. */
|
|
17
24
|
changes: number;
|
|
25
|
+
/** The region that answered (with read replicas). */
|
|
18
26
|
served_by_region?: string;
|
|
27
|
+
/** Whether the primary database answered (`false` for a read replica). */
|
|
19
28
|
served_by_primary?: boolean;
|
|
20
29
|
};
|
|
30
|
+
/** What `run()`, `all()` and each `batch()` statement return: the rows and the statement's metadata. */
|
|
21
31
|
interface D1Result<T = Record<string, unknown>> {
|
|
32
|
+
/** The rows, as objects keyed by column name (empty for a statement that returns none). */
|
|
22
33
|
results: T[];
|
|
34
|
+
/** Always `true`: a failure throws instead. */
|
|
23
35
|
success: true;
|
|
36
|
+
/** Timing, rows read and written, changes and the last inserted rowid. */
|
|
24
37
|
meta: D1Meta;
|
|
25
38
|
}
|
|
39
|
+
/** What `db.exec()` returns. */
|
|
26
40
|
interface D1ExecResult {
|
|
41
|
+
/** How many statements ran. */
|
|
27
42
|
count: number;
|
|
43
|
+
/** Their total time in ms. */
|
|
28
44
|
duration: number;
|
|
29
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* A prepared SQL statement, from `db.prepare(sql)`: bind its parameters, then run it with `first`, `all`, `run` or
|
|
48
|
+
* `raw`. Nothing runs until one of those is awaited.
|
|
49
|
+
*/
|
|
30
50
|
interface D1PreparedStatement {
|
|
51
|
+
/**
|
|
52
|
+
* Binds the values of the statement's `?` placeholders, in order, and returns a new statement (the original is
|
|
53
|
+
* unchanged). Values: strings, numbers, booleans (stored as 1/0), `null`, `ArrayBuffer`/`Uint8Array` (BLOB).
|
|
54
|
+
*
|
|
55
|
+
* @param values - One value per `?`, in order.
|
|
56
|
+
* @returns A statement with those parameters.
|
|
57
|
+
* @example
|
|
58
|
+
* const stmt = db.prepare('SELECT * FROM users WHERE email = ? AND active = ?').bind('ana@example.com', 1);
|
|
59
|
+
*/
|
|
31
60
|
bind(...values: unknown[]): D1PreparedStatement;
|
|
61
|
+
/**
|
|
62
|
+
* Runs the statement and returns the first row (or one column of it), or `null` when there is none.
|
|
63
|
+
*
|
|
64
|
+
* @param colName - Return only this column's value.
|
|
65
|
+
* @returns The first row, that column's value, or `null`.
|
|
66
|
+
* @throws SQL_ERROR SQLite refused the statement (`message` is SQLite's, as `D1_ERROR: …`).
|
|
67
|
+
* @example
|
|
68
|
+
* const user = await db.prepare('SELECT id, name FROM users WHERE email = ?').bind('ana@example.com').first();
|
|
69
|
+
* const count = await db.prepare('SELECT COUNT(*) AS n FROM users').first<number>('n');
|
|
70
|
+
* //=>
|
|
71
|
+
* user = { id: 42, name: 'Ana' } count = 128
|
|
72
|
+
*/
|
|
32
73
|
first<T = Record<string, unknown>>(colName?: string): Promise<T | null>;
|
|
74
|
+
/**
|
|
75
|
+
* Runs a statement that changes data (`INSERT`, `UPDATE`, `DELETE`, DDL) and returns its metadata (`changes`,
|
|
76
|
+
* `last_row_id`) — and its rows, with `RETURNING`.
|
|
77
|
+
*
|
|
78
|
+
* @returns The result: `results` (rows of a `RETURNING`) and `meta`.
|
|
79
|
+
* @throws SQL_ERROR SQLite refused the statement (a constraint, a syntax error).
|
|
80
|
+
* @example
|
|
81
|
+
* const r = await db.prepare('INSERT INTO users (email, name) VALUES (?, ?)').bind('ana@example.com', 'Ana').run();
|
|
82
|
+
* //=>
|
|
83
|
+
* {
|
|
84
|
+
* "success": true,
|
|
85
|
+
* "meta": { "duration": 0.31, "size_after": 12288, "rows_read": 1, "rows_written": 1, "last_row_id": 42, "changed_db": true, "changes": 1 },
|
|
86
|
+
* "results": []
|
|
87
|
+
* }
|
|
88
|
+
*/
|
|
33
89
|
run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
|
|
90
|
+
/**
|
|
91
|
+
* Runs a query and returns every row.
|
|
92
|
+
*
|
|
93
|
+
* @returns The result: `results` (the rows) and `meta`.
|
|
94
|
+
* @throws SQL_ERROR SQLite refused the statement.
|
|
95
|
+
* @example
|
|
96
|
+
* const { results } = await db.prepare("SELECT 'Ana' AS name, 42 AS age").all();
|
|
97
|
+
* //=>
|
|
98
|
+
* {
|
|
99
|
+
* "success": true,
|
|
100
|
+
* "meta": { "served_by_region": "WEUR", "served_by_primary": true, "duration": 0.1934, "changes": 0, "last_row_id": 0, "changed_db": false, "size_after": 12288, "rows_read": 0, "rows_written": 0 },
|
|
101
|
+
* "results": [{ "name": "Ana", "age": 42 }]
|
|
102
|
+
* }
|
|
103
|
+
*/
|
|
34
104
|
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
|
|
105
|
+
/**
|
|
106
|
+
* Runs a query and returns the rows as arrays of values (no column names), or with `columnNames: true` the names
|
|
107
|
+
* first.
|
|
108
|
+
*
|
|
109
|
+
* @param options - `{ columnNames: true }` puts the column names first.
|
|
110
|
+
* @param options.columnNames - `true`: the first array is the column names.
|
|
111
|
+
* @returns The rows as arrays.
|
|
112
|
+
* @throws SQL_ERROR SQLite refused the statement.
|
|
113
|
+
* @example
|
|
114
|
+
* const rows = await db.prepare('SELECT id, name FROM users LIMIT 2').raw({ columnNames: true });
|
|
115
|
+
* //=>
|
|
116
|
+
* [["id", "name"], [41, "Bob"], [42, "Ana"]]
|
|
117
|
+
*/
|
|
35
118
|
raw<T = unknown[]>(options: {
|
|
36
119
|
columnNames: true;
|
|
37
120
|
}): Promise<[string[], ...T[]]>;
|
|
@@ -39,19 +122,118 @@ interface D1PreparedStatement {
|
|
|
39
122
|
columnNames?: false;
|
|
40
123
|
}): Promise<T[]>;
|
|
41
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* A session for read replicas, from `db.withSession()`: its statements see a consistent view, and its bookmark can
|
|
127
|
+
* continue the view in a later request.
|
|
128
|
+
*/
|
|
42
129
|
interface D1DatabaseSession {
|
|
130
|
+
/**
|
|
131
|
+
* Prepares a statement in this session.
|
|
132
|
+
*
|
|
133
|
+
* @param sql - One SQL statement with `?` placeholders.
|
|
134
|
+
* @returns The prepared statement.
|
|
135
|
+
* @example
|
|
136
|
+
* const session = db.withSession('first-unconstrained');
|
|
137
|
+
* const posts = await session.prepare('SELECT * FROM posts ORDER BY id DESC LIMIT 10').all();
|
|
138
|
+
*/
|
|
43
139
|
prepare(sql: string): D1PreparedStatement;
|
|
140
|
+
/**
|
|
141
|
+
* Runs several statements in this session, as one atomic batch.
|
|
142
|
+
*
|
|
143
|
+
* @param statements - Statements prepared by this session.
|
|
144
|
+
* @returns One result per statement.
|
|
145
|
+
* @throws SQL_ERROR A statement failed; none was applied.
|
|
146
|
+
* @example
|
|
147
|
+
* const [users, posts] = await session.batch([session.prepare('SELECT * FROM users'), session.prepare('SELECT * FROM posts')]);
|
|
148
|
+
*/
|
|
44
149
|
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
|
|
150
|
+
/**
|
|
151
|
+
* The session's bookmark after its last statement: pass it to `withSession(bookmark)` in a later request to read at
|
|
152
|
+
* least that state. `null` before the first statement, and always over HTTPS and on Turso (one database, no
|
|
153
|
+
* replicas).
|
|
154
|
+
*
|
|
155
|
+
* @returns The bookmark, or `null`.
|
|
156
|
+
* @example
|
|
157
|
+
* const bookmark = session.getBookmark();
|
|
158
|
+
* //=>
|
|
159
|
+
* "0000002a-00000003-00004f5e-7a4ce4bd3c0e9b0e1f2c3d4e5f60718"
|
|
160
|
+
*/
|
|
45
161
|
getBookmark(): string | null;
|
|
46
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* The project's database, as `totalumD1()` returns it: Cloudflare's `D1Database` interface, so `drizzle(totalumD1())`
|
|
165
|
+
* works, and you can also run SQL by hand with `prepare`/`batch`.
|
|
166
|
+
*/
|
|
47
167
|
interface D1Database {
|
|
168
|
+
/**
|
|
169
|
+
* Prepares one SQL statement (with `?` placeholders); run it with `first`, `all`, `run` or `raw`. Nothing runs
|
|
170
|
+
* until then.
|
|
171
|
+
*
|
|
172
|
+
* @param sql - The SQL text. Several statements separated by `;` run together, atomically.
|
|
173
|
+
* @returns The prepared statement.
|
|
174
|
+
* @example
|
|
175
|
+
* const db = totalumD1();
|
|
176
|
+
* const user = await db.prepare('SELECT * FROM users WHERE id = ?').bind(42).first();
|
|
177
|
+
*/
|
|
48
178
|
prepare(sql: string): D1PreparedStatement;
|
|
179
|
+
/**
|
|
180
|
+
* Runs several statements in one round trip, as one atomic unit: all apply or none (D1 has no `BEGIN`/`COMMIT`; this
|
|
181
|
+
* is its transaction). Drizzle's `db.batch([...])` uses it.
|
|
182
|
+
*
|
|
183
|
+
* @param statements - Statements prepared by this database.
|
|
184
|
+
* @returns One result per statement, in order.
|
|
185
|
+
* @throws SQL_ERROR A statement failed; none was applied.
|
|
186
|
+
* @throws BATCH_FOREIGN_STATEMENT A statement prepared by another `totalumD1()` instance.
|
|
187
|
+
* @example
|
|
188
|
+
* const [debit, credit] = await db.batch([
|
|
189
|
+
* db.prepare('UPDATE accounts SET balance = balance - ? WHERE id = ?').bind(50, 1),
|
|
190
|
+
* db.prepare('UPDATE accounts SET balance = balance + ? WHERE id = ?').bind(50, 2),
|
|
191
|
+
* ]);
|
|
192
|
+
* //=>
|
|
193
|
+
* [
|
|
194
|
+
* { "success": true, "meta": { "changes": 1, … }, "results": [] },
|
|
195
|
+
* { "success": true, "meta": { "changes": 1, … }, "results": [] }
|
|
196
|
+
* ]
|
|
197
|
+
*/
|
|
49
198
|
batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
|
|
199
|
+
/**
|
|
200
|
+
* Runs a SQL script (several statements, no parameters): only in migrate mode, `totalumD1({ mode: 'migrate' })` from
|
|
201
|
+
* `scripts/migrate.ts`. For data, use `prepare` or `batch`.
|
|
202
|
+
*
|
|
203
|
+
* @param sql - The script.
|
|
204
|
+
* @returns How many statements ran and how long they took.
|
|
205
|
+
* @throws EXEC_REQUIRES_MIGRATE_MODE Called outside migrate mode.
|
|
206
|
+
* @throws SQL_ERROR A statement failed.
|
|
207
|
+
* @example
|
|
208
|
+
* const db = totalumD1({ mode: 'migrate' });
|
|
209
|
+
* await db.exec('CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL);');
|
|
210
|
+
* //=>
|
|
211
|
+
* { "count": 1, "duration": 0.42 }
|
|
212
|
+
*/
|
|
50
213
|
exec(sql: string): Promise<D1ExecResult>;
|
|
214
|
+
/**
|
|
215
|
+
* Not available: always throws `NOT_SUPPORTED`. Database backups are in the project's settings in Totalum.
|
|
216
|
+
*
|
|
217
|
+
* @returns Never resolves.
|
|
218
|
+
* @throws NOT_SUPPORTED Always.
|
|
219
|
+
* @example
|
|
220
|
+
* await db.dump(); // throws TotalumD1Error NOT_SUPPORTED
|
|
221
|
+
*/
|
|
51
222
|
dump(): Promise<ArrayBuffer>;
|
|
223
|
+
/**
|
|
224
|
+
* A session for read replicas: `'first-unconstrained'` reads from the nearest replica, `'first-primary'` starts at
|
|
225
|
+
* the primary, a bookmark continues a previous session. The template already wraps each request with
|
|
226
|
+
* `withTotalumSession`, so app code rarely needs this. Over HTTPS and on Turso the session is the database itself.
|
|
227
|
+
*
|
|
228
|
+
* @param constraintOrBookmark - `'first-unconstrained'`, `'first-primary'` or a bookmark from `getBookmark()`.
|
|
229
|
+
* @returns The session.
|
|
230
|
+
* @example
|
|
231
|
+
* const session = db.withSession('first-unconstrained');
|
|
232
|
+
* const { results } = await session.prepare('SELECT * FROM products LIMIT 20').all();
|
|
233
|
+
*/
|
|
52
234
|
withSession(constraintOrBookmark?: string): D1DatabaseSession;
|
|
53
235
|
}
|
|
54
|
-
/** `key`, `apiUrl` and `env` (HTTPS path only) resolve exactly as in every other namespace. */
|
|
236
|
+
/** The options of `totalumD1()`. `key`, `apiUrl` and `env` (HTTPS path only) resolve exactly as in every other namespace. */
|
|
55
237
|
interface TotalumD1Options extends TotalumClientOptions {
|
|
56
238
|
/** `'migrate'` (scripts/migrate.ts only) sends `x-totalum-migrate: 1` and enables `exec()`; default `'query'`. */
|
|
57
239
|
mode?: 'query' | 'migrate';
|
|
@@ -63,7 +245,10 @@ interface TotalumD1Options extends TotalumClientOptions {
|
|
|
63
245
|
transport?: 'auto' | 'https';
|
|
64
246
|
}
|
|
65
247
|
|
|
66
|
-
/**
|
|
248
|
+
/**
|
|
249
|
+
* The codes the database driver itself throws (before or without the Totalum API): no key, an unsupported call, a
|
|
250
|
+
* statement of another instance in a batch, the network, an unreadable answer.
|
|
251
|
+
*/
|
|
67
252
|
type TotalumD1ClientCode = Extract<SdkClientErrorCode, 'SDK_NOT_CONFIGURED' | 'NOT_SUPPORTED' | 'BATCH_FOREIGN_STATEMENT' | 'NETWORK_ERROR' | 'RESPONSE_PARSE_ERROR'>;
|
|
68
253
|
/** @deprecated Since 1.0.0: use `TotalumErrorCode` (the same type). */
|
|
69
254
|
type TotalumD1ErrorCode = TotalumErrorCode;
|
|
@@ -72,6 +257,7 @@ type TotalumD1ErrorCode = TotalumErrorCode;
|
|
|
72
257
|
* byte-identical to the binding's message when the failure is SQLite's.
|
|
73
258
|
*/
|
|
74
259
|
declare class TotalumD1Error extends TotalumError {
|
|
260
|
+
/** `'TotalumD1Error'`, or `'Error'` for SQLite's own failures (as the native binding throws them). */
|
|
75
261
|
name: string;
|
|
76
262
|
constructor(errorCode: TotalumErrorCode, message: string, options?: {
|
|
77
263
|
status?: number;
|
|
@@ -93,12 +279,35 @@ declare class TotalumD1Error extends TotalumError {
|
|
|
93
279
|
/** The Totalum API error envelope → typed error; `SQL_ERROR` is rebuilt as the binding's own error from `sqliteMessage`. */
|
|
94
280
|
static fromWire(errors: ErrorBody, status: number, requestId: string | undefined): TotalumD1Error;
|
|
95
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* Whether `e` is a database error (a `TotalumD1Error`): a SQL error, a refusal of the driver, or the Totalum API's
|
|
284
|
+
* answer to a statement.
|
|
285
|
+
*
|
|
286
|
+
* @param e - Anything caught.
|
|
287
|
+
* @returns `true` for a `TotalumD1Error` (then `e.errorCode`, `e.message` are typed).
|
|
288
|
+
* @example
|
|
289
|
+
* try {
|
|
290
|
+
* await db.insert(users).values({ email });
|
|
291
|
+
* } catch (e) {
|
|
292
|
+
* if (isTotalumD1Error(e) && e.message.includes('UNIQUE constraint failed')) return { error: 'Email already used' };
|
|
293
|
+
* throw e;
|
|
294
|
+
* }
|
|
295
|
+
*/
|
|
96
296
|
declare function isTotalumD1Error(e: unknown): e is TotalumD1Error;
|
|
97
297
|
|
|
98
|
-
/**
|
|
298
|
+
/**
|
|
299
|
+
* The name of the cookie `withTotalumSession` sets for 10 s after a write (`__tlm_d1_w`): while the browser holds it,
|
|
300
|
+
* its reads go to the primary database, so a user always sees what they just saved. Exported for apps that clear or
|
|
301
|
+
* inspect it.
|
|
302
|
+
*
|
|
303
|
+
* @example
|
|
304
|
+
* import { READ_YOUR_WRITES_COOKIE } from 'totalum-sdk/d1';
|
|
305
|
+
* const fresh = request.headers.get('cookie')?.includes(`${READ_YOUR_WRITES_COOKIE}=`);
|
|
306
|
+
*/
|
|
99
307
|
declare const READ_YOUR_WRITES_COOKIE = "__tlm_d1_w";
|
|
100
308
|
/**
|
|
101
|
-
*
|
|
309
|
+
* Wraps one request of the app's Worker entry (the template does it for you) so reads use the nearest read replica
|
|
310
|
+
* and writes stay consistent for the user who made them. In detail: a `GET`/`HEAD` reads through a
|
|
102
311
|
* `first-unconstrained` session — the nearest replica — unless the browser wrote in the last 10 s; any other method
|
|
103
312
|
* uses the plain binding (writes go to the primary; measured faster than any session) and its response sets the short
|
|
104
313
|
* cookie that sends that browser's next reads to the primary. A replica read that takes over `REPLICA_READ_TIMEOUT_MS`
|
|
@@ -107,14 +316,49 @@ declare const READ_YOUR_WRITES_COOKIE = "__tlm_d1_w";
|
|
|
107
316
|
* others; a sign-up waited on its first SELECT until the Worker was cancelled). `run` receives the env to hand to the
|
|
108
317
|
* app, whose `totalumD1()` reads `TOTALUM_DB` from it on every statement. No D1 binding (Turso, a laptop): `run(env)`
|
|
109
318
|
* unchanged.
|
|
319
|
+
*
|
|
320
|
+
* @param request - The incoming request.
|
|
321
|
+
* @param env - The Worker's env (with the `TOTALUM_DB` binding).
|
|
322
|
+
* @param run - Handles the request with the env to use (its `TOTALUM_DB` may be a session).
|
|
323
|
+
* @returns The response, with the short read-your-writes cookie after a write.
|
|
324
|
+
* @throws SQL_ERROR Whatever `run` throws is passed on unchanged.
|
|
325
|
+
* @example
|
|
326
|
+
* // worker.ts (the template's entry)
|
|
327
|
+
* import { withTotalumSession } from 'totalum-sdk/d1';
|
|
328
|
+
* import handler from './.open-next/worker.js';
|
|
329
|
+
*
|
|
330
|
+
* export default {
|
|
331
|
+
* fetch: (request: Request, env: Env, ctx: ExecutionContext) =>
|
|
332
|
+
* withTotalumSession(request, env, (env) => handler.fetch(request, env, ctx)),
|
|
333
|
+
* };
|
|
110
334
|
*/
|
|
111
335
|
declare function withTotalumSession<E extends object>(request: Request, env: E, run: (env: E) => Promise<Response>): Promise<Response>;
|
|
112
336
|
|
|
113
337
|
/**
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
* `initOpenNextCloudflareForDev()` binds under `next dev`, and an HTTPS client to the Totalum API everywhere else
|
|
117
|
-
* Detection happens on the first statement, never at call time
|
|
338
|
+
* The project's own database as a `D1Database`, wherever the code runs: the bound `TOTALUM_DB` inside a Worker (the
|
|
339
|
+
* preview and the published app), Turso when the environment moved there, the local D1 that
|
|
340
|
+
* `initOpenNextCloudflareForDev()` binds under `next dev`, and an HTTPS client to the Totalum API everywhere else (a
|
|
341
|
+
* script, a laptop: with `TOTALUM_PROJECT_KEY`). Detection happens on the first statement, never at call time, so
|
|
342
|
+
* `drizzle(totalumD1())` at module scope is fine. A transient failure of a read is retried for you.
|
|
343
|
+
*
|
|
344
|
+
* @param options - The key, API URL and environment for the HTTPS path, migrate mode, or an explicit binding.
|
|
345
|
+
* @returns The database: pass it to `drizzle()`, or use `prepare`/`batch` directly.
|
|
346
|
+
* @throws SDK_NOT_CONFIGURED Thrown by the first statement when no binding is found and `TOTALUM_PROJECT_KEY` is unset.
|
|
347
|
+
* @example
|
|
348
|
+
* // src/db/index.ts
|
|
349
|
+
* import { drizzle } from 'drizzle-orm/d1';
|
|
350
|
+
* import { totalumD1 } from 'totalum-sdk/d1';
|
|
351
|
+
* import * as schema from './schema';
|
|
352
|
+
*
|
|
353
|
+
* export const db = drizzle(totalumD1(), { schema });
|
|
354
|
+
*
|
|
355
|
+
* // anywhere on the server
|
|
356
|
+
* const latest = await db.select().from(schema.orders).orderBy(desc(schema.orders.createdAt)).limit(5);
|
|
357
|
+
* @example
|
|
358
|
+
* // plain SQL, from a script (npx tsx scripts/count-users.ts) — over HTTPS with TOTALUM_PROJECT_KEY
|
|
359
|
+
* const row = await totalumD1().prepare('SELECT COUNT(*) AS n FROM users').first();
|
|
360
|
+
* //=>
|
|
361
|
+
* { "n": 128 }
|
|
118
362
|
*/
|
|
119
363
|
declare function totalumD1(options?: TotalumD1Options): D1Database;
|
|
120
364
|
|
package/dist/d1/index.js
CHANGED
|
@@ -8,10 +8,30 @@ export { TotalumError, isTotalumError } from '../errors.js';
|
|
|
8
8
|
export { TotalumD1Error, isTotalumD1Error } from './errors.js';
|
|
9
9
|
export { READ_YOUR_WRITES_COOKIE, withTotalumSession } from './session.js';
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
* `initOpenNextCloudflareForDev()` binds under `next dev`, and an HTTPS client to the Totalum API everywhere else
|
|
14
|
-
* Detection happens on the first statement, never at call time
|
|
11
|
+
* The project's own database as a `D1Database`, wherever the code runs: the bound `TOTALUM_DB` inside a Worker (the
|
|
12
|
+
* preview and the published app), Turso when the environment moved there, the local D1 that
|
|
13
|
+
* `initOpenNextCloudflareForDev()` binds under `next dev`, and an HTTPS client to the Totalum API everywhere else (a
|
|
14
|
+
* script, a laptop: with `TOTALUM_PROJECT_KEY`). Detection happens on the first statement, never at call time, so
|
|
15
|
+
* `drizzle(totalumD1())` at module scope is fine. A transient failure of a read is retried for you.
|
|
16
|
+
*
|
|
17
|
+
* @param options - The key, API URL and environment for the HTTPS path, migrate mode, or an explicit binding.
|
|
18
|
+
* @returns The database: pass it to `drizzle()`, or use `prepare`/`batch` directly.
|
|
19
|
+
* @throws SDK_NOT_CONFIGURED Thrown by the first statement when no binding is found and `TOTALUM_PROJECT_KEY` is unset.
|
|
20
|
+
* @example
|
|
21
|
+
* // src/db/index.ts
|
|
22
|
+
* import { drizzle } from 'drizzle-orm/d1';
|
|
23
|
+
* import { totalumD1 } from 'totalum-sdk/d1';
|
|
24
|
+
* import * as schema from './schema';
|
|
25
|
+
*
|
|
26
|
+
* export const db = drizzle(totalumD1(), { schema });
|
|
27
|
+
*
|
|
28
|
+
* // anywhere on the server
|
|
29
|
+
* const latest = await db.select().from(schema.orders).orderBy(desc(schema.orders.createdAt)).limit(5);
|
|
30
|
+
* @example
|
|
31
|
+
* // plain SQL, from a script (npx tsx scripts/count-users.ts) — over HTTPS with TOTALUM_PROJECT_KEY
|
|
32
|
+
* const row = await totalumD1().prepare('SELECT COUNT(*) AS n FROM users').first();
|
|
33
|
+
* //=>
|
|
34
|
+
* { "n": 128 }
|
|
15
35
|
*/
|
|
16
36
|
export function totalumD1(options = {}) {
|
|
17
37
|
return lazyD1(() => resolveTarget(options), options.mode === 'migrate', {
|