@forestfuture/active-record 0.6.0 → 0.8.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 +5 -4
- package/config-schema.json +60 -0
- package/dist/adapter.d.mts +3 -2
- package/dist/adapter.mjs +5 -3
- package/dist/batch-ReqVoCfa.mjs +9559 -0
- package/dist/cli.d.mts +216 -46
- package/dist/cli.mjs +4 -3
- package/dist/command.mjs +1102 -529
- package/dist/d1.d.mts +60 -0
- package/dist/d1.mjs +334 -0
- package/dist/epoch-storage-CDlQZcBB.mjs +988 -0
- package/dist/for-adapters-B0xMP6Dq.d.mts +23 -0
- package/dist/for-adapters-CfXMGeOu.mjs +31 -0
- package/dist/for-adapters-DhNV1mWf.mjs +276 -0
- package/dist/{generated-model-CfDggoVN.mjs → generated-model-g5oWsDKE.mjs} +732 -540
- package/dist/index-BATasvJa.d.mts +241 -0
- package/dist/index.d.mts +4 -143
- package/dist/index.mjs +5 -3
- package/dist/metadata-CzntpYzC.d.mts +182 -0
- package/dist/plugin-wOSILvSB.mjs +699 -0
- package/dist/plugin-x5-d3TSN.mjs +1035 -0
- package/dist/postgresql.d.mts +64 -0
- package/dist/postgresql.mjs +604 -0
- package/dist/src-D56_3odT.mjs +46 -0
- package/dist/storage-override-n4w1cS_M.mjs +220 -0
- package/dist/validations-DHDVV8hB.d.mts +1996 -0
- package/llms-full.txt +3283 -656
- package/package.json +25 -2
- package/skills/active-record/SKILL.md +24 -16
- package/dist/adapter-BSvFhTDf.d.mts +0 -1293
- package/dist/batch-DBeYk5wx.mjs +0 -4171
- package/dist/epoch-storage-o2aoOH7H.mjs +0 -112
- package/dist/storage-override-BYBYP8Mj.mjs +0 -91
package/dist/d1.d.mts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { C as QueryEvent$1, D as SchemaAdapter, O as AnyDatabase, w as QueryListener$1 } from "./validations-DHDVV8hB.mjs";
|
|
2
|
+
import { i as ActiveRecordError } from "./index-BATasvJa.mjs";
|
|
3
|
+
/** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
|
|
4
|
+
export declare function d1({ binding }: {
|
|
5
|
+
binding: string;
|
|
6
|
+
}): SchemaAdapter;
|
|
7
|
+
/** What `onQuery` hears about a statement: its Model, SQL, bound values, timing, and D1's `meta`. */
|
|
8
|
+
type QueryEvent = QueryEvent$1<D1Meta>;
|
|
9
|
+
/** Hears each statement's `QueryEvent`, with D1's `meta`. */
|
|
10
|
+
type QueryListener = QueryListener$1<D1Meta>;
|
|
11
|
+
interface ConnectOptions {
|
|
12
|
+
/** Called once for every statement sent to D1, with D1's `meta`. */
|
|
13
|
+
onQuery?: QueryListener;
|
|
14
|
+
/**
|
|
15
|
+
* Sends every query through one D1 Session, so the request reads its own writes even when
|
|
16
|
+
* reads are served by replicas: `"first-primary"`, `"first-unconstrained"`, or a bookmark
|
|
17
|
+
* from an earlier request's `db.bookmark()`.
|
|
18
|
+
*/
|
|
19
|
+
session?: D1SessionConstraint | (D1SessionBookmark & {});
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A per-request wrapper around a D1 binding; every query goes through it. `db.batch` uses D1's
|
|
23
|
+
* `batch()`. There's no interactive `transaction()`, because D1 can't hold one open across awaits.
|
|
24
|
+
*/
|
|
25
|
+
export declare class Database extends AnyDatabase {
|
|
26
|
+
#private;
|
|
27
|
+
constructor(binding: D1Database, options?: ConnectOptions);
|
|
28
|
+
/**
|
|
29
|
+
* The Session's latest bookmark (null before its first query). Pass it to the next request's
|
|
30
|
+
* `connect(env.DB, { session: bookmark })` to read at least as new as this request wrote.
|
|
31
|
+
*/
|
|
32
|
+
bookmark(): D1SessionBookmark | null;
|
|
33
|
+
}
|
|
34
|
+
export declare function connect(binding: D1Database, options?: ConnectOptions): Database;
|
|
35
|
+
/** `bookmark()` was called on a Database opened without a `session`. */
|
|
36
|
+
export declare class NoSession extends ActiveRecordError {
|
|
37
|
+
name: string;
|
|
38
|
+
}
|
|
39
|
+
/** How `withSession` opens the request's Database, and where its bookmark travels. */
|
|
40
|
+
type SessionOptions = Omit<ConnectOptions, "session"> & {
|
|
41
|
+
/** Where a request with no bookmark starts its Session: `"first-unconstrained"` unless set. */
|
|
42
|
+
start?: D1SessionConstraint;
|
|
43
|
+
} & ({
|
|
44
|
+
/** The cookie the bookmark travels in: `"d1-bookmark"` unless set. */
|
|
45
|
+
cookie?: string;
|
|
46
|
+
header?: never;
|
|
47
|
+
} | {
|
|
48
|
+
cookie?: never;
|
|
49
|
+
/** The header the bookmark travels in, on the request and the response, instead of a cookie. */
|
|
50
|
+
header: string;
|
|
51
|
+
});
|
|
52
|
+
type Handler = (db: Database) => Response | Promise<Response>;
|
|
53
|
+
/**
|
|
54
|
+
* Runs `fn` with a Database whose Session starts from the request's bookmark, so the request
|
|
55
|
+
* reads at least as new as the user's last write, from any replica, and sets the Session's
|
|
56
|
+
* latest bookmark on the response it returns. An error from `fn` reaches the caller unchanged.
|
|
57
|
+
*/
|
|
58
|
+
export declare function withSession(request: Request, binding: D1Database, fn: Handler): Promise<Response>;
|
|
59
|
+
export declare function withSession(request: Request, binding: D1Database, options: SessionOptions, fn: Handler): Promise<Response>;
|
|
60
|
+
export type { ConnectOptions, QueryEvent, QueryListener, SessionOptions };
|
package/dist/d1.mjs
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { a as databaseExecutor, i as AnyDatabase, l as DatabaseExecutor, r as withDatabase } from "./batch-ReqVoCfa.mjs";
|
|
2
|
+
import { n as onlyRequested, t as workersEnv } from "./for-adapters-CfXMGeOu.mjs";
|
|
3
|
+
import { O as ActiveRecordError, p as hexOf, z as NoDatabase } from "./epoch-storage-CDlQZcBB.mjs";
|
|
4
|
+
import { M as boundValue } from "./generated-model-g5oWsDKE.mjs";
|
|
5
|
+
// src/adapters/d1/errors.ts
|
|
6
|
+
/** D1's error for a Session's bookmark it can't use, and the bookmark it repeats (#237). */
|
|
7
|
+
const rejectedBookmark = /invalid commitToken bookmark provided: (.*)$/s;
|
|
8
|
+
/** Whether `error` is D1 rejecting the bookmark a Session started from. */
|
|
9
|
+
function isRejectedBookmark(error) {
|
|
10
|
+
return error instanceof Error && rejectedBookmark.test(error.message);
|
|
11
|
+
}
|
|
12
|
+
/** What to read in `error`. A rejected bookmark repeats a request's text, so it says nothing. */
|
|
13
|
+
function messageOf(error) {
|
|
14
|
+
if (isRejectedBookmark(error)) return "";
|
|
15
|
+
return error instanceof Error ? error.message : String(error);
|
|
16
|
+
}
|
|
17
|
+
/** D1 constraint messages, e.g. "UNIQUE constraint failed: users.email: SQLITE_CONSTRAINT …". */
|
|
18
|
+
const KINDS = [
|
|
19
|
+
[/UNIQUE constraint failed: ([^:]+)/, "unique"],
|
|
20
|
+
[/NOT NULL constraint failed: ([^:]+)/, "notNull"],
|
|
21
|
+
[/FOREIGN KEY constraint failed/, "foreignKey"],
|
|
22
|
+
[/CHECK constraint failed/, "check"]
|
|
23
|
+
];
|
|
24
|
+
/** What D1's message names: "users.email, users.role" → users, [email, role]. */
|
|
25
|
+
function namedIn(list) {
|
|
26
|
+
const entries = (list ?? "").split(",").map((entry) => entry.trim().split("."));
|
|
27
|
+
const table = entries[0]?.length === 2 ? entries[0][0] : void 0;
|
|
28
|
+
return {
|
|
29
|
+
table,
|
|
30
|
+
columns: entries.filter(([name]) => name === table).map(([, column]) => column)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** What a D1 constraint failure says failed. Any other error, undefined. */
|
|
34
|
+
function constraintFailure(error) {
|
|
35
|
+
const message = messageOf(error);
|
|
36
|
+
for (const [pattern, kind] of KINDS) {
|
|
37
|
+
const match = pattern.exec(message);
|
|
38
|
+
if (match !== null) return {
|
|
39
|
+
kind,
|
|
40
|
+
...namedIn(match[1])
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The table D1's "no such table" names. Any other error, undefined. */
|
|
45
|
+
function missingTable(error) {
|
|
46
|
+
return /no such table: ([^\s:]+)/.exec(messageOf(error))?.[1];
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Workers' refusal of a D1 call outside a request (a query at a module's top level), as a
|
|
50
|
+
* `NoDatabase` saying where queries belong; any other error, undefined.
|
|
51
|
+
*/
|
|
52
|
+
function outsideRequest(error) {
|
|
53
|
+
if (!/within global scope/i.test(messageOf(error))) return void 0;
|
|
54
|
+
return new NoDatabase("Queries run during a request: Workers don't allow D1 calls at a module's top level. Move the query into your fetch handler, or a function it calls", { cause: error });
|
|
55
|
+
}
|
|
56
|
+
/** `bookmark()` was called on a Database opened without a `session`. */
|
|
57
|
+
var NoSession = class extends ActiveRecordError {
|
|
58
|
+
name = "NoSession";
|
|
59
|
+
};
|
|
60
|
+
// src/adapters/d1/driver.ts
|
|
61
|
+
/** How much of a rejected bookmark D1's error keeps, since a request may have sent any length. */
|
|
62
|
+
const shownBookmarkLength = 64;
|
|
63
|
+
/** Cuts a long rejected bookmark short in `error`'s message, and its cause's (workerd's). */
|
|
64
|
+
function shortenBookmarkIn(error) {
|
|
65
|
+
if (!(error instanceof Error)) return;
|
|
66
|
+
const bookmark = rejectedBookmark.exec(error.message)?.[1];
|
|
67
|
+
if (bookmark === void 0 || bookmark.length <= shownBookmarkLength) return;
|
|
68
|
+
const short = `${bookmark.slice(0, shownBookmarkLength)}…`;
|
|
69
|
+
error.message = error.message.replace(bookmark, short);
|
|
70
|
+
if (error.cause instanceof Error) error.cause.message = error.cause.message.replace(bookmark, short);
|
|
71
|
+
}
|
|
72
|
+
/** D1's result for a statement, as the core reads it: D1's `meta` kept for `onQuery`. */
|
|
73
|
+
function neutral({ results, meta }) {
|
|
74
|
+
return {
|
|
75
|
+
rows: results,
|
|
76
|
+
rowsAffected: meta.changes,
|
|
77
|
+
durationMs: meta.duration,
|
|
78
|
+
meta
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** The single place the library calls D1. */
|
|
82
|
+
var D1Driver = class {
|
|
83
|
+
#source;
|
|
84
|
+
/** Starts the Session again when D1 rejects the bookmark it started from (#237); once only. */
|
|
85
|
+
#startAgain;
|
|
86
|
+
/** The source each rejected statement went to, so one the Session has left is sent anew. */
|
|
87
|
+
#rejectedOn = /* @__PURE__ */ new WeakMap();
|
|
88
|
+
/** `source` is the D1 binding itself, or one D1 Session every query goes through. */
|
|
89
|
+
constructor(source) {
|
|
90
|
+
this.#source = source;
|
|
91
|
+
}
|
|
92
|
+
/** The D1 Session its statements go through now, if it has one. */
|
|
93
|
+
get session() {
|
|
94
|
+
return "getBookmark" in this.#source ? this.#source : void 0;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Arms a new Session for when D1 rejects the bookmark this one started from (a request's, which
|
|
98
|
+
* may be forged): `startAgain` opens it, and the rejected statement is sent again on it, since
|
|
99
|
+
* it never ran. Disarmed once a statement succeeds.
|
|
100
|
+
*/
|
|
101
|
+
whenBookmarkRejected(startAgain) {
|
|
102
|
+
this.#startAgain = startAgain;
|
|
103
|
+
}
|
|
104
|
+
async send(statement) {
|
|
105
|
+
return neutral(await this.#sent(() => this.#prepare(statement).all()));
|
|
106
|
+
}
|
|
107
|
+
read(statements) {
|
|
108
|
+
return this.#batch(statements);
|
|
109
|
+
}
|
|
110
|
+
write(statements) {
|
|
111
|
+
return this.#batch(statements);
|
|
112
|
+
}
|
|
113
|
+
/** D1's `batch()`: one round trip, and atomic, for reads and writes alike. */
|
|
114
|
+
async #batch(statements) {
|
|
115
|
+
return (await this.#sent(() => this.#source.batch(statements.map((statement) => this.#prepare(statement))))).map(neutral);
|
|
116
|
+
}
|
|
117
|
+
/** Sends with `send`: a success disarms the restart, and a failure's bookmark is shortened. */
|
|
118
|
+
async #sent(send) {
|
|
119
|
+
const source = this.#source;
|
|
120
|
+
try {
|
|
121
|
+
const sent = await send();
|
|
122
|
+
this.#startAgain = void 0;
|
|
123
|
+
return sent;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
shortenBookmarkIn(error);
|
|
126
|
+
if (isRejectedBookmark(error)) this.#rejectedOn.set(error, source);
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Whether D1 rejected the bookmark and the Session has started again, once, so a statement it
|
|
132
|
+
* rejected can be sent anew. Statements sent at once all fail; each is sent again.
|
|
133
|
+
*/
|
|
134
|
+
recover(error) {
|
|
135
|
+
if (!isRejectedBookmark(error)) return false;
|
|
136
|
+
if (this.#rejectedOn.get(error) !== this.#source) return true;
|
|
137
|
+
if (this.#startAgain === void 0) return false;
|
|
138
|
+
this.#source = this.#startAgain();
|
|
139
|
+
this.#startAgain = void 0;
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
#prepare({ sql, params }) {
|
|
143
|
+
return this.#source.prepare(sql).bind(...params.map(boundValue));
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
// src/adapters/d1/current-binding.ts
|
|
147
|
+
/** @internal The library's key for a D1 database's binding and Driver. */
|
|
148
|
+
const d1Parts = Symbol("d1Parts");
|
|
149
|
+
/** The Worker's bindings, from `cloudflare:workers`, read once; undefined outside a Worker. */
|
|
150
|
+
let bindings;
|
|
151
|
+
/** The `env` a test mocks with the D1 adapter inlined is this module's import, so it's imported here. */
|
|
152
|
+
function workerBindings() {
|
|
153
|
+
bindings ??= workersEnv(() => import("cloudflare:workers"));
|
|
154
|
+
return bindings;
|
|
155
|
+
}
|
|
156
|
+
/** One Database per D1 binding, for queries outside `withDatabase`: it holds nothing per-request. */
|
|
157
|
+
const defaults = /* @__PURE__ */ new WeakMap();
|
|
158
|
+
function defaultDatabase(binding, name) {
|
|
159
|
+
let db = defaults.get(binding);
|
|
160
|
+
if (db === void 0) {
|
|
161
|
+
db = new AnyDatabase(new DatabaseExecutor(d1Adapter, new D1Driver(binding)));
|
|
162
|
+
db[databaseExecutor].setOrigin({ binding: name });
|
|
163
|
+
defaults.set(binding, db);
|
|
164
|
+
}
|
|
165
|
+
return db;
|
|
166
|
+
}
|
|
167
|
+
/** The database a query on binding `name` uses now: the request's for it, or the binding's own. */
|
|
168
|
+
async function databaseFor(name, requested) {
|
|
169
|
+
const env = name === void 0 ? void 0 : await workerBindings();
|
|
170
|
+
if (env === void 0 || name === void 0) return onlyRequested(requested, name, "connect(env.DB)");
|
|
171
|
+
const binding = env[name];
|
|
172
|
+
if (binding === void 0) throw new NoDatabase(`The binding ${name} isn't in this Worker's env; check d1_databases in your Wrangler config`);
|
|
173
|
+
return requested.find((db) => d1Parts in db && db[d1Parts].binding === binding) ?? defaultDatabase(binding, name);
|
|
174
|
+
}
|
|
175
|
+
// src/adapters/d1/dialect.ts
|
|
176
|
+
/** A binary attribute's cells, each bytes, as hex text: what JSON can hold. */
|
|
177
|
+
function hexCells(cells) {
|
|
178
|
+
return cells.map((cell) => cell === null ? null : hexOf(cell));
|
|
179
|
+
}
|
|
180
|
+
/** A list's cells bound as one JSON value, and how a `json_each` row reads one back (#20). */
|
|
181
|
+
function jsonList(cells, isBinary) {
|
|
182
|
+
return {
|
|
183
|
+
value: JSON.stringify(isBinary ? hexCells(cells) : cells),
|
|
184
|
+
cell: isBinary ? "unhex(value)" : "value"
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
// src/adapters/d1/adapter.ts
|
|
188
|
+
const d1Adapter = {
|
|
189
|
+
name: "D1",
|
|
190
|
+
dialect: {
|
|
191
|
+
placeholder: () => "?",
|
|
192
|
+
inList(column, cells, { isBinary }) {
|
|
193
|
+
const { value, cell } = jsonList(cells, isBinary);
|
|
194
|
+
return {
|
|
195
|
+
sql: `${column} IN (SELECT ${cell} FROM json_each())`,
|
|
196
|
+
value
|
|
197
|
+
};
|
|
198
|
+
},
|
|
199
|
+
placeInList(column, cells, { isBinary }) {
|
|
200
|
+
const { value, cell } = jsonList(cells, isBinary);
|
|
201
|
+
return {
|
|
202
|
+
sql: `(SELECT MIN(key) FROM json_each() WHERE ${cell} IS ${column})`,
|
|
203
|
+
value
|
|
204
|
+
};
|
|
205
|
+
},
|
|
206
|
+
pagination(limit, offset, params) {
|
|
207
|
+
params.push(limit ?? -1);
|
|
208
|
+
if (offset === void 0) return ` LIMIT `;
|
|
209
|
+
params.push(offset);
|
|
210
|
+
return ` LIMIT OFFSET `;
|
|
211
|
+
},
|
|
212
|
+
bulkRows: (_table, attributes) => ({
|
|
213
|
+
select: attributes.map(({ isBinary }, index) => {
|
|
214
|
+
const cell = `value ->> '$[${index}]'`;
|
|
215
|
+
return isBinary ? `unhex(${cell})` : cell;
|
|
216
|
+
}).join(", "),
|
|
217
|
+
from: `json_each()`
|
|
218
|
+
}),
|
|
219
|
+
maxValueBytes: 2e6,
|
|
220
|
+
linkedKey: (key, keyAttribute, linked) => linked.isText && !keyAttribute.isText ? `CAST(${key} AS TEXT)` : key
|
|
221
|
+
},
|
|
222
|
+
maxBoundValues: 100,
|
|
223
|
+
constraintFailure,
|
|
224
|
+
missingTable,
|
|
225
|
+
refusal: outsideRequest,
|
|
226
|
+
databaseFor
|
|
227
|
+
};
|
|
228
|
+
/** The D1 database a generated schema's Models query: `adapter: d1({ binding: "DB" })`. */
|
|
229
|
+
function d1({ binding }) {
|
|
230
|
+
return {
|
|
231
|
+
adapter: d1Adapter,
|
|
232
|
+
binding
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
// src/adapters/d1/database.ts
|
|
236
|
+
/**
|
|
237
|
+
* A per-request wrapper around a D1 binding; every query goes through it. `db.batch` uses D1's
|
|
238
|
+
* `batch()`. There's no interactive `transaction()`, because D1 can't hold one open across awaits.
|
|
239
|
+
*/
|
|
240
|
+
var Database = class extends AnyDatabase {
|
|
241
|
+
#binding;
|
|
242
|
+
#driver;
|
|
243
|
+
constructor(binding, options = {}) {
|
|
244
|
+
const { session, onQuery } = options;
|
|
245
|
+
const driver = new D1Driver(session === void 0 ? binding : binding.withSession(session));
|
|
246
|
+
super(new DatabaseExecutor(d1Adapter, driver, onQuery));
|
|
247
|
+
this.#binding = binding;
|
|
248
|
+
this.#driver = driver;
|
|
249
|
+
}
|
|
250
|
+
/** @internal Its D1 binding (not its Session), to match Models' bindings, and its Driver. */
|
|
251
|
+
get [d1Parts]() {
|
|
252
|
+
return {
|
|
253
|
+
binding: this.#binding,
|
|
254
|
+
driver: this.#driver
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The Session's latest bookmark (null before its first query). Pass it to the next request's
|
|
259
|
+
* `connect(env.DB, { session: bookmark })` to read at least as new as this request wrote.
|
|
260
|
+
*/
|
|
261
|
+
bookmark() {
|
|
262
|
+
const { session } = this.#driver;
|
|
263
|
+
if (session === void 0) throw new NoSession("bookmark() needs a Database opened with a session: connect(env.DB, { session })");
|
|
264
|
+
return session.getBookmark();
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
function connect(binding, options) {
|
|
268
|
+
return new Database(binding, options);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* @internal A request's Database, for `withSession`: its Session starts from the bookmark the
|
|
272
|
+
* request carries, or `start` when it has none. A request's bookmark may be forged, so one D1
|
|
273
|
+
* rejects starts the Session again from `start` (#237); a bookmark given to `connect` throws.
|
|
274
|
+
*/
|
|
275
|
+
function connectForRequest(binding, bookmark, start, options) {
|
|
276
|
+
const db = new Database(binding, {
|
|
277
|
+
...options,
|
|
278
|
+
session: bookmark ?? start
|
|
279
|
+
});
|
|
280
|
+
if (bookmark !== void 0) db[d1Parts].driver.whenBookmarkRejected(() => binding.withSession(start));
|
|
281
|
+
return db;
|
|
282
|
+
}
|
|
283
|
+
// src/adapters/d1/with-session.ts
|
|
284
|
+
async function withSession(request, binding, ...args) {
|
|
285
|
+
const [options, fn] = args.length === 1 ? [{}, args[0]] : args;
|
|
286
|
+
const { start = "first-unconstrained", cookie, header, ...connectOptions } = options;
|
|
287
|
+
const carrier = carrierFor(cookie, header);
|
|
288
|
+
const bookmark = carrier.read(request);
|
|
289
|
+
const db = connectForRequest(binding, bookmark, start, connectOptions);
|
|
290
|
+
const response = await withDatabase(db, () => fn(db));
|
|
291
|
+
const latest = db.bookmark() ?? bookmark;
|
|
292
|
+
if (latest === void 0) return response;
|
|
293
|
+
return withHeaders(response, (headers) => carrier.write(headers, latest));
|
|
294
|
+
}
|
|
295
|
+
function carrierFor(cookie, header) {
|
|
296
|
+
if (header === void 0) return cookieCarrier(cookie ?? "d1-bookmark");
|
|
297
|
+
if (cookie !== void 0) throw new TypeError("withSession takes a cookie or a header for the bookmark, not both");
|
|
298
|
+
return headerCarrier(header);
|
|
299
|
+
}
|
|
300
|
+
function headerCarrier(name) {
|
|
301
|
+
return {
|
|
302
|
+
read: (request) => request.headers.get(name) || void 0,
|
|
303
|
+
write: (headers, bookmark) => headers.set(name, bookmark)
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
function cookieCarrier(name) {
|
|
307
|
+
return {
|
|
308
|
+
read: (request) => cookieValue(request, name),
|
|
309
|
+
write: (headers, bookmark) => headers.append("set-cookie", `${name}=${bookmark}; Path=/; HttpOnly; Secure; SameSite=Lax`)
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* `response` with its headers changed by `change`. A response whose headers can't change (one
|
|
314
|
+
* from `fetch()` or `Response.redirect()`) is copied first; any other is returned as it is, so a
|
|
315
|
+
* WebSocket upgrade keeps its socket.
|
|
316
|
+
*/
|
|
317
|
+
function withHeaders(response, change) {
|
|
318
|
+
try {
|
|
319
|
+
change(response.headers);
|
|
320
|
+
return response;
|
|
321
|
+
} catch {
|
|
322
|
+
const copy = new Response(response.body, response);
|
|
323
|
+
change(copy.headers);
|
|
324
|
+
return copy;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** The value of the request's cookie named `name`, if it sent one that isn't empty. */
|
|
328
|
+
function cookieValue(request, name) {
|
|
329
|
+
for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
|
|
330
|
+
const [key, ...value] = pair.split("=");
|
|
331
|
+
if (key?.trim() === name) return value.join("=").trim() || void 0;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
export { Database, NoSession, connect, d1, withSession };
|