topotopo 0.1.0 → 0.3.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 (80) hide show
  1. package/README.md +61 -12
  2. package/dist/cli.js +161 -23
  3. package/dist/graph/engine.js +18 -1
  4. package/dist/graph/params.d.ts +7 -1
  5. package/dist/graph/params.js +21 -8
  6. package/dist/graph/types.d.ts +28 -2
  7. package/dist/host/artifacts.d.ts +21 -0
  8. package/dist/host/artifacts.js +58 -0
  9. package/dist/host/export-targets.d.ts +33 -0
  10. package/dist/host/export-targets.js +84 -0
  11. package/dist/host/export_scene.py +200 -0
  12. package/dist/host/node.d.ts +8 -0
  13. package/dist/host/node.js +114 -0
  14. package/dist/host/types.d.ts +5 -0
  15. package/dist/inspect.js +5 -2
  16. package/dist/io/common.d.ts +6 -0
  17. package/dist/io/export.js +7 -4
  18. package/dist/io/gltf.d.ts +1 -1
  19. package/dist/io/gltf.js +167 -32
  20. package/dist/io/heightmap.d.ts +1 -1
  21. package/dist/io/import.d.ts +2 -2
  22. package/dist/io/import.js +10 -3
  23. package/dist/io/png-decode.d.ts +5 -2
  24. package/dist/io/png-decode.js +10 -3
  25. package/dist/io/targets.d.ts +31 -0
  26. package/dist/io/targets.js +75 -0
  27. package/dist/io/textures.d.ts +31 -2
  28. package/dist/io/textures.js +66 -18
  29. package/dist/io/unreal.js +22 -5
  30. package/dist/mcp/docs.d.ts +9 -2
  31. package/dist/mcp/docs.js +126 -2
  32. package/dist/mcp/inputs.d.ts +28 -0
  33. package/dist/mcp/inputs.js +377 -0
  34. package/dist/mcp/server.js +4 -1
  35. package/dist/mcp/tools.d.ts +1 -1
  36. package/dist/mcp/tools.js +118 -51
  37. package/dist/nodes/code.js +34 -6
  38. package/dist/nodes/copy.js +14 -4
  39. package/dist/nodes/flow.js +136 -35
  40. package/dist/nodes/heightfield.js +67 -11
  41. package/dist/nodes/texture.d.ts +1 -1
  42. package/dist/nodes/texture.js +61 -5
  43. package/dist/render/options.js +2 -1
  44. package/dist/render/raster.d.ts +2 -0
  45. package/dist/render/raster.js +3 -3
  46. package/dist/render/texview.d.ts +9 -1
  47. package/dist/render/texview.js +43 -2
  48. package/dist/viewer/app/api.js +64 -0
  49. package/dist/viewer/app/camera.js +250 -0
  50. package/dist/viewer/app/export-popover.js +68 -0
  51. package/dist/viewer/app/grid.js +217 -0
  52. package/dist/viewer/app/guides.js +402 -0
  53. package/dist/viewer/app/image-view.js +114 -0
  54. package/dist/viewer/app/keymap.js +199 -0
  55. package/dist/viewer/app/layers.js +244 -0
  56. package/dist/viewer/app/main.js +646 -0
  57. package/dist/viewer/app/markers.js +206 -0
  58. package/dist/viewer/app/mesh.js +172 -0
  59. package/dist/viewer/app/outliner.js +225 -0
  60. package/dist/viewer/app/outputs.css +73 -0
  61. package/dist/viewer/app/outputs.js +240 -0
  62. package/dist/viewer/app/props.js +432 -0
  63. package/dist/viewer/app/scene.js +529 -0
  64. package/dist/viewer/app/select.js +153 -0
  65. package/dist/viewer/app/selection.js +79 -0
  66. package/dist/viewer/app/status.js +20 -0
  67. package/dist/viewer/app/style.css +173 -0
  68. package/dist/viewer/app/undo.js +49 -0
  69. package/dist/viewer/app/units.js +51 -0
  70. package/dist/viewer/app/vars.js +64 -0
  71. package/dist/viewer/index.html +67 -184
  72. package/dist/viewer/outputs.d.ts +54 -0
  73. package/dist/viewer/outputs.js +436 -0
  74. package/dist/viewer/server.d.ts +47 -1
  75. package/dist/viewer/server.js +480 -17
  76. package/dist/workspace.d.ts +60 -4
  77. package/dist/workspace.js +131 -5
  78. package/package.json +9 -3
  79. package/shelf/brick_wall.json +1 -1
  80. package/shelf/wall_segment.json +2 -2
@@ -1,16 +1,33 @@
1
- // Live preview web server: serves a three.js viewer that shows any graph/node of the
2
- // workspace and refreshes over Server-Sent Events whenever a graph is rebuilt/edited.
3
- // Bound to 127.0.0.1 only.
1
+ // Live preview web server: serves the viewer page (index.html, a shell loading the ES modules of app/ and three.js
2
+ // from /vendor/three/; docs/design/viewer.md) that shows any graph/node of the workspace and refreshes over
3
+ // Server-Sent Events whenever a graph is rebuilt/edited.
4
+ // It is also the human's control surface: files dropped on the page are stored in the workspace's inputs/ (under
5
+ // `topotopo view`, the inputs/ beside the graph file) and shown as reference layers, the graph's exposed vars are set
6
+ // from generated controls (POST /api/vars), and markers clicked into the view (sites, paths, zones, volumes) become
7
+ // inputs/markers.json (POST /api/markers).
8
+ // Bound to 127.0.0.1 only; requests must name this server as their Host, and writes must come from its own page.
4
9
  import http from 'node:http';
