@lines-db/studio 0.16.7 → 0.16.9

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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # @lines-db/studio
2
2
 
3
+ ## 0.16.9
4
+
5
+ ### Patch Changes
6
+
7
+ - c9f3c43: fix(studio): update Zygiella to v0.1.5 to preserve Node.js 22.18.0 support
8
+ - Updated dependencies [feb9ed0]
9
+ - Updated dependencies [d69d352]
10
+ - Updated dependencies [7c9767d]
11
+ - Updated dependencies [1e6bca5]
12
+ - lines-db@0.19.4
13
+
14
+ ## 0.16.8
15
+
16
+ ### Patch Changes
17
+
18
+ - 2e3c0ef: Add `createStudioHandler`, which resolves to `{ token, fetch(request), close() }`. Its `fetch` is a Web-standard `(request: Request) => Promise<Response>` handler, so the studio can be served from a server of your own and framed by a page of the same origin. `startStudioServer` is now a thin `node:http` wrapper around it and behaves as before.
19
+
20
+ The page asks for the API with addresses relative to its own, so it works below any path, as long as it is opened with a trailing slash. `frameAncestors: 'self'` lets a page of the same origin frame the studio (`'none'` by default), and `requestHeaders` has the page send the given headers with every API request except the event stream, which an `EventSource` cannot give headers, for a host that checks them before passing a request on. The values are written into the page, so they are not secrets from whoever can load it. A write is rejected when its `Origin` is present and not the origin of the request URL.
21
+
3
22
  ## 0.16.7
4
23
 
5
24
  ### Patch Changes
package/README.ja.md CHANGED
@@ -91,4 +91,28 @@ console.log(studio.url);
91
91
  await studio.close();
92
92
  ```
93
93
 
94
+ ## 別のサーバーから配信する
95
+
96
+ `createStudioHandler`は`{ token, fetch(request), close() }`を返します。`fetch`はWeb標準のハンドラー`(request: Request) => Promise<Response>`で、サーバーを起動する代わりに、自前のサーバーへ組み込めます。ハンドラーはHostも、組み込むパスも検査しません。好きなパスに組み込み、受け取るURLからそのパスを取り除き、Hostは呼び出し側で検査してください。
97
+
98
+ ```js
99
+ import { createStudioHandler } from '@lines-db/studio';
100
+
101
+ const studio = await createStudioHandler({
102
+ dataDir: './data',
103
+ frameAncestors: 'self',
104
+ requestHeaders: { 'x-studio-host': 'embedded' },
105
+ });
106
+
107
+ // ハンドラーは起動時に1回だけ作り、リクエストごとに`studio.fetch`へ渡します。
108
+ // `close()`はファイル監視とイベントストリームを終了させ、再開できません。終了時にだけ呼びます。
109
+ const response = await studio.fetch(request);
110
+ await studio.close();
111
+ ```
112
+
113
+ - ページはAPIを自身からの相対アドレスで呼ぶため、末尾のスラッシュ付きで開けばどのパスでも動きます。
114
+ - `frameAncestors`の既定は`'none'`で、どのページもStudioをフレームに入れられません。`'self'`にすると同じオリジンのページがフレームに入れられます。
115
+ - `requestHeaders`は、リアルタイム更新のストリームを除くすべてのAPIリクエストに、ページが付けて送ります。リクエストを転送する前にヘッダーを検査する組み込み先のためのものです。ストリームはEventSourceが要求するためヘッダーを付けられず、組み込み先は`GET /api/events`をヘッダーなしで通す必要があります。値はページに書き込まれるため、ページを読み込める人には秘密になりません。
116
+ - 書き込みは、`Origin`ヘッダーがあり、リクエストURLのオリジンと一致しない場合に拒否します。`Origin`がないリクエストはこのチェックを通り、書き込みには引き続きトークンと`application/json`が必要です。
117
+
94
118
  TypeScriptのスキーマファイルには`amaro/transform`などのローダーが必要です。CLIは自動で登録します。コードから起動する場合は、スキーマを読み込む前にローダーを登録してください。
package/README.md CHANGED
@@ -91,4 +91,28 @@ console.log(studio.url);
91
91
  await studio.close();
92
92
  ```
