@notionhq/custom-blocks-dev-shell 0.1.114 → 0.1.116

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +108 -22
  3. package/THIRD_PARTY_LICENSES.md +133 -0
  4. package/bin/cli.js +3 -1
  5. package/dist/assets/index-DSaseWP_.js +11 -0
  6. package/dist/assets/index-Do-x8yIt.css +2 -0
  7. package/dist/index.html +2 -2
  8. package/dist-cli/cli/published-cli.js +8476 -0
  9. package/docs/bindings.md +84 -27
  10. package/docs/bridge/changelog.md +67 -0
  11. package/docs/bridge/protocol.md +204 -0
  12. package/docs/bridge/versioning.md +38 -0
  13. package/docs/data-sources.md +49 -36
  14. package/docs/host/README.md +177 -0
  15. package/docs/host/docs/compatibility.md +68 -0
  16. package/docs/host/docs/handlers.md +199 -0
  17. package/docs/host/docs/lifecycle.md +117 -0
  18. package/package.json +9 -28
  19. package/dist/assets/index-E1j3FxAu.css +0 -2
  20. package/dist/assets/index-F02ZboyS.js +0 -11
  21. package/dist-cli/block-csp.js +0 -84
  22. package/dist-cli/build-block-registry.js +0 -28
  23. package/dist-cli/convert-values.js +0 -222
  24. package/dist-cli/convert.js +0 -210
  25. package/dist-cli/data-sources.js +0 -167
  26. package/dist-cli/date-value.js +0 -46
  27. package/dist-cli/dev-shell-launcher.js +0 -226
  28. package/dist-cli/dev-shell-run.js +0 -72
  29. package/dist-cli/errors.js +0 -8
  30. package/dist-cli/materialize.js +0 -105
  31. package/dist-cli/ports.js +0 -20
  32. package/dist-cli/prebuilt.js +0 -23
  33. package/dist-cli/published-cli.js +0 -60
  34. package/dist-cli/resolve-bindings.js +0 -39
  35. package/dist-cli/runtime-error-client.js +0 -52
  36. package/dist-cli/serve-ui.js +0 -110
  37. package/dist-cli/shared-server.js +0 -70
  38. package/dist-cli/source-bindings.js +0 -17
  39. package/dist-cli/utils.js +0 -52
  40. package/dist-cli/vite-block-server.js +0 -125
  41. package/dist-cli/vite-middleware.js +0 -111
  42. package/dist-cli/worker-manifest.js +0 -141
