@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.
Files changed (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/bin/frame-host.d.ts +2 -0
  5. package/bin/frame-host.js +47 -0
  6. package/package.json +124 -4
  7. package/src/child.d.ts +37 -0
  8. package/src/child.js +64 -0
  9. package/src/connectors/connectors.d.ts +101 -0
  10. package/src/connectors/connectors.js +256 -0
  11. package/src/connectors/daemon-connectors.d.ts +34 -0
  12. package/src/connectors/daemon-connectors.js +73 -0
  13. package/src/connectors/index.d.ts +7 -0
  14. package/src/connectors/index.js +7 -0
  15. package/src/connectors/mcp-client.d.ts +157 -0
  16. package/src/connectors/mcp-client.js +483 -0
  17. package/src/daemon.d.ts +119 -0
  18. package/src/daemon.js +301 -0
  19. package/src/frame/access.d.ts +69 -0
  20. package/src/frame/access.js +168 -0
  21. package/src/frame/client/comments.css +1 -0
  22. package/src/frame/client/comments.js +58 -0
  23. package/src/frame/client/imports.d.ts +6 -0
  24. package/src/frame/client/imports.js +112 -0
  25. package/src/frame/client/mcp-shell.js +345 -0
  26. package/src/frame/client/mcp.js +253 -0
  27. package/src/frame/client/runtime.js +1363 -0
  28. package/src/frame/client/sample.js +762 -0
  29. package/src/frame/client/shell.css +51 -0
  30. package/src/frame/client/shell.html +29 -0
  31. package/src/frame/client/shell.js +1417 -0
  32. package/src/frame/comments.d.ts +102 -0
  33. package/src/frame/comments.js +379 -0
  34. package/src/frame/core.d.ts +313 -0
  35. package/src/frame/core.js +1757 -0
  36. package/src/frame/db.d.ts +162 -0
  37. package/src/frame/db.js +604 -0
  38. package/src/frame/declaration.d.ts +30 -0
  39. package/src/frame/declaration.js +60 -0
  40. package/src/frame/env.d.ts +262 -0
  41. package/src/frame/env.js +13 -0
  42. package/src/frame/files.d.ts +130 -0
  43. package/src/frame/files.js +472 -0
  44. package/src/frame/index.d.ts +35 -0
  45. package/src/frame/index.js +33 -0
  46. package/src/frame/local.d.ts +126 -0
  47. package/src/frame/local.js +612 -0
  48. package/src/frame/mcp-relay.d.ts +79 -0
  49. package/src/frame/mcp-relay.js +191 -0
  50. package/src/frame/page-api.d.ts +48 -0
  51. package/src/frame/page-api.js +1 -0
  52. package/src/frame/page-comments.d.ts +109 -0
  53. package/src/frame/page-comments.js +1 -0
  54. package/src/frame/page-db.d.ts +88 -0
  55. package/src/frame/page-db.js +1 -0
  56. package/src/frame/page-imports.d.ts +2 -0
  57. package/src/frame/page-imports.js +2 -0
  58. package/src/frame/page-services.d.ts +124 -0
  59. package/src/frame/page-services.js +1 -0
  60. package/src/frame/page-values.d.ts +90 -0
  61. package/src/frame/page-values.js +1 -0
  62. package/src/frame/sample-relay.d.ts +42 -0
  63. package/src/frame/sample-relay.js +186 -0
  64. package/src/frame/snapshot-action.d.ts +18 -0
  65. package/src/frame/snapshot-action.js +82 -0
  66. package/src/frame/wire.d.ts +198 -0
  67. package/src/frame/wire.js +21 -0
  68. package/src/index.d.ts +17 -0
  69. package/src/index.js +17 -0
  70. package/src/lan.d.ts +75 -0
  71. package/src/lan.js +200 -0
  72. package/src/legacy-env.d.ts +7 -0
  73. package/src/legacy-env.js +14 -0
  74. package/src/serve.d.ts +375 -0
  75. package/src/serve.js +811 -0
  76. package/src/snapshot.d.ts +41 -0
  77. package/src/snapshot.js +224 -0
  78. package/src/type-package.d.ts +48 -0
  79. package/src/type-package.js +114 -0
  80. package/src/ws.d.ts +50 -0
  81. package/src/ws.js +203 -0
  82. package/src/zip.d.ts +197 -0
  83. package/src/zip.js +662 -0
@@ -0,0 +1,472 @@
1
+ /**
2
+ * The artifact's files as an original page sees them: everything in the
3
+ * artifact folder except what the host keeps for itself, listed as
4
+ * `_files.json` `{ver, files: {path: {sha256, size, contentType}}}`. `ver`
5
+ * names one state of that list. `publish` writes a batch of files with
6
+ * optional per-file preconditions (`ifMatch`: the sha256 the page last saw, or
7
+ * null for "must not exist") and answers `conflict` when one does not hold.
8
+ * Blobs (the assets capability) are content-addressed files under `_blobs/`.
9
+ */
10
+ import { createHash, randomBytes } from 'node:crypto';
11
+ import { mkdirSync, readFileSync, readdirSync, lstatSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, existsSync } from 'node:fs';
12
+ import { basename, dirname, extname, join, resolve, sep } from 'node:path';
13
+ export const PUBLISH_MAX_PATHS = 256;
14
+ export const FILE_MAX_BYTES = 16 * 1024 * 1024;
15
+ export const BLOB_MAX_BYTES = 20 * 1024 * 1024;
16
+ export const BLOB_SVG_MAX_BYTES = 2 * 1024 * 1024;
17
+ export const BLOB_CODE_MAX_BYTES = 16 * 1024 * 1024;
18
+ export const BLOBS_MAX_FILES = 2000;
19
+ export const BLOBS_MAX_BYTES = 1024 * 1024 * 1024;
20
+ const WALK_MAX_FILES = 20_000;
21
+ const SHA = /^[0-9a-f]{64}$/;
22
+ const BLOB_ID = /^[0-9a-f]{32}$/;
23
+ export const BLOB_TYPES = new Set([
24
+ 'image/png',
25
+ 'image/jpeg',
26
+ 'image/gif',
27
+ 'image/webp',
28
+ 'image/svg+xml',
29
+ 'video/mp4',
30
+ 'video/webm',
31
+ 'application/pdf',
32
+ 'font/woff2',
33
+ 'font/woff',
34
+ 'font/ttf',
35
+ 'font/otf',
36
+ 'text/csv',
37
+ 'text/markdown',
38
+ 'application/json',
39
+ 'text/plain',
40
+ 'text/css',
41
+ 'text/javascript',
42
+ ]);
43
+ const TYPES = {
44
+ '.html': 'text/html; charset=utf-8',
45
+ '.htm': 'text/html; charset=utf-8',
46
+ '.js': 'text/javascript; charset=utf-8',
47
+ '.mjs': 'text/javascript; charset=utf-8',
48
+ '.css': 'text/css; charset=utf-8',
49
+ '.json': 'application/json; charset=utf-8',
50
+ '.md': 'text/markdown; charset=utf-8',
51
+ '.txt': 'text/plain; charset=utf-8',
52
+ '.csv': 'text/csv; charset=utf-8',
53
+ '.svg': 'image/svg+xml',
54
+ '.png': 'image/png',
55
+ '.jpg': 'image/jpeg',
56
+ '.jpeg': 'image/jpeg',
57
+ '.gif': 'image/gif',
58
+ '.webp': 'image/webp',
59
+ '.avif': 'image/avif',
60
+ '.ico': 'image/x-icon',
61
+ '.woff': 'font/woff',
62
+ '.woff2': 'font/woff2',
63
+ '.ttf': 'font/ttf',
64
+ '.otf': 'font/otf',
65
+ '.mp3': 'audio/mpeg',
66
+ '.wav': 'audio/wav',
67
+ '.ogg': 'audio/ogg',
68
+ '.mp4': 'video/mp4',
69
+ '.webm': 'video/webm',
70
+ '.pdf': 'application/pdf',
71
+ '.wasm': 'application/wasm',
72
+ '.xml': 'application/xml',
73
+ '.glb': 'model/gltf-binary',
74
+ '.fbx': 'model/x-fbx',
75
+ '.stl': 'model/stl',
76
+ '.usdz': 'model/vnd.usdz+zip',
77
+ '.3mf': 'model/3mf',
78
+ };
79
+ export const contentTypeOf = (file) => TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
80
+ export class FrameError extends Error {
81
+ code;
82
+ status;
83
+ extra;
84
+ constructor(code, message, status = 400, extra = {}) {
85
+ super(message);
86
+ this.code = code;
87
+ this.status = status;
88
+ this.extra = extra;
89
+ }
90
+ }
91
+ /**
92
+ * Paths of the type (never the artifact's): neither listed nor writable by a page. In any case: a folder on macOS or
93
+ * Windows is case-insensitive, so `SKILL.MD` there is `SKILL.md`.
94
+ */
95
+ export function typePath(rel) {
96
+ const low = rel.toLowerCase();
97
+ return low === 'index.html' || low === 'skill.md' || low === 'artifact-type' || low.startsWith('artifact-type/');
98
+ }
99
+ /** Paths the host keeps for itself (in any case, as {@link typePath}). */
100
+ export function reservedPath(rel) {
101
+ const segs = rel.toLowerCase().split('/');
102
+ if (segs.some((s) => s === '' || s === '.' || s === '..' || s.startsWith('.')))
103
+ return true;
104
+ if (segs[0].startsWith('_'))
105
+ return true;
106
+ if (segs[0] === 'db' || segs[0] === 'history' || segs[0] === 'node_modules')
107
+ return true;
108
+ const low = rel.toLowerCase();
109
+ if (low === 'comments.json' || low.endsWith('.lock'))
110
+ return true;
111
+ return false;
112
+ }
113
+ /** The longest name one folder entry may have, in bytes (APFS, ext4 and NTFS hold 255). */
114
+ const SEGMENT_MAX_BYTES = 255;
115
+ /**
116
+ * Whether `file` (there or not yet) stays under `root` once links are followed: the real path of `file`, or of its
117
+ * nearest ancestor that exists, is `root`'s or under it. A link in the artifact folder (or in `db/`, `_blobs/`) to a
118
+ * folder or file outside is how a write or a read would leave it; this is checked before each.
119
+ */
120
+ export function staysInside(root, file) {
121
+ let realRoot;
122
+ try {
123
+ realRoot = realpathSync(root);
124
+ }
125
+ catch (error) {
126
+ // No folder yet (a first write makes it): nothing under it exists, so no link can lead out of it.
127
+ // A dangling link there is something, and is refused.
128
+ const code = error.code;
129
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
130
+ return false;
131
+ try {
132
+ lstatSync(root);
133
+ return false;
134
+ }
135
+ catch {
136
+ const top = resolve(root);
137
+ const at = resolve(file);
138
+ return at === top || at.startsWith(top + sep);
139
+ }
140
+ }
141
+ for (let p = file;;) {
142
+ try {
143
+ const real = realpathSync(p);
144
+ return real === realRoot || real.startsWith(realRoot + sep);
145
+ }
146
+ catch (error) {
147
+ const code = error.code;
148
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
149
+ return false;
150
+ const up = dirname(p);
151
+ if (up === p)
152
+ return false;
153
+ p = up;
154
+ }
155
+ }
156
+ }
157
+ /** A folder on disk, where a link can lead out of it: {@link staysInside}, and links followed (`realpathSync`). */
158
+ export const LINK_GUARD = Object.freeze({ inside: staysInside, real: (path) => realpathSync(path) });
159
+ /** A storage with no links (a virtual file system): containment is the path's own. */
160
+ export const PLAIN_GUARD = Object.freeze({
161
+ inside: (root, file) => {
162
+ const top = resolve(root);
163
+ const at = resolve(file);
164
+ return at === top || at.startsWith(top + sep);
165
+ },
166
+ real: (path) => resolve(path),
167
+ });
168
+ /** A page-relative path, normalized, or null when it is not one. */
169
+ export function cleanPath(p) {
170
+ if (typeof p !== 'string' || !p || p.length > 1024 || p.includes('\\') || p.includes('\0'))
171
+ return null;
172
+ const rel = p.replace(/^\/+/, '');
173
+ if (!rel || rel.split('/').some((s) => s === '' || s === '.' || s === '..' || Buffer.byteLength(s) > SEGMENT_MAX_BYTES))
174
+ return null;
175
+ return rel;
176
+ }
177
+ function writeAtomic(file, data) {
178
+ mkdirSync(dirname(file), { recursive: true });
179
+ const tmp = join(dirname(file), `.${basename(file)}.${randomBytes(8).toString('hex')}.tmp`);
180
+ // `wx`: a temporary name someone made first (a link planted there) is never written through.
181
+ writeFileSync(tmp, data, { flag: 'wx' });
182
+ renameSync(tmp, file);
183
+ }
184
+ export class FileStore {
185
+ root;
186
+ /** rel → the hash of the file at that mtime and size. */
187
+ cache = new Map();
188
+ ownIndex;
189
+ guard;
190
+ current = null;
191
+ constructor(root, options = {}) {
192
+ this.root = root;
193
+ this.ownIndex = options.ownIndex === true;
194
+ this.guard = options.guard ?? LINK_GUARD;
195
+ }
196
+ /** A path of the type's here: {@link typePath}, but for a page's own `index.html`. */
197
+ ofType(rel) {
198
+ return typePath(rel) && !(this.ownIndex && rel === 'index.html');
199
+ }
200
+ sha(rel, st) {
201
+ const have = this.cache.get(rel);
202
+ if (have && have.mtimeMs === st.mtimeMs && have.size === st.size)
203
+ return have.sha256;
204
+ const sha256 = createHash('sha256').update(readFileSync(join(this.root, rel))).digest('hex');
205
+ this.cache.set(rel, { mtimeMs: st.mtimeMs, size: st.size, sha256 });
206
+ return sha256;
207
+ }
208
+ /** The current listing. */
209
+ manifest() {
210
+ const files = {};
211
+ let count = 0;
212
+ const walk = (dir, prefix) => {
213
+ let entries;
214
+ try {
215
+ entries = readdirSync(dir, { withFileTypes: true });
216
+ }
217
+ catch {
218
+ return;
219
+ }
220
+ for (const e of entries) {
221
+ const rel = prefix ? `${prefix}/${e.name}` : e.name;
222
+ if (reservedPath(rel) || this.ofType(rel))
223
+ continue;
224
+ if (e.isDirectory())
225
+ walk(join(dir, e.name), rel);
226
+ else if (e.isFile() && ++count <= WALK_MAX_FILES) {
227
+ try {
228
+ const st = statSync(join(dir, e.name));
229
+ files[rel] = { sha256: this.sha(rel, st), size: st.size, contentType: contentTypeOf(rel) };
230
+ }
231
+ catch {
232
+ // gone between readdir and stat
233
+ }
234
+ }
235
+ }
236
+ };
237
+ walk(this.root, '');
238
+ const sorted = Object.fromEntries(Object.keys(files)
239
+ .sort()
240
+ .map((k) => [k, files[k]]));
241
+ const ver = createHash('sha256')
242
+ .update(Object.entries(sorted)
243
+ .map(([k, v]) => `${k}\0${v.sha256}`)
244
+ .join('\n'))
245
+ .digest('hex')
246
+ .slice(0, 12);
247
+ this.current = { ver, files: sorted };
248
+ return this.current;
249
+ }
250
+ /** The artifact file a page asks for: an absolute path, or null. */
251
+ resolve(rel) {
252
+ const clean = cleanPath(rel);
253
+ if (!clean || reservedPath(clean) || this.ofType(clean))
254
+ return null;
255
+ const file = join(this.root, clean);
256
+ if (!file.startsWith(this.root + sep))
257
+ return null;
258
+ try {
259
+ const real = this.guard.real(file);
260
+ const realRoot = this.guard.real(this.root);
261
+ if (!real.startsWith(realRoot + sep))
262
+ return null;
263
+ return statSync(real).isFile() ? real : null;
264
+ }
265
+ catch {
266
+ return null;
267
+ }
268
+ }
269
+ /** Writes a batch. Throws {@link FrameError} `conflict` (with `live`, `paths`) when a precondition fails. */
270
+ publish(files) {
271
+ const entries = Object.entries(files ?? {});
272
+ if (entries.length === 0) {
273
+ const m = this.manifest();
274
+ return { version: m.ver, changed: [], shas: {}, unchanged: true };
275
+ }
276
+ if (entries.length > PUBLISH_MAX_PATHS)
277
+ throw new FrameError('too_large', `At most ${PUBLISH_MAX_PATHS} paths in one publish.`, 413);
278
+ const plan = [];
279
+ for (const [p, spec] of entries) {
280
+ const rel = cleanPath(p);
281
+ if (!rel)
282
+ throw new FrameError('invalid_content', `${JSON.stringify(p)} is not a file path.`);
283
+ if (this.ofType(rel))
284
+ throw new FrameError('read_only_path', `${rel} belongs to the type and cannot be written.`, 403);
285
+ if (reservedPath(rel))
286
+ throw new FrameError(rel.startsWith('_') ? 'invalid_content' : 'read_only_path', `${rel} is reserved for the host.`, 403);
287
+ if (spec.ifMatch !== undefined && spec.ifMatch !== null && !SHA.test(spec.ifMatch))
288
+ throw new FrameError('invalid_content', `${rel}: ifMatch is a lowercase sha256 or null.`);
289
+ if (!spec.delete) {
290
+ if (!Buffer.isBuffer(spec.data))
291
+ throw new FrameError('invalid_content', `${rel}: no content.`);
292
+ if (spec.data.length > FILE_MAX_BYTES)
293
+ throw new FrameError('too_large', `${rel} is over ${FILE_MAX_BYTES} bytes.`, 413);
294
+ }
295
+ if (!this.guard.inside(this.root, join(this.root, rel)))
296
+ throw new FrameError('read_only_path', `${rel} leads out of the artifact folder (a link).`, 403);
297
+ plan.push({ rel, ...spec });
298
+ }
299
+ const before = this.manifest();
300
+ const conflicts = [];
301
+ for (const w of plan) {
302
+ if (w.ifMatch === undefined)
303
+ continue;
304
+ const actual = before.files[w.rel]?.sha256 ?? null;
305
+ if (actual !== w.ifMatch)
306
+ conflicts.push({ path: w.rel, expected: w.ifMatch, actual });
307
+ }
308
+ if (conflicts.length) {
309
+ throw new FrameError('conflict', 'The files changed since this page read them.', 409, {
310
+ live: before.ver,
311
+ paths: conflicts,
312
+ changed: conflicts.map((c) => c.path),
313
+ });
314
+ }
315
+ const changed = [];
316
+ const shas = {};
317
+ for (const w of plan) {
318
+ const file = join(this.root, w.rel);
319
+ if (w.delete) {
320
+ if (before.files[w.rel]) {
321
+ rmSync(file, { force: true });
322
+ this.cache.delete(w.rel);
323
+ changed.push({ path: w.rel, sha256: null });
324
+ }
325
+ continue;
326
+ }
327
+ const sha256 = createHash('sha256').update(w.data).digest('hex');
328
+ shas[w.rel] = sha256;
329
+ if (before.files[w.rel]?.sha256 === sha256)
330
+ continue;
331
+ writeAtomic(file, w.data);
332
+ // Two writes of equally long content inside one filesystem clock tick share mtime and size, so a cache entry
333
+ // would still hold the hash of the content this one replaced: the next `manifest()` read, and a page's
334
+ // `ifMatch`, then saw the old state. The file just written is re-read instead, as a delete already does.
335
+ this.cache.delete(w.rel);
336
+ changed.push({ path: w.rel, sha256 });
337
+ }
338
+ const after = this.manifest();
339
+ return { version: after.ver, changed, shas, ...(changed.length === 0 ? { unchanged: true } : {}) };
340
+ }
341
+ }
342
+ /** Who claims an asset: `uploaders`, or the older single `uploader`; none (`[]`): a blob from before either, the owner's. */
343
+ export function blobClaims(meta) {
344
+ if (Array.isArray(meta.uploaders))
345
+ return meta.uploaders.filter((u) => typeof u === 'string');
346
+ return typeof meta.uploader === 'string' ? [meta.uploader] : [];
347
+ }
348
+ /** The most bytes an asset of `type` may have. */
349
+ export function blobLimit(type) {
350
+ if (type === 'image/svg+xml')
351
+ return BLOB_SVG_MAX_BYTES;
352
+ if (type === 'text/css' || type === 'text/javascript')
353
+ return BLOB_CODE_MAX_BYTES;
354
+ return BLOB_MAX_BYTES;
355
+ }
356
+ export class BlobStore {
357
+ root;
358
+ dir;
359
+ guard;
360
+ constructor(root, options = {}) {
361
+ this.root = root;
362
+ this.dir = join(root, '_blobs');
363
+ this.guard = options.guard ?? LINK_GUARD;
364
+ }
365
+ meta(id) {
366
+ if (!BLOB_ID.test(id) || !this.guard.inside(this.root, join(this.dir, id)))
367
+ return null;
368
+ try {
369
+ const m = JSON.parse(readFileSync(join(this.dir, `${id}.json`), 'utf8'));
370
+ return existsSync(join(this.dir, id)) ? { id, ...m } : null;
371
+ }
372
+ catch {
373
+ return null;
374
+ }
375
+ }
376
+ fileOf(id) {
377
+ return this.meta(id) ? join(this.dir, id) : null;
378
+ }
379
+ /** The assets, oldest first; `only`: those this test keeps (the usage still counts them all). */
380
+ list(only) {
381
+ let names = [];
382
+ try {
383
+ if (this.guard.inside(this.root, this.dir))
384
+ names = readdirSync(this.dir);
385
+ }
386
+ catch {
387
+ // none yet
388
+ }
389
+ const all = [];
390
+ for (const n of names) {
391
+ if (!BLOB_ID.test(n))
392
+ continue;
393
+ const m = this.meta(n);
394
+ if (m)
395
+ all.push(m);
396
+ }
397
+ all.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)));
398
+ const bytes = all.reduce((s, a) => s + (a.sizeBytes ?? 0), 0);
399
+ const assets = all
400
+ .filter((m) => !only || only(m))
401
+ .map((m) => ({ id: m.id, url: `/_blob/${m.id}`, contentType: m.contentType, sizeBytes: m.sizeBytes, createdAt: m.createdAt }));
402
+ return { assets, usage: { files: all.length, bytes, maxFiles: BLOBS_MAX_FILES, maxBytes: BLOBS_MAX_BYTES } };
403
+ }
404
+ /**
405
+ * Stores an asset by its content: the same bytes twice are one asset, and a second uploader adds its claim (so it
406
+ * lists and deletes it as its own). A claim added to a blob that had none (the owner's) leaves the owner, an editor,
407
+ * holding it as before.
408
+ */
409
+ upload(data, contentType, uploader) {
410
+ const raw = typeof contentType === 'string' ? contentType.split(';')[0].trim().toLowerCase() : '';
411
+ if (!raw)
412
+ throw new FrameError('invalid_request', 'upload() needs a content type.');
413
+ if (!BLOB_TYPES.has(raw))
414
+ throw new FrameError('unsupported_type', `Assets of type ${raw} are not supported.`);
415
+ if (!data.length)
416
+ throw new FrameError('invalid_request', 'An empty file.');
417
+ const max = blobLimit(raw);
418
+ if (data.length > max)
419
+ throw new FrameError('too_large', `An asset of type ${raw} is at most ${max} bytes.`, 413);
420
+ if (!this.guard.inside(this.root, this.dir))
421
+ throw new FrameError('quota_or_state', '_blobs/ leads out of the artifact folder (a link).', 403);
422
+ const id = createHash('sha256').update(data).digest('hex').slice(0, 32);
423
+ if (!this.meta(id)) {
424
+ const { usage } = this.list();
425
+ if (usage.files + 1 > BLOBS_MAX_FILES || usage.bytes + data.length > BLOBS_MAX_BYTES) {
426
+ throw new FrameError('quota_or_state', 'The artifact holds as many assets as it can.', 413);
427
+ }
428
+ mkdirSync(this.dir, { recursive: true });
429
+ writeFileSync(join(this.dir, id), data);
430
+ writeFileSync(join(this.dir, `${id}.json`), `${JSON.stringify({ contentType: raw, sizeBytes: data.length, createdAt: new Date().toISOString(), ...(uploader ? { uploaders: [uploader] } : {}) })}\n`);
431
+ }
432
+ else if (uploader) {
433
+ const have = this.meta(id);
434
+ const claims = blobClaims(have);
435
+ if (!claims.includes(uploader))
436
+ this.writeMeta(have, [...claims, uploader]);
437
+ }
438
+ const m = this.meta(id);
439
+ return { id, url: `/_blob/${id}`, sizeBytes: m.sizeBytes, contentType: m.contentType, createdAt: m.createdAt };
440
+ }
441
+ writeMeta(meta, uploaders) {
442
+ const { id: _id, uploader: _old, uploaders: _was, ...rest } = meta;
443
+ writeFileSync(join(this.dir, `${meta.id}.json`), `${JSON.stringify({ ...rest, uploaders })}\n`);
444
+ }
445
+ /**
446
+ * Deletes by id or `/_blob/<id>` url. `claimant`: a viewer below editor, who removes only its own claim (else
447
+ * `not_uploader`); the bytes go once no claim is left. Without one (an editor): the asset goes, whoever claims it.
448
+ */
449
+ delete(ref, claimant) {
450
+ const match = /^(?:\/?_blob\/)?([0-9a-f]{32})$/.exec(String(ref ?? '').replace(/^https?:\/\/[^/]+/, ''));
451
+ if (!match)
452
+ throw new FrameError('invalid_request', 'delete() takes an asset id or its /_blob/ url.');
453
+ const id = match[1];
454
+ const meta = this.meta(id);
455
+ if (!meta)
456
+ return { deleted: false };
457
+ if (claimant !== undefined) {
458
+ const claims = blobClaims(meta);
459
+ if (!claims.includes(claimant))
460
+ throw new FrameError('not_uploader', 'Only whoever uploaded an asset (or an editor) may delete it.', 403);
461
+ const left = claims.filter((c) => c !== claimant);
462
+ if (left.length) {
463
+ this.writeMeta(meta, left);
464
+ return { deleted: true };
465
+ }
466
+ }
467
+ rmSync(join(this.dir, id), { force: true });
468
+ rmSync(join(this.dir, `${id}.json`), { force: true });
469
+ return { deleted: true };
470
+ }
471
+ }
472
+ export { writeAtomic };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * frame-host: serves an original artifact type (a folder whose index.html
3
+ * declares itself in an inline `// artifact.json` block) so its page runs as
4
+ * it would in its first home.
5
+ *
6
+ * Three windows take part:
7
+ *
8
+ * the outer Shell (the daemon's /a/<id>)
9
+ * └─ embeds ─▶ the inner shell (this server, /f/<token>/, Site.page)
10
+ * └─ embeds ─▶ the original page on its own origin
11
+ * (http://<id>.frame.localhost:<port>/_f/<ver>/, Site.content)
12
+ *
13
+ * The page gets `window.openartifacts` from the Frame Runtime this server injects
14
+ * first in its <head> (client/runtime.ts). Every capability call is a
15
+ * `__frame_cap` postMessage to the inner shell (client/shell.ts), which
16
+ * carries it here over HTTP and pushes events (db changes, room, file and
17
+ * comment changes, rewiring) back from one event stream.
18
+ *
19
+ * Backends live in the artifact folder: db/ (db.ts), comments.json
20
+ * (comments.ts), the files the page publishes and _blobs/ (files.ts). An
21
+ * agent's edits land on disk; a watcher sends them to open pages.
22
+ *
23
+ * The parts: core.ts serves one artifact to any number of viewers from plain
24
+ * data, and takes everything about where it runs from an environment (env.ts,
25
+ * `FrameEnv`); local.ts is that environment on this computer, with the Node
26
+ * HTTP adapter frame-host mounts (`FrameSite`, `mountFrameSite`). A hosted site
27
+ * imports core.ts and env.ts only.
28
+ */
29
+ export { CONTRACT, FrameCore, frameActions, mountFrameCore, pageDeclaration, replyBytes, storedFile, wireUser } from './core.js';
30
+ export { CLIENT_DIR, FrameSite, localFrameEnv, localTypeSource, localUser, mountFrameSite, type FrameSiteContext, type LocalFrameOptions } from './local.js';
31
+ export { parseDeclaration, readDeclaration, DECLARATION_LINE, type Declaration } from './declaration.js';
32
+ export { FrameError, LINK_GUARD, PLAIN_GUARD, type PathGuard } from './files.js';
33
+ export { FRAME_LEVELS } from './env.js';
34
+ export type * from './env.js';
35
+ export type * from './wire.js';
@@ -0,0 +1,33 @@
1
+ /**
2
+ * frame-host: serves an original artifact type (a folder whose index.html
3
+ * declares itself in an inline `// artifact.json` block) so its page runs as
4
+ * it would in its first home.
5
+ *
6
+ * Three windows take part:
7
+ *
8
+ * the outer Shell (the daemon's /a/<id>)
9
+ * └─ embeds ─▶ the inner shell (this server, /f/<token>/, Site.page)
10
+ * └─ embeds ─▶ the original page on its own origin
11
+ * (http://<id>.frame.localhost:<port>/_f/<ver>/, Site.content)
12
+ *
13
+ * The page gets `window.openartifacts` from the Frame Runtime this server injects
14
+ * first in its <head> (client/runtime.ts). Every capability call is a
15
+ * `__frame_cap` postMessage to the inner shell (client/shell.ts), which
16
+ * carries it here over HTTP and pushes events (db changes, room, file and
17
+ * comment changes, rewiring) back from one event stream.
18
+ *
19
+ * Backends live in the artifact folder: db/ (db.ts), comments.json
20
+ * (comments.ts), the files the page publishes and _blobs/ (files.ts). An
21
+ * agent's edits land on disk; a watcher sends them to open pages.
22
+ *
23
+ * The parts: core.ts serves one artifact to any number of viewers from plain
24
+ * data, and takes everything about where it runs from an environment (env.ts,
25
+ * `FrameEnv`); local.ts is that environment on this computer, with the Node
26
+ * HTTP adapter frame-host mounts (`FrameSite`, `mountFrameSite`). A hosted site
27
+ * imports core.ts and env.ts only.
28
+ */
29
+ export { CONTRACT, FrameCore, frameActions, mountFrameCore, pageDeclaration, replyBytes, storedFile, wireUser } from "./core.js";
30
+ export { CLIENT_DIR, FrameSite, localFrameEnv, localTypeSource, localUser, mountFrameSite } from "./local.js";
31
+ export { parseDeclaration, readDeclaration, DECLARATION_LINE } from "./declaration.js";
32
+ export { FrameError, LINK_GUARD, PLAIN_GUARD } from "./files.js";
33
+ export { FRAME_LEVELS } from "./env.js";
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The frame core on this computer: frame-host's environment
3
+ * ({@link localFrameEnv}) and its Node HTTP adapter ({@link FrameSite}).
4
+ *
5
+ * Everything a hosted site has no use for, or that a Worker lacks, is here
6
+ * and only here: the type folder and the client folder read from disk (with
7
+ * the link checks), `fs.watch` on both folders, `os.userInfo` for the owner's
8
+ * name, `stripTypeScriptTypes` for the client scripts run from source,
9
+ * `import.meta.url` for where they are, and `IncomingMessage` /
10
+ * `ServerResponse` / `createReadStream` for requests. Every viewer here is the
11
+ * owner, and a request comes in only from this computer, but for the visit of
12
+ * a `snapshot` (frame/snapshot-action.ts): its inner shell is loaded at
13
+ * `/snapshot/<credential>/`, which the site claims only while that visit lasts
14
+ * ({@link FrameSite.beginSnapshot}), and every request under it is a read-only
15
+ * viewer nobody else sees (no writes, no presence, no event but `hello`).
16
+ */
17
+ import type { IncomingMessage, ServerResponse } from 'node:http';
18
+ import type { Duplex } from 'node:stream';
19
+ import type { Site, SiteContext, StreamResponse } from '../serve.js';
20
+ import { FrameCore } from './core.js';
21
+ import { type Declaration } from './declaration.js';
22
+ import type { FrameEnv, FrameTypeSource, FrameViewer } from './env.js';
23
+ import type { FrameSession } from './wire.js';
24
+ /**
25
+ * Where the browser scripts and the shell page are: `$OPEN_ARTIFACTS_FRAME_CLIENT_DIR`,
26
+ * else `client/` beside this module (src/frame/client from source, or
27
+ * dist/daemon/frame-host/client beside the bundle).
28
+ */
29
+ export declare const CLIENT_DIR: string;
30
+ /** What {@link mountFrameSite} takes: serve()'s context, plus the type folder. */
31
+ export interface FrameSiteContext extends SiteContext {
32
+ /** The type folder (default `OPEN_ARTIFACTS_TYPE_DIR`, else the working directory). */
33
+ typeDir?: string;
34
+ /**
35
+ * Page mode, for a page type (`openArtifacts.style: "page"`): the page is the artifact's own `index.html`, in its root,
36
+ * which it may replace (`artifact.publish(html)`), and its capabilities are the ones `.artifact.json` declares (the
37
+ * agent's `capabilities`), never the page's own `// artifact.json` block.
38
+ */
39
+ page?: boolean;
40
+ /**
41
+ * Sent on every response of the page's own origin (its index.html, its files, the type's `artifact-type/`
42
+ * files): frame-host gives a restricted type's pages `installedTypeCsp` (`OPEN_ARTIFACTS_TYPE_RESTRICTED=1`),
43
+ * which keeps them to their own origin and the manifest's `openArtifacts.network`. Absent: no policy.
44
+ */
45
+ contentSecurityPolicy?: string | null;
46
+ /** The same origin grant used to construct the restricted page's policy. */
47
+ allowedNetworkOrigins?: readonly string[];
48
+ /**
49
+ * The type's root is not trusted (installed, or a project not trusted yet): the inner shell frames the page with
50
+ * `RESTRICTED_FRAME_SANDBOX` (no popups, no top navigation). Absent: no sandbox, as before.
51
+ */
52
+ restricted?: boolean;
53
+ }
54
+ /** Whether `viewer` is a snapshot visit's. */
55
+ export declare function isSnapshotViewer(viewer: FrameViewer): boolean;
56
+ /** The owner, as every request on this computer is. */
57
+ export declare function localUser(): FrameViewer;
58
+ /** The type folder on disk. */
59
+ export declare function localTypeSource(typeDir: string): FrameTypeSource;
60
+ /**
61
+ * The page side of `sample` from source: client/sample.ts takes its checks and helpers from the protocol's
62
+ * sample.ts (a build bundles the two), so here both are stripped and joined in one script, the protocol's part first
63
+ * (its exports become plain declarations) and the client's import of it left out.
64
+ */
65
+ export declare function sampleScriptFromSource(clientFile: string, protocolFile: string): string;
66
+ /** What {@link localFrameEnv} takes besides serve()'s context. */
67
+ export interface LocalFrameOptions {
68
+ typeDir: string;
69
+ page: boolean;
70
+ contentSecurityPolicy: string | null;
71
+ allowedNetworkOrigins?: readonly string[];
72
+ restricted: boolean;
73
+ }
74
+ /** frame-host's environment: this computer, its owner, the type folder, the client folder, `fs.watch`. */
75
+ export declare function localFrameEnv(root: string, ctx: SiteContext, options: LocalFrameOptions, type?: FrameTypeSource): FrameEnv;
76
+ /** Mounts one artifact folder. Throws when the type folder carries no declaration or the server has no content hosts. */
77
+ export declare function mountFrameSite(root: string, ctx: FrameSiteContext): Promise<FrameSite>;
78
+ /** One open artifact of an original type, on this computer: the core, answering Node's requests. */
79
+ export declare class FrameSite extends FrameCore implements Site {
80
+ /** The type folder. */
81
+ readonly typeDir: string;
82
+ /** Snapshot visits under way: credential → their viewer. */
83
+ private readonly visits;
84
+ constructor(root: string, typeDir: string, declaration: Declaration, env: FrameEnv);
85
+ /**
86
+ * Starts a snapshot visit: a one-time credential (unguessable, this artifact's only) and the address of the inner
87
+ * shell under it, `<shell origin>/snapshot/<credential>/`. Until `end()`, every request under that address is a
88
+ * read-only viewer of its own (the owner's level and name, so the page draws as the person sees it): it reads, each
89
+ * write is refused, it is no peer of anyone, and its event stream says `hello` and nothing more. After `end()` the
90
+ * address is not this site's any more (404). The credential is never logged.
91
+ */
92
+ beginSnapshot(): {
93
+ url: string;
94
+ end(): void;
95
+ };
96
+ /** Snapshot visits under way. */
97
+ get snapshotVisits(): number;
98
+ /** A snapshot visit's address, while it lasts (serve() then routes it here: `Site.claims`). */
99
+ claims(pathname: string): boolean;
100
+ /** The visit's own session: no comments UI or agent in the inner shell, and `snapshot` (it waits for no one). */
101
+ session(viewer: FrameViewer): FrameSession;
102
+ /** A snapshot's viewer reads only: every other call is refused before the core runs it. */
103
+ capability(cap: string, method: string, a: Record<string, unknown>, client: string, viewer: FrameViewer, forShell?: boolean): Promise<unknown>;
104
+ /** A snapshot's visit draws the page as it is: it asks no model. */
105
+ protected sampleDisabled(viewer: FrameViewer): boolean;
106
+ /**
107
+ * The inner shell's own POSTs other than capability calls, for a snapshot's viewer: an upload, a title, the agent
108
+ * and its activity are answered here, as for a viewer who may not, and never reach the core (null: the core answers).
109
+ */
110
+ private snapshotShellReply;
111
+ handle(req: IncomingMessage, res: ServerResponse | StreamResponse): Promise<void>;
112
+ /**
113
+ * `POST /api/frame/sample`: the call's NDJSON stream, written line by line as the daemon sends it. The inner shell
114
+ * closing its request (the page cancelled, or went away) aborts the daemon's.
115
+ */
116
+ private sample;
117
+ /**
118
+ * A snapshot visit's event stream: `hello` (no peers), then nothing. It is not one of the core's connections, so no
119
+ * open view sees it among its peers, and nothing it would hear (a reload, a peer) changes the picture.
120
+ */
121
+ private quietEvents;
122
+ /** The event stream of one inner shell: JSON objects, over a `baoyu-sse` WebSocket or as SSE. */
123
+ private events;
124
+ content(req: IncomingMessage, res: ServerResponse): Promise<void>;
125
+ contentUpgrade(_req: IncomingMessage, socket: Duplex): void;
126
+ }