5
10
  import fs from 'node:fs';
6
11
  import path from 'node:path';
12
+ import zlib from 'node:zlib';
13
+ import { Transform } from 'node:stream';
14
+ import { pipeline } from 'node:stream/promises';
7
15
  import { fileURLToPath } from 'node:url';
8
- import { exportGeometryAsync } from '../io/export.js';
16
+ import { GeoBuilder } from '../core/geometry.js';
17
+ import { exportGeometry, exportGeometryAsync } from '../io/export.js';
9
18
  import { summarize } from '../inspect.js';
10
19
  import { withHeightfieldPreview } from '../core/heightfield.js';
20
+ import { withImagePreview } from '../render/texview.js';
11
21
  import { wiringOf } from '../graph/engine.js';
12
- // index.html sits next to this module (the build copies it to dist/viewer/)
22
+ import { createOutputs } from './outputs.js';
23
+ import { renderGeometry } from '../render/raster.js';
24
+ import { encodePNG } from '../render/png.js';
25
+ import { imageFromPNGFile } from '../io/textures.js';
26
+ // the page's guide rules, shared so the page and this server check a marker list the same way
27
+ import { MARKER_KINDS as KINDS, MarkerError, parseMarkers as parseMarkerList } from './app/markers.js';
28
+ // index.html and app/ sit next to this module (the build copies them to dist/viewer/)
13
29
  const here = path.dirname(fileURLToPath(import.meta.url));
30
+ const appDir = path.join(here, 'app');
14
31
  // three.js where Node resolves it: this checkout's node_modules, or the hoisted copy next to an installed package