@@ -1,60 +0,0 @@
1
- /**
2
- * Published launcher entry point for custom block authors. This file is the
3
- * entry point for `ntn workers customblocks dev` and `npx @notionhq/custom-blocks-dev-shell`.
4
- *
5
- * The shared launcher orchestrates building the worker, reading its manifest,
6
- * creating one Vite middleware instance per custom block, and owning the ports, output, and
7
- * lifecycle. This entry point starts the dev shell and supplies the package's
8
- * prebuilt shell adapter with the block registry and data sources.
9
- *
10
- * Other subcommands like `convert` exit before any dev shell machinery starts.
11
- */
12
- import { existsSync } from "node:fs";
13
- import { basename, dirname, join, resolve } from "node:path";
14
- import { fileURLToPath } from "node:url";
15
- import { runConvert } from "./convert.js";
16
- import { readDataSources } from "./data-sources.js";
17
- import { launchDevShell } from "./dev-shell-launcher.js";
18
- import { formatUnknownErrorWithStack } from "./errors.js";
19
- import { copyPrebuiltDataSources } from "./prebuilt.js";
20
- import { createUiHandler } from "./serve-ui.js";
21
- const __dirname = dirname(fileURLToPath(import.meta.url));
22
- const createShellLaunch = async ({ plan, shared, log }) => {
23
- const distDir = resolve(__dirname, "..", "dist");
24
- if (!existsSync(join(distDir, "index.html"))) {
25
- throw new Error(`No prebuilt UI found at ${distDir}. This package was not assembled ` +
26
- `correctly; reinstall it.`);
27
- }
28
- const prebuiltDir = resolve(__dirname, "..", "data");
29
- shared.routes.set("localhost", {
30
- handle: createUiHandler(distDir, {
31
- blocks: plan.registry,
32
- dataSources: plan.dataSources,
33
- prebuiltFilenames: readDataSources(prebuiltDir).map(source => source.filename),
34
- }, () => {
35
- const written = copyPrebuiltDataSources(prebuiltDir, plan.dataDir);
36
- if (written.length > 0) {
37
- log(basename(plan.workerDir), `Added example data sources: ${written.join(", ")}`);
38
- }
39
- return readDataSources(plan.dataDir);
40
- }),
41
- });
42
- };
43
- async function main() {
44
- const argv = process.argv.slice(2);
45
- // One-shot subcommands return before any dev shell machinery starts.
46
- if (argv[0] === "convert") {
47
- await runConvert(argv.slice(1));
48
- return;
49
- }
50
- await launchDevShell({
51
- argv,
52
- workerBaseDir: process.cwd(),
53
- detectFromDir: process.cwd(),
54
- createShellLaunch,
55
- });
56
- }
57
- main().catch(error => {
58
- console.error(formatUnknownErrorWithStack(error));
59
- process.exitCode = 1;
60
- });
@@ -1,39 +0,0 @@
1
- /** Validate explicit file selections before servers start. */
2
- export function resolveLaunchBindings(blocks, sources, overrides) {
3
- const targets = blocks.flatMap(block => Object.entries(block.config.manifest.dataSources).map(([slotKey]) => ({
4
- blockKey: block.key,
5
- slotKey,
6
- target: `${block.key}.${slotKey}`,
7
- })));
8
- const explicit = validateOverrides(targets.map(candidate => candidate.target), sources, overrides);
9
- const registryBindings = new Map();
10
- for (const { blockKey, slotKey, target } of targets) {
11
- const source = explicit.get(target);
12
- if (source === undefined) {
13
- continue;
14
- }
15
- const bindings = registryBindings.get(blockKey) ??
16
- Object.create(null);
17
- bindings[slotKey] = `${source.filename}.json`;
18
- registryBindings.set(blockKey, bindings);
19
- }
20
- return { registryBindings };
21
- }
22
- function validateOverrides(targets, sources, overrides) {
23
- const explicit = new Map();
24
- for (const { target, filename } of overrides) {
25
- const matches = targets.filter(candidate => candidate === target);
26
- if (matches.length !== 1) {
27
- throw new Error(`${matches.length === 0 ? "Unknown" : "Ambiguous"} binding target "${target}". Available targets: ${targets.join(", ") || "(none)"}.`);
28
- }
29
- if (explicit.has(target)) {
30
- throw new Error(`Duplicate --bind target "${target}". Specify each target once.`);
31
- }
32
- const source = sources.find(candidate => `${candidate.filename}.json` === filename);
33
- if (source === undefined) {
34
- throw new Error(`Cannot bind ${target}: data/${filename} does not exist. Available files: ${sources.map(candidate => `${candidate.filename}.json`).join(", ") || "(none)"}.`);
35
- }
36
- explicit.set(target, source);
37
- }
38
- return explicit;
39
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * This script runs before the block entry module. The block and shell use
3
- * different origins, so the iframe must report its own uncaught errors.
4
- */
5
- export const RUNTIME_ERROR_CLIENT_SOURCE = `
6
- const MESSAGE_TYPE = "notion-custom-blocks-dev-shell:runtime-error"
7
-
8
- function report(error, fallback, location) {
9
- const message =
10
- typeof error === "object" &&
11
- error !== null &&
12
- typeof error.message === "string"
13
- ? error.message
14
- : typeof error === "string"
15
- ? error
16
- : fallback
17
- const stack =
18
- typeof error === "object" &&
19
- error !== null &&
20
- typeof error.stack === "string"
21
- ? error.stack
22
- : undefined
23
- const filename =
24
- location !== undefined && typeof location.filename === "string"
25
- ? location.filename
26
- : undefined
27
- const lineno =
28
- location !== undefined && typeof location.lineno === "number"
29
- ? location.lineno
30
- : undefined
31
- const colno =
32
- location !== undefined && typeof location.colno === "number"
33
- ? location.colno
34
- : undefined
35
- window.parent.postMessage({
36
- type: MESSAGE_TYPE,
37
- error: { message, stack, filename, lineno, colno },
38
- }, "*")
39
- }
40
-
41
- window.addEventListener("error", event => {
42
- report(event.error, event.message || "Uncaught error", {
43
- filename: event.filename,
44
- lineno: event.lineno,
45
- colno: event.colno,
46
- })
47
- })
48
-
49
- window.addEventListener("unhandledrejection", event => {
50
- report(event.reason, "Unhandled promise rejection")
51
- })
52
- `;
@@ -1,110 +0,0 @@
1
- /**
2
- * Dependency-free static server for the prebuilt dev shell UI (`dist/`).
3
- *
4
- * The published UI is a plain Vite build, so the block registry can't ride in
5
- * through build-time `import.meta.env` vars the way it does under
6
- * `scripts/dev.ts`. Instead, this server injects a `window.__DEV_SHELL_CONFIG__`
7
- * script into `index.html` as it is served; `src/helpers/blocks.ts` prefers
8
- * that global over the baked-in env values.
9
- */
10
- import { readFileSync } from "node:fs";
11
- import { extname, join, normalize, resolve, sep } from "node:path";
12
- import { formatUnknownError } from "./errors.js";
13
- const CONTENT_TYPES = {
14
- ".html": "text/html; charset=utf-8",
15
- ".js": "text/javascript; charset=utf-8",
16
- ".mjs": "text/javascript; charset=utf-8",
17
- ".css": "text/css; charset=utf-8",
18
- ".json": "application/json; charset=utf-8",
19
- ".svg": "image/svg+xml",
20
- ".png": "image/png",
21
- ".ico": "image/x-icon",
22
- ".woff": "font/woff",
23
- ".woff2": "font/woff2",
24
- ".map": "application/json; charset=utf-8",
25
- };
26
- /** `index.html` with the runtime config injected ahead of the bundle script. */
27
- function injectConfig(html, config) {
28
- const tag = `<script>window.__DEV_SHELL_CONFIG__ = ${JSON.stringify(config).replace(/</g, "\\u003c")}</script>`;
29
- if (html.includes("<head>")) {
30
- return html.replace("<head>", `<head>\n\t\t${tag}`);
31
- }
32
- return `${tag}\n${html}`;
33
- }
34
- /**
35
- * Serve `distDir` as a request handler. Unknown extensionless paths fall back to
36
- * `index.html`.
37
- *
38
- * `addPrebuiltData`, when given, backs `POST /api/prebuilt-data`: it writes
39
- * the pre-built sources into the worker's data directory and returns
40
- * the directory's updated contents.
41
- */
42
- export function createUiHandler(distDir, config, addPrebuiltData) {
43
- const dist = resolve(distDir);
44
- const rawIndexHtml = readFileSync(join(dist, "index.html"), "utf-8");
45
- // Server-owned: updated by the add endpoint, while the caller's `config`
46
- // stays an untouched input.
47
- let dataSources = config.dataSources;
48
- return (req, res) => {
49
- let urlPath;
50
- try {
51
- urlPath = decodeURIComponent(req.url?.split("?", 1)[0] ?? "/");
52
- }
53
- catch {
54
- res.writeHead(400);
55
- res.end();
56
- return;
57
- }
58
- // Routed on the raw URL path: normalize() is platform-specific, so it
59
- // would rewrite "/api/..." to "\api\..." on Windows and never match.
60
- if (urlPath === "/api/prebuilt-data") {
61
- if (req.method !== "POST") {
62
- res.writeHead(405, { Allow: "POST" });
63
- res.end();
64
- return;
65
- }
66
- if (addPrebuiltData === undefined) {
67
- res.writeHead(404);
68
- res.end();
69
- return;
70
- }
71
- try {
72
- dataSources = addPrebuiltData();
73
- }
74
- catch (error) {
75
- res.writeHead(500, { "Content-Type": CONTENT_TYPES[".json"] });
76
- res.end(JSON.stringify({ error: formatUnknownError(error) }));
77
- return;
78
- }
79
- res.writeHead(200, { "Content-Type": CONTENT_TYPES[".json"] });
80
- res.end(JSON.stringify({ dataSources }));
81
- return;
82
- }
83
- const path = normalize(urlPath);
84
- const filePath = join(dist, path);
85
- if (!filePath.startsWith(dist + sep) && filePath !== dist) {
86
- res.writeHead(403);
87
- res.end();
88
- return;
89
- }
90
- const ext = extname(filePath);
91
- if (path === "/" || path === `${sep}index.html` || ext === "") {
92
- res.writeHead(200, { "Content-Type": CONTENT_TYPES[".html"] });
93
- // Injected per request: `dataSources` changes when pre-built data is
94
- // added, and a reload must see the updated collection.
95
- res.end(injectConfig(rawIndexHtml, { ...config, dataSources }));
96
- return;
97
- }
98
- try {
99
- const body = readFileSync(filePath);
100
- res.writeHead(200, {
101
- "Content-Type": CONTENT_TYPES[ext] ?? "application/octet-stream",
102
- });
103
- res.end(body);
104
- }
105
- catch {
106
- res.writeHead(404);
107
- res.end();
108
- }
109
- };
110
- }
@@ -1,70 +0,0 @@
1
- import { createServer } from "node:http";
2
- import { DEFAULT_DEV_SHELL_PORT } from "./ports.js";
3
- /** The only listening server in a run. Vite upgrade targets never listen. */
4
- export class SharedServer {
5
- routes = new Map();
6
- server = createServer((req, res) => {
7
- const route = this.routes.get(this.hostname(req.headers.host));
8
- if (route) {
9
- route.handle(req, res);
10
- }
11
- else {
12
- res.writeHead(404);
13
- res.end("Unknown dev shell hostname");
14
- }
15
- });
16
- sockets = new Set();
17
- port = 0;
18
- constructor() {
19
- this.server.on("connection", socket => {
20
- this.sockets.add(socket);
21
- socket.on("close", () => this.sockets.delete(socket));
22
- });
23
- this.server.on("upgrade", (req, socket, head) => {
24
- const route = this.routes.get(this.hostname(req.headers.host));
25
- if (!route?.upgrades?.emit("upgrade", req, socket, head)) {
26
- socket.destroy();
27
- }
28
- });
29
- }
30
- hostname(host) {
31
- return (host ?? "").split(":")[0].toLowerCase();
32
- }
33
- async listen(port = DEFAULT_DEV_SHELL_PORT, strict = false) {
34
- for (;;) {
35
- try {
36
- await new Promise((resolve, reject) => {
37
- const onError = (error) => {
38
- this.server.off("listening", onListening);
39
- reject(error);
40
- };
41
- const onListening = () => {
42
- this.server.off("error", onError);
43
- resolve();
44
- };
45
- this.server.once("error", onError);
46
- this.server.once("listening", onListening);
47
- this.server.listen(port, "127.0.0.1");
48
- });
49
- this.port = this.server.address().port;
50
- return this.port;
51
- }
52
- catch (error) {
53
- if (error.code !== "EADDRINUSE") {
54
- throw error;
55
- }
56
- if (strict || port === 65535) {
57
- throw new Error(`Port ${port} is already in use. Stop the other server or choose --port <port>.`, { cause: error });
58
- }
59
- port++;
60
- }
61
- }
62
- }
63
- async close() {
64
- this.routes.clear();
65
- for (const socket of this.sockets) {
66
- socket.destroy();
67
- }
68
- await new Promise(resolve => this.server.close(() => resolve()));
69
- }
70
- }
@@ -1,17 +0,0 @@
1
- export function parseBindingOverride(value) {
2
- const separator = value.indexOf("=");
3
- const target = value.slice(0, separator);
4
- const filename = value.slice(separator + 1);
5
- const dot = target.indexOf(".");
6
- if (separator < 0 ||
7
- dot <= 0 ||
8
- dot === target.length - 1 ||
9
- target !== target.trim() ||
10
- filename !== filename.trim() ||
11
- !filename.endsWith(".json") ||
12
- filename === ".json" ||
13
- /[\\/\0]/.test(filename)) {
14
- throw new Error("--bind requires <capabilityKey>.<dataSourceKey>=<sampleDataFileName.json>. Use a filename in data/.");
15
- }
16
- return { target, filename };
17
- }
package/dist-cli/utils.js DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * Throws when a discriminated union switch is not exhaustive.
3
- */
4
- export function unreachable(value) {
5
- throw new Error(`[custom-blocks-dev-shell] Unexpected value encountered: ${JSON.stringify(value)}`);
6
- }
7
- /** Lowercase, non-alphanumerics collapsed to `_`; undefined when nothing survives. */
8
- export function slugify(name) {
9
- const slug = name
10
- .toLowerCase()
11
- .replace(/[^a-z0-9]+/g, "_")
12
- .replace(/^_+|_+$/g, "");
13
- return slug.length > 0 ? slug : undefined;
14
- }
15
- /**
16
- * Claim `base` as a key in `used`, suffixing `_2`, `_3`, … while it is
17
- * already taken. Mutates `used` so later claims see this one.
18
- */
19
- export function claimUniqueKey(base, used) {
20
- let key = base;
21
- for (let counter = 2; used.has(key); counter++) {
22
- key = `${base}_${counter}`;
23
- }
24
- used.add(key);
25
- return key;
26
- }
27
- export function parseCliArgs({ argv, handlers, onUnknown, onPositional, }) {
28
- const takeValue = (name, index) => {
29
- const value = argv[index];
30
- if (value === undefined || value.startsWith("--")) {
31
- throw new Error(`${name} requires a value.`);
32
- }
33
- return value;
34
- };
35
- for (let index = 0; index < argv.length; index++) {
36
- const arg = argv[index];
37
- const separator = arg.indexOf("=");
38
- const name = separator === -1 ? arg : arg.slice(0, separator);
39
- const handler = handlers[name];
40
- if (handler === undefined) {
41
- if (arg.startsWith("-")) {
42
- onUnknown(arg);
43
- }
44
- else {
45
- onPositional(arg);
46
- }
47
- continue;
48
- }
49
- const value = separator === -1 ? takeValue(name, ++index) : arg.slice(separator + 1);
50
- handler(value);
51
- }
52
- }
@@ -1,125 +0,0 @@
1
- /**
2
- * Provides shared Vite server setup for both dev shell launchers. It generates a
3
- * Vite config for each block.
4
- */
5
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
6
- import { relative, resolve } from "node:path";
7
- import { RUNTIME_ERROR_CLIENT_SOURCE } from "./runtime-error-client.js";
8
- /** Import specifier from `fromDir` to `toPath`, POSIX-style for ESM. */
9
- function relativeImport(fromDir, toPath) {
10
- const rel = relative(fromDir, toPath).split(/[\\/]/).join("/");
11
- return rel.startsWith(".") ? rel : `./${rel}`;
12
- }
13
- /**
14
- * Write a per-block Vite config wrapper into the run's `.dev-shell/` directory.
15
- * Preserve the block's config and plugins, but pin its root and isolate its cache
16
- * from other blocks and concurrent runs. The wrapper also
17
- * serves `/manifest` from the block's slice of the worker manifest. The wrapper
18
- * plays the part production infra does and answers the SDK's manifest fetch
19
- * directly from the worker declaration. Return the wrapper path for Vite.
20
- */
21
- export function writeBlockViteConfig(blockDir, capability, configDir, hostname) {
22
- const key = capability.key;
23
- const dir = configDir;
24
- mkdirSync(dir, { recursive: true });
25
- const blockConfig = ["ts", "mts", "cts", "js", "mjs", "cjs"]
26
- .map(ext => resolve(blockDir, `vite.config.${ext}`))
27
- .find(existsSync);
28
- const toRoot = relativeImport(dir, blockDir);
29
- const toCache = relativeImport(dir, resolve(dir, "cache", hostname));
30
- const baseImport = blockConfig !== undefined
31
- ? `import base from ${JSON.stringify(relativeImport(dir, blockConfig))}`
32
- : `const base = {}`;
33
- const file = resolve(dir, `${hostname}.mjs`);
34
- writeFileSync(file, `import { fileURLToPath } from "node:url"
35
- ${baseImport}
36
-
37
- const here = p => fileURLToPath(new URL(p, import.meta.url))
38
- const resolved =
39
- typeof base === "function"
40
- ? await base({ command: "serve", mode: "development" })
41
- : await base
42
-
43
- const manifest = ${JSON.stringify(JSON.stringify(capability.config.manifest))}
44
-
45
- // Inject before the block entry module so errors thrown during module
46
- // evaluation are reported even when the block never sends connect.
47
- const captureRuntimeErrors = {
48
- name: "dev-shell:capture-runtime-errors",
49
- transformIndexHtml: {
50
- order: "pre",
51
- handler() {
52
- return [{
53
- tag: "script",
54
- attrs: { type: "module" },
55
- children: ${JSON.stringify(RUNTIME_ERROR_CLIENT_SOURCE)},
56
- injectTo: "head-pre",
57
- }]
58
- },
59
- },
60
- }
61
-
62
- /**
63
- * Allows Notion apps and local hosts to read the dev server's manifest.
64
- * CORS checks the requesting page's origin, so hosted Notion origins must
65
- * be allowed even though the manifest is served from localhost.
66
- */
67
- function isAllowedManifestOrigin(origin) {
68
- if (!origin) {
69
- return false
70
- }
71
-
72
- const localOrigin = ${/^https?:\/\/(?:(?:[a-z0-9-]+\.)*localhost|127\.0\.0\.1|\[::1\]|local\.notion\.so)(?::[0-9]+)?$/i}
73
- const notionOrigin = ${/^https:\/\/(?:(?:dev|stg|www)\.notion\.so|app(?:\.(?:local|dev|stg|prod|canary))?\.notion\.com)$/i}
74
-
75
- return localOrigin.test(origin) || notionOrigin.test(origin)
76
- }
77
-
78
- const serveWorkerManifest = {
79
- name: "dev-shell:worker-block-manifest",
80
- enforce: "pre",
81
- configureServer(server) {
82
- server.middlewares.use((req, res, next) => {
83
- if (req.url?.split("?", 1)[0] !== "/manifest") {
84
- next()
85
- return
86
- }
87
- // Notion hosts read custom blocks' manifests for in-app preview.
88
- // Allow CORS for these reads without opening other routes.
89
- const { origin } = req.headers
90
- if (isAllowedManifestOrigin(origin)) {
91
- res.setHeader("Access-Control-Allow-Origin", origin)
92
- }
93
- res.setHeader("Vary", "Origin")
94
- res.setHeader("Content-Type", "application/json")
95
- res.end(manifest)
96
- })
97
- },
98
- }
99
-
100
- export default {
101
- ...resolved,
102
- root: here(${JSON.stringify(toRoot)}),
103
- cacheDir: here(${JSON.stringify(toCache)}),
104
- server: {
105
- ...(resolved.server ?? {}),
106
- // Block servers are local development dependencies of the shell.
107
- host: "127.0.0.1",
108
- },
109
- define: {
110
- ...(resolved.define ?? {}),
111
- // Initialization handshake scenarios fixture uses this key to identify the
112
- // selected scenario, via the custom block capability key. The key needs to be
113
- // serialized as a JavaScript string literal, then serialized again for this
114
- // generated config.
115
- "import.meta.env.VITE_CUSTOM_BLOCK_KEY": ${JSON.stringify(JSON.stringify(key))},
116
- },
117
- plugins: [
118
- serveWorkerManifest,
119
- captureRuntimeErrors,
120
- ...(resolved.plugins ?? []),
121
- ],
122
- }
123
- `);
124
- return file;
125
- }
@@ -1,111 +0,0 @@
1
- import { createServer } from "node:http";
2
- import { createRequire } from "node:module";
3
- import { join } from "node:path";
4
- import { pathToFileURL } from "node:url";
5
- import { buildCustomBlockDevShellResponseHeaders, } from "./block-csp.js";
6
- /** Resolve Vite from the project, including for the dependency-free published CLI. */
7
- export async function mountVite(options) {
8
- const { projectDir, hostname, shared, config } = options;
9
- const blockHeaders = options.blockPolicy === false
10
- ? undefined
11
- : buildCustomBlockDevShellResponseHeaders({
12
- blockOrigin: `http://${hostname}:${shared.port}`,
13
- shellOrigin: `http://localhost:${shared.port}`,
14
- ...options.blockPolicy,
15
- });
16
- let vitePath;
17
- try {
18
- vitePath = createRequire(join(projectDir, "package.json")).resolve("vite");
19
- }
20
- catch {
21
- throw new Error(`Could not resolve "vite" from ${projectDir}. Add vite to the project's devDependencies and reinstall.`);
22
- }
23
- const vite = (await import(pathToFileURL(vitePath).href));
24
- // Vite owns upgrade listeners on this unbound server, including across restarts.
25
- const upgrades = createServer();
26
- let partialServer;
27
- const ownership = {
28
- name: "dev-shell:server-ownership",
29
- enforce: "pre",
30
- configureServer: {
31
- order: "pre",
32
- handler(server) {
33
- partialServer = server;
34
- },
35
- },
36
- };
37
- const transport = {
38
- name: "dev-shell:shared-listener",
39
- enforce: "post",
40
- configResolved(resolved) {
41
- resolved.server.middlewareMode = { server: upgrades };
42
- resolved.server.open = false;
43
- if (blockHeaders !== undefined) {
44
- // Vite's asset middleware writes these headers after the route middleware.
45
- resolved.server.headers = {
46
- ...resolved.server.headers,
47
- ...blockHeaders,
48
- };
49
- }
50
- resolved.server.origin = `http://${hostname}:${shared.port}`;
51
- const ws = {
52
- server: upgrades,
53
- host: hostname,
54
- port: shared.port,
55
- clientPort: shared.port,
56
- protocol: "ws",
57
- path: "/",
58
- };
59
- // Each worker uses its own installed Vite version.
60
- // Older versions configure WebSocket transport through server.hmr.
61
- // Remove the fallback when we require Vite 8.2 or later in worker projects.
62
- if ("ws" in resolved.server) {
63
- resolved.server.ws = ws;
64
- }
65
- else {
66
- resolved.server.hmr = {
67
- ...(typeof resolved.server.hmr === "object"
68
- ? resolved.server.hmr
69
- : {}),
70
- ...ws,
71
- };
72
- }
73
- },
74
- };
75
- let server;
76
- try {
77
- server = await vite.createServer({
78
- ...config,
79
- plugins: [ownership, ...(config.plugins ?? []), transport],
80
- });
81
- }
82
- catch (error) {
83
- try {
84
- await partialServer?.close();
85
- }
86
- finally {
87
- upgrades.removeAllListeners();
88
- }
89
- throw error;
90
- }
91
- shared.routes.set(hostname, {
92
- handle: (req, res) => {
93
- if (blockHeaders !== undefined) {
94
- for (const [name, value] of Object.entries(blockHeaders)) {
95
- res.setHeader(name, value);
96
- }
97
- }
98
- server.middlewares(req, res);
99
- },
100
- upgrades,
101
- });
102
- return async () => {
103
- shared.routes.delete(hostname);
104
- // Let initial imports settle before Vite cancels dependency discovery.
105
- // The run's shutdown deadline still bounds this wait.
106
- await server
107
- .waitForRequestsIdle()
108
- .finally(() => server.close())
109
- .finally(() => upgrades.removeAllListeners());
110
- };
111
- }