93
93
 
94
+ ## Serve from another server
95
+
96
+ `createStudioHandler` resolves to `{ token, fetch(request), close() }`. Its `fetch` is a Web-standard handler, `(request: Request) => Promise<Response>`, to mount in a server of your own instead of starting one. It checks neither the Host nor which path it is mounted under, so mount it at a path of your choice, strip that path from the URL it receives, and check the Host yourself.
97
+
98
+ ```js
99
+ import { createStudioHandler } from '@lines-db/studio';
100
+
101
+ const studio = await createStudioHandler({
102
+ dataDir: './data',
103
+ frameAncestors: 'self',
104
+ requestHeaders: { 'x-studio-host': 'embedded' },
105
+ });
106
+
107
+ // Create the handler once at startup and pass every request to `studio.fetch`.
108
+ // `close()` stops the file watchers and ends the event streams for good, so call it only at shutdown.
109
+ const response = await studio.fetch(request);
110
+ await studio.close();
111
+ ```
112
+
113
+ - The page requests the API with addresses relative to its own, so it works at any path, as long as the page is opened with a trailing slash.
114
+ - `frameAncestors` is `'none'` by default, which keeps every page from framing the studio. `'self'` lets a page of the same origin frame it.
115
+ - `requestHeaders` are sent by the page with every API request except the live-reload stream, for a host that checks them before passing a request on. The stream is requested by an event source, which cannot send headers, so the host has to let `GET /api/events` through without them. The values are written into the page, so they are not secrets from anyone who can load it.
116
+ - A write is rejected when its `Origin` header is present and is not the origin of the request URL. A request without `Origin` passes this check, and a write still needs the token and `application/json`.
117
+
94
118
  TypeScript schema files require a loader such as `amaro/transform`. The lines-db CLI registers it automatically. When starting from code, register a loader before loading the schemas.
package/dist/index.d.mts CHANGED
@@ -1,20 +1,34 @@
1
1
  import { WriteFilledValues } from "lines-db";
2
- interface StudioServerOptions {
2
+ interface StudioHandlerOptions {
3
3
  dataDir: string | string[];
4
4
  schemaDir?: string;
5
5
  /** Directory holding the built page. Defaults to the one shipped with the package */
6
6
  uiDir?: string;
7
7
  /** Which values the schema fills in a save writes into the file. Defaults to 'primaryKey' */
8
8
  writeFilledValues?: WriteFilledValues;
9
+ /** Which pages may frame the studio: none, or those of its own origin. Defaults to 'none' */
10
+ frameAncestors?: 'none' | 'self';
11
+ /** Headers the page sends with every API request, for a host that checks them before passing the request on */
12
+ requestHeaders?: Record<string, string>;
13
+ }
14
+ interface StudioServerOptions extends StudioHandlerOptions {
9
15
  host?: string;
10
16
  port?: number;
11
17
  }
18
+ interface StudioHandler {
19
+ /** The token every API request presents, generated at start-up and handed to the page */
20
+ token: string;
21
+ /** Answers a request whose path is relative to the studio's root; checking the Host is left to the caller */
22
+ fetch(request: Request): Promise<Response>;
23
+ close(): Promise<void>;
24
+ }
12
25
  interface StudioServer {
13
26
  url: string;
14
27
  /** The token every API request presents, generated at start-up and handed to the page */
15
28
  token: string;
16
29
  close(): Promise<void>;
17
30
  }
31
+ export declare function createStudioHandler(options: StudioHandlerOptions): Promise<StudioHandler>;
18
32
  export declare function startStudioServer(options: StudioServerOptions): Promise<StudioServer>;
19
- export type { StudioServer, StudioServerOptions };
33
+ export type { StudioHandler, StudioHandlerOptions, StudioServer, StudioServerOptions };
20
34
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA+BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UAiCiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;;EAEpB;;EAEA,iBAAiB;;UAGF,4BAA4B;EAC3C;EACA;;UAGe;;EAEf;;EAEA,MAAM,SAAS,UAAU,QAAQ;EACjC,SAAS;;UAGM;EACf;;EAEA;EACA,SAAS;;wBAwBW,oBAAoB,SAAS,uBAAuB,QAAQ;wBA4mB5D,kBAAkB,SAAS,sBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -4,6 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { readFile, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { createServer } from "node:http";
6
6
  import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
7
+ import { Readable, pipeline } from "node:stream";
7
8
  import { fileURLToPath, pathToFileURL } from "node:url";
8
9
  import { watch } from "zygiella";
9
10
  import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
@@ -261,7 +262,7 @@ function replaceRows(content, replaced) {
261
262
  }).join("\n");
262
263
  }