15
32
  const threeDir = (() => {
16
33
  try {
@@ -21,22 +38,366 @@ const threeDir = (() => {
21
38
  }
22
39
  })();
23
40
  const MIME = { '.js': 'text/javascript', '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.json': 'application/json', '.glb': 'model/gltf-binary' };
24
- export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ?? 7341)) {
41
+ /** largest file POST /api/inputs accepts */
42
+ export const MAX_UPLOAD = 512 * 1024 * 1024;
43
+ /** uploads in progress are written next to their target as `.<name>.<n>.part`, then renamed */
44
+ const PART_RE = /(^|\/)\.[^/]*\.part$/;
45
+ class HttpError extends Error {
46
+ status;
47
+ constructor(status, msg) { super(msg); this.status = status; }
48
+ }
49
+ /** The shape every geometry route serves: the same GLB options as /api/geo; images alone show as textured quads. */
50
+ const toGLB = (g) => exportGeometryAsync(withImagePreview(withHeightfieldPreview(g)), 'glb', { splitByName: false, lineMode: 'lines', custom: false });
51
+ const issueText = (e) => `[${e.node}] ${e.message}`;
52
+ /**
53
+ * A dropped file's name as stored in inputs/: a plain basename with its extension. Path separators and ".." are
54
+ * rejected; characters Windows cannot store become "_".
55
+ */
56
+ export function inputFileName(raw) {
57
+ const s = raw.normalize('NFC').trim();
58
+ if (!s || /[\\/]/.test(s) || s.includes('..') || s.includes('\0'))
59
+ throw new HttpError(400, `bad file name ${JSON.stringify(raw)}: give a plain file name, without folders or ".."`);
60
+ let n = s.replace(/[<>:"|?*\u0000-\u001f]/g, '_').replace(/[. ]+$/, '');
61
+ if (!n || n.startsWith('.'))
62
+ throw new HttpError(400, `bad file name ${JSON.stringify(raw)}: it must not start with "."`);
63
+ if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(n))
64
+ n = '_' + n;
65
+ if (n.length > 200)
66
+ throw new HttpError(400, 'file name longer than 200 characters');
67
+ return n;
68
+ }
69
+ // ---------------------------------------------------------------- markers
70
+ // What a person clicks into the view to direct the agent: "village here" (site), "road along here" (path), "keep this
71
+ // area empty" (zone, volume). The page sends the editable list; the server stores it and writes the geometry agents
72
+ // read as inputs/markers.json, in the conventions of help topic "inputs" (string attributes name and role).
73
+ export const MARKER_KINDS = KINDS;
74
+ /**
75
+ * A marker list (the POST /api/markers body, or the stored list) checked and normalised by the page's own rules
76
+ * (app/markers.js): names trimmed and unique (ignoring case), the defaults filled in, ids given to markers without
77
+ * one. Throws HttpError 400 naming the problem.
78
+ */
79
+ export function parseMarkers(body) {
80
+ try {
81
+ return parseMarkerList(body);
82
+ }
83
+ catch (e) {
84
+ throw e instanceof MarkerError ? new HttpError(400, e.message) : e;
85
+ }
86
+ }
87
+ /**
88
+ * The geometry of inputs/markers.json. Sites are points with name, role "site", pscale = radius and orient (identity);
89
+ * paths are open polylines, zones closed ones facing up, volumes closed boxes of 6 quads facing out; those carry prim
90
+ * name and role.
91
+ */
92
+ export function markersGeometry(list) {
93
+ const b = new GeoBuilder();
94
+ for (const m of list) {
95
+ if (m.kind === 'site') {
96
+ const [x, y, z] = m.points[0];
97
+ const p = b.addPoint(x, y, z);
98
+ b.attrib('point', 'name', 1, 'string').set(p, m.name);
99
+ b.attrib('point', 'role', 1, 'string').set(p, 'site');
100
+ b.attrib('point', 'pscale').set(p, m.radius ?? 5);
101
+ b.attrib('point', 'orient', 4).set(p, [0, 0, 0, 1]);
102
+ continue;
103
+ }
104
+ const prims = [];
105
+ if (m.kind === 'volume') {
106
+ const [a, c] = m.points;
107
+ const lo = [Math.min(a[0], c[0]), Math.min(a[1], c[1]), Math.min(a[2], c[2])];
108
+ const hi = [Math.max(a[0], c[0]), lo[1] + (m.height ?? 10), Math.max(a[2], c[2])];
109
+ // corner (i, j, k) is point base + 4i + 2j + k, at the low (0) or high (1) side of x, y, z
110
+ const base = b.numPoints;
111
+ for (let i = 0; i < 2; i++)
112
+ for (let j = 0; j < 2; j++)
113
+ for (let k = 0; k < 2; k++)
114
+ b.addPoint(i ? hi[0] : lo[0], j ? hi[1] : lo[1], k ? hi[2] : lo[2]);
115
+ // the box node's winding: counter-clockwise seen from outside
116
+ for (let ax = 0; ax < 3; ax++)
117
+ for (const s of [0, 1]) {
118
+ const u = (ax + 1) % 3, v = (ax + 2) % 3;
119
+ const quad = [[0, 0], [1, 0], [1, 1], [0, 1]];
120
+ if (!s)
121
+ quad.reverse();
122
+ prims.push(b.addPrim(quad.map(([cu, cv]) => { const c3 = [0, 0, 0]; c3[ax] = s; c3[u] = cu; c3[v] = cv; return base + 4 * c3[0] + 2 * c3[1] + c3[2]; })));
123
+ }
124
+ }
125
+ else {
126
+ let pts = m.points;
127
+ if (m.kind === 'zone') {
128
+ // drawn either way round; stored counter-clockwise seen from above, so the polygon faces up (+Y)
129
+ let ny = 0;
130
+ for (let k = 0; k < pts.length; k++) {
131
+ const p = pts[k], q = pts[(k + 1) % pts.length];
132
+ ny += (p[2] - q[2]) * (p[0] + q[0]);
133
+ }
134
+ if (ny < 0)
135
+ pts = pts.slice().reverse();
136
+ }
137
+ prims.push(b.addPrim(pts.map(([x, y, z]) => b.addPoint(x, y, z)), m.kind === 'zone'));
138
+ }
139
+ for (const pr of prims) {
140
+ b.attrib('prim', 'name', 1, 'string').set(pr, m.name);
141
+ b.attrib('prim', 'role', 1, 'string').set(pr, m.kind);
142
+ }
143
+ }
144
+ return b.build();
145
+ }
146
+ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ?? 7341), opts = {}) {
25
147
  const clients = new Set();
26
- ws.listeners.add((ev) => {
148
+ const broadcast = (ev) => {
27
149
  const msg = `data: ${JSON.stringify(ev)}\n\n`;
28
150
  for (const c of clients)
29
151
  c.write(msg);
152
+ };
153
+ ws.listeners.add(broadcast);
154
+ const outputs = createOutputs(ws, () => broadcast({ outputs: true }), { persistGraph: opts.persistGraph });
155
+ // ---------------------------------------------------------------- inputs/
156
+ let inputsVersion = 0;
157
+ const inputsChanged = () => broadcast({ inputs: ++inputsVersion });
158
+ const listInputs = () => ws.listInputs().filter((f) => !PART_RE.test(f.path));
159
+ const inputsWhere = opts.inputsWhere ?? (path.dirname(ws.inputDir) === ws.dir ? 'in the workspace' : `in ${path.dirname(ws.inputDir)}`);
160
+ // Files copied into inputs/ by other means (file manager, an agent) show up too, once the folder exists. The viewer
161
+ // does not make it just to watch it (`topotopo view`'s inputs/ beside the graph file appears with the first drop):
162
+ // uploads and listings start the watch when the folder is there by then.
163
+ let watcher = null, watchTimer, closed = false;
164
+ const changed = () => { clearTimeout(watchTimer); watchTimer = setTimeout(inputsChanged, 250); };
165
+ const unwatch = (w = watcher) => { w?.close(); if (watcher === w)
166
+ watcher = null; };
167
+ const watchInputs = () => {
168
+ if (watcher || closed)
169
+ return;
170
+ try {
171
+ if (!fs.statSync(ws.inputDir, { throwIfNoEntry: false })?.isDirectory())
172
+ return;
173
+ const w = fs.watch(ws.inputDir, { recursive: true }, (_ev, f) => {
174
+ const rel = f ? String(f) : '';
175
+ // The folder itself went away. Windows says so with no error but a stream of events naming it by absolute path,
176
+ // which goes on after the folder is made again. Stop; the listing this change prompts watches a new folder.
177
+ if (path.isAbsolute(rel) || !fs.existsSync(ws.inputDir)) {
178
+ unwatch(w);
179
+ changed();
180
+ return;
181
+ }
182
+ if (!PART_RE.test(rel.split(path.sep).join('/')))
183
+ changed();
184
+ });
185
+ w.on('error', () => { unwatch(w); changed(); });
186
+ w.unref();
187
+ watcher = w;
188
+ }
189
+ catch { /* no watch: uploads through the viewer still notify */ }
190
+ };
191
+ watchInputs();
192
+ /** `path` query of /api/input*: a file below inputs/ (posix, relative). */
193
+ const inputPath = (raw) => {
194
+ const rel = (raw ?? '').replace(/\\/g, '/');
195
+ const parts = rel.split('/');
196
+ if (!rel || rel.startsWith('/') || /^[A-Za-z]:/.test(rel) || parts.some((s) => s === '' || s === '.' || s === '..'))
197
+ throw new HttpError(400, `bad input path ${JSON.stringify(raw)}: give a path relative to inputs/ as GET /api/inputs lists it`);
198
+ const root = path.resolve(ws.inputDir);
199
+ const abs = path.resolve(root, ...parts);
200
+ if (!abs.startsWith(root + path.sep))
201
+ throw new HttpError(400, `input path ${JSON.stringify(raw)} leaves inputs/`);
202
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
203
+ throw new HttpError(404, `no input "${rel}" (GET /api/inputs lists them)`);
204
+ const realRelative = path.relative(fs.realpathSync(root), fs.realpathSync(abs));
205
+ if (realRelative.startsWith('..') || path.isAbsolute(realRelative))
206
+ throw new HttpError(400, 'input path leaves inputs/');
207
+ return { rel, abs };
208
+ };
209
+ const inputThumbs = new Map();
210
+ const imageType = (p) => ({ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp' })[path.extname(p).toLowerCase()];
211
+ /** The one-node graph that loads an input. */
212
+ const inputGraph = (rel, abs) => {
213
+ // "inputs/<rel>", the path a graph's file node uses, resolves against the host's base directory: the folder that
214
+ // holds inputs/ under the MCP server (the workspace) and under `topotopo view` (the graph file's folder). A
215
+ // workspace whose engine resolves paths elsewhere (an embedding app, a test) gets the absolute path.
216
+ const ref = `inputs/${rel}`;
217
+ const p = path.resolve(ws.engine.host.resolvePath(ref)) === abs ? ref : abs;
218
+ return { nodes: { f: { type: 'file', params: { path: p } } }, output: 'f' };
219
+ };
220
+ const upload = async (req, u) => {
221
+ const name = inputFileName(u.searchParams.get('name') ?? '');
222
+ const overwrite = u.searchParams.get('overwrite') === '1';
223
+ const root = path.resolve(ws.inputDir);
224
+ const dest = path.join(root, name);
225
+ if (path.dirname(dest) !== root)
226
+ throw new HttpError(400, `bad file name "${name}"`);
227
+ const len = Number(req.headers['content-length']);
228
+ if (len > MAX_UPLOAD)
229
+ throw new HttpError(413, `${name} is ${(len / 2 ** 20).toFixed(0)} MB; uploads are limited to ${MAX_UPLOAD / 2 ** 20} MB`);
230
+ const exists = () => fs.existsSync(dest);
231
+ const conflict = { status: 409, body: { ok: false, exists: true, path: name, error: `inputs/${name} exists (overwrite=1 replaces it)` } };
232
+ if (!overwrite && exists())
233
+ return conflict;
234
+ // the first drop makes the folder (again, after it was deleted): a watch from before is on a folder that is gone
235
+ if (fs.mkdirSync(root, { recursive: true }) !== undefined)
236
+ unwatch();
237
+ const part = path.join(root, `.${name}.${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}.part`);
238
+ let n = 0;
239
+ const limit = new Transform({
240
+ transform(chunk, _enc, cb) { n += chunk.length; cb(n > MAX_UPLOAD ? new HttpError(413, `uploads are limited to ${MAX_UPLOAD / 2 ** 20} MB`) : null, chunk); },
241
+ });
242
+ try {
243
+ await pipeline(req, limit, fs.createWriteStream(part, { flags: 'wx' }));
244
+ if (!overwrite && exists()) {
245
+ fs.rmSync(part, { force: true });
246
+ return conflict;
247
+ }
248
+ fs.renameSync(part, dest);
249
+ }
250
+ catch (e) {
251
+ fs.rmSync(part, { force: true });
252
+ throw e;
253
+ }
254
+ watchInputs();
255
+ inputsChanged();
256
+ return { status: 200, body: { ok: true, path: name, size: n } };
257
+ };
258
+ // ---------------------------------------------------------------- markers
259
+ // The editable list is inputs/.markers.json (a dot-file: not listed, not read by agents); the geometry is
260
+ // inputs/markers.json. An empty list removes both.
261
+ const markersListFile = () => path.join(ws.inputDir, '.markers.json');
262
+ const markersGeoFile = () => path.join(ws.inputDir, 'markers.json');
263
+ /** Written as a dot-file next to the target and renamed, so readers never see half a file. */
264
+ const writeAtomic = (file, data) => {
265
+ const part = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}.part`);
266
+ try {
267
+ fs.writeFileSync(part, data);
268
+ fs.renameSync(part, file);
269
+ }
270
+ catch (e) {
271
+ fs.rmSync(part, { force: true });
272
+ throw e;
273
+ }
274
+ };
275
+ const loadMarkers = () => {
276
+ let text;
277
+ try {
278
+ text = fs.readFileSync(markersListFile(), 'utf8');
279
+ }
280
+ catch {
281
+ return { markers: [] };
282
+ }
283
+ try {
284
+ return { markers: parseMarkers(JSON.parse(text)) };
285
+ }
286
+ catch (e) {
287
+ return { markers: [], error: `inputs/.markers.json is unreadable (${e.message}); saving markers replaces it` };
288
+ }
289
+ };
290
+ const saveMarkers = (list) => {
291
+ let counts = { points: 0, prims: 0 };
292
+ if (!list.length)
293
+ for (const f of [markersGeoFile(), markersListFile()])
294
+ fs.rmSync(f, { force: true });
295
+ else {
296
+ const g = markersGeometry(list);
297
+ counts = { points: g.numPoints, prims: g.numPrims };
298
+ // as for an upload: the first marker makes the folder (again, after it was deleted), and a watch from before is
299
+ // on a folder that is gone
300
+ if (fs.mkdirSync(ws.inputDir, { recursive: true }) !== undefined)
301
+ unwatch();
302
+ writeAtomic(markersGeoFile(), exportGeometry(g, 'json'));
303
+ writeAtomic(markersListFile(), JSON.stringify({ markers: list }, null, 1));
304
+ }
305
+ watchInputs();
306
+ inputsChanged();
307
+ return { ok: true, count: list.length, path: list.length ? 'markers.json' : null, ...counts };
308
+ };
309
+ // ---------------------------------------------------------------- POST /api/vars
310
+ // One edit + cook at a time per graph. Requests that arrive while one runs are merged (the latest value of each
311
+ // var wins) and applied by a single further cook; every request is answered once its values are applied.
312
+ const varQueues = new Map();
313
+ const applyBatch = async (name, b) => {
314
+ const prev = ws.graphs.get(name);
315
+ if (!prev)
316
+ return { status: 404, body: { ok: false, ms: 0, errors: [`no graph ${name}`] } };
317
+ try {
318
+ const { graph, report } = await ws.edit(name, [{ op: 'vars', vars: b.vars }]);
319
+ return { status: 200, body: { ok: report.ok, ms: report.ms, errors: report.errors.map(issueText), vars: graph.vars ?? {} } };
320
+ }
321
+ catch (e) {
322
+ // rejected edits carry their issues (one string each); op errors are plain messages
323
+ return { status: 400, body: { ok: false, ms: 0, errors: Array.isArray(e?.errors) ? e.errors.map(issueText) : [String(e?.message ?? e)] } };
324
+ }
325
+ };
326
+ const applyVars = (name, vars) => new Promise((resolve) => {
327
+ let q = varQueues.get(name);
328
+ if (!q)
329
+ varQueues.set(name, q = { busy: false, next: null });
330
+ if (q.next) {
331
+ Object.assign(q.next.vars, vars);
332
+ q.next.waiters.push(resolve);
333
+ }
334
+ else
335
+ q.next = { vars: { ...vars }, waiters: [resolve] };
336
+ if (q.busy)
337
+ return;
338
+ q.busy = true;
339
+ (async () => {
340
+ try {
341
+ while (q.next) {
342
+ const b = q.next;
343
+ q.next = null;
344
+ const r = await applyBatch(name, b).catch((e) => ({ status: 500, body: { ok: false, ms: 0, errors: [String(e?.message ?? e)] } }));
345
+ for (const w of b.waiters)
346
+ w(r);
347
+ }
348
+ }
349
+ finally {
350
+ q.busy = false;
351
+ }
352
+ })();
353
+ });
354
+ const readJSON = (req, max = 4 << 20) => new Promise((resolve, reject) => {
355
+ const chunks = [];
356
+ let n = 0;
357
+ req.on('data', (c) => { n += c.length; if (n <= max)
358
+ chunks.push(c); });
359
+ req.on('end', () => {
360
+ if (n > max)
361
+ return reject(new HttpError(413, `request body over ${max >> 20} MB`));
362
+ const s = Buffer.concat(chunks).toString('utf8');
363
+ try {
364
+ resolve(s.trim() ? JSON.parse(s) : {});
365
+ }
366
+ catch (e) {
367
+ reject(new HttpError(400, `body is not JSON: ${e.message}`));
368
+ }
369
+ });
370
+ req.on('error', reject);
30
371
  });
372
+ // ---------------------------------------------------------------- routes
31
373
  const server = http.createServer(async (req, res) => {
374
+ const send = (code, body, type = 'text/plain; charset=utf-8') => {
375
+ res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store' });
376
+ res.end(body);
377
+ };
378
+ const json = (code, body) => send(code, JSON.stringify(body), MIME['.json']);
379
+ let route = '';
32
380
  try {
381
+ // DNS rebinding: only requests addressed to this server; cross-site writes: only from this server's own page
382
+ const host = String(req.headers.host ?? '');
383
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host))
384
+ return json(403, { error: `unexpected Host "${host}"` });
385
+ const origin = req.headers.origin;
386
+ if (req.method !== 'GET' && req.method !== 'HEAD' && origin !== undefined && origin !== `http://${host}`)
387
+ return json(403, { error: `cross-origin ${req.method} refused (${origin})` });
33
388
  const u = new URL(req.url ?? '/', 'http://localhost');
34
- const send = (code, body, type = 'text/plain; charset=utf-8') => {
35
- res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store' });
36
- res.end(body);
37
- };
389
+ route = u.pathname;
390
+ if (await outputs.handle(req, res, u, readJSON))
391
+ return;
38
392
  if (u.pathname === '/' || u.pathname === '/index.html')
39
393
  return send(200, fs.readFileSync(path.join(here, 'index.html')), MIME['.html']);
394
+ // the page's modules and style sheet
395
+ if (u.pathname.startsWith('/app/')) {
396
+ const p = path.resolve(appDir, decodeURIComponent(u.pathname.slice('/app/'.length)));
397
+ if (!p.startsWith(appDir + path.sep) || !fs.statSync(p, { throwIfNoEntry: false })?.isFile())
398
+ return send(404, 'not found');
399
+ return send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream');
400
+ }
40
401
  if (u.pathname.startsWith('/vendor/three/')) {
41
402
  const rel = decodeURIComponent(u.pathname.slice('/vendor/three/'.length));
42
403
  const p = path.resolve(threeDir, rel);
@@ -56,6 +417,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
56
417
  const last = ws.lastReport.get(name);
57
418
  return {
58
419
  name, output: last?.target ?? g.output ?? null, version: ws.versions.get(name) ?? 0,
420
+ vars: g.vars ?? {}, params: g.params ?? {},
59
421
  nodes: Object.entries(g.nodes).map(([n, spec]) => {
60
422
  const def = ws.engine.resolveDef(spec.type);
61
423
  const r = last?.results.get(n);
@@ -63,7 +425,91 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
63
425
  }),
64
426
  };
65
427
  });
66
- return send(200, JSON.stringify(out), MIME['.json']);
428
+ return json(200, out);
429
+ }
430
+ // the last cook of a graph, for the page's status bar: cook time, errors and warnings
431
+ if (u.pathname === '/api/report') {
432
+ const name = u.searchParams.get('graph') ?? 'main';
433
+ if (!ws.graphs.has(name))
434
+ return json(404, { error: `no graph ${name}` });
435
+ const r = ws.lastReport.get(name), version = ws.versions.get(name) ?? 0;
436
+ if (!r)
437
+ return json(200, { graph: name, version, cooked: false });
438
+ return json(200, { graph: name, version, cooked: true, target: r.target, ok: r.ok, ms: r.ms, errors: r.errors.map(issueText), warnings: r.warnings.map(issueText) });
439
+ }
440
+ if (u.pathname === '/api/vars') {
441
+ if (req.method !== 'POST')
442
+ return json(405, { ok: false, ms: 0, errors: ['POST {"vars": {...}}'] });
443
+ const name = u.searchParams.get('graph') ?? 'main';
444
+ const body = await readJSON(req);
445
+ const vars = body?.vars ?? {};
446
+ if (!vars || typeof vars !== 'object' || Array.isArray(vars))
447
+ throw new HttpError(400, '"vars" must be an object {name: value}');
448
+ if (!ws.graphs.has(name))
449
+ return json(404, { ok: false, ms: 0, errors: [`no graph ${name}`] });
450
+ const r = await applyVars(name, vars);
451
+ return json(r.status, r.body);
452
+ }
453
+ if (u.pathname === '/api/inputs') {
454
+ if (req.method === 'POST') {
455
+ const r = await upload(req, u);
456
+ return json(r.status, r.body);
457
+ }
458
+ watchInputs();
459
+ return json(200, listInputs());
460
+ }
461
+ // where dropped files go: the absolute folder, and in words for the page ("beside house.json")
462
+ if (u.pathname === '/api/inputs_dir')
463
+ return json(200, { dir: ws.inputDir, where: inputsWhere });
464
+ if (u.pathname === '/api/markers') {
465
+ if (req.method === 'POST')
466
+ return json(200, saveMarkers(parseMarkers(await readJSON(req))));
467
+ if (req.method !== 'GET' && req.method !== 'HEAD')
468
+ return json(405, { ok: false, error: 'GET, or POST {"markers": [...]}' });
469
+ return json(200, loadMarkers());
470
+ }
471
+ if (u.pathname === '/api/input_image' || u.pathname === '/api/input_thumb') {
472
+ if (req.method !== 'GET')
473
+ throw new HttpError(405, 'GET required');
474
+ const { rel, abs } = inputPath(u.searchParams.get('path')), mime = imageType(abs);
475
+ if (mime)
476
+ return send(200, fs.readFileSync(abs), mime);
477
+ if (u.pathname === '/api/input_image')
478
+ throw new HttpError(400, 'choose a PNG, JPEG or WebP image');
479
+ const stat = fs.statSync(abs), key = `${abs}:${stat.size}:${stat.mtimeMs}`;
480
+ if (!inputThumbs.has(key)) {
481
+ if (inputThumbs.size >= 128)
482
+ inputThumbs.delete(inputThumbs.keys().next().value);
483
+ const pending = (async () => {
484
+ await new Promise((resolve) => setImmediate(resolve));
485
+ const r = await ws.engine.cook(inputGraph(rel, abs));
486
+ if (!r.ok || !r.geo)
487
+ throw new HttpError(422, r.errors.map(issueText).join('\n'));
488
+ const image = renderGeometry(withHeightfieldPreview(r.geo), { size: 160, views: ['persp'], viewLabels: false });
489
+ return encodePNG(image.rgba.subarray(0, image.width * 160 * 4), image.width, 160, (d) => zlib.deflateSync(d));
490
+ })();
491
+ inputThumbs.set(key, pending);
492
+ }
493
+ return send(200, await inputThumbs.get(key), 'image/png');
494
+ }
495
+ if (u.pathname === '/api/input' || u.pathname === '/api/input_info') {
496
+ const { rel, abs } = inputPath(u.searchParams.get('path'));
497
+ if (u.pathname === '/api/input_info' && imageType(abs)) {
498
+ let summary = `${imageType(abs)} · ${fs.statSync(abs).size} bytes`;
499
+ // Preserve the existing PNG summary contract without cooking a file-node graph.
500
+ if (path.extname(abs).toLowerCase() === '.png') {
501
+ const geo = new GeoBuilder().build();
502
+ geo.volumes.push(imageFromPNGFile(fs.readFileSync(abs), abs));
503
+ summary = summarize(geo);
504
+ }
505
+ return json(200, { path: rel, summary, image: true });
506
+ }
507
+ const r = await ws.engine.cook(inputGraph(rel, abs));
508
+ if (!r.ok || !r.geo)
509
+ return json(500, { error: r.errors.map(issueText).join('\n') });
510
+ if (u.pathname === '/api/input_info')
511
+ return json(200, { path: rel, summary: summarize(r.geo), ms: r.ms });
512
+ return send(200, await toGLB(r.geo), MIME['.glb']);
67
513
  }
68
514
  if (u.pathname === '/api/geo' || u.pathname === '/api/info') {
69
515
  const name = u.searchParams.get('graph') ?? 'main';
@@ -73,16 +519,20 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
73
519
  return send(404, JSON.stringify({ error: `no graph ${name}` }), MIME['.json']);
74
520
  const r = await ws.engine.cook(g, { target: node });
75
521
  if (!r.ok || !r.geo)
76
- return send(500, JSON.stringify({ error: r.errors.map((e) => `[${e.node}] ${e.message}`).join('\n') }), MIME['.json']);
522
+ return send(500, JSON.stringify({ error: r.errors.map(issueText).join('\n') }), MIME['.json']);
77
523
  if (u.pathname === '/api/info')
78
524
  return send(200, JSON.stringify({ target: r.target, summary: summarize(r.geo), ms: r.ms }), MIME['.json']);
79
- return send(200, await exportGeometryAsync(withHeightfieldPreview(r.geo), 'glb', { splitByName: false, lineMode: 'lines', custom: false }), MIME['.glb']);
525
+ return send(200, await toGLB(r.geo), MIME['.glb']);
80
526
  }
81
527
  send(404, 'not found');
82
528
  }
83
529
  catch (e) {
84
- res.writeHead(500, { 'content-type': 'application/json' });
85
- res.end(JSON.stringify({ error: String(e?.message ?? e) }));
530
+ if (res.headersSent || res.destroyed)
531
+ return;
532
+ const status = e instanceof HttpError ? e.status : 500;
533
+ const msg = String(e?.message ?? e);
534
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...(status === 413 ? { connection: 'close' } : {}) });
535
+ res.end(JSON.stringify(route === '/api/vars' ? { ok: false, ms: 0, errors: [msg] } : { ok: false, error: msg }));
86
536
  }
