@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
package/src/serve.js
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `serve()`: the skeleton of a type server. One process per type, started by
|
|
3
|
+
* the daemon through `entry.start` (or by hand). It listens on `OPEN_ARTIFACTS_PORT` (or
|
|
4
|
+
* a free port), prints the {@link ReadyLine}, answers the daemon's `/__open-artifacts/*`
|
|
5
|
+
* routes behind `Bearer OPEN_ARTIFACTS_SECRET`, and hands every request under
|
|
6
|
+
* `/<kind>/<token>/` to that artifact's {@link Site}.
|
|
7
|
+
*
|
|
8
|
+
* A type plugs in with `mountSite(root, context)`, which returns a
|
|
9
|
+
* {@link Site}: the object that serves one artifact's pages.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { EventEmitter } from 'node:events';
|
|
13
|
+
import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { createServer } from 'node:http';
|
|
15
|
+
import { hostname } from 'node:os';
|
|
16
|
+
import { basename, isAbsolute, join, resolve } from 'node:path';
|
|
17
|
+
import { threadId } from 'node:worker_threads';
|
|
18
|
+
import { WorkspaceDirectory } from '@openartifactsai/protocol/workspace-files';
|
|
19
|
+
import { OPEN_ARTIFACTS_PROTOCOL, OpenArtifactsError, TYPE_SERVER_ROUTES, adoptLegacyRequest, currentActionName, errorBody, withLegacyMarker, } from '@openartifactsai/protocol';
|
|
20
|
+
import { TypeApi } from "./daemon.js";
|
|
21
|
+
import { LanNetwork } from "./lan.js";
|
|
22
|
+
import { acceptWebSocket } from "./ws.js";
|
|
23
|
+
import { sendArchive } from "./zip.js";
|
|
24
|
+
/** Protocol version this SDK speaks. */
|
|
25
|
+
export const PROTOCOL = OPEN_ARTIFACTS_PROTOCOL;
|
|
26
|
+
/** File a mounted artifact's folder gets, naming the server that serves it. */
|
|
27
|
+
export const STATE_FILE = '.artifact-server.json';
|
|
28
|
+
/** Per-artifact log file, in the artifact folder. */
|
|
29
|
+
const LOG_FILE = '.artifact-server.log';
|
|
30
|
+
/** WebSocket subprotocol that carries a site's server-sent event stream. */
|
|
31
|
+
export const STREAM_PROTOCOL = 'baoyu-sse';
|
|
32
|
+
/** Close codes at and above this one mean "the stream was refused with HTTP status (code - 4000)". */
|
|
33
|
+
const STREAM_REFUSED = 4000;
|
|
34
|
+
/** Host of an artifact's own origin: `<artifact id>.frame.localhost:<port>`. */
|
|
35
|
+
const CONTENT_HOST = /^(art_[0-9a-z]+)\.frame\.localhost:(\d+)$/;
|
|
36
|
+
const isLoopback = (address) => address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
|
|
37
|
+
/** What a long action's call answers with, besides its task id. */
|
|
38
|
+
export const LONG_ACTION_NOTE = 'This action runs in the background: its result comes to you as a message that starts with "[Artifact task finished]".';
|
|
39
|
+
// ---- helpers ---------------------------------------------------------------------------------------------------------
|
|
40
|
+
function sendJson(res, status, body) {
|
|
41
|
+
const text = JSON.stringify(body ?? null);
|
|
42
|
+
res.writeHead(status, {
|
|
43
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
44
|
+
'Cache-Control': 'no-store',
|
|
45
|
+
'Content-Length': Buffer.byteLength(text),
|
|
46
|
+
});
|
|
47
|
+
res.end(text);
|
|
48
|
+
}
|
|
49
|
+
function readJsonBody(req, limit = 8 << 20) {
|
|
50
|
+
return new Promise((resolvePromise, reject) => {
|
|
51
|
+
const chunks = [];
|
|
52
|
+
let size = 0;
|
|
53
|
+
req.on('data', (chunk) => {
|
|
54
|
+
size += chunk.length;
|
|
55
|
+
if (size > limit) {
|
|
56
|
+
reject(new OpenArtifactsError('too_large', 'The request body is too large.', { status: 413 }));
|
|
57
|
+
req.destroy();
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
chunks.push(chunk);
|
|
61
|
+
});
|
|
62
|
+
req.on('end', () => {
|
|
63
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
64
|
+
if (!text)
|
|
65
|
+
return resolvePromise({});
|
|
66
|
+
try {
|
|
67
|
+
const value = JSON.parse(text);
|
|
68
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
69
|
+
resolvePromise(value);
|
|
70
|
+
else
|
|
71
|
+
reject(new OpenArtifactsError('invalid_argument', 'The body is not a JSON object.', { status: 400 }));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
reject(new OpenArtifactsError('invalid_argument', 'The body is not JSON.', { status: 400 }));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
req.on('error', reject);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function listenOn(server, port, host) {
|
|
81
|
+
return new Promise((resolvePromise, reject) => {
|
|
82
|
+
const onError = (error) => {
|
|
83
|
+
server.off('listening', onListening);
|
|
84
|
+
reject(error);
|
|
85
|
+
};
|
|
86
|
+
const onListening = () => {
|
|
87
|
+
server.off('error', onError);
|
|
88
|
+
resolvePromise(server.address().port);
|
|
89
|
+
};
|
|
90
|
+
server.once('error', onError);
|
|
91
|
+
server.once('listening', onListening);
|
|
92
|
+
server.listen(port, host);
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const notFound = (res) => {
|
|
96
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }).end('Not found');
|
|
97
|
+
};
|
|
98
|
+
// ---- StreamResponse --------------------------------------------------------------------------------------------------
|
|
99
|
+
/**
|
|
100
|
+
* The part of an HTTP response a site's event-stream handler uses, carried
|
|
101
|
+
* over one WebSocket: every `write` is one text message, `end` closes it
|
|
102
|
+
* (with `4000 + status` when the handler refused the stream). Emits `close`
|
|
103
|
+
* when the client goes away.
|
|
104
|
+
*/
|
|
105
|
+
export class StreamResponse extends EventEmitter {
|
|
106
|
+
/** The WebSocket the stream goes out on. */
|
|
107
|
+
ws;
|
|
108
|
+
/** Status the handler set. */
|
|
109
|
+
statusCode = 200;
|
|
110
|
+
/** Mirrors `ServerResponse.headersSent`. */
|
|
111
|
+
headersSent = false;
|
|
112
|
+
/** Mirrors `ServerResponse.writableEnded`. */
|
|
113
|
+
writableEnded = false;
|
|
114
|
+
/** Mirrors `ServerResponse.destroyed`. */
|
|
115
|
+
destroyed = false;
|
|
116
|
+
/** Wraps an accepted WebSocket. */
|
|
117
|
+
constructor(ws) {
|
|
118
|
+
super();
|
|
119
|
+
this.ws = ws;
|
|
120
|
+
}
|
|
121
|
+
/** Records the status; headers do not travel. */
|
|
122
|
+
writeHead(status, ..._rest) {
|
|
123
|
+
this.statusCode = status;
|
|
124
|
+
this.headersSent = true;
|
|
125
|
+
return this;
|
|
126
|
+
}
|
|
127
|
+
/** Headers do not travel; a no-op. */
|
|
128
|
+
setHeader(..._args) {
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
/** A no-op. */
|
|
132
|
+
flushHeaders() { }
|
|
133
|
+
/** Sends `chunk` as one text message while the stream is open with status 200. */
|
|
134
|
+
write(chunk) {
|
|
135
|
+
if (this.statusCode === 200 && !this.writableEnded)
|
|
136
|
+
this.ws.sendText(String(chunk));
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
/** Ends the stream, closing the WebSocket. */
|
|
140
|
+
end(chunk) {
|
|
141
|
+
if (this.writableEnded)
|
|
142
|
+
return this;
|
|
143
|
+
if (chunk !== undefined)
|
|
144
|
+
this.write(chunk);
|
|
145
|
+
this.writableEnded = true;
|
|
146
|
+
this.ws.close(this.statusCode === 200 ? 1000 : STREAM_REFUSED + Math.min(this.statusCode, 999));
|
|
147
|
+
return this;
|
|
148
|
+
}
|
|
149
|
+
/** Ends the stream. */
|
|
150
|
+
destroy() {
|
|
151
|
+
this.destroyed = true;
|
|
152
|
+
return this.end();
|
|
153
|
+
}
|
|
154
|
+
/** The client went away. */
|
|
155
|
+
closed() {
|
|
156
|
+
this.writableEnded = true;
|
|
157
|
+
this.emit('close');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const stringArg = (args, name) => {
|
|
161
|
+
const value = args[name];
|
|
162
|
+
if (typeof value !== 'string' || !value)
|
|
163
|
+
throw new OpenArtifactsError('invalid_argument', `args.${name} must be a non-empty string.`, { status: 400 });
|
|
164
|
+
return value;
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* The agent's operations on an artifact through a type library: `check`,
|
|
168
|
+
* `upload` and `info` for the agent's `call`, and the reserved `open-artifacts.db.*` and
|
|
169
|
+
* `open-artifacts.comments.*` the ArtifactData and ArtifactComments tools use. `config`
|
|
170
|
+
* is the type's `open-artifacts` block (`style`, `projectDir`).
|
|
171
|
+
*/
|
|
172
|
+
export function libraryActions(lib, config = {}) {
|
|
173
|
+
const style = config.style ?? 'root';
|
|
174
|
+
const target = (root) => (style === 'project' ? join(root, config.projectDir ?? 'project') : root);
|
|
175
|
+
const actions = {};
|
|
176
|
+
if (typeof lib.check === 'function') {
|
|
177
|
+
const check = lib.check.bind(lib);
|
|
178
|
+
actions.check = { title: 'Check the artifact', run: async ({ root }) => ({ check: await check(target(root)) }) };
|
|
179
|
+
}
|
|
180
|
+
if (typeof lib.upload === 'function') {
|
|
181
|
+
const upload = lib.upload.bind(lib);
|
|
182
|
+
actions.upload = {
|
|
183
|
+
title: 'Add a file (args.file: an absolute path; name, group)',
|
|
184
|
+
run: async ({ root }, args) => {
|
|
185
|
+
const file = args.file;
|
|
186
|
+
if (typeof file !== 'string' || !isAbsolute(file))
|
|
187
|
+
throw new OpenArtifactsError('invalid_argument', 'upload: args.file is an absolute path.', { status: 400 });
|
|
188
|
+
const name = typeof args.name === 'string' && args.name ? args.name : basename(file);
|
|
189
|
+
if (style === 'project')
|
|
190
|
+
return { upload: await upload(target(root), new Uint8Array(readFileSync(file)), name, args.group) };
|
|
191
|
+
return { upload: await upload(target(root), file, name) };
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
actions.info = {
|
|
196
|
+
title: 'What the artifact holds',
|
|
197
|
+
run: async ({ root }) => ({ info: typeof lib.readInfo === 'function' ? await lib.readInfo(target(root)) : null }),
|
|
198
|
+
};
|
|
199
|
+
if (typeof lib.readDb === 'function' && typeof lib.writeDb === 'function') {
|
|
200
|
+
const readDb = lib.readDb.bind(lib);
|
|
201
|
+
const writeDb = lib.writeDb.bind(lib);
|
|
202
|
+
actions['open-artifacts.db.read'] = {
|
|
203
|
+
hidden: true,
|
|
204
|
+
run: ({ root }, args) => readDb(root, typeof args.path === 'string' && args.path ? args.path : undefined, { query: args.query, limit: args.limit, cursor: args.cursor }),
|
|
205
|
+
};
|
|
206
|
+
actions['open-artifacts.db.write'] = {
|
|
207
|
+
hidden: true,
|
|
208
|
+
run: async ({ root }, args) => ({ writes: await writeDb(root, Array.isArray(args.writes) ? args.writes : [], { requireIfMatch: args.require_if_match === true }) }),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
if (typeof lib.commentThreads === 'function') {
|
|
212
|
+
const threads = lib.commentThreads.bind(lib);
|
|
213
|
+
actions['open-artifacts.comments.read'] = { hidden: true, run: async ({ root }, args) => ({ threads: await threads(root, !!args.all) }) };
|
|
214
|
+
if (typeof lib.replyComment === 'function') {
|
|
215
|
+
const reply = lib.replyComment.bind(lib);
|
|
216
|
+
actions['open-artifacts.comments.reply'] = {
|
|
217
|
+
hidden: true,
|
|
218
|
+
run: async ({ root }, args) => ({ thread: await reply(root, stringArg(args, 'thread_id'), stringArg(args, 'text'), !!args.resolve) }),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
if (typeof lib.resolveComment === 'function') {
|
|
222
|
+
const resolveComment = lib.resolveComment.bind(lib);
|
|
223
|
+
actions['open-artifacts.comments.resolve'] = {
|
|
224
|
+
hidden: true,
|
|
225
|
+
run: async ({ root }, args) => ({ thread: await resolveComment(root, stringArg(args, 'thread_id'), !!args.reopen) }),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return actions;
|
|
230
|
+
}
|
|
231
|
+
/** The type's `artifact-type.json`, read from `dir` (default `OPEN_ARTIFACTS_TYPE_DIR`); `{}` when there is none. */
|
|
232
|
+
export function typeManifest(dir = process.env.OPEN_ARTIFACTS_TYPE_DIR) {
|
|
233
|
+
if (!dir)
|
|
234
|
+
return {};
|
|
235
|
+
try {
|
|
236
|
+
const value = JSON.parse(readFileSync(join(dir, 'artifact-type.json'), 'utf8'));
|
|
237
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
return {};
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** A type server built on the SDK: the `/__open-artifacts/*` routes plus routing to each artifact's site. */
|
|
244
|
+
export class TypeServer {
|
|
245
|
+
/** Type id. */
|
|
246
|
+
type;
|
|
247
|
+
/** Version reported by `/__open-artifacts/health`. */
|
|
248
|
+
version;
|
|
249
|
+
/** The Type API client. */
|
|
250
|
+
daemon;
|
|
251
|
+
/** Diagnostic log. */
|
|
252
|
+
log;
|
|
253
|
+
/** The loopback HTTP server. */
|
|
254
|
+
server;
|
|
255
|
+
/** The LAN listeners. */
|
|
256
|
+
lan;
|
|
257
|
+
/** Port once listening. */
|
|
258
|
+
port = 0;
|
|
259
|
+
options;
|
|
260
|
+
secret;
|
|
261
|
+
idleMs;
|
|
262
|
+
byId = new Map();
|
|
263
|
+
byPage = new Map();
|
|
264
|
+
mounting = new Map();
|
|
265
|
+
hosts = new Set();
|
|
266
|
+
lastActivity = Date.now();
|
|
267
|
+
timer = null;
|
|
268
|
+
/** Creates the server; call {@link listen} next. */
|
|
269
|
+
constructor(options) {
|
|
270
|
+
if (typeof options?.mountSite !== 'function')
|
|
271
|
+
throw new TypeError('serve() needs mountSite(root, context).');
|
|
272
|
+
this.options = options;
|
|
273
|
+
this.type = options.type ?? process.env.OPEN_ARTIFACTS_TYPE ?? 'type';
|
|
274
|
+
this.version = options.version ?? '0';
|
|
275
|
+
this.secret = options.secret !== undefined ? options.secret : process.env.OPEN_ARTIFACTS_SECRET || null;
|
|
276
|
+
this.daemon = options.daemon ?? new TypeApi();
|
|
277
|
+
this.log = options.log ?? ((line) => process.stderr.write(`[${new Date().toISOString()}] ${line}\n`));
|
|
278
|
+
this.idleMs = options.idleMs ?? Number(process.env.OPEN_ARTIFACTS_SERVER_IDLE_MS ?? 15 * 60_000);
|
|
279
|
+
this.server = this.makeServer();
|
|
280
|
+
this.lan = new LanNetwork({
|
|
281
|
+
port: () => this.port,
|
|
282
|
+
createServer: () => this.makeServer(),
|
|
283
|
+
stillShared: () => this.anySharing(),
|
|
284
|
+
log: (line) => this.log(line),
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
/** `http://127.0.0.1:<port>`, without a trailing slash. */
|
|
288
|
+
get origin() {
|
|
289
|
+
return `http://127.0.0.1:${this.port}`;
|
|
290
|
+
}
|
|
291
|
+
/** Number of mounted artifacts. */
|
|
292
|
+
get openCount() {
|
|
293
|
+
return this.byId.size;
|
|
294
|
+
}
|
|
295
|
+
makeServer() {
|
|
296
|
+
const server = createServer((req, res) => {
|
|
297
|
+
this.onRequest(req, res).catch((error) => {
|
|
298
|
+
if (res.headersSent)
|
|
299
|
+
return void res.destroy();
|
|
300
|
+
const status = error?.status;
|
|
301
|
+
sendJson(res, typeof status === 'number' ? status : 500, errorBody(error));
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
server.on('upgrade', (req, socket, head) => this.onUpgrade(req, socket, head));
|
|
305
|
+
return server;
|
|
306
|
+
}
|
|
307
|
+
/** Listens on the configured port, or any free one when it is taken. */
|
|
308
|
+
async listen() {
|
|
309
|
+
const want = this.options.port ?? Number(process.env.OPEN_ARTIFACTS_PORT || 0);
|
|
310
|
+
const host = this.options.host ?? '127.0.0.1';
|
|
311
|
+
try {
|
|
312
|
+
this.port = await listenOn(this.server, want, host);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (error.code !== 'EADDRINUSE' || !want)
|
|
316
|
+
throw error;
|
|
317
|
+
// The last port is taken: any free one (share links name the port, so the daemon offers the same one first).
|
|
318
|
+
this.port = await listenOn(this.server, 0, host);
|
|
319
|
+
}
|
|
320
|
+
this.hosts = new Set([`127.0.0.1:${this.port}`, `localhost:${this.port}`, `[::1]:${this.port}`]);
|
|
321
|
+
this.timer = setInterval(() => this.tick(), 60_000);
|
|
322
|
+
this.timer.unref();
|
|
323
|
+
return this;
|
|
324
|
+
}
|
|
325
|
+
/** The line the daemon waits for, with the protocol version and type for logs. */
|
|
326
|
+
readyLine() {
|
|
327
|
+
// Both markers: a daemon from before the rename may start this server and waits for `openArtifact: 'ready'`.
|
|
328
|
+
return withLegacyMarker({ openArtifacts: 'ready', url: `${this.origin}/`, protocol: PROTOCOL, type: this.type });
|
|
329
|
+
}
|
|
330
|
+
/** Prints the ready line to `out` (default stdout). */
|
|
331
|
+
ready(out = process.stdout) {
|
|
332
|
+
out.write(`${JSON.stringify(this.readyLine())}\n`);
|
|
333
|
+
}
|
|
334
|
+
tick() {
|
|
335
|
+
if (this.idleMs <= 0)
|
|
336
|
+
return;
|
|
337
|
+
const now = Date.now();
|
|
338
|
+
// Sites nobody asked anything of for a while, with no stream open and not shared, go.
|
|
339
|
+
for (const entry of [...this.byId.values()]) {
|
|
340
|
+
if (entry.streams <= 0 && now - entry.lastUsed > this.idleMs && !this.sharing(entry))
|
|
341
|
+
this.unmount(entry.id);
|
|
342
|
+
}
|
|
343
|
+
if (!this.byId.size && now - this.lastActivity > this.idleMs) {
|
|
344
|
+
this.log('idle: exiting');
|
|
345
|
+
if (this.options.onIdle)
|
|
346
|
+
this.options.onIdle();
|
|
347
|
+
else {
|
|
348
|
+
this.close();
|
|
349
|
+
process.exit(0);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
sharing(entry) {
|
|
354
|
+
return !!entry.site.share?.listening;
|
|
355
|
+
}
|
|
356
|
+
anySharing() {
|
|
357
|
+
return [...this.byId.values()].some((entry) => this.sharing(entry));
|
|
358
|
+
}
|
|
359
|
+
hostAllowed(req) {
|
|
360
|
+
const host = String(req.headers.host ?? '');
|
|
361
|
+
return this.hosts.has(host) || this.lan.hostAllowed(host) || this.contentIdOf(req) !== null;
|
|
362
|
+
}
|
|
363
|
+
/** The artifact id of a request on an artifact's own origin, or null. */
|
|
364
|
+
contentIdOf(req) {
|
|
365
|
+
if (!this.options.contentHosts || !this.port)
|
|
366
|
+
return null;
|
|
367
|
+
const match = CONTENT_HOST.exec(String(req.headers.host ?? '').toLowerCase());
|
|
368
|
+
if (!match || Number(match[2]) !== this.port || !isLoopback(req.socket.remoteAddress))
|
|
369
|
+
return null;
|
|
370
|
+
return match[1];
|
|
371
|
+
}
|
|
372
|
+
/** The mounted site whose own origin a request is on, or null when it is not on one. */
|
|
373
|
+
contentEntry(req) {
|
|
374
|
+
const id = this.contentIdOf(req);
|
|
375
|
+
if (id === null)
|
|
376
|
+
return null;
|
|
377
|
+
return { entry: this.byId.get(id) ?? null };
|
|
378
|
+
}
|
|
379
|
+
// ---- artifacts -----------------------------------------------------------------------------------------------------
|
|
380
|
+
/** Mounts an artifact (or finds it mounted); idempotent. */
|
|
381
|
+
async open(request) {
|
|
382
|
+
const { id, root, title } = request;
|
|
383
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(id))
|
|
384
|
+
throw new OpenArtifactsError('invalid_argument', 'open needs an artifact id.', { status: 400 });
|
|
385
|
+
if (typeof root !== 'string' || !isAbsolute(root)) {
|
|
386
|
+
throw new OpenArtifactsError('invalid_argument', 'open needs the artifact root (an absolute path).', { status: 400 });
|
|
387
|
+
}
|
|
388
|
+
const have = this.byId.get(id);
|
|
389
|
+
const identity = request.workspaceDirectory;
|
|
390
|
+
const workspace = identity ? new WorkspaceDirectory(identity.root, identity) : have?.workspace;
|
|
391
|
+
const target = workspace?.resolve(root) ?? resolve(root);
|
|
392
|
+
if (have && have.root === target && have.workspace?.root === workspace?.root) {
|
|
393
|
+
have.lastUsed = Date.now();
|
|
394
|
+
if (title)
|
|
395
|
+
have.title = title;
|
|
396
|
+
return have;
|
|
397
|
+
}
|
|
398
|
+
if (have)
|
|
399
|
+
this.unmount(id);
|
|
400
|
+
const busy = this.mounting.get(id);
|
|
401
|
+
if (busy)
|
|
402
|
+
return busy;
|
|
403
|
+
const work = this.mount(id, target, title, workspace).finally(() => this.mounting.delete(id));
|
|
404
|
+
this.mounting.set(id, work);
|
|
405
|
+
return work;
|
|
406
|
+
}
|
|
407
|
+
async mount(id, root, title, workspace) {
|
|
408
|
+
if (!existsSync(root))
|
|
409
|
+
throw new OpenArtifactsError('not_found', `The folder ${root} is gone.`, { status: 404 });
|
|
410
|
+
const logPath = join(root, LOG_FILE);
|
|
411
|
+
const log = (line) => {
|
|
412
|
+
try {
|
|
413
|
+
appendFileSync(workspace ? new WorkspaceDirectory(workspace.resolve(root)).resolve(logPath) : logPath, `[${new Date().toISOString()}] ${line}\n`);
|
|
414
|
+
}
|
|
415
|
+
catch {
|
|
416
|
+
// A read-only or vanished folder.
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
let agentName;
|
|
420
|
+
try {
|
|
421
|
+
agentName = (await this.daemon.artifact(id)).agentName || undefined;
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
agentName = undefined;
|
|
425
|
+
}
|
|
426
|
+
let agentWakesIdle;
|
|
427
|
+
try {
|
|
428
|
+
agentWakesIdle = (await this.daemon.presence(id)).wakesIdle;
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
agentWakesIdle = undefined;
|
|
432
|
+
}
|
|
433
|
+
const wake = async (body) => {
|
|
434
|
+
const out = await this.daemon.wake(id, body);
|
|
435
|
+
if (out.status === 'failed')
|
|
436
|
+
throw new OpenArtifactsError('daemon_failed', 'The agent could not be reached.');
|
|
437
|
+
return out;
|
|
438
|
+
};
|
|
439
|
+
const site = await this.options.mountSite(root, {
|
|
440
|
+
id,
|
|
441
|
+
title: title ?? '',
|
|
442
|
+
workspace,
|
|
443
|
+
daemon: this.daemon,
|
|
444
|
+
log,
|
|
445
|
+
network: this.lan.network,
|
|
446
|
+
local: (req) => isLoopback(req.socket.remoteAddress),
|
|
447
|
+
agentHook: { thread: (view) => wake({ threads: [view] }), request: (request) => wake({ requests: [request] }) },
|
|
448
|
+
...(agentName ? { agentName } : {}),
|
|
449
|
+
...(agentWakesIdle === false ? { agentWakesIdle } : {}),
|
|
450
|
+
contentOrigin: this.options.contentHosts && CONTENT_HOST.test(`${id}.frame.localhost:${this.port}`) ? `http://${id}.frame.localhost:${this.port}` : null,
|
|
451
|
+
open: async () => {
|
|
452
|
+
throw new OpenArtifactsError('unsupported', 'Opening another folder from a page is not supported here.');
|
|
453
|
+
},
|
|
454
|
+
});
|
|
455
|
+
const other = this.byPage.get(site.page);
|
|
456
|
+
if (other) {
|
|
457
|
+
site.close();
|
|
458
|
+
throw new OpenArtifactsError('conflict', `${other.root} is already open at ${site.page}.`, { status: 409 });
|
|
459
|
+
}
|
|
460
|
+
const entry = { id, root, title: title ?? '', site, page: site.page, workspace, streams: 0, lastUsed: Date.now() };
|
|
461
|
+
this.byId.set(id, entry);
|
|
462
|
+
this.byPage.set(site.page, entry);
|
|
463
|
+
try {
|
|
464
|
+
await site.share?.start?.(false);
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
this.unmount(id);
|
|
468
|
+
throw error;
|
|
469
|
+
}
|
|
470
|
+
try {
|
|
471
|
+
const record = {
|
|
472
|
+
pid: process.pid,
|
|
473
|
+
...(threadId ? { thread: threadId } : {}),
|
|
474
|
+
url: `${this.origin}${site.page}`,
|
|
475
|
+
port: this.port,
|
|
476
|
+
root,
|
|
477
|
+
kind: site.page.split('/')[1] ?? '',
|
|
478
|
+
startedAt: new Date().toISOString(),
|
|
479
|
+
openArtifacts: id,
|
|
480
|
+
};
|
|
481
|
+
writeFileSync(join(root, STATE_FILE), `${JSON.stringify(record, null, 2)}\n`);
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
// Tools looking for this server will not find it; the page still works.
|
|
485
|
+
}
|
|
486
|
+
this.log(`mounted ${id} at ${site.page}`);
|
|
487
|
+
log(`serving ${root} at ${this.origin}${site.page} (open-artifacts type server ${this.type})`);
|
|
488
|
+
return entry;
|
|
489
|
+
}
|
|
490
|
+
/** Unmounts an artifact; false when it was not mounted. */
|
|
491
|
+
unmount(id) {
|
|
492
|
+
const entry = this.byId.get(id);
|
|
493
|
+
if (!entry)
|
|
494
|
+
return false;
|
|
495
|
+
this.byId.delete(id);
|
|
496
|
+
this.byPage.delete(entry.page);
|
|
497
|
+
try {
|
|
498
|
+
const file = join(entry.root, STATE_FILE);
|
|
499
|
+
const state = JSON.parse(readFileSync(file, 'utf8'));
|
|
500
|
+
if (state.pid === process.pid && (state.thread ?? 0) === threadId)
|
|
501
|
+
rmSync(file, { force: true });
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
// Nothing written, or someone else's.
|
|
505
|
+
}
|
|
506
|
+
try {
|
|
507
|
+
entry.site.close();
|
|
508
|
+
}
|
|
509
|
+
catch (error) {
|
|
510
|
+
this.log(`closing ${id}: ${error instanceof Error ? error.message : String(error)}`);
|
|
511
|
+
}
|
|
512
|
+
return true;
|
|
513
|
+
}
|
|
514
|
+
/** The site whose address `pathname` is under, with the path below it. */
|
|
515
|
+
under(pathname) {
|
|
516
|
+
const [, first, second] = pathname.split('/');
|
|
517
|
+
const entry = first && second ? this.byPage.get(`/${first}/${second}/`) : undefined;
|
|
518
|
+
if (entry)
|
|
519
|
+
return { entry, rest: pathname.slice(entry.page.length - 1) };
|
|
520
|
+
for (const e of this.byPage.values())
|
|
521
|
+
if (e.site.claims?.(pathname))
|
|
522
|
+
return { entry: e, rest: pathname };
|
|
523
|
+
return null;
|
|
524
|
+
}
|
|
525
|
+
/** The site of the page that referred this request (same host only). */
|
|
526
|
+
referred(req) {
|
|
527
|
+
const referer = req.headers.referer;
|
|
528
|
+
if (typeof referer !== 'string')
|
|
529
|
+
return null;
|
|
530
|
+
try {
|
|
531
|
+
const at = new URL(referer);
|
|
532
|
+
return at.host === req.headers.host ? (this.under(at.pathname)?.entry ?? null) : null;
|
|
533
|
+
}
|
|
534
|
+
catch {
|
|
535
|
+
return null;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
requireAuthorized(entry) {
|
|
539
|
+
if (entry.workspace && entry.workspace.resolve(entry.root) !== entry.root) {
|
|
540
|
+
throw new OpenArtifactsError('not_granted', 'The authorized artifact directory changed.', { status: 403 });
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
/** The site that answers a path outside every site's address: share links, uploads, common paths, the referrer. */
|
|
544
|
+
async answering(req, pathname) {
|
|
545
|
+
const link = /^\/s\/([A-Za-z0-9_-]{16,64})$/.exec(pathname);
|
|
546
|
+
if (link)
|
|
547
|
+
return [...this.byPage.values()].find((e) => e.site.share?.sharing?.linkRole?.(link[1])) ?? null;
|
|
548
|
+
const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(pathname);
|
|
549
|
+
if (blob) {
|
|
550
|
+
const referred = this.referred(req);
|
|
551
|
+
const all = [...this.byPage.values()];
|
|
552
|
+
for (const e of referred ? [referred, ...all.filter((x) => x !== referred)] : all)
|
|
553
|
+
if (await e.site.hasBlob?.(blob[1]))
|
|
554
|
+
return e;
|
|
555
|
+
return null;
|
|
556
|
+
}
|
|
557
|
+
for (const e of this.byPage.values())
|
|
558
|
+
if (e.site.common?.(pathname))
|
|
559
|
+
return e;
|
|
560
|
+
return this.referred(req);
|
|
561
|
+
}
|
|
562
|
+
// ---- requests ------------------------------------------------------------------------------------------------------
|
|
563
|
+
async onRequest(req, res) {
|
|
564
|
+
this.lastActivity = Date.now();
|
|
565
|
+
if (!this.hostAllowed(req)) {
|
|
566
|
+
req.resume();
|
|
567
|
+
res.writeHead(421, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Misdirected request');
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const content = this.contentEntry(req);
|
|
571
|
+
if (content) {
|
|
572
|
+
const site = content.entry?.site;
|
|
573
|
+
if (!content.entry || !site?.content) {
|
|
574
|
+
req.resume();
|
|
575
|
+
return notFound(res);
|
|
576
|
+
}
|
|
577
|
+
this.requireAuthorized(content.entry);
|
|
578
|
+
content.entry.lastUsed = Date.now();
|
|
579
|
+
await site.content(req, res);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
// A daemon from before the rename asks `/__open-artifact/*`: the same routes.
|
|
583
|
+
adoptLegacyRequest(req);
|
|
584
|
+
const url = new URL(req.url ?? '/', 'http://local');
|
|
585
|
+
if (url.pathname.startsWith('/__open-artifacts/'))
|
|
586
|
+
return this.openArtifactsRoute(req, res, url);
|
|
587
|
+
return this.siteRequest(req, res, url);
|
|
588
|
+
}
|
|
589
|
+
async siteRequest(req, res, url) {
|
|
590
|
+
const at = this.under(url.pathname);
|
|
591
|
+
if (at) {
|
|
592
|
+
this.requireAuthorized(at.entry);
|
|
593
|
+
at.entry.lastUsed = Date.now();
|
|
594
|
+
if (at.rest === '') {
|
|
595
|
+
req.resume();
|
|
596
|
+
res.writeHead(308, { Location: `${url.pathname}/${url.search}`, 'Cache-Control': 'no-store' }).end();
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
req.url = `${at.rest}${url.search}`;
|
|
600
|
+
await at.entry.site.handle(req, res);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const entry = await this.answering(req, url.pathname);
|
|
604
|
+
if (entry) {
|
|
605
|
+
this.requireAuthorized(entry);
|
|
606
|
+
entry.lastUsed = Date.now();
|
|
607
|
+
await entry.site.handle(req, res);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
req.resume();
|
|
611
|
+
notFound(res);
|
|
612
|
+
}
|
|
613
|
+
/** The daemon's routes: from this computer, with the secret, never from a page. */
|
|
614
|
+
async openArtifactsRoute(req, res, url) {
|
|
615
|
+
const granted = isLoopback(req.socket.remoteAddress) &&
|
|
616
|
+
(!this.secret || req.headers.authorization === `Bearer ${this.secret}`) &&
|
|
617
|
+
req.headers.origin === undefined;
|
|
618
|
+
if (!granted) {
|
|
619
|
+
req.resume();
|
|
620
|
+
return sendJson(res, 401, { code: 'unauthorized', message: "The /__open-artifacts/* routes are the Open Artifacts daemon's." });
|
|
621
|
+
}
|
|
622
|
+
const path = url.pathname;
|
|
623
|
+
if (path === TYPE_SERVER_ROUTES.archive && this.options.archive) {
|
|
624
|
+
const entry = this.byId.get(url.searchParams.get('id') ?? '');
|
|
625
|
+
if (!entry) {
|
|
626
|
+
req.resume();
|
|
627
|
+
return sendJson(res, 404, { code: 'not_found', message: `${url.searchParams.get('id')} is not open here.`, fix: 'Open it first (/__open-artifacts/open).' });
|
|
628
|
+
}
|
|
629
|
+
this.requireAuthorized(entry);
|
|
630
|
+
entry.lastUsed = Date.now();
|
|
631
|
+
return sendArchive(req, res, entry.root);
|
|
632
|
+
}
|
|
633
|
+
const get = req.method === 'GET';
|
|
634
|
+
const body = get ? {} : await readJsonBody(req);
|
|
635
|
+
const artifact = (id) => {
|
|
636
|
+
const entry = this.byId.get(String(id ?? ''));
|
|
637
|
+
if (!entry)
|
|
638
|
+
throw new OpenArtifactsError('not_found', `${String(id)} is not open here.`, { status: 404, fix: 'Open it first (/__open-artifacts/open).' });
|
|
639
|
+
this.requireAuthorized(entry);
|
|
640
|
+
entry.lastUsed = Date.now();
|
|
641
|
+
return entry;
|
|
642
|
+
};
|
|
643
|
+
if (path === TYPE_SERVER_ROUTES.health) {
|
|
644
|
+
const health = { openArtifacts: 1, type: this.type, version: this.version, open: this.byId.size };
|
|
645
|
+
// Both markers: a daemon from before the rename checks `openArtifact === 1`.
|
|
646
|
+
return sendJson(res, 200, withLegacyMarker(health));
|
|
647
|
+
}
|
|
648
|
+
if (path === TYPE_SERVER_ROUTES.open && !get) {
|
|
649
|
+
const entry = await this.open(body);
|
|
650
|
+
const page = `${this.origin}${entry.page}`;
|
|
651
|
+
const result = { url: page, page_url: page };
|
|
652
|
+
return sendJson(res, 200, result);
|
|
653
|
+
}
|
|
654
|
+
if (path === TYPE_SERVER_ROUTES.close && !get) {
|
|
655
|
+
const { id } = body;
|
|
656
|
+
return sendJson(res, 200, { closed: this.unmount(String(id ?? '')) });
|
|
657
|
+
}
|
|
658
|
+
if (path === TYPE_SERVER_ROUTES.share) {
|
|
659
|
+
const entry = artifact(get ? url.searchParams.get('id') : body.id);
|
|
660
|
+
const share = entry.site.share;
|
|
661
|
+
if (!share || typeof share.shareView !== 'function' || typeof share.share !== 'function') {
|
|
662
|
+
throw new OpenArtifactsError('unsupported', `${this.type} pages cannot be shared.`, { status: 409 });
|
|
663
|
+
}
|
|
664
|
+
if (get)
|
|
665
|
+
return sendJson(res, 200, await share.shareView());
|
|
666
|
+
const { id: _id, ...action } = body;
|
|
667
|
+
return sendJson(res, 200, await share.share(action));
|
|
668
|
+
}
|
|
669
|
+
if (path === TYPE_SERVER_ROUTES.actions.slice(0, -1) && get) {
|
|
670
|
+
const actions = Object.entries(this.options.actions ?? {})
|
|
671
|
+
.filter(([, a]) => !a.hidden)
|
|
672
|
+
.map(([name, a]) => ({
|
|
673
|
+
name,
|
|
674
|
+
title: a.title ?? name,
|
|
675
|
+
...(a.description ? { description: a.description } : {}),
|
|
676
|
+
...(a.effect ? { effect: a.effect } : {}),
|
|
677
|
+
...(a.schema ? { schema: a.schema } : {}),
|
|
678
|
+
...(a.long ? { long: true } : {}),
|
|
679
|
+
}));
|
|
680
|
+
return sendJson(res, 200, { actions });
|
|
681
|
+
}
|
|
682
|
+
if (path.startsWith(TYPE_SERVER_ROUTES.actions) && !get) {
|
|
683
|
+
// A daemon from before the rename calls the reserved actions by their older names (`open-artifact.db.read`).
|
|
684
|
+
const name = currentActionName(decodeURIComponent(path.slice(TYPE_SERVER_ROUTES.actions.length)));
|
|
685
|
+
const action = Object.hasOwn(this.options.actions ?? {}, name) ? this.options.actions[name] : undefined;
|
|
686
|
+
if (!action)
|
|
687
|
+
throw new OpenArtifactsError('unknown_action', `${this.type} has no action ${name}.`, { status: 404 });
|
|
688
|
+
const entry = artifact(body.id);
|
|
689
|
+
const args = body.args && typeof body.args === 'object' && !Array.isArray(body.args) ? body.args : {};
|
|
690
|
+
const ref = { id: entry.id, root: entry.root, title: entry.title, site: entry.site };
|
|
691
|
+
if (action.long && this.daemon.available)
|
|
692
|
+
return sendJson(res, 200, this.runLong(name, action, ref, args));
|
|
693
|
+
return sendJson(res, 200, await action.run(ref, args));
|
|
694
|
+
}
|
|
695
|
+
if (path === TYPE_SERVER_ROUTES.summary && get && this.options.summary) {
|
|
696
|
+
const entry = artifact(url.searchParams.get('id'));
|
|
697
|
+
return sendJson(res, 200, await this.options.summary({ id: entry.id, root: entry.root }));
|
|
698
|
+
}
|
|
699
|
+
req.resume();
|
|
700
|
+
return sendJson(res, 404, { code: 'not_found', message: `No route ${path}.` });
|
|
701
|
+
}
|
|
702
|
+
/** Starts a long action and answers with its task; the end goes to the daemon (`open-artifacts.type.task`). */
|
|
703
|
+
runLong(name, action, ref, args) {
|
|
704
|
+
const task = `task_${randomBytes(8).toString('hex')}`;
|
|
705
|
+
const report = (body) => this.daemon.task(task, body).then(() => undefined, (error) => this.log(`task ${task} (${name}): reporting failed: ${error instanceof Error ? error.message : String(error)}`));
|
|
706
|
+
const progress = (fraction) => {
|
|
707
|
+
if (Number.isFinite(fraction))
|
|
708
|
+
void report({ progress: Math.max(0, Math.min(1, fraction)) });
|
|
709
|
+
};
|
|
710
|
+
void (async () => {
|
|
711
|
+
try {
|
|
712
|
+
const result = await action.run(ref, args, { id: task, progress });
|
|
713
|
+
await report({ done: true, result: result ?? null });
|
|
714
|
+
}
|
|
715
|
+
catch (error) {
|
|
716
|
+
await report({ done: true, error: errorBody(error) });
|
|
717
|
+
}
|
|
718
|
+
})();
|
|
719
|
+
return { task, pending: true, note: LONG_ACTION_NOTE };
|
|
720
|
+
}
|
|
721
|
+
onUpgrade(req, socket, head) {
|
|
722
|
+
socket.on('error', () => { });
|
|
723
|
+
this.lastActivity = Date.now();
|
|
724
|
+
if (!this.hostAllowed(req)) {
|
|
725
|
+
socket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
const content = this.contentEntry(req);
|
|
729
|
+
if (content) {
|
|
730
|
+
const site = content.entry?.site;
|
|
731
|
+
if (!content.entry || !site?.contentUpgrade) {
|
|
732
|
+
socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
content.entry.lastUsed = Date.now();
|
|
736
|
+
site.contentUpgrade(req, socket, head);
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
const url = new URL(req.url ?? '/', 'http://local');
|
|
740
|
+
const at = this.under(url.pathname);
|
|
741
|
+
if (!at) {
|
|
742
|
+
socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
at.entry.lastUsed = Date.now();
|
|
746
|
+
req.url = `${at.rest}${url.search}`;
|
|
747
|
+
const asked = String(req.headers['sec-websocket-protocol'] ?? '')
|
|
748
|
+
.split(',')
|
|
749
|
+
.map((s) => s.trim());
|
|
750
|
+
if (asked.includes(STREAM_PROTOCOL))
|
|
751
|
+
return this.stream(at.entry, req, socket, head, url);
|
|
752
|
+
if (at.entry.site.upgrade)
|
|
753
|
+
return at.entry.site.upgrade(req, socket, head);
|
|
754
|
+
socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
|
|
755
|
+
}
|
|
756
|
+
/** A site's event stream (SSE) carried over a WebSocket ({@link STREAM_PROTOCOL}). */
|
|
757
|
+
stream(entry, req, socket, head, url) {
|
|
758
|
+
const ws = acceptWebSocket(req, socket, head, STREAM_PROTOCOL);
|
|
759
|
+
if (!ws)
|
|
760
|
+
return;
|
|
761
|
+
const last = url.searchParams.get('__lastEventId');
|
|
762
|
+
if (last !== null) {
|
|
763
|
+
req.headers['last-event-id'] = last;
|
|
764
|
+
url.searchParams.delete('__lastEventId');
|
|
765
|
+
req.url = `${(req.url ?? '').split('?')[0]}${url.search}`;
|
|
766
|
+
}
|
|
767
|
+
req.method = 'GET';
|
|
768
|
+
const response = new StreamResponse(ws);
|
|
769
|
+
entry.streams += 1;
|
|
770
|
+
ws.handlers = {
|
|
771
|
+
close: () => {
|
|
772
|
+
entry.streams -= 1;
|
|
773
|
+
entry.lastUsed = Date.now();
|
|
774
|
+
this.lastActivity = Date.now();
|
|
775
|
+
response.closed();
|
|
776
|
+
req.emit('close');
|
|
777
|
+
},
|
|
778
|
+
};
|
|
779
|
+
Promise.resolve()
|
|
780
|
+
.then(() => entry.site.handle(req, response))
|
|
781
|
+
.catch(() => ws.close(STREAM_REFUSED + 500));
|
|
782
|
+
}
|
|
783
|
+
/** Unmounts everything and stops listening. */
|
|
784
|
+
close() {
|
|
785
|
+
if (this.timer)
|
|
786
|
+
clearInterval(this.timer);
|
|
787
|
+
this.timer = null;
|
|
788
|
+
for (const id of [...this.byId.keys()])
|
|
789
|
+
this.unmount(id);
|
|
790
|
+
this.lan.close();
|
|
791
|
+
this.server.close();
|
|
792
|
+
this.server.closeAllConnections();
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* Runs a type server: listens, prints the ready line, and closes everything
|
|
797
|
+
* on SIGTERM / SIGINT. Resolves with the {@link TypeServer}.
|
|
798
|
+
*/
|
|
799
|
+
export async function serve(options) {
|
|
800
|
+
const server = new TypeServer(options);
|
|
801
|
+
await server.listen();
|
|
802
|
+
const stop = () => {
|
|
803
|
+
server.close();
|
|
804
|
+
process.exit(0);
|
|
805
|
+
};
|
|
806
|
+
process.once('SIGTERM', stop);
|
|
807
|
+
process.once('SIGINT', stop);
|
|
808
|
+
server.ready();
|
|
809
|
+
server.log(`${server.type} type server at ${server.origin}/ (pid ${process.pid}${threadId ? `, thread ${threadId}` : ''}, ${hostname()})`);
|
|
810
|
+
return server;
|
|
811
|
+
}
|