@notionhq/custom-blocks-dev-shell 0.1.69 → 0.1.70
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 +24 -12
- package/dist/assets/index-B-371Yik.css +2 -0
- package/dist/assets/index-DGEHqWJN.js +11 -0
- package/dist/index.html +2 -2
- package/dist-cli/build-block-registry.js +27 -8
- package/dist-cli/dev-shell-launcher.js +66 -80
- package/dist-cli/dev-shell-run.js +72 -0
- package/dist-cli/ports.js +7 -23
- package/dist-cli/published-cli.js +7 -25
- package/dist-cli/serve-ui.js +6 -13
- package/dist-cli/shared-server.js +70 -0
- package/dist-cli/vite-block-server.js +17 -65
- package/dist-cli/vite-middleware.js +89 -0
- package/package.json +1 -1
- package/dist/assets/index-BOt07-3a.css +0 -2
- package/dist/assets/index-jvcNWLYF.js +0 -11
- package/dist-cli/process-supervisor.js +0 -164
package/dist/index.html
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Workers local shell</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-DGEHqWJN.js"></script>
|
|
8
|
+
<link rel="stylesheet" crossorigin href="/assets/index-B-371Yik.css">
|
|
9
9
|
</head>
|
|
10
10
|
<body>
|
|
11
11
|
<div id="root"></div>
|
|
@@ -1,9 +1,28 @@
|
|
|
1
|
-
import {
|
|
2
|
-
/** The registry for a worker's blocks,
|
|
3
|
-
export function buildBlockRegistry(blocks,
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { DEFAULT_DEV_SHELL_PORT } from "./ports.js";
|
|
2
|
+
/** The registry for a worker's blocks, with unique localhost hostnames. */
|
|
3
|
+
export function buildBlockRegistry(blocks, port = DEFAULT_DEV_SHELL_PORT) {
|
|
4
|
+
const used = new Set();
|
|
5
|
+
return blocks.map(capability => {
|
|
6
|
+
const stem = capability.key
|
|
7
|
+
.toLowerCase()
|
|
8
|
+
.replace(/[^a-z0-9-]+/g, "-")
|
|
9
|
+
.replace(/^-+|-+$/g, "")
|
|
10
|
+
.slice(0, 63)
|
|
11
|
+
.replace(/-+$/g, "") || "block";
|
|
12
|
+
let hostname = stem;
|
|
13
|
+
let suffix = 1;
|
|
14
|
+
// Distinct capability keys can normalize to the same hostname.
|
|
15
|
+
// Add a suffix to keep hostnames unique within the 63-character label limit.
|
|
16
|
+
while (used.has(hostname)) {
|
|
17
|
+
const ending = `-${++suffix}`;
|
|
18
|
+
hostname = stem.slice(0, 63 - ending.length).replace(/-+$/g, "") + ending;
|
|
19
|
+
}
|
|
20
|
+
used.add(hostname);
|
|
21
|
+
return {
|
|
22
|
+
key: capability.key,
|
|
23
|
+
manifest: capability.config.manifest,
|
|
24
|
+
name: capability.key,
|
|
25
|
+
url: `http://${hostname}.localhost:${port}/`,
|
|
26
|
+
};
|
|
27
|
+
});
|
|
9
28
|
}
|
|
@@ -1,23 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared orchestration for the repository and published dev shell launchers.
|
|
3
3
|
*
|
|
4
|
-
* It builds the worker and reads its manifest,
|
|
5
|
-
* custom block, and owns
|
|
4
|
+
* It builds the worker and reads its manifest, creates one Vite middleware instance per
|
|
5
|
+
* custom block, and owns resource cleanup. Each launcher entry point
|
|
6
6
|
* supplies a small shell adapter, but otherwise delegates to this module.
|
|
7
7
|
*/
|
|
8
|
-
import { existsSync,
|
|
9
|
-
import {
|
|
10
|
-
import { basename, dirname, join, resolve } from "node:path";
|
|
8
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
|
9
|
+
import { basename, join, resolve } from "node:path";
|
|
11
10
|
import { buildBlockRegistry, } from "./build-block-registry.js";
|
|
12
11
|
import { readDataSources } from "./data-sources.js";
|
|
12
|
+
import { DevShellRun, installProcessSignalHandlers, } from "./dev-shell-run.js";
|
|
13
13
|
import { formatUnknownErrorWithStack } from "./errors.js";
|
|
14
14
|
import { materializeWorkerSchemaDataSources } from "./materialize.js";
|
|
15
|
-
import {
|
|
16
|
-
import { installProcessSignalHandlers, ProcessSupervisor, } from "./process-supervisor.js";
|
|
15
|
+
import { DEFAULT_DEV_SHELL_PORT, parsePort } from "./ports.js";
|
|
17
16
|
import { resolveLaunchBindings } from "./resolve-bindings.js";
|
|
17
|
+
import { SharedServer } from "./shared-server.js";
|
|
18
18
|
import { parseBindingOverride, } from "./source-bindings.js";
|
|
19
19
|
import { parseCliArgs } from "./utils.js";
|
|
20
20
|
import { writeBlockViteConfig } from "./vite-block-server.js";
|
|
21
|
+
import { mountVite } from "./vite-middleware.js";
|
|
21
22
|
import { blockCapabilities, findWorkerDir, generateWorkerManifest, } from "./worker-manifest.js";
|
|
22
23
|
const dim = "\x1b[2m";
|
|
23
24
|
const bold = "\x1b[1m";
|
|
@@ -34,33 +35,35 @@ export async function prepareWorkerLaunchPlan(workerDir, options = {}) {
|
|
|
34
35
|
build: options.build,
|
|
35
36
|
});
|
|
36
37
|
const capabilities = blockCapabilities(manifest);
|
|
37
|
-
const
|
|
38
|
-
|
|
38
|
+
const registry = buildBlockRegistry(capabilities, options.shellPort ?? DEFAULT_DEV_SHELL_PORT);
|
|
39
|
+
const configDir = options.configDir ?? join(root, ".dev-shell");
|
|
39
40
|
const blocks = capabilities.map((capability, index) => {
|
|
40
41
|
const blockDir = resolve(root, capability.config.source.path);
|
|
42
|
+
const hostname = new URL(registry[index].url).hostname;
|
|
41
43
|
return {
|
|
42
44
|
capability,
|
|
43
45
|
blockDir,
|
|
44
|
-
|
|
45
|
-
|
|
46
|
+
hostname,
|
|
47
|
+
configFile: writeBlockViteConfig(blockDir, capability, configDir, hostname),
|
|
46
48
|
};
|
|
47
49
|
});
|
|
48
50
|
const dataDir = resolve(root, "data");
|
|
49
51
|
materializeWorkerSchemaDataSources(manifest, dataDir);
|
|
50
52
|
return {
|
|
51
53
|
workerDir: root,
|
|
54
|
+
configDir,
|
|
52
55
|
dataDir,
|
|
53
56
|
manifestPath,
|
|
54
57
|
blocks,
|
|
55
|
-
registry
|
|
58
|
+
registry,
|
|
56
59
|
dataSources: readDataSources(dataDir),
|
|
57
60
|
};
|
|
58
61
|
}
|
|
59
62
|
export function parseWorkerLaunchArgs(argv) {
|
|
60
63
|
const args = {
|
|
61
64
|
worker: undefined,
|
|
62
|
-
shellPort:
|
|
63
|
-
|
|
65
|
+
shellPort: DEFAULT_DEV_SHELL_PORT,
|
|
66
|
+
strictPort: false,
|
|
64
67
|
bindings: [],
|
|
65
68
|
};
|
|
66
69
|
let hasPositionalWorker = false;
|
|
@@ -82,14 +85,12 @@ export function parseWorkerLaunchArgs(argv) {
|
|
|
82
85
|
},
|
|
83
86
|
"--port": value => {
|
|
84
87
|
args.shellPort = parsePort("--port", value);
|
|
85
|
-
|
|
86
|
-
"--block-base-port": value => {
|
|
87
|
-
args.blockBasePort = parsePort("--block-base-port", value);
|
|
88
|
+
args.strictPort = true;
|
|
88
89
|
},
|
|
89
90
|
},
|
|
90
91
|
onUnknown: arg => {
|
|
91
92
|
throw new Error(`Unknown dev shell option "${arg}". Supported: --worker <dir>, ` +
|
|
92
|
-
`--port <port>, --
|
|
93
|
+
`--port <port>, --bind <capabilityKey>.<dataSourceKey>=<sampleDataFileName>.`);
|
|
93
94
|
},
|
|
94
95
|
onPositional: arg => {
|
|
95
96
|
// The published launcher passes its optional worker path positionally.
|
|
@@ -107,43 +108,6 @@ export function parseWorkerLaunchArgs(argv) {
|
|
|
107
108
|
});
|
|
108
109
|
return args;
|
|
109
110
|
}
|
|
110
|
-
function resolveWorkerViteBin(workerDir) {
|
|
111
|
-
let vitePkgPath;
|
|
112
|
-
try {
|
|
113
|
-
const workerRequire = createRequire(join(workerDir, "package.json"));
|
|
114
|
-
vitePkgPath = workerRequire.resolve("vite/package.json");
|
|
115
|
-
}
|
|
116
|
-
catch {
|
|
117
|
-
throw new Error(`Could not resolve "vite" from ${workerDir}. Add vite to the worker's ` +
|
|
118
|
-
`devDependencies and reinstall.`);
|
|
119
|
-
}
|
|
120
|
-
const vitePkg = JSON.parse(readFileSync(vitePkgPath, "utf-8"));
|
|
121
|
-
const bin = typeof vitePkg.bin === "string" ? vitePkg.bin : vitePkg.bin?.vite;
|
|
122
|
-
if (bin === undefined) {
|
|
123
|
-
throw new Error(`The vite package at ${vitePkgPath} exposes no bin.`);
|
|
124
|
-
}
|
|
125
|
-
return resolve(dirname(vitePkgPath), bin);
|
|
126
|
-
}
|
|
127
|
-
function createBlockProcesses(plan) {
|
|
128
|
-
if (plan.blocks.length === 0) {
|
|
129
|
-
return [];
|
|
130
|
-
}
|
|
131
|
-
const viteBin = resolveWorkerViteBin(plan.workerDir);
|
|
132
|
-
return plan.blocks.map(block => ({
|
|
133
|
-
name: block.capability.key,
|
|
134
|
-
command: process.execPath,
|
|
135
|
-
args: [
|
|
136
|
-
viteBin,
|
|
137
|
-
"--config",
|
|
138
|
-
block.configFile,
|
|
139
|
-
"--port",
|
|
140
|
-
String(block.port),
|
|
141
|
-
"--strictPort",
|
|
142
|
-
],
|
|
143
|
-
cwd: plan.workerDir,
|
|
144
|
-
detached: process.platform !== "win32",
|
|
145
|
-
}));
|
|
146
|
-
}
|
|
147
111
|
function logNamed(name, message) {
|
|
148
112
|
console.log(`${label(name)} ${message}`);
|
|
149
113
|
}
|
|
@@ -185,13 +149,7 @@ function logWorkerPlan(workerName, plan) {
|
|
|
185
149
|
: "No data sources — create data/<key>.json files " +
|
|
186
150
|
"(format: node_modules/@notionhq/custom-blocks-dev-shell/docs/data-sources.md).");
|
|
187
151
|
}
|
|
188
|
-
|
|
189
|
-
const { args, workerDir } = resolveWorkerLaunch(options);
|
|
190
|
-
const workerName = basename(workerDir);
|
|
191
|
-
logNamed(workerName, "Extracting worker manifest...");
|
|
192
|
-
const plan = await prepareWorkerLaunchPlan(workerDir, {
|
|
193
|
-
blockBasePort: args.blockBasePort,
|
|
194
|
-
});
|
|
152
|
+
function applyBindingsAndLog(args, plan, workerDir) {
|
|
195
153
|
const { registryBindings } = resolveLaunchBindings(plan.blocks.map(block => block.capability), plan.dataSources, args.bindings);
|
|
196
154
|
for (const entry of plan.registry) {
|
|
197
155
|
const bindings = registryBindings.get(entry.key);
|
|
@@ -199,32 +157,60 @@ async function prepareWorkerLaunch(options) {
|
|
|
199
157
|
entry.sampleFilesByDataSource = bindings;
|
|
200
158
|
}
|
|
201
159
|
}
|
|
202
|
-
logWorkerPlan(
|
|
203
|
-
validateShellPort(args.shellPort, args.blockBasePort, plan.blocks.length);
|
|
204
|
-
const shell = await options.createShellLaunch({
|
|
205
|
-
args,
|
|
206
|
-
plan,
|
|
207
|
-
log: logNamed,
|
|
208
|
-
});
|
|
209
|
-
return { args, plan, shell };
|
|
160
|
+
logWorkerPlan(basename(workerDir), plan);
|
|
210
161
|
}
|
|
211
162
|
export async function launchDevShell(options) {
|
|
212
163
|
const { installSignalHandlers = true } = options;
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
onProcessError: (name, error) => console.error(`${label(name)} dev server failed: ${error.message}`),
|
|
217
|
-
};
|
|
218
|
-
const run = options.createRun?.() ?? new ProcessSupervisor(callbacks);
|
|
164
|
+
const shared = new SharedServer();
|
|
165
|
+
const beforeCleanup = () => shared.close();
|
|
166
|
+
const run = options.createRun?.(beforeCleanup) ?? new DevShellRun(beforeCleanup);
|
|
219
167
|
if (installSignalHandlers) {
|
|
220
168
|
installProcessSignalHandlers(run);
|
|
221
169
|
}
|
|
222
170
|
try {
|
|
223
|
-
const { args,
|
|
224
|
-
|
|
225
|
-
|
|
171
|
+
const { args, workerDir } = resolveWorkerLaunch(options);
|
|
172
|
+
const originalCwd = process.cwd();
|
|
173
|
+
// One worker owns the process for the run, including Vite config reloads
|
|
174
|
+
// and plugin callbacks. Resolve CLI paths before changing directories.
|
|
175
|
+
process.chdir(workerDir);
|
|
176
|
+
run.addResource(() => process.chdir(originalCwd));
|
|
177
|
+
args.shellPort = await shared.listen(args.shellPort, args.strictPort);
|
|
178
|
+
const tempRoot = join(workerDir, ".dev-shell");
|
|
179
|
+
mkdirSync(tempRoot, { recursive: true });
|
|
180
|
+
const configDir = mkdtempSync(join(tempRoot, "run-"));
|
|
181
|
+
run.addResource(() => rmSync(configDir, { recursive: true, force: true }));
|
|
182
|
+
logNamed(basename(workerDir), "Extracting worker manifest...");
|
|
183
|
+
const plan = await prepareWorkerLaunchPlan(workerDir, {
|
|
184
|
+
shellPort: args.shellPort,
|
|
185
|
+
configDir,
|
|
186
|
+
});
|
|
187
|
+
if (run.closing) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
applyBindingsAndLog(args, plan, workerDir);
|
|
191
|
+
const closeShell = await options.createShellLaunch({
|
|
192
|
+
plan,
|
|
193
|
+
shared,
|
|
194
|
+
log: logNamed,
|
|
195
|
+
});
|
|
196
|
+
if (closeShell) {
|
|
197
|
+
run.addResource(closeShell);
|
|
198
|
+
}
|
|
199
|
+
for (const block of plan.blocks) {
|
|
200
|
+
if (run.closing) {
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const close = await mountVite({
|
|
204
|
+
projectDir: workerDir,
|
|
205
|
+
hostname: block.hostname,
|
|
206
|
+
shared,
|
|
207
|
+
config: { configFile: block.configFile, root: block.blockDir },
|
|
208
|
+
});
|
|
209
|
+
run.addResource(close);
|
|
210
|
+
}
|
|
211
|
+
if (run.closing) {
|
|
212
|
+
return;
|
|
226
213
|
}
|
|
227
|
-
run.start([...shell.processes, ...createBlockProcesses(plan)]);
|
|
228
214
|
printSummary(args, plan.registry);
|
|
229
215
|
}
|
|
230
216
|
catch (error) {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Own the listener and Vite resources for one dev shell run. */
|
|
2
|
+
const SHUTDOWN_GRACE_MS = 1500;
|
|
3
|
+
export class DevShellRun {
|
|
4
|
+
beforeCleanup;
|
|
5
|
+
resources = [];
|
|
6
|
+
shuttingDown = false;
|
|
7
|
+
constructor(beforeCleanup) {
|
|
8
|
+
this.beforeCleanup = beforeCleanup;
|
|
9
|
+
}
|
|
10
|
+
get closing() {
|
|
11
|
+
return this.shuttingDown;
|
|
12
|
+
}
|
|
13
|
+
addResource(resource) {
|
|
14
|
+
if (this.closing) {
|
|
15
|
+
void closeResource(resource);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
this.resources.push(resource);
|
|
19
|
+
}
|
|
20
|
+
shutdown(signal) {
|
|
21
|
+
if (signal === "exit") {
|
|
22
|
+
const alreadyClosing = this.closing;
|
|
23
|
+
this.shuttingDown = true;
|
|
24
|
+
if (!alreadyClosing) {
|
|
25
|
+
void closeResource(this.beforeCleanup);
|
|
26
|
+
}
|
|
27
|
+
// Exit handlers cannot await promises. Start all remaining cleanup,
|
|
28
|
+
// including file removal when an earlier async cleanup timed out.
|
|
29
|
+
for (let resource = this.resources.pop(); resource; resource = this.resources.pop()) {
|
|
30
|
+
void closeResource(resource);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (this.closing) {
|
|
35
|
+
process.exit(process.exitCode ?? 130);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
this.shuttingDown = true;
|
|
39
|
+
console.log("\n\x1b[2mShutting down...\x1b[0m");
|
|
40
|
+
void this.finishShutdown();
|
|
41
|
+
}
|
|
42
|
+
async finishShutdown() {
|
|
43
|
+
const timeout = setTimeout(() => {
|
|
44
|
+
process.exit(process.exitCode ?? 130);
|
|
45
|
+
}, SHUTDOWN_GRACE_MS);
|
|
46
|
+
await closeResource(this.beforeCleanup);
|
|
47
|
+
for (let resource = this.resources.pop(); resource; resource = this.resources.pop()) {
|
|
48
|
+
await closeResource(resource);
|
|
49
|
+
}
|
|
50
|
+
clearTimeout(timeout);
|
|
51
|
+
process.exit(process.exitCode ?? 0);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function closeResource(resource) {
|
|
55
|
+
try {
|
|
56
|
+
await resource();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
console.error("Dev shell cleanup failed:", error);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function installProcessSignalHandlers(run) {
|
|
63
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
|
|
64
|
+
process.on(signal, () => run.shutdown(signal));
|
|
65
|
+
}
|
|
66
|
+
process.on("exit", () => run.shutdown("exit"));
|
|
67
|
+
process.on("uncaughtException", error => {
|
|
68
|
+
console.error(error);
|
|
69
|
+
process.exitCode = 1;
|
|
70
|
+
run.shutdown("SIGTERM");
|
|
71
|
+
});
|
|
72
|
+
}
|
package/dist-cli/ports.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Port defaults and validation shared by the repository and published launchers.
|
|
3
3
|
*/
|
|
4
|
-
/**
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
/**
|
|
5
|
+
* The default port for the dev shell, all blocks, and hot reload.
|
|
6
|
+
* By default, the dev shell starts on this port.
|
|
7
|
+
* If this port is occupied, the launcher tries higher ports in sequence until it finds an available port.
|
|
8
|
+
* The --port option overrides this value and disables automatic port selection.
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_DEV_SHELL_PORT = 9873;
|
|
8
11
|
/** Highest valid TCP port. */
|
|
9
12
|
const MAX_PORT = 65535;
|
|
10
13
|
/** Parse and validate a named CLI port option. */
|
|
@@ -15,22 +18,3 @@ export function parsePort(name, raw) {
|
|
|
15
18
|
}
|
|
16
19
|
return port;
|
|
17
20
|
}
|
|
18
|
-
/** Reject a sequential block-port range that would exceed the TCP port limit. */
|
|
19
|
-
export function validateBlockPortRange(blockBasePort, blockCount) {
|
|
20
|
-
const lastPort = blockBasePort + blockCount - 1;
|
|
21
|
-
if (blockCount > 0 && lastPort > MAX_PORT) {
|
|
22
|
-
throw new Error(`--block-base-port ${blockBasePort} is too high for ${blockCount} ` +
|
|
23
|
-
`block servers; the last block port would be ${lastPort}, but ports ` +
|
|
24
|
-
`cannot exceed ${MAX_PORT}.`);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
/** Reject a shell port that overlaps the sequential block-port range. */
|
|
28
|
-
export function validateShellPort(shellPort, blockBasePort, blockCount) {
|
|
29
|
-
if (blockCount > 0 &&
|
|
30
|
-
shellPort >= blockBasePort &&
|
|
31
|
-
shellPort < blockBasePort + blockCount) {
|
|
32
|
-
throw new Error(`--port ${shellPort} collides with the block server ports ` +
|
|
33
|
-
`(${blockBasePort}–${blockBasePort + blockCount - 1}); ` +
|
|
34
|
-
`pick a port outside that range or move --block-base-port.`);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* entry point for `ntn workers customblocks dev` and `npx @notionhq/custom-blocks-dev-shell`.
|
|
4
4
|
*
|
|
5
5
|
* The shared launcher orchestrates building the worker, reading its manifest,
|
|
6
|
-
*
|
|
6
|
+
* creating one Vite middleware instance per custom block, and owning the ports, output, and
|
|
7
7
|
* lifecycle. This entry point starts the dev shell and supplies the package's
|
|
8
8
|
* prebuilt shell adapter with the block registry and data sources.
|
|
9
9
|
*
|
|
@@ -17,18 +17,17 @@ import { readDataSources } from "./data-sources.js";
|
|
|
17
17
|
import { launchDevShell } from "./dev-shell-launcher.js";
|
|
18
18
|
import { formatUnknownErrorWithStack } from "./errors.js";
|
|
19
19
|
import { copyPrebuiltDataSources } from "./prebuilt.js";
|
|
20
|
-
import {
|
|
20
|
+
import { createUiHandler } from "./serve-ui.js";
|
|
21
21
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
22
|
-
const createShellLaunch = async ({
|
|
22
|
+
const createShellLaunch = async ({ plan, shared, log }) => {
|
|
23
23
|
const distDir = resolve(__dirname, "..", "dist");
|
|
24
24
|
if (!existsSync(join(distDir, "index.html"))) {
|
|
25
25
|
throw new Error(`No prebuilt UI found at ${distDir}. This package was not assembled ` +
|
|
26
26
|
`correctly; reinstall it.`);
|
|
27
27
|
}
|
|
28
28
|
const prebuiltDir = resolve(__dirname, "..", "data");
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
server = await serveUi(distDir, args.shellPort, {
|
|
29
|
+
shared.routes.set("localhost", {
|
|
30
|
+
handle: createUiHandler(distDir, {
|
|
32
31
|
blocks: plan.registry,
|
|
33
32
|
dataSources: plan.dataSources,
|
|
34
33
|
prebuiltFilenames: readDataSources(prebuiltDir).map(source => source.filename),
|
|
@@ -38,25 +37,8 @@ const createShellLaunch = async ({ args, plan, log }) => {
|
|
|
38
37
|
log(basename(plan.workerDir), `Added example data sources: ${written.join(", ")}`);
|
|
39
38
|
}
|
|
40
39
|
return readDataSources(plan.dataDir);
|
|
41
|
-
})
|
|
42
|
-
}
|
|
43
|
-
catch (error) {
|
|
44
|
-
const code = error.code;
|
|
45
|
-
if (code === "EADDRINUSE") {
|
|
46
|
-
throw new Error(`Port ${args.shellPort} is already in use. Stop whatever holds it ` +
|
|
47
|
-
`or rerun with --port <port> (and --block-base-port <port> for the ` +
|
|
48
|
-
`block servers).`);
|
|
49
|
-
}
|
|
50
|
-
throw error;
|
|
51
|
-
}
|
|
52
|
-
return {
|
|
53
|
-
processes: [],
|
|
54
|
-
resources: [
|
|
55
|
-
() => new Promise(resolve => {
|
|
56
|
-
server.close(() => resolve());
|
|
57
|
-
}),
|
|
58
|
-
],
|
|
59
|
-
};
|
|
40
|
+
}),
|
|
41
|
+
});
|
|
60
42
|
};
|
|
61
43
|
async function main() {
|
|
62
44
|
const argv = process.argv.slice(2);
|
package/dist-cli/serve-ui.js
CHANGED
|
@@ -8,7 +8,6 @@
|
|
|
8
8
|
* that global over the baked-in env values.
|
|
9
9
|
*/
|
|
10
10
|
import { readFileSync } from "node:fs";
|
|
11
|
-
import { createServer } from "node:http";
|
|
12
11
|
import { extname, join, normalize, resolve, sep } from "node:path";
|
|
13
12
|
import { formatUnknownError } from "./errors.js";
|
|
14
13
|
const CONTENT_TYPES = {
|
|
@@ -26,27 +25,27 @@ const CONTENT_TYPES = {
|
|
|
26
25
|
};
|
|
27
26
|
/** `index.html` with the runtime config injected ahead of the bundle script. */
|
|
28
27
|
function injectConfig(html, config) {
|
|
29
|
-
const tag = `<script>window.__DEV_SHELL_CONFIG__ = ${JSON.stringify(config)}</script>`;
|
|
28
|
+
const tag = `<script>window.__DEV_SHELL_CONFIG__ = ${JSON.stringify(config).replace(/</g, "\\u003c")}</script>`;
|
|
30
29
|
if (html.includes("<head>")) {
|
|
31
30
|
return html.replace("<head>", `<head>\n\t\t${tag}`);
|
|
32
31
|
}
|
|
33
32
|
return `${tag}\n${html}`;
|
|
34
33
|
}
|
|
35
34
|
/**
|
|
36
|
-
* Serve `distDir`
|
|
37
|
-
* `index.html`.
|
|
35
|
+
* Serve `distDir` as a request handler. Unknown extensionless paths fall back to
|
|
36
|
+
* `index.html`.
|
|
38
37
|
*
|
|
39
38
|
* `addPrebuiltData`, when given, backs `POST /api/prebuilt-data`: it writes
|
|
40
39
|
* the pre-built sources into the worker's data directory and returns
|
|
41
40
|
* the directory's updated contents.
|
|
42
41
|
*/
|
|
43
|
-
export function
|
|
42
|
+
export function createUiHandler(distDir, config, addPrebuiltData) {
|
|
44
43
|
const dist = resolve(distDir);
|
|
45
44
|
const rawIndexHtml = readFileSync(join(dist, "index.html"), "utf-8");
|
|
46
45
|
// Server-owned: updated by the add endpoint, while the caller's `config`
|
|
47
46
|
// stays an untouched input.
|
|
48
47
|
let dataSources = config.dataSources;
|
|
49
|
-
|
|
48
|
+
return (req, res) => {
|
|
50
49
|
let urlPath;
|
|
51
50
|
try {
|
|
52
51
|
urlPath = decodeURIComponent(req.url?.split("?", 1)[0] ?? "/");
|
|
@@ -107,11 +106,5 @@ export function serveUi(distDir, port, config, addPrebuiltData) {
|
|
|
107
106
|
res.writeHead(404);
|
|
108
107
|
res.end();
|
|
109
108
|
}
|
|
110
|
-
}
|
|
111
|
-
return new Promise((resolvePromise, reject) => {
|
|
112
|
-
server.once("error", reject);
|
|
113
|
-
// Loopback only: every response embeds the worker's block registry, and
|
|
114
|
-
// the per-block Vite servers are localhost-only too.
|
|
115
|
-
server.listen(port, "127.0.0.1", () => resolvePromise(server));
|
|
116
|
-
});
|
|
109
|
+
};
|
|
117
110
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
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
|
+
}
|