87
537
  });
88
538
  const listen = (p) => new Promise((resolve, reject) => {
@@ -105,5 +555,18 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
105
555
  const keepAlive = setInterval(() => { for (const c of clients)
106
556
  c.write(': ping\n\n'); }, 20000);
107
557
  keepAlive.unref();
108
- return { url: `http://127.0.0.1:${actual}/`, close: () => { clearInterval(keepAlive); server.close(); } };
558
+ return {
559
+ url: `http://127.0.0.1:${actual}/`,
560
+ close: () => {
561
+ closed = true;
562
+ outputs.close();
563
+ clearInterval(keepAlive);
564
+ clearTimeout(watchTimer);
565
+ unwatch();
566
+ ws.listeners.delete(broadcast);
567
+ for (const c of clients)
568
+ c.end();
569
+ server.close();
570
+ },
571
+ };
109
572
  }
@@ -1,9 +1,12 @@
1
1
  import { Engine } from './graph/engine.ts';
2
- import type { CookReport } from './graph/engine.ts';
3
- import type { GraphSpec, NodeSpec } from './graph/types.ts';
2
+ import type { CookReport, Issue } from './graph/engine.ts';
3
+ import type { ExportTarget, GraphSpec, NodeSpec } from './graph/types.ts';
4
4
  export interface EditOp {
5
- op: 'set' | 'add' | 'remove' | 'connect' | 'rename' | 'output' | 'vars' | 'bypass' | 'replace' | 'insert';
5
+ op: 'set' | 'add' | 'remove' | 'connect' | 'rename' | 'output' | 'vars' | 'bypass' | 'replace' | 'insert' | 'export';
6
6
  node?: string;
7
+ /** op export: the named output (omitted: the default output) and its target (null removes it) */
8
+ output?: string;
9
+ export?: ExportTarget | null;
7
10
  params?: Record<string, any>;
8
11
  spec?: NodeSpec;
9
12
  type?: string;
@@ -16,6 +19,36 @@ export interface EditOp {
16
19
  value?: boolean;
17
20
  note?: string;
18
21
  }
22
+ /** A file under <workspace>/inputs. */
23
+ export interface InputFile {
24
+ /** posix path relative to inputs/ (a file node reads it as "inputs/" + path) */
25
+ path: string;
26
+ kind: 'geometry' | 'image' | 'other';
27
+ /** lower-case extension without the dot ("points.json" counts as one) */
28
+ ext: string;
29
+ size: number;
30
+ /** modification time, ms since the epoch */
31
+ mtime: number;
32
+ }
33
+ /** Lower-case extension of a file name without the dot; ".points.json" is one extension, dot-files have none. */
34
+ export declare function inputExt(file: string): string;
35
+ export declare function inputKind(ext: string): InputFile['kind'];
36
+ export interface WorkspaceOptions {
37
+ /**
38
+ * The inputs folder when it is not <dir>/inputs. `topotopo view` keeps its workspace in a scratch folder but puts
39
+ * inputs/ beside the graph file, where the graph's file nodes read "inputs/<name>" and the files outlive the viewer.
40
+ * load() does not create a folder given here: the first file written into it does (the viewer's upload route), so a
41
+ * graph that never gets a drop leaves no empty inputs/ beside it.
42
+ */
43
+ inputs?: string;
44
+ /** Persistent exports directory; view mode places it beside the source graph. */
45
+ exports?: string;
46
+ }
47
+ /** Thrown by Workspace.edit when the edited graph does not validate; the stored graph is unchanged. */
48
+ export declare class EditRejected extends Error {
49
+ errors: Issue[];
50
+ constructor(errors: Issue[]);
51
+ }
19
52
  export declare class Workspace {
20
53
  dir: string;
21
54
  engine: Engine;
@@ -26,10 +59,18 @@ export declare class Workspace {
26
59
  graph: string;
27
60
  version: number;
28
61
  }) => void>;
29
- constructor(dir: string, engine: Engine);
62
+ /** the inputs folder given to the constructor (WorkspaceOptions.inputs), if any */
63
+ private inputsAt;
64
+ private exportsAt;
65
+ constructor(dir: string, engine: Engine, opts?: WorkspaceOptions);
30
66
  get graphDir(): string;
31
67
  get assetDir(): string;
32
68
  get exportDir(): string;
69
+ /**
70
+ * files people drop in: meshes, guide curves and points, PNG masks and heightmaps (read as "inputs/<path>");
71
+ * <dir>/inputs unless the constructor was given another folder
72
+ */
73
+ get inputDir(): string;
33
74
  load(): {
34
75
  graphs: number;
35
76
  assets: number;
@@ -41,6 +82,8 @@ export declare class Workspace {
41
82
  getGraph(name: string): GraphSpec;
42
83
  setGraph(name: string, spec: GraphSpec): void;
43
84
  deleteGraph(name: string): void;
85
+ /** Every file under inputs/, recursively: posix paths relative to it, sorted. Dot-files and dot-folders are skipped. */
86
+ listInputs(): InputFile[];
44
87
  /** Merge nodes/vars/output of `patch` into an existing graph (upsert). */
45
88
  mergeGraph(name: string, patch: GraphSpec): GraphSpec;
46
89
  /** Apply edit operations; returns the new graph (not yet stored) and notes. */
@@ -48,5 +91,18 @@ export declare class Workspace {
48
91
  graph: GraphSpec;
49
92
  notes: string[];
50
93
  };
94
+ /**
95
+ * The one path for an edit, whoever makes it (the MCP edit tool, the viewer's controls): apply the ops, validate
96
+ * (an invalid result throws EditRejected listing the per-node errors and stores nothing), store, cook at `frame`,
97
+ * then notify the listeners. They hear after the cook so that what they read (lastReport, cached geometry) is the
98
+ * new version's; a cook that throws still notifies, since the graph was stored.
99
+ */
100
+ edit(name: string, ops: EditOp[], opts?: {
101
+ frame?: number;
102
+ }): Promise<{
103
+ graph: GraphSpec;
104
+ notes: string[];
105
+ report: CookReport;
106
+ }>;
51
107
  cook(name: string, target?: string, frame?: number): Promise<CookReport>;
52
108
  }