263
264
  // src/server.ts
264
- async function startStudioServer(options) {
265
+ async function createStudioHandler(options) {
265
266
  const dataDirs = [];
266
267
  const seen = /* @__PURE__ */ new Set();
267
268
  for (const dir of [options.dataDir].flat()) {
@@ -274,7 +275,6 @@ async function startStudioServer(options) {
274
275
  if (dataDirs.length === 0) throw new Error("Studio requires at least one data directory");
275
276
  const dataDir = dataDirs[0];
276
277
  const schemaDir = options.schemaDir ?? dataDir;
277
- const host = options.host ?? "127.0.0.1";
278
278
  const uiDir = options.uiDir ?? shippedUiDir();
279
279
  const token = randomBytes(24).toString("base64url");
280
280
  const writeFilledValues = options.writeFilledValues ?? "primaryKey";
@@ -355,9 +355,10 @@ async function startStudioServer(options) {
355
355
  }
356
356
  return byTable.get(name);
357
357
  };
358
+ const encoder = new TextEncoder();
358
359
  const eventClients = /* @__PURE__ */ new Set();
359
360
  const notifyChanged = () => {
360
- for (const client of eventClients) client.write("event: changed\ndata: {}\n\n");
361
+ for (const client of eventClients) client.enqueue(encoder.encode("event: changed\ndata: {}\n\n"));
361
362
  };
362
363
  const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
363
364
  let watchTimer;
@@ -424,102 +425,103 @@ async function startStudioServer(options) {
424
425
  watchedDependencies = wanted;
425
426
  };
426
427
  watchDependencies();
427
- const server = createServer((req, res) => {
428
- handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
429
- });
430
- async function handle(req, res) {
431
- const { port } = server.address();
432
- const allowedHosts = /* @__PURE__ */ new Set([
433
- `${host}:${port}`,
434
- `127.0.0.1:${port}`,
435
- `localhost:${port}`,
436
- `[::1]:${port}`
437
- ]);
438
- if (!allowedHosts.has(req.headers.host ?? "")) {
439
- sendJson(res, 403, { message: "Requests must be addressed to the local studio server" });
440
- return;
441
- }
442
- const url = new URL(req.url ?? "/", "http://localhost");
443
- if (req.method === "GET" && !url.pathname.startsWith("/api/")) {
444
- await servePage(res, uiDir, url.pathname, token);
445
- return;
446
- }
447
- if (!sameToken(bearerToken(req) ?? (url.pathname === "/api/events" ? url.searchParams.get("token") : null) ?? "", token)) {
448
- sendJson(res, 401, { message: "This page holds no token of this run of lines-db studio. Reload it to get one." });
449
- return;
428
+ let closing = false;
429
+ const fetch = async (request) => {
430
+ if (closing) return jsonResponse(503, { message: "The studio is shutting down" });
431
+ try {
432
+ return await handle(request);
433
+ } catch (error) {
434
+ return jsonResponse(error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) });
450
435
  }
436
+ };
437
+ async function handle(request) {
438
+ const url = new URL(request.url);
439
+ if (request.method === "GET" && !url.pathname.startsWith("/api/")) return servePage(uiDir, url.pathname, {
440
+ token,
441
+ frameAncestors: options.frameAncestors ?? "none",
442
+ requestHeaders: options.requestHeaders
443
+ });
444
+ if (!sameToken(bearerToken(request) ?? (url.pathname === "/api/events" ? url.searchParams.get("token") : null) ?? "", token)) return jsonResponse(401, { message: "This page holds no token of this run of lines-db studio. Reload it to get one." });
451
445
  const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
452
- if (req.method === "GET" && url.pathname === "/api/events") {
453
- res.writeHead(200, {
446
+ if (request.method === "GET" && url.pathname === "/api/events") {
447
+ let client;
448
+ const end = () => {
449
+ request.signal.removeEventListener("abort", end);
450
+ if (!eventClients.delete(client)) return;
451
+ try {
452
+ client.close();
453
+ } catch {}
454
+ };
455
+ const stream = new ReadableStream({
456
+ start(controller) {
457
+ client = controller;
458
+ if (request.signal.aborted) {
459
+ controller.close();
460
+ return;
461
+ }
462
+ eventClients.add(controller);
463
+ request.signal.addEventListener("abort", end, { once: true });
464
+ controller.enqueue(encoder.encode(": connected\n\n"));
465
+ },
466
+ cancel: end
467
+ });
468
+ return new Response(stream, { headers: {
454
469
  "Content-Type": "text/event-stream",
455
470
  "Cache-Control": "no-store"
456
- });
457
- res.write(": connected\n\n");
458
- eventClients.add(res);
459
- req.on("close", () => eventClients.delete(res));
460
- return;
461
- }
462
- if (req.method === "GET" && url.pathname === "/api/tables") {
463
- sendJson(res, 200, await serialize(async () => {
464
- await reloadIfChangedUnlocked();
465
- const current = snapshot;
466
- const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));
467
- const tables = [];
468
- for (const name of loadedTables) {
469
- const columns = await loadedColumnsOf(current, name);
470
- const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;
471
- const rowCount = unwrap(current.db.queryOne(`SELECT COUNT(*) AS n FROM "${name.replaceAll("\"", "\"\"")}"`))?.n ?? 0;
472
- tables.push({
473
- name,
474
- columns,
475
- primaryKey,
476
- rowCount,
477
- invalidRows: 0,
478
- readOnlyReason: whyReadOnly(current.db, name),
479
- schemaFile: null,
480
- references: await referencesFor(current, name)
481
- });
482
- }
483
- for (const [name, { issues }] of current.invalid) {
484
- const { columns, rowCount } = await invalidColumnsOf(current, name);
485
- tables.push({
486
- name,
487
- columns,
488
- primaryKey: null,
489
- rowCount,
490
- invalidRows: issues.size,
491
- readOnlyReason: null,
492
- schemaFile: null,
493
- references: await referencesFor(current, name)
494
- });
495
- }
496
- for (const table of tables) {
497
- const schemaPath = await findSchemaFile(schemaDir, table.name);
498
- table.schemaFile = schemaPath ? basename(schemaPath) : null;
499
- }
500
- tables.sort((a, b) => a.name.localeCompare(b.name));
501
- return {
502
- dataDir,
503
- dataDirs,
504
- schemaDir: resolve(schemaDir),
505
- tables,
506
- problems: current.problems
507
- };
508
- }));
509
- return;
471
+ } });
510
472
  }
473
+ if (request.method === "GET" && url.pathname === "/api/tables") return jsonResponse(200, await serialize(async () => {
474
+ await reloadIfChangedUnlocked();
475
+ const current = snapshot;
476
+ const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));
477
+ const tables = [];
478
+ for (const name of loadedTables) {
479
+ const columns = await loadedColumnsOf(current, name);
480
+ const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;
481
+ const rowCount = unwrap(current.db.queryOne(`SELECT COUNT(*) AS n FROM "${name.replaceAll("\"", "\"\"")}"`))?.n ?? 0;
482
+ tables.push({
483
+ name,
484
+ columns,
485
+ primaryKey,
486
+ rowCount,
487
+ invalidRows: 0,
488
+ readOnlyReason: whyReadOnly(current.db, name),
489
+ schemaFile: null,
490
+ references: await referencesFor(current, name)
491
+ });
492
+ }
493
+ for (const [name, { issues }] of current.invalid) {
494
+ const { columns, rowCount } = await invalidColumnsOf(current, name);
495
+ tables.push({
496
+ name,
497
+ columns,
498
+ primaryKey: null,
499
+ rowCount,
500
+ invalidRows: issues.size,
501
+ readOnlyReason: null,
502
+ schemaFile: null,
503
+ references: await referencesFor(current, name)
504
+ });
505
+ }
506
+ for (const table of tables) {
507
+ const schemaPath = await findSchemaFile(schemaDir, table.name);
508
+ table.schemaFile = schemaPath ? basename(schemaPath) : null;
509
+ }
510
+ tables.sort((a, b) => a.name.localeCompare(b.name));
511
+ return {
512
+ dataDir,
513
+ dataDirs,
514
+ schemaDir: resolve(schemaDir),
515
+ tables,
516
+ problems: current.problems
517
+ };
518
+ }));
511
519
  const [, , tableName, resource, encodedKey] = segments;
512
520
  if (segments[0] === "api" && segments[1] === "tables" && resource === "schema" && segments.length === 4) {
513
- if (req.method !== "GET") {
514
- sendJson(res, 405, { message: "Method not allowed" });
515
- return;
516
- }
521
+ if (request.method !== "GET") return jsonResponse(405, { message: "Method not allowed" });
517
522
  await reloadIfChanged();
518
523
  const schemaPath = Boolean(snapshot.db.getSchema(tableName)) || snapshot.invalid.has(tableName) ? await findSchemaFile(schemaDir, tableName) : void 0;
519
- if (!schemaPath) {
520
- sendJson(res, 404, { message: `Table '${tableName}' has no schema file` });
521
- return;
522
- }
524
+ if (!schemaPath) return jsonResponse(404, { message: `Table '${tableName}' has no schema file` });
523
525
  const loaded = snapshot.invalid.has(tableName) ? void 0 : snapshot.db.getSchema(tableName);
524
526
  const declared = loaded && await readDeclaredColumns(schemaPath, schemaDir);
525
527
  const flagsOf = (name) => {
@@ -529,7 +531,7 @@ async function startStudioServer(options) {
529
531
  ...column?.unique ? { unique: true } : {}
530
532
  };
531
533
  };
532
- sendJson(res, 200, {
534
+ return jsonResponse(200, {
533
535
  file: basename(schemaPath),
534
536
  source: await readFile(schemaPath, "utf-8"),
535
537
  definition: loaded ? {
@@ -547,72 +549,51 @@ async function startStudioServer(options) {
547
549
  indexes: loaded.indexes ?? []
548
550
  } : null
549
551
  });
550
- return;
551
552
  }
552
553
  const isRows = segments[0] === "api" && segments[1] === "tables" && resource === "rows" && segments.length <= 5;
553
554
  const isChanges = segments[0] === "api" && segments[1] === "tables" && (resource === "changes" || resource === "check") && segments.length === 4;
554
- if (!isRows && !isChanges) {
555
- sendJson(res, 404, { message: "Not found" });
556
- return;
557
- }
558
- if (isRows && req.method === "GET" && encodedKey === void 0) {
555
+ if (!isRows && !isChanges) return jsonResponse(404, { message: "Not found" });
556
+ if (isRows && request.method === "GET" && encodedKey === void 0) {
559
557
  await reloadIfChanged();
560
558
  const invalid = snapshot.invalid.get(tableName);
561
559
  if (invalid) {
562
- if (invalid.rows) {
563
- sendJson(res, 200, {
564
- rows: invalid.rows,
565
- defaulted: invalid.rows.map(() => []),
566
- issues: Object.fromEntries(invalid.issues),
567
- revision: invalid.revision
568
- });
569
- return;
570
- }
560
+ if (invalid.rows) return jsonResponse(200, {
561
+ rows: invalid.rows,
562
+ defaulted: invalid.rows.map(() => []),
563
+ issues: Object.fromEntries(invalid.issues),
564
+ revision: invalid.revision
565
+ });
571
566
  const { rows, contentHash } = unwrap(await JsonlReader.readSnapshot(invalid.file));
572
567
  const read = unwrap(rows);
573
- sendJson(res, 200, {
568
+ return jsonResponse(200, {
574
569
  rows: read,
575
570
  defaulted: read.map(() => []),
576
571
  issues: Object.fromEntries(invalid.issues),
577
572
  revision: contentHash
578
573
  });
579
- return;
580
- }
581
- if (!snapshot.db.getSchema(tableName)) {
582
- sendJson(res, 404, { message: `Table '${tableName}' does not exist` });
583
- return;
584
574
  }
575
+ if (!snapshot.db.getSchema(tableName)) return jsonResponse(404, { message: `Table '${tableName}' does not exist` });
585
576
  const rows = unwrap(await snapshot.db.findWithDefaults(tableName));
586
- sendJson(res, 200, {
577
+ return jsonResponse(200, {
587
578
  rows: rows.map(({ row }) => row),
588
579
  defaulted: rows.map(({ defaulted }) => defaulted),
589
580
  inputs: rows.map(({ input }) => input)
590
581
  });
591
- return;
592
- }
593
- const write = isChanges ? req.method === "POST" ? resource === "check" ? { kind: "check" } : { kind: "batch" } : void 0 : writeOperation(req.method, encodedKey);
594
- if (!write) {
595
- sendJson(res, 405, { message: "Method not allowed" });
596
- return;
597
- }
598
- const origin = req.headers.origin;
599
- if (origin !== void 0 && !allowedHosts.has(origin.replace(/^http:\/\//, ""))) {
600
- sendJson(res, 403, { message: "Writes are accepted from the studio page only" });
601
- return;
602
- }
603
- if (write.kind !== "delete" && !isJsonMediaType(req.headers["content-type"])) {
604
- sendJson(res, 415, { message: "Writes must be sent as application/json" });
605
- return;
606
582
  }
583
+ const write = isChanges ? request.method === "POST" ? resource === "check" ? { kind: "check" } : { kind: "batch" } : void 0 : writeOperation(request.method, encodedKey);
584
+ if (!write) return jsonResponse(405, { message: "Method not allowed" });
585
+ const origin = request.headers.get("origin");
586
+ if (origin !== null && origin !== url.origin) return jsonResponse(403, { message: "Writes are accepted from the studio page only" });
587
+ if (write.kind !== "delete" && !isJsonMediaType(request.headers.get("content-type") ?? void 0)) return jsonResponse(415, { message: "Writes must be sent as application/json" });
607
588
  let batch;
608
- if (write.kind === "batch" || write.kind === "check") batch = changeBatch(await readJson(req));
589
+ if (write.kind === "batch" || write.kind === "check") batch = changeBatch(await readJson(request));
609
590
  else if (write.kind === "delete") batch = {
610
591
  inserts: [],
611
592
  updates: [],
612
593
  deletes: [write.key]
613
594
  };
614
595
  else {
615
- const body = writeBody(await readJson(req));
596
+ const body = writeBody(await readJson(request));
616
597
  batch = write.kind === "insert" ? {
617
598
  inserts: [body.row ?? {}],
618
599
  insertDataDirs: body.dataDir ? [body.dataDir] : void 0,
@@ -833,9 +814,42 @@ async function startStudioServer(options) {
833
814
  changed: true
834
815
  };
835
816
  });
836
- sendJson(res, outcome.status, outcome.body);
837
- if (outcome.changed || reloaded) notifyChanged();
817
+ if (outcome.changed || reloaded) setImmediate(notifyChanged);
818
+ return jsonResponse(outcome.status, outcome.body);
838
819
  }
820
+ return {
821
+ token,
822
+ fetch,
823
+ close: async () => {
824
+ closing = true;
825
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
826
+ clearTimeout(watchTimer);
827
+ for (const client of eventClients) client.close();
828
+ eventClients.clear();
829
+ await serialize(() => snapshot.db.close());
830
+ }
831
+ };
832
+ }
833
+ async function startStudioServer(options) {
834
+ const host = options.host ?? "127.0.0.1";
835
+ const studio = await createStudioHandler(options);
836
+ const server = createServer((req, res) => {
837
+ const { port } = server.address();
838
+ const allowedHosts = /* @__PURE__ */ new Set([
839
+ `${host}:${port}`,
840
+ `127.0.0.1:${port}`,
841
+ `localhost:${port}`,
842
+ `[::1]:${port}`
843
+ ]);
844
+ let respond;
845
+ if (!allowedHosts.has(req.headers.host ?? "")) respond = Promise.resolve(jsonResponse(403, { message: "Requests must be addressed to the local studio server" }));
846
+ else try {
847
+ respond = studio.fetch(toRequest(req, res));
848
+ } catch {
849
+ respond = Promise.resolve(jsonResponse(400, { message: "The request cannot be served" }));
850
+ }
851
+ respond.then((response) => sendResponse(res, response)).catch(() => res.destroy());
852
+ });
839
853
  try {
840
854
  await new Promise((resolve, reject) => {
841
855
  server.once("error", reject);
@@ -845,23 +859,46 @@ async function startStudioServer(options) {
845
859
  });
846
860
  });
847
861
  } catch (error) {
848
- await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
849
- await snapshot.db.close();
862
+ await studio.close();
850
863
  throw error;
851
864
  }
852
865
  const { port } = server.address();
853
866
  return {
854
867
  url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
855
- token,
868
+ token: studio.token,
856
869
  close: async () => {
857
- await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
858
- clearTimeout(watchTimer);
859
870
  server.closeAllConnections();
860
871
  await new Promise((resolve) => server.close(() => resolve()));
861
- await serialize(() => snapshot.db.close());
872
+ await studio.close();
862
873
  }
863
874
  };
864
875
  }
876
+ function toRequest(req, res) {
877
+ const aborted = new AbortController();
878
+ res.on("close", () => aborted.abort());
879
+ const headers = new Headers();
880
+ for (const [name, value] of Object.entries(req.headers)) for (const each of [value ?? []].flat()) headers.append(name, each);
881
+ const method = req.method ?? "GET";
882
+ const hasBody = method !== "GET" && method !== "HEAD";
883
+ return new Request(new URL(req.url ?? "/", `http://${req.headers.host}`), {
884
+ method,
885
+ headers,
886
+ signal: aborted.signal,
887
+ ...hasBody ? {
888
+ body: Readable.toWeb(req),
889
+ duplex: "half"
890
+ } : {}
891
+ });
892
+ }
893
+ function sendResponse(res, response) {
894
+ res.writeHead(response.status, Object.fromEntries(response.headers));
895
+ if (!response.body) {
896
+ res.end();
897
+ return;
898
+ }
899
+ res.flushHeaders();
900
+ pipeline(Readable.fromWeb(response.body), res, () => {});
901
+ }
865
902
  async function replaceUnchangedFile(file, next, expected) {
866
903
  await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
867
904
  }
@@ -1195,39 +1232,36 @@ const CONTENT_TYPES = {
1195
1232
  function shippedUiDir() {
1196
1233
  return fileURLToPath(new URL("../ui", import.meta.url));
1197
1234
  }
1198
- /** Serve a file of the built page, the page itself carrying the token */
1199
- async function servePage(res, uiDir, pathname, token) {
1235
+ function escapeAttribute(value) {
1236
+ return value.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1237
+ }
1238
+ async function servePage(uiDir, pathname, page) {
1200
1239
  const isPage = pathname === "/" || pathname === "/index.html";
1201
1240
  const file = resolve(uiDir, `.${isPage ? "/index.html" : pathname}`);
1202
- if (relative(uiDir, file).startsWith("..")) {
1203
- sendJson(res, 404, { message: "Not found" });
1204
- return;
1205
- }
1241
+ if (relative(uiDir, file).startsWith("..")) return jsonResponse(404, { message: "Not found" });
1206
1242
  const content = await readFile(file).catch((error) => {
1207
1243
  if (error.code === "ENOENT" || error.code === "EISDIR") return void 0;
1208
1244
  throw error;
1209
1245
  });
1210
1246
  if (!content) {
1211
- if (isPage) {
1212
- res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
1213
- res.end("The studio page has not been built. Run `pnpm build` in the lines-db repository.");
1214
- return;
1215
- }
1216
- sendJson(res, 404, { message: "Not found" });
1217
- return;
1247
+ if (isPage) return new Response("The studio page has not been built. Run `pnpm build` in the lines-db repository.", {
1248
+ status: 503,
1249
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
1250
+ });
1251
+ return jsonResponse(404, { message: "Not found" });
1218
1252
  }
1219
1253
  const nonce = randomBytes(18).toString("base64");
1220
- const body = isPage ? Buffer.from(content.toString("utf8").replace("</head>", `<meta name="csp-nonce" content="${nonce}"><meta name="studio-token" content="${token}"></head>`)) : content;
1221
- res.writeHead(200, {
1254
+ const requestHeaders = page.requestHeaders ? `<meta name="studio-request-headers" content="${escapeAttribute(JSON.stringify(page.requestHeaders))}">` : "";
1255
+ const body = isPage ? Buffer.from(content.toString("utf8").replace("</head>", () => `<meta name="csp-nonce" content="${nonce}"><meta name="studio-token" content="${page.token}">${requestHeaders}</head>`)) : content;
1256
+ return new Response(body, { headers: {
1222
1257
  "Content-Type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream",
1223
- "Content-Security-Policy": `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
1258
+ "Content-Security-Policy": `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors '${page.frameAncestors}'`,
1224
1259
  "Cache-Control": isPage ? "no-store" : "public, max-age=31536000, immutable",
1225
1260
  "X-Content-Type-Options": "nosniff"
1226
- });
1227
- res.end(body);
1261
+ } });
1228
1262
  }
1229
- function bearerToken(req) {
1230
- return /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1];
1263
+ function bearerToken(request) {
1264
+ return /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1];
1231
1265
  }
1232
1266
  function sameToken(presented, token) {
1233
1267
  const a = Buffer.from(presented);
@@ -1256,14 +1290,14 @@ function writeOperation(method, encodedKey) {
1256
1290
  key
1257
1291
  };
1258
1292
  }
1259
- function sendJson(res, status, body) {
1260
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
1261
- res.end(JSON.stringify(body));
1293
+ function jsonResponse(status, body) {
1294
+ return new Response(JSON.stringify(body), {
1295
+ status,
1296
+ headers: { "Content-Type": "application/json; charset=utf-8" }
1297
+ });
1262
1298
  }
1263
- async function readJson(req) {
1264
- const chunks = [];
1265
- for await (const chunk of req) chunks.push(chunk);
1266
- return parseJson(Buffer.concat(chunks).toString("utf8"), "The request body is not JSON");
1299
+ async function readJson(request) {
1300
+ return parseJson(await request.text(), "The request body is not JSON");
1267
1301
  }
1268
1302
  function isJsonObject(value) {
1269
1303
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1319,6 +1353,6 @@ function parseJson(text, message) {
1319
1353
  function errorMessage(error) {
1320
1354
  return error instanceof Error ? error.message : String(error);
1321
1355
  }
1322
- export { startStudioServer };
1356
+ export { createStudioHandler, startStudioServer };
1323
1357
 
1324
1358
  //# sourceMappingURL=index.mjs.map