@tinkered/bun 0.0.0-stage → 0.18.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/dist/index.mjs ADDED
@@ -0,0 +1,540 @@
1
+ import { i as Tools } from "./client-MAqzflMe.mjs";
2
+ import { capsule, data, operation, tag, transport } from "@tinkered/core";
3
+ //#region src/ws.ts
4
+ const { kept, openInput, protocol, request, requestStop, sendInput, traceparentOf } = transport;
5
+ /** The input of an op only this transport calls: its one caller builds it, so it is typed only. */
6
+ const given = () => (raw) => raw;
7
+ /** True for an object of string values only: the `x-meta` header of a bytes POST. */
8
+ const isTextRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((each) => typeof each === "string");
9
+ /** Makes one WebSocket server. */
10
+ function createWs() {
11
+ const path = tag({ label: "ws.path" });
12
+ const codec = tag({ label: "ws.codec" }).optional;
13
+ const services = tag({ label: "ws.services" }).required;
14
+ const strict = tag({
15
+ label: "ws.strict",
16
+ default: false
17
+ });
18
+ /** The public origin a socket comes from. Unset, it is the request URL's own origin; behind a
19
+ * TLS proxy that is `http://<host>`, so the app binds its public `https` origin here. */
20
+ const origin = tag({
21
+ label: "ws.origin",
22
+ default: null
23
+ });
24
+ /** The largest frame in, and the most unsent bytes out, per socket (1 MiB). */
25
+ const maxPayload = tag({
26
+ label: "ws.maxPayload",
27
+ default: 1048576,
28
+ parse: (raw) => {
29
+ if (!Number.isSafeInteger(raw) || Number(raw) <= 0) throw new TypeError("not a positive whole number of bytes");
30
+ return Number(raw);
31
+ }
32
+ });
33
+ const maxWatches = tag({
34
+ label: "ws.maxWatches",
35
+ default: 256
36
+ });
37
+ /** The most bytes POSTs at once, on this server. */
38
+ const maxUploads = tag({
39
+ label: "ws.maxUploads",
40
+ default: 8
41
+ });
42
+ /** The most time a bytes POST may take, in ms (5 min). */
43
+ const uploadDeadline = tag({
44
+ label: "ws.uploadDeadline",
45
+ default: 3e5
46
+ });
47
+ const serve = operation({
48
+ label: "ws.serve",
49
+ input: sendInput,
50
+ run: () => {
51
+ throw new Error("ws: no server here");
52
+ }
53
+ });
54
+ const serveStream = operation({
55
+ label: "ws.serveStream",
56
+ input: openInput,
57
+ run: () => {
58
+ throw new Error("ws: no server here");
59
+ }
60
+ });
61
+ /**
62
+ * A bytes POST's body: the request's stream, read once and only when the implementation reads
63
+ * it, counted (`over` once past `max`, whatever Content-Length said) and cut at `stop`.
64
+ */
65
+ const bodyOf = operation({
66
+ label: "ws.body",
67
+ input: given(),
68
+ run: (_, { input: { req, max, type, stop } }) => ({
69
+ type,
70
+ read: false,
71
+ seen: 0,
72
+ over: false,
73
+ stream() {
74
+ if (this.read) throw new TypeError("The body was read already.");
75
+ this.read = true;
76
+ const counted = new TransformStream({ transform: (chunk, out) => {
77
+ this.seen += chunk.byteLength;
78
+ if (this.seen <= max) return out.enqueue(chunk);
79
+ this.over = true;
80
+ out.error(/* @__PURE__ */ new RangeError("The body is over its max."));
81
+ } });
82
+ return (req.body ?? new Blob().stream()).pipeThrough(counted, { signal: stop });
83
+ },
84
+ bytes() {
85
+ return new Response(this.stream()).bytes();
86
+ },
87
+ text() {
88
+ return new Response(this.stream()).text();
89
+ },
90
+ arrayBuffer() {
91
+ return new Response(this.stream()).arrayBuffer();
92
+ }
93
+ })
94
+ });
95
+ /**
96
+ * The guards of a bytes POST, before a byte is read: the first that fails answers, in the order
97
+ * of the comment at the top. Else the call's text, meta and type, read off the headers.
98
+ */
99
+ const admit = operation({
100
+ label: "ws.admit",
101
+ input: given(),
102
+ run: async (_, { input: { req, limit = {
103
+ max: 0,
104
+ types: []
105
+ }, origin, busy } }) => {
106
+ const h = Object.fromEntries(req.headers);
107
+ const type = String(h["content-type"]).split(";")[0].trim().toLowerCase();
108
+ const meta = await Promise.resolve(h["x-meta"] ?? "{}").then(JSON.parse).catch(() => null);
109
+ const status = [
110
+ [limit.max > 0, 404],
111
+ [[void 0, origin].includes(h.origin), 403],
112
+ [h["x-input"] !== void 0, 400],
113
+ [String(h["x-input"]).length <= 2048 && String(h["x-meta"]).length <= 2048, 431],
114
+ [isTextRecord(meta), 400],
115
+ [limit.types.includes(type), 415],
116
+ [!(Number(h["content-length"]) > limit.max), 413],
117
+ [!busy, 503]
118
+ ].find(([ok]) => !ok)?.[1];
119
+ if (!status) return {
120
+ text: String(h["x-input"]),
121
+ meta,
122
+ type
123
+ };
124
+ return new Response(null, {
125
+ status,
126
+ headers: status === 503 ? { "retry-after": "1" } : void 0
127
+ });
128
+ }
129
+ });
130
+ const held = data({
131
+ label: "transport.server",
132
+ initial: null
133
+ });
134
+ return { server: capsule({
135
+ label: "ws.server",
136
+ config: {
137
+ path: path.required,
138
+ origin,
139
+ codec,
140
+ services,
141
+ strict,
142
+ maxPayload,
143
+ maxWatches,
144
+ maxUploads,
145
+ uploadDeadline
146
+ },
147
+ hooks: {
148
+ async start({ config, load, next, raise, log }) {
149
+ const allowed = config.origin === null ? "" : String(URL.parse(config.origin)?.origin);
150
+ if (!/^(https?:\/\/|$)/.test(allowed)) raise("MissingConfig", {
151
+ label: "ws.server",
152
+ key: "origin"
153
+ });
154
+ const p = await load(protocol, kept);
155
+ const routesOf = p.routesOf(config.services, raise, log, config.strict);
156
+ const side = {
157
+ codec: p.given(config.codec) ?? p.json,
158
+ routes: routesOf
159
+ };
160
+ /** The addresses that take bytes, with their limits, from the service that owns each. */
161
+ const uploadsAt = new Map([...routesOf].flatMap(([address, one]) => {
162
+ const limit = one.uploads?.[address];
163
+ return limit ? [[address, limit]] : [];
164
+ }));
165
+ load(held, kept).set({
166
+ side,
167
+ protocol: p
168
+ });
169
+ await next();
170
+ const upgrade = (req, scope, bun) => {
171
+ const url = new URL(req.url);
172
+ if (url.pathname !== config.path) return void 0;
173
+ if (![null, new URL(allowed, url).origin].includes(req.headers.get("origin"))) return new Response(null, { status: 403 });
174
+ const own = {
175
+ req,
176
+ scope,
177
+ gone: new AbortController(),
178
+ watches: /* @__PURE__ */ new Map(),
179
+ out: [],
180
+ /** Queues one message; the first of a tick schedules the frame. */
181
+ emit(ws, message) {
182
+ if (own.gone.signal.aborted || own.out.push(message) > 1) return;
183
+ setImmediate(() => {
184
+ if (!own.gone.signal.aborted) ws.send(JSON.stringify(own.out.splice(0)));
185
+ });
186
+ },
187
+ pusher(ws, i) {
188
+ return (t) => own.emit(ws, {
189
+ i,
190
+ t
191
+ });
192
+ },
193
+ /** One message: a stop, or a call or watch that fits. */
194
+ async one(ws, m) {
195
+ if (m.x) return own.watches.get(m.i)?.abort();
196
+ const bad = typeof m.a !== "string" || typeof m.t !== "string";
197
+ const full = !!m.w && own.watches.size >= config.maxWatches;
198
+ if (bad || full) return own.emit(ws, {
199
+ i: m.i,
200
+ e: bad ? 400 : 429
201
+ });
202
+ return own.run(ws, m);
203
+ },
204
+ /** A call or a watch, in its own session of the scope. */
205
+ async run(ws, m) {
206
+ const meta = Object(m.m);
207
+ const trace = traceparentOf(meta.traceparent);
208
+ const stop = m.w ? new AbortController() : void 0;
209
+ const left = AbortSignal.any(stop ? [stop.signal, own.gone.signal] : [own.gone.signal]);
210
+ const tags = [request(req), requestStop(left)];
211
+ const session = await Promise.resolve().then(() => scope.createSession({
212
+ trace,
213
+ tags
214
+ })).catch(() => null);
215
+ if (!session) return own.emit(ws, {
216
+ i: m.i,
217
+ e: 503
218
+ });
219
+ const input = {
220
+ address: String(m.a),
221
+ text: String(m.t),
222
+ meta
223
+ };
224
+ if (!m.w) {
225
+ const reply = await session.run(serve, { input }).finally(() => session.close());
226
+ return own.emit(ws, reply === null ? {
227
+ i: m.i,
228
+ e: 404
229
+ } : {
230
+ i: m.i,
231
+ t: reply
232
+ });
233
+ }
234
+ own.watches.set(m.i, stop);
235
+ const push = own.pusher(ws, m.i);
236
+ await Promise.resolve(session.run(serveStream, { input: {
237
+ ...input,
238
+ left,
239
+ push
240
+ } })).then((found) => own.emit(ws, found ? {
241
+ i: m.i,
242
+ end: 1
243
+ } : {
244
+ i: m.i,
245
+ e: 404
246
+ })).catch((error) => {
247
+ log.error("ws stream failed", {
248
+ address: m.a,
249
+ cause: String(error)
250
+ });
251
+ own.emit(ws, {
252
+ i: m.i,
253
+ end: 1
254
+ });
255
+ }).finally(() => (own.watches.delete(m.i), void session.close()));
256
+ }
257
+ };
258
+ return bun.upgrade(req, { data: own }) ? null : new Response(null, { status: 426 });
259
+ };
260
+ /** The bytes POSTs running now. */
261
+ let uploading = 0;
262
+ /**
263
+ * A bytes POST: undefined when it is not one (not this path), else the reply. The guards
264
+ * run in the order of the comment at the top; the body is read only by the implementation.
265
+ */
266
+ const post = async (req, scope) => {
267
+ const url = new URL(req.url);
268
+ const address = decodeURIComponent(url.pathname.slice(config.path.length + 1));
269
+ const limit = uploadsAt.get(address);
270
+ if (req.method !== "POST" || !url.pathname.startsWith(`${config.path}/`)) return;
271
+ const busy = uploading >= config.maxUploads;
272
+ const origin = new URL(allowed, url).origin;
273
+ const admitted = await scope.run(admit, { input: {
274
+ req,
275
+ limit,
276
+ origin,
277
+ busy
278
+ } });
279
+ if (admitted instanceof Response) return admitted;
280
+ const { text, meta, type } = admitted;
281
+ const stop = AbortSignal.any([req.signal, AbortSignal.timeout(config.uploadDeadline)]);
282
+ const trace = traceparentOf(meta.traceparent);
283
+ const tags = [request(req), requestStop(stop)];
284
+ const session = await Promise.resolve().then(() => scope.createSession({
285
+ trace,
286
+ tags
287
+ })).catch(() => null);
288
+ if (!session) return new Response(null, { status: 503 });
289
+ uploading += 1;
290
+ const body = session.run(bodyOf, { input: {
291
+ req,
292
+ max: limit.max,
293
+ type,
294
+ stop
295
+ } });
296
+ const reply = await session.run(serve, { input: {
297
+ address,
298
+ text,
299
+ meta,
300
+ body
301
+ } }).finally(() => {
302
+ uploading -= 1;
303
+ req.body?.cancel().catch(() => void 0);
304
+ return session.close();
305
+ });
306
+ if (body.over) return new Response(null, { status: 413 });
307
+ if (reply === null) return new Response(null, { status: 404 });
308
+ return new Response(reply, { headers: {
309
+ "content-type": "application/json",
310
+ "cache-control": "no-store"
311
+ } });
312
+ };
313
+ const websocket = {
314
+ maxPayloadLength: config.maxPayload,
315
+ backpressureLimit: config.maxPayload,
316
+ closeOnBackpressureLimit: true,
317
+ idleTimeout: 60,
318
+ sendPings: true,
319
+ message(ws, frame) {
320
+ Promise.resolve(typeof frame === "string" ? frame : "").then((text) => JSON.parse(text)).catch(() => null).then((msgs) => {
321
+ if (!(Array.isArray(msgs) && msgs.length <= 32 && msgs.every((m) => Number.isSafeInteger(Object(m).i)))) return ws.close(1008, "bad frame");
322
+ for (const m of msgs) ws.data.one(ws, m).catch((error) => log.error("ws message failed", { error: String(error) }));
323
+ });
324
+ },
325
+ close(ws) {
326
+ ws.data.gone.abort(/* @__PURE__ */ new Error("socket closed"));
327
+ }
328
+ };
329
+ /** The largest body any key takes: the host sets Bun's `maxRequestBodySize` from it. */
330
+ const maxBody = Math.max(0, ...[...routesOf.values()].flatMap((one) => Object.values(one.uploads ?? {})).map((l) => l.max));
331
+ /** The handler `serve` asks: the socket's path, then a bytes POST; else not ours. */
332
+ const fetch = async (req, scope, bun) => {
333
+ const upgraded = upgrade(req, scope, bun);
334
+ return upgraded === void 0 ? post(req, scope) : upgraded;
335
+ };
336
+ return {
337
+ upgrade,
338
+ post,
339
+ fetch,
340
+ websocket,
341
+ maxBody
342
+ };
343
+ },
344
+ /** Every run of the scope passes here: one that is not this transport's reads `op` only. */
345
+ run(event) {
346
+ const { op, call: invocation } = event;
347
+ if (op !== serve && op !== serveStream) return event.next();
348
+ const { side, protocol: p } = event.load(held, kept).get();
349
+ const hook = new Tools(event);
350
+ const input = invocation?.input ?? invocation?.rawInput;
351
+ return op === serve ? p.serveText(side, hook, input) : p.streamText(side, hook, input);
352
+ }
353
+ }
354
+ }) };
355
+ }
356
+ /** The default WebSocket server. */
357
+ const ws = createWs();
358
+ //#endregion
359
+ //#region src/serve.ts
360
+ const port = tag({ label: "serve.port" });
361
+ const pages = tag({
362
+ label: "serve.pages",
363
+ default: {}
364
+ });
365
+ const handlers = tag({
366
+ label: "serve.handlers",
367
+ default: []
368
+ });
369
+ /** The one handler that owns Bun's `websocket`: Bun takes one per server. */
370
+ const websocket = tag({
371
+ label: "serve.websocket",
372
+ default: null
373
+ });
374
+ const paths = tag({
375
+ label: "serve.paths",
376
+ default: []
377
+ });
378
+ const development = tag({
379
+ label: "serve.development",
380
+ default: false
381
+ });
382
+ const stdout = tag({
383
+ label: "serve.stdout",
384
+ default: null
385
+ });
386
+ /** Where the server listens, once it does; null before. */
387
+ const url = data({
388
+ label: "serve.url",
389
+ initial: null
390
+ });
391
+ /** The server and the session its handlers answer in. */
392
+ const live = data({
393
+ label: "serve.live",
394
+ initial: null
395
+ });
396
+ const held = {
397
+ role: "state",
398
+ explain: "The listening server"
399
+ };
400
+ const opened = {
401
+ role: "handler",
402
+ explain: "The handlers answer in this session"
403
+ };
404
+ /** Every path a handler gets, beside the page: `/api/*`, `/rpc`, `/rpc/*`, then the app's own. */
405
+ const handlerPaths = [
406
+ "/api/*",
407
+ "/rpc",
408
+ "/rpc/*"
409
+ ];
410
+ /**
411
+ * `Bun.serve` for the life of the scope (Effect's `BunHttpServer.layer`, Go's `http.Server`).
412
+ * It goes first in `capsules`, so its start wraps the others: it listens once every handler has
413
+ * started, and its close stops the port before the handlers close. Its config comes from the cmd
414
+ * (the seam): it reads no `process.env`. Signals and exit codes stay with the host, `run`.
415
+ * - `websocket`: the one handler that brings Bun's `websocket` (ws.server); asked first;
416
+ * - `handlers`: capsules whose start returns a {@link Handler}, asked in order;
417
+ * - `pages`: the client's routes, for every path no handler takes;
418
+ * - `paths`: more Bun route patterns for the handlers;
419
+ * - `stdout`: where it prints `tinker: listening on <url>`.
420
+ */
421
+ const serve = capsule({
422
+ label: "serve",
423
+ config: {
424
+ port: port.required,
425
+ pages,
426
+ websocket,
427
+ handlers,
428
+ paths,
429
+ development,
430
+ stdout
431
+ },
432
+ exports: { url },
433
+ hooks: {
434
+ async start({ config, next, session, load, raise }) {
435
+ await next();
436
+ const scope = session({}, opened);
437
+ const socket = config.websocket && scope.resolve(config.websocket);
438
+ const rest = config.handlers.map((handler) => scope.resolve(handler));
439
+ if (rest.some((handler) => handler.websocket !== void 0)) raise("MissingConfig", {
440
+ label: "serve",
441
+ key: "websocket"
442
+ });
443
+ const found = socket ? [socket, ...rest] : rest;
444
+ const answer = async (request, bun) => {
445
+ for (const handler of found) {
446
+ const reply = await handler.fetch(request, scope, bun);
447
+ if (reply !== void 0) return reply ?? void 0;
448
+ }
449
+ return new Response(null, { status: 404 });
450
+ };
451
+ const server = Bun.serve({
452
+ port: config.port,
453
+ idleTimeout: 60,
454
+ maxRequestBodySize: Math.max(1048576, ...found.map((handler) => handler.maxBody ?? 0)),
455
+ websocket: socket?.websocket,
456
+ fetch: () => new Response(null, { status: 404 }),
457
+ development: config.development && {
458
+ hmr: false,
459
+ console: true
460
+ },
461
+ routes: {
462
+ ...Object.fromEntries([...handlerPaths, ...config.paths].map((path) => [path, answer])),
463
+ ...config.pages
464
+ }
465
+ });
466
+ load(live, held).set({
467
+ server,
468
+ handlers: scope
469
+ });
470
+ load(url, held).set(server.url);
471
+ config.stdout?.write(`tinker: listening on ${server.url}\n`);
472
+ },
473
+ async close({ load, next }) {
474
+ const own = load(live, held).get();
475
+ await own?.server.stop();
476
+ await own?.handlers.close();
477
+ return next();
478
+ }
479
+ }
480
+ });
481
+ //#endregion
482
+ //#region src/run.ts
483
+ /** POSIX exit codes for a stop by signal: 128 plus the signal's number. */
484
+ const signalCodes = {
485
+ SIGHUP: 129,
486
+ SIGINT: 130,
487
+ SIGTERM: 143
488
+ };
489
+ /** A startup throw of these kinds is a config error: exit 78 (EX_CONFIG). */
490
+ const configKinds = [
491
+ "MissingTag",
492
+ "MissingConfig",
493
+ "DataValidationFailed"
494
+ ];
495
+ /** The exit code for a startup throw: 78 for a config error or a bad URL, else 1. */
496
+ const startCode = (error) => configKinds.includes(Object(error).kind) || Object(error).code === "ERR_INVALID_URL" ? 78 : 1;
497
+ /** The first failure in the root close results, app first: a failed root's error, else its first teardown error. */
498
+ const failureOf = (closed) => [closed ?? []].flat().flatMap((end) => end.status === "failed" ? [end.error] : end.teardownErrors ?? []).at(0);
499
+ /**
500
+ * Runs one command, and owns OS signals and the exit code (Effect's `runMain`, Go's `main`):
501
+ * - a startup throw exits 78 for a config error (a missing tag or config key, a value that
502
+ * failed its schema, a bad URL), else 1;
503
+ * - a failed root exits 1; a signal exits 128 + its number;
504
+ * - SIGHUP (a closed terminal) stops it like SIGTERM, so `nohup` does not keep it alive;
505
+ * - a stop during start ends with the stop's own code, and no second line.
506
+ * A command that calls `exit` during start gets that code. The host waits for its root to close.
507
+ */
508
+ async function run(main) {
509
+ const stop = new AbortController();
510
+ let code = 0;
511
+ const exit = (next, reason) => {
512
+ const { kind, payload } = Object(reason);
513
+ if (kind !== void 0) console.error(`tinker: ${kind} ${JSON.stringify(payload)}`);
514
+ else if (reason !== void 0) console.error(reason);
515
+ code ||= next;
516
+ stop.abort(reason);
517
+ };
518
+ for (const [name, signalCode] of Object.entries(signalCodes)) process.once(name, () => exit(signalCode));
519
+ const failed = (error) => {
520
+ if (stop.signal.aborted && error === stop.signal.reason) return;
521
+ exit(startCode(error), error);
522
+ };
523
+ const started = await Promise.resolve().then(() => main({
524
+ env: process.env,
525
+ args: process.argv.slice(2),
526
+ cwd: process.cwd(),
527
+ signal: stop.signal,
528
+ stdout: process.stdout,
529
+ stderr: process.stderr,
530
+ exit
531
+ })).catch(failed);
532
+ if (!started) return process.exit(code);
533
+ const ready = await Promise.resolve(started.ready).then(() => true, (error) => (failed(error), false));
534
+ const closed = await started.closed;
535
+ const failure = ready ? failureOf(closed) : void 0;
536
+ if (failure !== void 0) exit(1, failure);
537
+ process.exit(code);
538
+ }
539
+ //#endregion
540
+ export { createWs, run, serve, ws };
package/dist/sql.d.mts ADDED
@@ -0,0 +1,15 @@
1
+ import { SQL } from "bun";
2
+ //#region src/sql.d.ts
3
+ /** Postgres on `Bun.SQL`. */
4
+ export declare const bunSql: import("@tinkered/core").Capsule.Handle<{
5
+ readonly url: import("@tinkered/core").Edge<"required", import("@tinkered/core").Tag.Handle<URL>>;
6
+ readonly max: import("@tinkered/core").Tag.Defaulted<number>;
7
+ }, {
8
+ readonly connection: import("@tinkered/core").Resource.Handle<Promise<{
9
+ db: import("drizzle-orm/bun-sql/postgres").BunSQLDatabase<import("drizzle-orm").EmptyRelations> & {
10
+ $client: SQL;
11
+ };
12
+ migrate: (folder: string) => Promise<undefined>;
13
+ }>>;
14
+ }, void>;
15
+ //#endregion
package/dist/sql.mjs ADDED
@@ -0,0 +1,54 @@
1
+ import { capsule, resource, tag } from "@tinkered/core";
2
+ import { SQL } from "bun";
3
+ import { migrate } from "drizzle-orm/bun-sql/migrator";
4
+ import { drizzle } from "drizzle-orm/bun-sql/postgres";
5
+ //#region src/sql.ts
6
+ /** A whole number above 0. */
7
+ const positive = (raw) => {
8
+ if (!Number.isSafeInteger(raw) || Number(raw) <= 0) throw new TypeError("not a whole number above 0");
9
+ return Number(raw);
10
+ };
11
+ const url = tag({
12
+ label: "bunSql.url",
13
+ secret: true,
14
+ parse: (raw) => {
15
+ if (!(raw instanceof URL)) throw new TypeError("not a URL");
16
+ return raw;
17
+ }
18
+ });
19
+ const max = tag({
20
+ label: "bunSql.max",
21
+ default: 10,
22
+ parse: positive
23
+ });
24
+ /** The pool, its Drizzle db and its migrator; the pool closes with the scope. */
25
+ const connection = resource({
26
+ label: "bunSql.connection",
27
+ depends: {
28
+ url,
29
+ max
30
+ },
31
+ factory: async ({ url, max }, { defer }) => {
32
+ const client = new SQL({
33
+ url: url.href,
34
+ max
35
+ });
36
+ defer(() => client.close());
37
+ const db = drizzle({ client });
38
+ return {
39
+ db,
40
+ migrate: async (folder) => void await migrate(db, { migrationsFolder: folder })
41
+ };
42
+ }
43
+ });
44
+ /** Postgres on `Bun.SQL`. */
45
+ const bunSql = capsule({
46
+ label: "bunSql",
47
+ config: {
48
+ url: url.required,
49
+ max
50
+ },
51
+ exports: { connection }
52
+ });
53
+ //#endregion
54
+ export { bunSql };
@@ -0,0 +1,20 @@
1
+ import { Database } from "bun:sqlite";
2
+ //#region src/sqlite.d.ts
3
+ /** SQLite on `bun:sqlite`. */
4
+ export declare const bunSqlite: import("@tinkered/core").Capsule.Handle<{
5
+ readonly file: import("@tinkered/core").Tag.Defaulted<string>;
6
+ }, {
7
+ readonly connection: import("@tinkered/core").Resource.Handle<Promise<{
8
+ db: import("drizzle-orm/bun-sqlite").SQLiteBunDatabase<import("drizzle-orm").EmptyRelations> & {
9
+ $client: Database;
10
+ };
11
+ migrate: (folder: string) => Promise<undefined>;
12
+ begin: () => Promise<{
13
+ tx: import("drizzle-orm/bun-sqlite").SQLiteBunDatabase<import("drizzle-orm").EmptyRelations> & {
14
+ $client: Database;
15
+ };
16
+ end: (commit: boolean) => Promise<undefined>;
17
+ }>;
18
+ }>>;
19
+ }, void>;
20
+ //#endregion
@@ -0,0 +1,45 @@
1
+ import { capsule, resource, tag } from "@tinkered/core";
2
+ import { Database } from "bun:sqlite";
3
+ import { drizzle } from "drizzle-orm/bun-sqlite";
4
+ import { migrate } from "drizzle-orm/bun-sqlite/migrator";
5
+ //#region src/sqlite.ts
6
+ /** The database file; `:memory:` keeps it in memory. */
7
+ const file = tag({
8
+ label: "bunSqlite.file",
9
+ default: ":memory:",
10
+ parse: (raw) => {
11
+ if (typeof raw !== "string" || raw === "") throw new TypeError("not a file name");
12
+ return raw;
13
+ }
14
+ });
15
+ /** The database, in WAL mode with foreign keys on; it closes with the scope. */
16
+ const connection = resource({
17
+ label: "bunSqlite.connection",
18
+ depends: { file },
19
+ factory: async ({ file }, { defer }) => {
20
+ const client = new Database(file);
21
+ client.exec("PRAGMA journal_mode = WAL");
22
+ client.exec("PRAGMA foreign_keys = ON");
23
+ defer(() => client.close());
24
+ const db = drizzle({ client });
25
+ return {
26
+ db,
27
+ migrate: async (folder) => void migrate(db, { migrationsFolder: folder }),
28
+ begin: async () => {
29
+ client.exec("BEGIN IMMEDIATE");
30
+ return {
31
+ tx: db,
32
+ end: async (commit) => void client.exec(commit ? "COMMIT" : "ROLLBACK")
33
+ };
34
+ }
35
+ };
36
+ }
37
+ });
38
+ /** SQLite on `bun:sqlite`. */
39
+ const bunSqlite = capsule({
40
+ label: "bunSqlite",
41
+ config: { file },
42
+ exports: { connection }
43
+ });
44
+ //#endregion
45
+ export { bunSqlite };