@floless/app 0.113.1 → 0.113.3

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.
@@ -52462,7 +52462,7 @@ function awareNpmVersion() {
52462
52462
  }
52463
52463
  }
52464
52464
  var SHELL_META = /[&|;<>^"'`$()%\r\n\0]/;
52465
- function runRaw(args, onSpawn, envOverride) {
52465
+ function runRaw(args, onSpawn, envOverride, timeoutMs) {
52466
52466
  const invoker = currentInvoker();
52467
52467
  const [bin, ...preArgs] = invoker.head;
52468
52468
  if (!bin) throw new AwareError("aware CLI invoker not resolved");
@@ -52471,6 +52471,10 @@ function runRaw(args, onSpawn, envOverride) {
52471
52471
  if (bad !== void 0) throw new AwareError(`refusing to pass unsafe argument to shell: ${bad}`);
52472
52472
  }
52473
52473
  const argv = [...preArgs, ...args];
52474
+ const limit = timeoutMs ?? RUN_TIMEOUT_MS;
52475
+ if (!Number.isFinite(limit) || limit <= 0) {
52476
+ throw new AwareError(`invalid aware timeout: ${limit}`);
52477
+ }
52474
52478
  return new Promise((resolve11, reject) => {
52475
52479
  const child = (0, import_node_child_process2.spawn)(bin, argv, {
52476
52480
  shell: invoker.shell,
@@ -52485,8 +52489,8 @@ function runRaw(args, onSpawn, envOverride) {
52485
52489
  child.stderr.on("data", (d) => stderr = cap(stderr, d));
52486
52490
  const timer = setTimeout(() => {
52487
52491
  killTree(child);
52488
- reject(new AwareError(`aware ${args.join(" ")} timed out after ${RUN_TIMEOUT_MS}ms`));
52489
- }, RUN_TIMEOUT_MS);
52492
+ reject(new AwareError(`aware ${args.join(" ")} timed out after ${limit}ms`));
52493
+ }, limit);
52490
52494
  child.on("error", (err2) => {
52491
52495
  clearTimeout(timer);
52492
52496
  reject(new AwareError(`failed to spawn aware: ${err2.message}`, err2));
@@ -52606,31 +52610,15 @@ async function hostInstances(host) {
52606
52610
  resolve11({ code, stdout, stderr });
52607
52611
  });
52608
52612
  });
52609
- const parse = (stdout) => {
52610
- try {
52611
- const body = JSON.parse(stdout.trim());
52612
- const rows2 = Array.isArray(body.instances) ? body.instances : [];
52613
- return rows2.map((raw) => {
52614
- const r = raw ?? {};
52615
- return {
52616
- pid: typeof r.pid === "number" ? r.pid : null,
52617
- version: typeof r.version === "string" ? r.version : null,
52618
- addinLoaded: typeof r.addin_loaded === "boolean" ? r.addin_loaded : null
52619
- };
52620
- });
52621
- } catch {
52622
- return [];
52623
- }
52624
- };
52625
52613
  let out = await probe();
52626
52614
  let answered = spoke(out.stdout);
52627
- let instances = parse(out.stdout);
52615
+ let instances = parseHostInstances(out.stdout);
52628
52616
  let env2;
52629
52617
  if (host === "sketchup" && instances.length === 0) {
52630
52618
  const override = sketchupDiscoveryEnv();
52631
52619
  out = await probe(override);
52632
52620
  answered = answered || spoke(out.stdout);
52633
- instances = parse(out.stdout);
52621
+ instances = parseHostInstances(out.stdout);
52634
52622
  if (instances.length > 0) env2 = override;
52635
52623
  }
52636
52624
  if (instances.length === 0) {
@@ -52643,6 +52631,23 @@ async function hostInstances(host) {
52643
52631
  }
52644
52632
  return { ok: true, instances, env: env2 };
52645
52633
  }
52634
+ function parseHostInstances(stdout) {
52635
+ try {
52636
+ const body = JSON.parse(stdout.trim());
52637
+ const rows2 = Array.isArray(body.instances) ? body.instances : [];
52638
+ return rows2.map((raw) => {
52639
+ const r = raw ?? {};
52640
+ return {
52641
+ pid: typeof r.pid === "number" ? r.pid : null,
52642
+ version: typeof r.version === "string" ? r.version : null,
52643
+ rhinoId: typeof r.rhino_id === "string" && r.rhino_id.trim() ? r.rhino_id : null,
52644
+ addinLoaded: typeof r.addin_loaded === "boolean" ? r.addin_loaded : null
52645
+ };
52646
+ });
52647
+ } catch {
52648
+ return [];
52649
+ }
52650
+ }
52646
52651
  function spoke(stdout) {
52647
52652
  try {
52648
52653
  const body = JSON.parse(stdout.trim());
@@ -53392,7 +53397,7 @@ var aware = {
53392
53397
  const { code, stdout, stderr } = await runRaw(args, (child) => {
53393
53398
  reg2 = { child, cancelled: false };
53394
53399
  activeRun = reg2;
53395
- }, opts.env);
53400
+ }, opts.env, opts.timeoutMs);
53396
53401
  if (reg2 && reg2.cancelled) {
53397
53402
  throw new AwareError("Run cancelled", { cancelled: true });
53398
53403
  }
@@ -54158,7 +54163,7 @@ function appVersion() {
54158
54163
  return resolveVersion({
54159
54164
  isSea: isSea2(),
54160
54165
  sqVersionXml: readSqVersionXml(),
54161
- define: true ? "0.113.1" : void 0,
54166
+ define: true ? "0.113.3" : void 0,
54162
54167
  pkgVersion: readPkgVersion()
54163
54168
  });
54164
54169
  }
@@ -54174,7 +54179,7 @@ function resolveChannel(s) {
54174
54179
  function appChannel() {
54175
54180
  return resolveChannel({
54176
54181
  isSea: isSea2(),
54177
- define: true ? "0.113.1" : void 0,
54182
+ define: true ? "0.113.3" : void 0,
54178
54183
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
54179
54184
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
54180
54185
  modulePath: process.argv[1]
@@ -54705,9 +54710,9 @@ function autoLabels(style, n) {
54705
54710
  return out;
54706
54711
  }
54707
54712
  function labelsFor(override, style, n) {
54708
- const own = String(override || "").trim().split(/\s+/).filter(Boolean);
54713
+ const own2 = String(override || "").trim().split(/\s+/).filter(Boolean);
54709
54714
  const auto = autoLabels(style, n);
54710
- return auto.map((a, i) => own[i] != null ? own[i] : a);
54715
+ return auto.map((a, i) => own2[i] != null ? own2[i] : a);
54711
54716
  }
54712
54717
  function sane(g) {
54713
54718
  return !!(g && Array.isArray(g.origin) && g.origin.length >= 2 && isFinite(g.origin[0]) && isFinite(g.origin[1]));
@@ -57105,13 +57110,14 @@ function clearApproval(id) {
57105
57110
  const { approvedAt: _drop, ...rest } = meta;
57106
57111
  writeMeta({ ...rest, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
57107
57112
  }
57108
- function duplicateProject(id, name) {
57113
+ function duplicateProject(id, name, onCreated) {
57109
57114
  const src = readMeta(safeProjectId(id));
57110
57115
  if (!src) throw new ProjectError(`unknown project: ${id}`);
57111
57116
  const copy = createProject({
57112
57117
  name: typeof name === "string" && name.trim() ? name.trim() : `${src.name} (copy)`,
57113
57118
  app: src.app
57114
57119
  });
57120
+ onCreated?.(copy);
57115
57121
  (0, import_node_fs17.cpSync)(projectDir(src.id), projectDir(copy.id), {
57116
57122
  recursive: true,
57117
57123
  filter: (p) => !p.endsWith("project.json") && !isReservedProjectInternalPath(p)
@@ -58673,13 +58679,42 @@ function blobHashOf(node) {
58673
58679
  const ref = obj2[BLOB_KEY];
58674
58680
  return keys.length === 1 && keys[0] === BLOB_KEY && typeof ref === "string" && HASH_RE.test(ref) ? ref : null;
58675
58681
  }
58676
- function rehydrate(node, id) {
58677
- if (Array.isArray(node)) return node.map((x) => rehydrate(x, id));
58682
+ function versionBlobHash(node) {
58683
+ return blobHashOf(node);
58684
+ }
58685
+ function readVersionBlob(id, hash2) {
58686
+ if (!HASH_RE.test(hash2)) return null;
58687
+ try {
58688
+ const value = (0, import_node_fs25.readFileSync)((0, import_node_path22.join)(objectsDir(id), hash2), "utf8");
58689
+ return (0, import_node_crypto12.createHash)("sha256").update(value).digest("hex") === hash2 ? value : null;
58690
+ } catch {
58691
+ return null;
58692
+ }
58693
+ }
58694
+ async function readVersionBlobAsync(id, hash2) {
58695
+ if (!HASH_RE.test(hash2)) return null;
58696
+ try {
58697
+ const value = await (0, import_promises2.readFile)((0, import_node_path22.join)(objectsDir(id), hash2), "utf8");
58698
+ return (0, import_node_crypto12.createHash)("sha256").update(value).digest("hex") === hash2 ? value : null;
58699
+ } catch {
58700
+ return null;
58701
+ }
58702
+ }
58703
+ function rehydrate(node, id, blobs = /* @__PURE__ */ new Map()) {
58704
+ if (Array.isArray(node)) return node.map((x) => rehydrate(x, id, blobs));
58678
58705
  if (node && typeof node === "object") {
58679
58706
  const hash2 = blobHashOf(node);
58680
- if (hash2 !== null) return (0, import_node_fs25.readFileSync)((0, import_node_path22.join)(objectsDir(id), hash2), "utf8");
58707
+ if (hash2 !== null) {
58708
+ let value = blobs.get(hash2);
58709
+ if (value === void 0) {
58710
+ value = readVersionBlob(id, hash2);
58711
+ blobs.set(hash2, value);
58712
+ }
58713
+ if (value === null) throw new Error(`missing or corrupt version blob: ${hash2}`);
58714
+ return value;
58715
+ }
58681
58716
  const out = {};
58682
- for (const [k, v] of Object.entries(node)) out[k] = rehydrate(v, id);
58717
+ for (const [k, v] of Object.entries(node)) out[k] = rehydrate(v, id, blobs);
58683
58718
  return out;
58684
58719
  }
58685
58720
  return node;
@@ -58826,9 +58861,11 @@ async function readVersionAsync(id, n) {
58826
58861
  collectBlobRefs(snap.contract, refs);
58827
58862
  if (refs.size === 0) return snap.contract;
58828
58863
  const blobs = /* @__PURE__ */ new Map();
58829
- await Promise.all([...refs].map(async (hash2) => {
58830
- blobs.set(hash2, await (0, import_promises2.readFile)((0, import_node_path22.join)(objectsDir(id), hash2), "utf8"));
58831
- }));
58864
+ for (const hash2 of refs) {
58865
+ const value = await readVersionBlobAsync(id, hash2);
58866
+ if (value === null) throw new Error(`missing or corrupt version blob: ${hash2}`);
58867
+ blobs.set(hash2, value);
58868
+ }
58832
58869
  return rehydrateFrom(snap.contract, blobs);
58833
58870
  } catch {
58834
58871
  return null;
@@ -60940,9 +60977,6 @@ function resolveAppContract(appId, operation, readAppFn) {
60940
60977
  }
60941
60978
  return { kind: "contract", doc };
60942
60979
  }
60943
- function resolvedDoc(resolved) {
60944
- return resolved.kind === "contract" ? resolved.doc : null;
60945
- }
60946
60980
  function appContractState(appId, app, resolve11 = (id, op, readAppFn) => resolveAppContract(id, op, readAppFn)) {
60947
60981
  try {
60948
60982
  const baked = bakedContractNode(app);
@@ -63641,8 +63675,8 @@ function braceSetback(member, support, at) {
63641
63675
  const forward = [tA, tB].filter((t2) => Number.isFinite(t2) && t2 > 0);
63642
63676
  if (!forward.length) return { mm: 0, skew };
63643
63677
  const t = Math.min(...forward);
63644
- const own = Math.hypot(farPt[0] - endPt[0], farPt[1] - endPt[1], farPt[2] - endPt[2]);
63645
- return t < own * 0.5 ? { mm: t, skew } : null;
63678
+ const own2 = Math.hypot(farPt[0] - endPt[0], farPt[1] - endPt[1], farPt[2] - endPt[2]);
63679
+ return t < own2 * 0.5 ? { mm: t, skew } : null;
63646
63680
  }
63647
63681
  function expandBraceGusset(joint, brace, support, nativeSupport) {
63648
63682
  const p = joint.params;
@@ -65767,11 +65801,11 @@ function readSelectionFromBody(body) {
65767
65801
  if (body == null) return null;
65768
65802
  const isObject2 = typeof body === "object" && !Array.isArray(body);
65769
65803
  if (!isObject2) return "invalid";
65770
- const own = body;
65771
- if (!Object.prototype.hasOwnProperty.call(own, "memberIds")) {
65772
- return Object.keys(own).length === 0 ? null : "invalid";
65804
+ const own2 = body;
65805
+ if (!Object.prototype.hasOwnProperty.call(own2, "memberIds")) {
65806
+ return Object.keys(own2).length === 0 ? null : "invalid";
65773
65807
  }
65774
- const raw = own.memberIds;
65808
+ const raw = own2.memberIds;
65775
65809
  const wellFormed = Array.isArray(raw) && raw.length > 0 && raw.length <= MAX_SELECTION_MEMBERS && raw.every((id) => typeof id === "string" && id.trim() !== "");
65776
65810
  if (!wellFormed) return "invalid";
65777
65811
  return [...new Set(raw)];
@@ -67039,6 +67073,273 @@ function registerSteelPrepassRoute(app, deps) {
67039
67073
  );
67040
67074
  }
67041
67075
 
67076
+ // contract-access-routes.ts
67077
+ var projectPublicationBody = (state2, what) => {
67078
+ if (state2 === "project-publication-missing-project") {
67079
+ return {
67080
+ ok: false,
67081
+ error: `the project that published this model isn't available in Workspaces \u2014 check Archived, or import a project archive if you have one, before trying ${what} it`,
67082
+ code: state2
67083
+ };
67084
+ }
67085
+ if (state2 === "project-publication-availability-unknown") {
67086
+ return {
67087
+ ok: false,
67088
+ error: `couldn't check whether a project is available \u2014 try again before using this model`,
67089
+ code: state2
67090
+ };
67091
+ }
67092
+ return {
67093
+ ok: false,
67094
+ error: "this model was published from a project, and a project using this workflow is available in Workspaces \u2014 open Workspaces to continue with a project",
67095
+ code: state2
67096
+ };
67097
+ };
67098
+ var publicationBodyFor = (deps, appId, what) => projectPublicationBody(deps.projectPublicationState(appId), what);
67099
+ var resolvedDocument = (resolved) => resolved.kind === "contract" ? resolved.doc : null;
67100
+ var isVector = (doc) => typeof doc === "object" && doc !== null && doc.type === "drawing.vector/v1";
67101
+ var validAppId = (id) => /^[a-z0-9][a-z0-9._-]*$/i.test(id);
67102
+ function appExportSource(deps, resolved, appId, action, reply) {
67103
+ switch (resolved.kind) {
67104
+ case "contract":
67105
+ return { kind: "app", appId, doc: resolved.doc };
67106
+ case "project-publication":
67107
+ reply.status(404).send(publicationBodyFor(deps, appId, "to export"));
67108
+ return null;
67109
+ case "none":
67110
+ reply.status(404).send({
67111
+ ok: false,
67112
+ error: action === "export" ? "no contract to export" : "no contract to bake"
67113
+ });
67114
+ return null;
67115
+ default: {
67116
+ const exhaustive = resolved;
67117
+ return exhaustive;
67118
+ }
67119
+ }
67120
+ }
67121
+ async function projectExportSource(deps, appId, project, reply) {
67122
+ const gate = deps.projectExportGate(appId, project);
67123
+ if (gate) {
67124
+ reply.status(gate.status).send({ ok: false, error: gate.error });
67125
+ return null;
67126
+ }
67127
+ let snapshot;
67128
+ try {
67129
+ snapshot = deps.currentApprovedSnapshot(project);
67130
+ } catch (error) {
67131
+ const mapped = deps.workspaceSnapshotError(error);
67132
+ if (!mapped) throw error;
67133
+ reply.status(mapped.status).send({ ok: false, error: mapped.error });
67134
+ return null;
67135
+ }
67136
+ return { kind: "project", appId, project, snapshot };
67137
+ }
67138
+ function registerContractAccessRoutes(app, deps) {
67139
+ app.get("/api/app/:id", async (req) => {
67140
+ const loaded2 = deps.readApp(req.params.id);
67141
+ return {
67142
+ ok: true,
67143
+ app: loaded2,
67144
+ // Computed from the object already read: no second parse, and never mixed into AWARE's app spec.
67145
+ contractState: deps.appContractState(req.params.id, loaded2)
67146
+ };
67147
+ });
67148
+ app.get("/api/contract/:appId", async (req, reply) => {
67149
+ const project = req.query.project || void 0;
67150
+ if (project) {
67151
+ const bad = deps.projectAppMismatch(req.params.appId, project);
67152
+ if (bad) return reply.status(404).send({ ok: false, error: bad });
67153
+ }
67154
+ let doc;
67155
+ let publication = false;
67156
+ if (project) {
67157
+ doc = deps.readAcceptedForRequest(req.params.appId, project);
67158
+ } else {
67159
+ const resolved = deps.resolveAppContract(req.params.appId);
67160
+ doc = resolvedDocument(resolved);
67161
+ publication = resolved.kind === "project-publication";
67162
+ }
67163
+ if (doc == null && req.query.quietMissing === "1") return reply.status(204).send();
67164
+ if (doc == null && publication) {
67165
+ return reply.status(404).send(publicationBodyFor(deps, req.params.appId, "to see"));
67166
+ }
67167
+ if (doc == null) return reply.status(404).send({ ok: false, error: "no contract for this app yet" });
67168
+ const tag = deps.storeEtag(req.params.appId, project);
67169
+ if (tag) reply.header("ETag", tag);
67170
+ return isVector(doc) ? deps.postProcessVector(doc) : doc;
67171
+ });
67172
+ app.post(
67173
+ "/api/contract/:appId/scene",
67174
+ { bodyLimit: 25 * 1024 * 1024 },
67175
+ async (req, reply) => {
67176
+ const project = req.query.project || void 0;
67177
+ if (project) {
67178
+ const bad = deps.projectAppMismatch(req.params.appId, project);
67179
+ if (bad) return reply.status(404).send({ ok: false, error: bad });
67180
+ }
67181
+ let candidate;
67182
+ let publication = false;
67183
+ if (req.body && "contract" in req.body) {
67184
+ candidate = req.body.contract;
67185
+ } else {
67186
+ const resolved = deps.resolveAppContract(req.params.appId);
67187
+ candidate = resolvedDocument(resolved);
67188
+ publication = resolved.kind === "project-publication";
67189
+ }
67190
+ if (candidate == null && publication) {
67191
+ return reply.status(404).send(publicationBodyFor(deps, req.params.appId, "to view"));
67192
+ }
67193
+ if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to render" });
67194
+ return deps.continueScene({ appId: req.params.appId, project, candidate }, reply);
67195
+ }
67196
+ );
67197
+ app.post("/api/contract/:appId/export-ifc", async (req, reply) => {
67198
+ const appId = req.params.appId;
67199
+ const project = req.query.project || void 0;
67200
+ return deps.withLifecycleLock(project ? "project" : "app", project || appId, async () => {
67201
+ let input;
67202
+ if (project) {
67203
+ const gate = deps.projectExportGate(appId, project);
67204
+ if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
67205
+ let snapshot;
67206
+ try {
67207
+ snapshot = deps.currentApprovedSnapshot(project);
67208
+ } catch (error) {
67209
+ const mapped = deps.workspaceSnapshotError(error);
67210
+ if (mapped) return reply.status(mapped.status).send({ ok: false, error: mapped.error });
67211
+ throw error;
67212
+ }
67213
+ input = { kind: "project", appId, project, snapshot };
67214
+ } else {
67215
+ const resolved = deps.resolveAppContract(appId);
67216
+ const doc = resolvedDocument(resolved);
67217
+ if (doc == null && resolved.kind === "project-publication") {
67218
+ return reply.status(404).send(publicationBodyFor(deps, appId, "to export"));
67219
+ }
67220
+ if (doc == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
67221
+ input = { kind: "app", appId, doc };
67222
+ }
67223
+ return deps.continueIfcExport(input, reply);
67224
+ });
67225
+ });
67226
+ app.post("/api/contract/:appId/export-svg", async (req, reply) => {
67227
+ const appId = req.params.appId;
67228
+ const project = req.query.project || void 0;
67229
+ const execute = async () => {
67230
+ if (!validAppId(appId)) {
67231
+ return reply.status(400).send({ ok: false, error: `invalid appId: ${appId}` });
67232
+ }
67233
+ if (project) {
67234
+ const gate = deps.projectExportGate(appId, project);
67235
+ if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
67236
+ let snapshot;
67237
+ try {
67238
+ snapshot = deps.currentApprovedSnapshot(project);
67239
+ } catch (error) {
67240
+ const mapped = deps.workspaceSnapshotError(error);
67241
+ if (mapped) return reply.status(mapped.status).send({ ok: false, error: mapped.error });
67242
+ throw error;
67243
+ }
67244
+ return deps.continueSvgExport({ kind: "project", appId, project, snapshot }, reply);
67245
+ }
67246
+ const resolved = deps.resolveAppContract(appId);
67247
+ const doc = resolvedDocument(resolved);
67248
+ if (doc == null && resolved.kind === "project-publication") {
67249
+ return reply.status(404).send(publicationBodyFor(deps, appId, "to export"));
67250
+ }
67251
+ if (doc == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
67252
+ return deps.continueSvgExport({ kind: "app", appId, doc }, reply);
67253
+ };
67254
+ return project ? deps.withLifecycleLock("project", project, execute) : execute();
67255
+ });
67256
+ app.post("/api/contract/:appId/export-bom/:format", async (req, reply) => {
67257
+ const { appId, format } = req.params;
67258
+ const project = req.query.project || void 0;
67259
+ const execute = async () => {
67260
+ if (format !== "csv" && format !== "xlsx") {
67261
+ return reply.status(400).send({
67262
+ ok: false,
67263
+ error: `unknown format "${format}" \u2014 use csv or xlsx`
67264
+ });
67265
+ }
67266
+ if (!validAppId(appId)) {
67267
+ return reply.status(400).send({ ok: false, error: `invalid appId: ${appId}` });
67268
+ }
67269
+ const source = project ? await projectExportSource(deps, appId, project, reply) : appExportSource(deps, deps.resolveAppContract(appId), appId, "export", reply);
67270
+ if (!source) return;
67271
+ return deps.continueBomExport({ source, format }, reply);
67272
+ };
67273
+ return project ? deps.withLifecycleLock("project", project, execute) : execute();
67274
+ });
67275
+ app.post("/api/contract/:appId/export-tekla", async (req, reply) => {
67276
+ const appId = req.params.appId;
67277
+ const project = req.query.project || void 0;
67278
+ const selection = deps.parseSelection(req.body);
67279
+ if (selection === "invalid") {
67280
+ return reply.status(400).send({
67281
+ ok: false,
67282
+ error: "Could not read which members to send. Try again, and if it keeps happening, reload the editor."
67283
+ });
67284
+ }
67285
+ return deps.withLifecycleLock(project ? "project" : "app", project || appId, async () => {
67286
+ const source = project ? await projectExportSource(deps, appId, project, reply) : appExportSource(deps, deps.resolveAppContract(appId), appId, "bake", reply);
67287
+ if (!source) return;
67288
+ return deps.continueTeklaExport({ source, selection }, reply);
67289
+ }, { label: "sending the model to Tekla" });
67290
+ });
67291
+ app.post("/api/contract/:appId/export-host/:host", async (req, reply) => {
67292
+ const { appId, host } = req.params;
67293
+ const project = req.query.project || void 0;
67294
+ const hostLabel = deps.genericBakeHostLabel(host);
67295
+ if (!hostLabel) {
67296
+ return reply.status(404).send({ ok: false, error: `no bake target called "${host}"` });
67297
+ }
67298
+ const selection = deps.parseSelection(req.body);
67299
+ if (selection === "invalid") {
67300
+ return reply.status(400).send({
67301
+ ok: false,
67302
+ error: "Could not read which members to send. Try again, and if it keeps happening, reload the editor."
67303
+ });
67304
+ }
67305
+ const rawPid = req.body?.hostPid;
67306
+ const hostPid = typeof rawPid === "number" && Number.isInteger(rawPid) && rawPid > 0 ? rawPid : void 0;
67307
+ return deps.withLifecycleLock(project ? "project" : "app", project || appId, async () => {
67308
+ const source = project ? await projectExportSource(deps, appId, project, reply) : appExportSource(deps, deps.resolveAppContract(appId), appId, "bake", reply);
67309
+ if (!source) return;
67310
+ return deps.continueGenericHostExport({ source, host, selection, hostPid }, reply);
67311
+ }, { label: `sending the model to ${hostLabel}` });
67312
+ });
67313
+ }
67314
+
67315
+ // contract-access-errors.ts
67316
+ function replyContractPolicyError(error, request, reply) {
67317
+ const stateShaped = error.code === "contract-not-activated" || error.code === "contract-type-unknown" || error.code === "contract-type-wrong-app" || error.code === "contract-authority-unresolved";
67318
+ if (stateShaped) {
67319
+ request.log.warn({ code: error.code, err: error }, "contract policy refused stored state");
67320
+ }
67321
+ return reply.status(stateShaped ? 409 : 400).send({
67322
+ ok: false,
67323
+ error: error.message,
67324
+ code: error.code
67325
+ });
67326
+ }
67327
+ function replyLifecycleLockBusyError(error, logger, reply) {
67328
+ const retryAfter = error.busy.remainingMs == null ? 5 : Math.min(60, Math.max(1, Math.ceil(error.busy.remainingMs / 1e3)));
67329
+ logger.warn({
67330
+ kind: error.busy.kind,
67331
+ key: error.busy.key,
67332
+ label: error.busy.label,
67333
+ elapsedMs: error.busy.elapsedMs
67334
+ }, "lifecycle lock busy \u2014 request refused");
67335
+ return reply.status(error.status).header("Retry-After", String(retryAfter)).send({
67336
+ ok: false,
67337
+ error: error.message,
67338
+ code: "lifecycle-busy",
67339
+ busy: error.busy
67340
+ });
67341
+ }
67342
+
67042
67343
  // project-export-files.ts
67043
67344
  var import_node_fs31 = require("node:fs");
67044
67345
  var import_node_path27 = require("node:path");
@@ -67647,6 +67948,19 @@ function registerWorkspaceDataRoutes(app) {
67647
67948
  );
67648
67949
  }
67649
67950
 
67951
+ // project-publication-state.ts
67952
+ function classifyProjectPublicationState(appId, liveProjects) {
67953
+ return liveProjects.some((project) => project.app === appId) ? "project-publication" : "project-publication-missing-project";
67954
+ }
67955
+ function readProjectPublicationState(appId, readLiveProjects, reportError) {
67956
+ try {
67957
+ return classifyProjectPublicationState(appId, readLiveProjects());
67958
+ } catch (error) {
67959
+ reportError(error);
67960
+ return "project-publication-availability-unknown";
67961
+ }
67962
+ }
67963
+
67650
67964
  // confidential-images.ts
67651
67965
  var CONFIDENTIAL_IMAGE_KEYS = /* @__PURE__ */ new Set([
67652
67966
  "raster_b64",
@@ -68636,26 +68950,224 @@ function mappingApplies(v1Doc, v1Keys, migration, view) {
68636
68950
  }
68637
68951
 
68638
68952
  // version-diff.ts
68639
- function fullPair(id, n, toSkel, fromVersion, fromSkel) {
68640
- if (!isModelV2(toSkel) && !isModelV2(fromSkel)) return { kind: "ok", to: toSkel, from: fromSkel };
68641
- const to = readVersion(id, n);
68642
- if (fromVersion == null) return to == null ? { kind: "unreadable", side: "to" } : { kind: "ok", to, from: void 0 };
68643
- const from = readVersion(id, fromVersion);
68644
- if (to == null || from == null) {
68645
- return { kind: "unreadable", side: to == null && from == null ? "both" : to == null ? "to" : "from" };
68646
- }
68647
- return { kind: "ok", to, from };
68648
- }
68649
- async function fullPairAsync(id, n, toSkel, fromVersion, fromSkel) {
68650
- if (!isModelV2(toSkel) && !isModelV2(fromSkel)) return { kind: "ok", to: toSkel, from: fromSkel };
68651
- const to = await readVersionAsync(id, n);
68652
- if (fromVersion == null) return to == null ? { kind: "unreadable", side: "to" } : { kind: "ok", to, from: void 0 };
68653
- const from = await readVersionAsync(id, fromVersion);
68654
- if (to == null || from == null) {
68655
- return { kind: "unreadable", side: to == null && from == null ? "both" : to == null ? "to" : "from" };
68656
- }
68657
- return { kind: "ok", to, from };
68953
+ var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
68954
+ var own = (obj2, key) => Object.prototype.hasOwnProperty.call(obj2, key);
68955
+ var take = (obj2, keys) => {
68956
+ const out = {};
68957
+ for (const key of keys) if (own(obj2, key)) out[key] = obj2[key];
68958
+ return out;
68959
+ };
68960
+ var mapPicked = (value, keys) => Array.isArray(value) ? value.map((row) => isRecord(row) ? take(row, keys) : row) : value;
68961
+ function selectV1DiffFields(doc) {
68962
+ if (!isRecord(doc)) return doc;
68963
+ const out = take(doc, ["type", "weights"]);
68964
+ if (own(doc, "connections")) out.connections = mapPicked(doc.connections, ["id", "type", "detail"]);
68965
+ if (own(doc, "joints")) {
68966
+ out.joints = mapPicked(doc.joints, [
68967
+ "id",
68968
+ "kind",
68969
+ "main",
68970
+ "secondaries",
68971
+ "at",
68972
+ "conn",
68973
+ "detail",
68974
+ "note",
68975
+ "params",
68976
+ "place"
68977
+ ]);
68978
+ }
68979
+ if (own(doc, "plans")) {
68980
+ out.plans = Array.isArray(doc.plans) ? doc.plans.map((plan) => {
68981
+ if (!isRecord(plan)) return plan;
68982
+ const picked = take(plan, ["sheet", "pt_per_ft", "default_tos"]);
68983
+ if (own(plan, "members")) {
68984
+ picked.members = Array.isArray(plan.members) ? plan.members.map((member) => {
68985
+ if (!isRecord(member)) return member;
68986
+ const m = take(member, ["id", "mark", "profile", "role", "wp", "material"]);
68987
+ if (own(member, "ends")) m.ends = mapPicked(member.ends, ["tos", "tosDef", "conn", "detail", "note"]);
68988
+ if (own(member, "col")) {
68989
+ m.col = isRecord(member.col) ? take(member.col, ["tos", "bos", "conn", "detail", "note"]) : member.col;
68990
+ }
68991
+ return m;
68992
+ }) : plan.members;
68993
+ }
68994
+ return picked;
68995
+ }) : doc.plans;
68996
+ }
68997
+ return out;
68998
+ }
68999
+ function resolveSelectedSync(id, node, blobs = /* @__PURE__ */ new Map()) {
69000
+ const hash2 = versionBlobHash(node);
69001
+ if (hash2 !== null) {
69002
+ let value = blobs.get(hash2);
69003
+ if (value === void 0) {
69004
+ value = readVersionBlob(id, hash2);
69005
+ blobs.set(hash2, value);
69006
+ }
69007
+ return value === null ? { ok: false } : { ok: true, value };
69008
+ }
69009
+ if (Array.isArray(node)) {
69010
+ const value = [];
69011
+ for (const item of node) {
69012
+ const resolved = resolveSelectedSync(id, item, blobs);
69013
+ if (!resolved.ok) return resolved;
69014
+ value.push(resolved.value);
69015
+ }
69016
+ return { ok: true, value };
69017
+ }
69018
+ if (isRecord(node)) {
69019
+ const value = {};
69020
+ for (const [key, item] of Object.entries(node)) {
69021
+ const resolved = resolveSelectedSync(id, item, blobs);
69022
+ if (!resolved.ok) return resolved;
69023
+ value[key] = resolved.value;
69024
+ }
69025
+ return { ok: true, value };
69026
+ }
69027
+ return { ok: true, value: node };
69028
+ }
69029
+ async function resolveSelectedAsync(id, node, blobs = /* @__PURE__ */ new Map()) {
69030
+ const hash2 = versionBlobHash(node);
69031
+ if (hash2 !== null) {
69032
+ let value = blobs.get(hash2);
69033
+ if (value === void 0) {
69034
+ value = await readVersionBlobAsync(id, hash2);
69035
+ blobs.set(hash2, value);
69036
+ }
69037
+ return value === null ? { ok: false } : { ok: true, value };
69038
+ }
69039
+ if (Array.isArray(node)) {
69040
+ const value = [];
69041
+ for (const item of node) {
69042
+ const resolved = await resolveSelectedAsync(id, item, blobs);
69043
+ if (!resolved.ok) return resolved;
69044
+ value.push(resolved.value);
69045
+ }
69046
+ return { ok: true, value };
69047
+ }
69048
+ if (isRecord(node)) {
69049
+ const value = {};
69050
+ for (const [key, item] of Object.entries(node)) {
69051
+ const resolved = await resolveSelectedAsync(id, item, blobs);
69052
+ if (!resolved.ok) return resolved;
69053
+ value[key] = resolved.value;
69054
+ }
69055
+ return { ok: true, value };
69056
+ }
69057
+ return { ok: true, value: node };
69058
+ }
69059
+ var finite = (value) => typeof value === "number" && Number.isFinite(value);
69060
+ var optionalString2 = (obj2, key) => !own(obj2, key) || typeof obj2[key] === "string";
69061
+ var optionalFiniteOrNull = (obj2, key) => !own(obj2, key) || obj2[key] === null || finite(obj2[key]);
69062
+ function validateV1Projection(value) {
69063
+ if (!isRecord(value)) return { ok: false, reason: "not-record" };
69064
+ if (declaredTypeOf(value) !== STEEL_V1) return { ok: false, reason: "unsupported-type" };
69065
+ if (!Array.isArray(value.plans)) return { ok: false, reason: "invalid-plans" };
69066
+ const out = { type: STEEL_V1, plans: [] };
69067
+ if (own(value, "weights")) {
69068
+ if (!isRecord(value.weights) || Object.values(value.weights).some((weight) => weight !== null && !finite(weight))) {
69069
+ return { ok: false, reason: "invalid-weights" };
69070
+ }
69071
+ out.weights = { ...value.weights };
69072
+ }
69073
+ if (own(value, "connections")) {
69074
+ if (!Array.isArray(value.connections)) return { ok: false, reason: "invalid-connections" };
69075
+ const connections = [];
69076
+ for (const row of value.connections) {
69077
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id || !optionalString2(row, "type") || !optionalString2(row, "detail")) {
69078
+ return { ok: false, reason: "invalid-connection" };
69079
+ }
69080
+ connections.push({ ...row });
69081
+ }
69082
+ out.connections = connections;
69083
+ }
69084
+ if (own(value, "joints")) {
69085
+ if (!Array.isArray(value.joints)) return { ok: false, reason: "invalid-joints" };
69086
+ const joints = [];
69087
+ for (const row of value.joints) {
69088
+ if (!isRecord(row) || typeof row.id !== "string" || !row.id || typeof row.kind !== "string" || !row.kind || !["main", "at", "conn", "detail", "note"].every((key) => optionalString2(row, key))) {
69089
+ return { ok: false, reason: "invalid-joint" };
69090
+ }
69091
+ if (own(row, "secondaries") && (!Array.isArray(row.secondaries) || row.secondaries.some((id) => typeof id !== "string"))) {
69092
+ return { ok: false, reason: "invalid-joint-references" };
69093
+ }
69094
+ if (own(row, "params") && !isRecord(row.params)) return { ok: false, reason: "invalid-joint-params" };
69095
+ if (own(row, "place") && (!Array.isArray(row.place) || row.place.length !== 3 || row.place.some((n) => !finite(n)))) {
69096
+ return { ok: false, reason: "invalid-joint-place" };
69097
+ }
69098
+ joints.push({ ...row });
69099
+ }
69100
+ out.joints = joints;
69101
+ }
69102
+ const plans = [];
69103
+ for (const plan of value.plans) {
69104
+ if (!isRecord(plan) || typeof plan.sheet !== "string" || !plan.sheet || !Array.isArray(plan.members)) {
69105
+ return { ok: false, reason: "invalid-plan" };
69106
+ }
69107
+ if (own(plan, "pt_per_ft") && (!finite(plan.pt_per_ft) || plan.pt_per_ft <= 0)) {
69108
+ return { ok: false, reason: "invalid-plan-scale" };
69109
+ }
69110
+ if (!optionalFiniteOrNull(plan, "default_tos")) return { ok: false, reason: "invalid-plan-elevation" };
69111
+ const projectedPlan = take(plan, ["sheet", "pt_per_ft", "default_tos"]);
69112
+ const members = [];
69113
+ for (const member of plan.members) {
69114
+ if (!isRecord(member) || typeof member.id !== "string" || !member.id || typeof member.profile !== "string" || !optionalString2(member, "mark") || !optionalString2(member, "role") || !optionalString2(member, "material") || !Array.isArray(member.wp) || member.wp.length !== 2 || member.wp.some((point) => !Array.isArray(point) || point.length !== 2 || point.some((n) => !finite(n)))) {
69115
+ return { ok: false, reason: "invalid-member" };
69116
+ }
69117
+ const projectedMember = take(member, ["id", "mark", "profile", "role", "wp", "material"]);
69118
+ if (own(member, "ends")) {
69119
+ if (!Array.isArray(member.ends)) return { ok: false, reason: "invalid-member-ends" };
69120
+ const ends = [];
69121
+ for (const end of member.ends.slice(0, 2)) {
69122
+ if (!isRecord(end) || !optionalFiniteOrNull(end, "tos") || own(end, "tosDef") && typeof end.tosDef !== "boolean" || !["conn", "detail", "note"].every((key) => optionalString2(end, key))) {
69123
+ return { ok: false, reason: "invalid-member-end" };
69124
+ }
69125
+ ends.push({ ...end });
69126
+ }
69127
+ projectedMember.ends = ends;
69128
+ }
69129
+ if (own(member, "col")) {
69130
+ if (!isRecord(member.col) || !optionalFiniteOrNull(member.col, "tos") || !optionalFiniteOrNull(member.col, "bos") || !["conn", "detail", "note"].every((key) => optionalString2(member.col, key))) {
69131
+ return { ok: false, reason: "invalid-member-column" };
69132
+ }
69133
+ projectedMember.col = { ...member.col };
69134
+ }
69135
+ members.push(projectedMember);
69136
+ }
69137
+ projectedPlan.members = members;
69138
+ plans.push(projectedPlan);
69139
+ }
69140
+ out.plans = plans;
69141
+ return { ok: true, doc: out };
69142
+ }
69143
+ function classifyV1Resolved(resolved) {
69144
+ if (!resolved.ok) return { kind: "unreadable", reason: "missing-consumed-blob" };
69145
+ const projected = validateV1Projection(resolved.value);
69146
+ return projected.ok ? { kind: "eligible", format: "v1", doc: projected.doc } : { kind: "unsupported", reason: projected.reason };
69147
+ }
69148
+ function loadDiffDocument(id, n, skeleton) {
69149
+ if (!isRecord(skeleton)) return { kind: "unsupported", reason: "not-record" };
69150
+ const type = declaredTypeOf(skeleton);
69151
+ if (type === STEEL_V2) {
69152
+ const doc = readVersion(id, n);
69153
+ if (doc == null) return { kind: "unreadable", reason: "missing-v2-blob" };
69154
+ return readModel(doc) ? { kind: "eligible", format: "v2", doc } : { kind: "unsupported", reason: "invalid-v2" };
69155
+ }
69156
+ if (type !== STEEL_V1) return { kind: "unsupported", reason: "unsupported-type" };
69157
+ return classifyV1Resolved(resolveSelectedSync(id, selectV1DiffFields(skeleton)));
69158
+ }
69159
+ async function loadDiffDocumentAsync(id, n, skeleton) {
69160
+ if (!isRecord(skeleton)) return { kind: "unsupported", reason: "not-record" };
69161
+ const type = declaredTypeOf(skeleton);
69162
+ if (type === STEEL_V2) {
69163
+ const doc = await readVersionAsync(id, n);
69164
+ if (doc == null) return { kind: "unreadable", reason: "missing-v2-blob" };
69165
+ return readModel(doc) ? { kind: "eligible", format: "v2", doc } : { kind: "unsupported", reason: "invalid-v2" };
69166
+ }
69167
+ if (type !== STEEL_V1) return { kind: "unsupported", reason: "unsupported-type" };
69168
+ return classifyV1Resolved(await resolveSelectedAsync(id, selectV1DiffFields(skeleton)));
68658
69169
  }
69170
+ var unreadableSide = (from, to) => from?.kind === "unreadable" && to.kind === "unreadable" ? "both" : from?.kind === "unreadable" ? "from" : "to";
68659
69171
  function identityContextFor(from, to) {
68660
69172
  if (!isModelV2(from) && !isModelV2(to)) return void 0;
68661
69173
  const declares = (doc) => {
@@ -68673,6 +69185,46 @@ function identityContextFor(from, to) {
68673
69185
  frameContinuous: !remigrated
68674
69186
  };
68675
69187
  }
69188
+ async function analyzeVersionDiffLedger(id, input, observer) {
69189
+ const ordered = [...new Map(input.filter((row) => Number.isInteger(row.n) && row.n > 0).map((row) => [row.n, row])).values()].sort((a, b) => a.n - b.n);
69190
+ const eligibility = /* @__PURE__ */ new Map();
69191
+ for (const row of ordered) {
69192
+ observer?.snapshotStarted?.(row.n);
69193
+ try {
69194
+ const skeleton = await readVersionSkeletonAsync(id, row.n);
69195
+ if (skeleton == null) {
69196
+ eligibility.set(row.n, "unreadable");
69197
+ continue;
69198
+ }
69199
+ const state2 = await loadDiffDocumentAsync(id, row.n, skeleton);
69200
+ eligibility.set(row.n, state2.kind);
69201
+ } finally {
69202
+ observer?.snapshotFinished?.(row.n);
69203
+ }
69204
+ }
69205
+ const defaults = /* @__PURE__ */ new Map();
69206
+ let previousApproval = null;
69207
+ for (const row of ordered) {
69208
+ if (row.kind === "approve") {
69209
+ defaults.set(row.n, previousApproval);
69210
+ previousApproval = row.n;
69211
+ } else {
69212
+ defaults.set(row.n, row.n > 1 ? row.n - 1 : null);
69213
+ }
69214
+ }
69215
+ const rows2 = /* @__PURE__ */ new Map();
69216
+ const eligibleVersions = ordered.filter((row) => eligibility.get(row.n) === "eligible").map((row) => row.n);
69217
+ for (const row of ordered) {
69218
+ const diffBase = defaults.get(row.n) ?? null;
69219
+ const toEligible = eligibility.get(row.n) === "eligible";
69220
+ rows2.set(row.n, {
69221
+ diffSupported: diffBase !== null && toEligible && eligibility.get(diffBase) === "eligible",
69222
+ diffBase
69223
+ });
69224
+ }
69225
+ const diffSupported = ordered.length > 0 && ordered.every((row) => eligibility.get(row.n) === "eligible");
69226
+ return { rows: rows2, eligibility, eligibleVersions, diffSupported };
69227
+ }
68676
69228
  var summaryCache = /* @__PURE__ */ new Map();
68677
69229
  var baseForVersion = (n, bases) => {
68678
69230
  if (bases?.has(n)) {
@@ -68708,21 +69260,6 @@ var cautionsForWarnings = (warnings) => {
68708
69260
  }
68709
69261
  return cautions;
68710
69262
  };
68711
- var unavailableDiff = (from, to, side) => ({
68712
- from,
68713
- to,
68714
- ...from === 0 ? { firstVersion: true } : {},
68715
- tonnage: { fromLb: 0, toLb: 0, netLb: 0, fromTons: 0, toTons: 0, netTons: 0 },
68716
- added: [],
68717
- removed: [],
68718
- resized: [],
68719
- moved: [],
68720
- material: [],
68721
- connections: [],
68722
- unchanged: 0,
68723
- comparison: "suppressed",
68724
- warnings: { invalidModelV2: side }
68725
- });
68726
69263
  var unavailableSummary = (from, side) => ({
68727
69264
  from,
68728
69265
  headline: "Comparison unavailable",
@@ -68830,30 +69367,18 @@ async function summarizeVersionChangesAsync(id, versions, bases) {
68830
69367
  const missing = uncachedVersions(id, versions, out, bases);
68831
69368
  if (!missing.length) return out;
68832
69369
  try {
68833
- const needed = /* @__PURE__ */ new Set();
68834
69370
  for (const n of missing) {
68835
- needed.add(n);
68836
- const base = baseForVersion(n, bases);
68837
- if (base != null) needed.add(base);
68838
- }
68839
- const docs = /* @__PURE__ */ new Map();
68840
- await Promise.all([...needed].map(async (n) => {
68841
- docs.set(n, await readVersionSkeletonAsync(id, n));
68842
- }));
68843
- for (const n of missing) {
68844
- const toSkel = docs.get(n);
69371
+ const toSkel = await readVersionSkeletonAsync(id, n);
68845
69372
  if (toSkel == null) continue;
68846
69373
  const fromVersion = baseForVersion(n, bases);
68847
- const fromSkel = fromVersion != null ? docs.get(fromVersion) : void 0;
69374
+ const fromSkel = fromVersion != null ? await readVersionSkeletonAsync(id, fromVersion) : void 0;
68848
69375
  if (fromVersion != null && fromSkel == null) continue;
68849
69376
  await new Promise((resolve11) => setImmediate(resolve11));
68850
- const pair = await fullPairAsync(id, n, toSkel, fromVersion, fromSkel);
68851
- if (pair.kind === "missing") continue;
68852
- if (pair.kind === "unreadable") {
68853
- out.set(n, unavailableSummary(fromVersion, pair.side));
68854
- continue;
68855
- }
68856
- const { summary, cacheable } = summarizeSnapshots(n, pair.to, fromVersion, pair.from);
69377
+ const to = await loadDiffDocumentAsync(id, n, toSkel);
69378
+ if (to.kind !== "eligible") continue;
69379
+ const from = fromVersion != null ? await loadDiffDocumentAsync(id, fromVersion, fromSkel) : void 0;
69380
+ if (from && from.kind !== "eligible") continue;
69381
+ const { summary, cacheable } = summarizeSnapshots(n, to.doc, fromVersion, from?.doc);
68857
69382
  if (cacheable) summaryCache.set(summaryKey(id, n, fromVersion), summary);
68858
69383
  out.set(n, summary);
68859
69384
  }
@@ -68866,28 +69391,37 @@ function appSupportsDiff(app) {
68866
69391
  }
68867
69392
  function computeVersionDiff(id, n, base) {
68868
69393
  if (!Number.isInteger(n) || n < 1) return { code: 400, body: { ok: false, error: "n must be a positive integer version number" } };
68869
- const head = listVersions(id)[0]?.n ?? 0;
68870
- if (head === 0) return { code: 404, body: { ok: false, error: "no versions for this project" } };
69394
+ const logged = new Set(listVersions(id).map((version) => version.n));
69395
+ if (logged.size === 0) return { code: 404, body: { ok: false, error: "no versions for this project" } };
69396
+ if (!logged.has(n)) return { code: 404, body: { ok: false, error: `version v${n} not found` } };
68871
69397
  const toSkel = readVersionSkeleton(id, n);
68872
- if (toSkel == null) return { code: 404, body: { ok: false, error: `version v${n} not found` } };
68873
69398
  if (n === 1) {
68874
- let own = {};
68875
- if (isModelV2(toSkel)) {
68876
- const full = readVersion(id, n);
68877
- if (full == null || readModel(full) == null) {
68878
- return { code: 200, body: { ok: true, diff: unavailableDiff(0, 1, "to") } };
68879
- }
68880
- } else {
68881
- own = diffContracts({}, toSkel).warnings;
69399
+ if (toSkel == null) {
69400
+ return {
69401
+ code: 503,
69402
+ body: { ok: false, status: "unavailable", error: "Comparison unavailable", reason: "to" }
69403
+ };
69404
+ }
69405
+ const to2 = loadDiffDocument(id, n, toSkel);
69406
+ if (to2.kind === "unreadable") {
69407
+ return {
69408
+ code: 503,
69409
+ body: { ok: false, status: "unavailable", error: "Comparison unavailable", reason: "to" }
69410
+ };
69411
+ }
69412
+ if (to2.kind === "unsupported") {
69413
+ return { code: 409, body: { ok: false, error: "this saved version is not a supported steel contract" } };
68882
69414
  }
69415
+ const own2 = to2.format === "v1" ? diffContracts({}, to2.doc).warnings : {};
68883
69416
  const warnings = {
68884
- ...own.duplicateKeys?.length ? { duplicateKeys: own.duplicateKeys } : {},
68885
- ...own.ambiguousJoints?.length ? { ambiguousJoints: own.ambiguousJoints } : {}
69417
+ ...own2.duplicateKeys?.length ? { duplicateKeys: own2.duplicateKeys } : {},
69418
+ ...own2.ambiguousJoints?.length ? { ambiguousJoints: own2.ambiguousJoints } : {}
68886
69419
  };
68887
69420
  return {
68888
69421
  code: 200,
68889
69422
  body: {
68890
69423
  ok: true,
69424
+ status: "available",
68891
69425
  diff: {
68892
69426
  from: 0,
68893
69427
  to: 1,
@@ -68907,18 +69441,35 @@ function computeVersionDiff(id, n, base) {
68907
69441
  }
68908
69442
  const b = base ?? n - 1;
68909
69443
  if (!Number.isInteger(b) || b < 1 || b >= n) return { code: 400, body: { ok: false, error: `base must be an integer in 1..${n - 1}` } };
69444
+ if (!logged.has(b)) return { code: 404, body: { ok: false, error: `base version v${b} not found` } };
68910
69445
  const fromSkel = readVersionSkeleton(id, b);
68911
- if (fromSkel == null) return { code: 404, body: { ok: false, error: `base version v${b} not found` } };
68912
- const pair = fullPair(id, n, toSkel, b, fromSkel);
68913
- if (pair.kind === "missing") return { code: 404, body: { ok: false, error: `version v${n} not found` } };
68914
- if (pair.kind === "unreadable") {
68915
- return { code: 200, body: { ok: true, diff: unavailableDiff(b, n, pair.side) } };
69446
+ if (toSkel == null || fromSkel == null) {
69447
+ const reason = toSkel == null && fromSkel == null ? "both" : toSkel == null ? "to" : "from";
69448
+ return {
69449
+ code: 503,
69450
+ body: { ok: false, status: "unavailable", error: "Comparison unavailable", reason }
69451
+ };
68916
69452
  }
68917
- const { to, from } = pair;
68918
- const diff = diffContracts(from, to, identityContextFor(from, to));
69453
+ const to = loadDiffDocument(id, n, toSkel);
69454
+ const from = loadDiffDocument(id, b, fromSkel);
69455
+ if (to.kind === "unreadable" || from.kind === "unreadable") {
69456
+ return {
69457
+ code: 503,
69458
+ body: {
69459
+ ok: false,
69460
+ status: "unavailable",
69461
+ error: "Comparison unavailable",
69462
+ reason: unreadableSide(from, to)
69463
+ }
69464
+ };
69465
+ }
69466
+ if (to.kind === "unsupported" || from.kind === "unsupported") {
69467
+ return { code: 409, body: { ok: false, error: "these saved versions are not a supported steel comparison pair" } };
69468
+ }
69469
+ const diff = diffContracts(from.doc, to.doc, identityContextFor(from.doc, to.doc));
68919
69470
  diff.from = b;
68920
69471
  diff.to = n;
68921
- return { code: 200, body: { ok: true, diff } };
69472
+ return { code: 200, body: { ok: true, status: "available", diff } };
68922
69473
  }
68923
69474
 
68924
69475
  // contract-bake.ts
@@ -69382,8 +69933,32 @@ var INPUTS_TEMPFILE = /floless-agent-inputs-/i;
69382
69933
  function withoutInputsFile(message) {
69383
69934
  return message.replace(/\s+--inputs\s+@.*?\.json(?=\s|$)/gi, "").trim();
69384
69935
  }
69936
+ function structuredReceiptMessage(stderr) {
69937
+ for (const line of stderr.split(/\r?\n/)) {
69938
+ for (let offset = line.indexOf("{"); offset >= 0; offset = line.indexOf("{", offset + 1)) {
69939
+ try {
69940
+ const receipt = JSON.parse(line.slice(offset));
69941
+ const result = receipt.result && typeof receipt.result === "object" ? receipt.result : receipt;
69942
+ const failed = Array.isArray(result.failed) ? result.failed : [];
69943
+ const first = failed.find((row) => !!row && typeof row === "object");
69944
+ if (first) {
69945
+ if (typeof first.message === "string" && first.message.trim()) return first.message.trim();
69946
+ if (typeof first.code === "string" && first.code.trim()) return first.code.trim();
69947
+ }
69948
+ } catch {
69949
+ }
69950
+ }
69951
+ }
69952
+ return null;
69953
+ }
69385
69954
  function awareFailureMessage(e, fallback) {
69386
- const lines = (awareStderr(e) ?? "").split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
69955
+ const stderr = awareStderr(e) ?? "";
69956
+ const structured = structuredReceiptMessage(stderr);
69957
+ if (structured) {
69958
+ const message2 = withoutInputsFile(structured);
69959
+ return message2 && !INPUTS_TEMPFILE.test(message2) ? message2 : fallback;
69960
+ }
69961
+ const lines = stderr.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
69387
69962
  const marked = lines.find((line) => /^error\b/i.test(line));
69388
69963
  const chosen = marked ?? lines[lines.length - 1];
69389
69964
  const message = chosen ? withoutInputsFile(chosen.replace(/^error\b:?\s*/i, "") || chosen) : e instanceof Error && e.message ? withoutInputsFile(e.message) : "";
@@ -72682,6 +73257,36 @@ function writeSketchupApp(dir, appId, scene) {
72682
73257
  bakeSceneIntoApp(flo, scene, "sketchup-2026");
72683
73258
  return flo;
72684
73259
  }
73260
+ function writeRhinoApp(dir, appId, scene, rhinoId, hostPid) {
73261
+ (0, import_node_fs37.mkdirSync)(dir, { recursive: true });
73262
+ const flo = (0, import_node_path32.join)(dir, `${appId}.flo`);
73263
+ const exactRhinoId = typeof rhinoId === "string" && rhinoId.trim() ? rhinoId.trim() : null;
73264
+ (0, import_node_fs37.writeFileSync)(flo, [
73265
+ `app: ${appId}`,
73266
+ "version: 0.1.0",
73267
+ "display-name: Steel to Rhino",
73268
+ "description: Rhino objects created from an approved steel.takeoff/v1 contract. The same canonical scene remains the source of truth while AWARE converts it to the open document units.",
73269
+ "exposes-as-agent: false",
73270
+ "requires:",
73271
+ " - rhino-8@0.1.x",
73272
+ "layout: linear",
73273
+ "nodes:",
73274
+ " - id: bake-rhino",
73275
+ " agent: rhino-8",
73276
+ " command: bake-scene",
73277
+ " mode: write",
73278
+ " safety:",
73279
+ " snapshot: true",
73280
+ " config:",
73281
+ ...exactRhinoId ? [` rhino_id: ${JSON.stringify(exactRhinoId)}`] : [],
73282
+ ...hostPid != null && Number.isInteger(hostPid) && hostPid > 0 ? [` host_pid: ${hostPid}`] : [],
73283
+ " label: FloLess",
73284
+ " scene: {}",
73285
+ ""
73286
+ ].join("\n"));
73287
+ bakeSceneIntoApp(flo, scene, "rhino-8");
73288
+ return flo;
73289
+ }
72685
73290
  function writeTeklaApp(dir, appId, scene, teklaVersion = "2026.0") {
72686
73291
  (0, import_node_fs37.mkdirSync)(dir, { recursive: true });
72687
73292
  const flo = (0, import_node_path32.join)(dir, `${appId}.flo`);
@@ -73558,7 +74163,8 @@ var import_node_child_process6 = require("node:child_process");
73558
74163
  var HOST_PROCESS_NAMES = {
73559
74164
  teklastructures: "tekla",
73560
74165
  revit: "revit",
73561
- sketchup: "sketchup"
74166
+ sketchup: "sketchup",
74167
+ rhino: "rhino"
73562
74168
  };
73563
74169
  var DEFAULT_DEPS2 = {
73564
74170
  runPowerShell: (script) => new Promise((resolve11, reject) => {
@@ -73751,11 +74357,18 @@ async function resolveHostAtPoint(cssX, cssY, dpr, probe) {
73751
74357
 
73752
74358
  // host-readiness.ts
73753
74359
  var HOST_BAKE_AWARE_FLOOR = "0.104.0";
74360
+ var HOST_BAKE_AWARE_FLOORS = {
74361
+ tekla: HOST_BAKE_AWARE_FLOOR,
74362
+ revit: HOST_BAKE_AWARE_FLOOR,
74363
+ sketchup: HOST_BAKE_AWARE_FLOOR,
74364
+ rhino: "0.106.0"
74365
+ };
73754
74366
  var SUPPORTED_REVIT_VERSIONS = /* @__PURE__ */ new Set(["2026"]);
73755
74367
  var HOST_LABELS = {
73756
74368
  tekla: "Tekla Structures",
73757
74369
  revit: "Revit",
73758
- sketchup: "SketchUp"
74370
+ sketchup: "SketchUp",
74371
+ rhino: "Rhino"
73759
74372
  };
73760
74373
  var DEFAULT_DEPS3 = {
73761
74374
  npmVersion: () => aware.npmVersion(),
@@ -73765,22 +74378,23 @@ var DEFAULT_DEPS3 = {
73765
74378
  };
73766
74379
  async function hostReadiness(host, deps = DEFAULT_DEPS3, targetPid) {
73767
74380
  const label2 = HOST_LABELS[host];
74381
+ const floor = HOST_BAKE_AWARE_FLOORS[host];
73768
74382
  const awareVersion = deps.npmVersion();
73769
- const awareCurrent = !!awareVersion && compareSemver(awareVersion, HOST_BAKE_AWARE_FLOOR) >= 0;
74383
+ const awareCurrent = !!awareVersion && compareSemver(awareVersion, floor) >= 0;
73770
74384
  const bridge = deps.bridgeStatus(host);
73771
74385
  const bridgeCurrent = !!bridge.path && bridge.version === awareVersion;
73772
74386
  const base = {
73773
74387
  host,
73774
- aware: { version: awareVersion, floor: HOST_BAKE_AWARE_FLOOR, current: awareCurrent },
74388
+ aware: { version: awareVersion, floor, current: awareCurrent },
73775
74389
  bridge: { present: !!bridge.path, version: bridge.version, current: bridgeCurrent },
73776
- session: { open: false, version: null, pid: null }
74390
+ session: { open: false, version: null, pid: null, rhinoId: null }
73777
74391
  };
73778
74392
  if (!awareCurrent) {
73779
74393
  return {
73780
74394
  ...base,
73781
74395
  ok: false,
73782
74396
  state: "aware-update-required",
73783
- message: `Couldn\u2019t send \u2014 this needs AWARE ${HOST_BAKE_AWARE_FLOOR} or newer. Update it, then try again.`,
74397
+ message: `Couldn\u2019t send \u2014 this needs AWARE ${floor} or newer. Update it, then try again.`,
73784
74398
  recovery: { action: "update-aware", label: "Update AWARE" }
73785
74399
  };
73786
74400
  }
@@ -73856,7 +74470,7 @@ async function hostReadiness(host, deps = DEFAULT_DEPS3, targetPid) {
73856
74470
  recovery: { action: "open-host", label: `Open ${label2}` }
73857
74471
  };
73858
74472
  }
73859
- const found = { open: true, version: session.version, pid: session.pid };
74473
+ const found = { open: true, version: session.version, pid: session.pid, rhinoId: session.rhinoId ?? null };
73860
74474
  if (targetPid == null && probe.instances.length > 1) {
73861
74475
  return {
73862
74476
  ...base,
@@ -73886,6 +74500,26 @@ async function hostReadiness(host, deps = DEFAULT_DEPS3, targetPid) {
73886
74500
  recovery: null
73887
74501
  };
73888
74502
  }
74503
+ if (host === "rhino" && !session.version) {
74504
+ return {
74505
+ ...base,
74506
+ session: found,
74507
+ ok: false,
74508
+ state: "host-version-unsupported",
74509
+ message: "Couldn\u2019t send \u2014 FloLess couldn\u2019t verify that the open session is Rhino 8. Restart Rhino, then try again.",
74510
+ recovery: null
74511
+ };
74512
+ }
74513
+ if (host === "rhino" && session.version && !/^8(?:\.|$)/.test(session.version)) {
74514
+ return {
74515
+ ...base,
74516
+ session: found,
74517
+ ok: false,
74518
+ state: "host-version-unsupported",
74519
+ message: `Couldn\u2019t send \u2014 FloLess can only build into Rhino 8, and the open session is Rhino ${session.version}.`,
74520
+ recovery: null
74521
+ };
74522
+ }
73889
74523
  if (host === "revit" && session.addinLoaded === false) {
73890
74524
  return {
73891
74525
  ...base,
@@ -73908,7 +74542,13 @@ async function hostReadiness(host, deps = DEFAULT_DEPS3, targetPid) {
73908
74542
  }
73909
74543
 
73910
74544
  // host-bake.ts
73911
- var GENERIC_BAKE_HOSTS = ["revit", "sketchup"];
74545
+ var GENERIC_BAKE_HOSTS = ["revit", "sketchup", "rhino"];
74546
+ function genericBakeTarget(hostPid, session) {
74547
+ return {
74548
+ hostPid,
74549
+ rhinoId: session.rhinoId ?? void 0
74550
+ };
74551
+ }
73912
74552
  function isGenericBakeHost(value) {
73913
74553
  return typeof value === "string" && GENERIC_BAKE_HOSTS.includes(value);
73914
74554
  }
@@ -73916,7 +74556,7 @@ var DESCRIPTORS = {
73916
74556
  revit: {
73917
74557
  host: "revit",
73918
74558
  label: HOST_LABELS.revit,
73919
- writeApp: (dir, appId, scene, hostPid) => writeRevitApp(dir, appId, scene, hostPid),
74559
+ writeApp: (dir, appId, scene, target) => writeRevitApp(dir, appId, scene, target?.hostPid),
73920
74560
  nodeId: "bake-revit",
73921
74561
  unavailable: "Revit must be open with a document, and the FloLess add-in loaded, to receive this."
73922
74562
  },
@@ -73928,6 +74568,15 @@ var DESCRIPTORS = {
73928
74568
  writeApp: (dir, appId, scene) => writeSketchupApp(dir, appId, scene),
73929
74569
  nodeId: "bake-sketchup",
73930
74570
  unavailable: "SketchUp must be open with a model to receive this."
74571
+ },
74572
+ rhino: {
74573
+ host: "rhino",
74574
+ label: HOST_LABELS.rhino,
74575
+ // Carry both identities. The sidecar requires them to agree, preventing a process-table verdict
74576
+ // about one Rhino window from authorizing a write into another rhinocode session.
74577
+ writeApp: (dir, appId, scene, target) => writeRhinoApp(dir, appId, scene, target?.rhinoId, target?.hostPid),
74578
+ nodeId: "bake-rhino",
74579
+ unavailable: "Rhino must be open with a document to receive this."
73931
74580
  }
73932
74581
  };
73933
74582
  function hostBakeDescriptor(host) {
@@ -73938,6 +74587,7 @@ function looksLikeHostUnavailable(host, ...messages) {
73938
74587
  if (!haystack) return false;
73939
74588
  const signals = [
73940
74589
  "no " + host + " instance",
74590
+ ...host === "rhino" ? ["no rhino script server session matches"] : [],
73941
74591
  "not running",
73942
74592
  "no instance",
73943
74593
  "no running",
@@ -78339,9 +78989,7 @@ async function startServer() {
78339
78989
  return reply.status(404).send({ ok: false, error: err2.message });
78340
78990
  }
78341
78991
  if (err2 instanceof ContractPolicyError) {
78342
- const stateShaped = err2.code === "contract-not-activated" || err2.code === "contract-type-unknown" || err2.code === "contract-type-wrong-app" || err2.code === "contract-authority-unresolved";
78343
- if (stateShaped) req.log.warn({ code: err2.code, err: err2 }, "contract policy refused stored state");
78344
- return reply.status(stateShaped ? 409 : 400).send({ ok: false, error: err2.message, code: err2.code });
78992
+ return replyContractPolicyError(err2, req, reply);
78345
78993
  }
78346
78994
  if (err2 instanceof ContractError) {
78347
78995
  return reply.status(400).send({ ok: false, error: err2.message });
@@ -78356,19 +79004,7 @@ async function startServer() {
78356
79004
  return reply.status(400).send({ ok: false, error: err2.message });
78357
79005
  }
78358
79006
  if (err2 instanceof LifecycleLockBusyError) {
78359
- const retryAfter = err2.busy.remainingMs == null ? 5 : Math.min(60, Math.max(1, Math.ceil(err2.busy.remainingMs / 1e3)));
78360
- app.log.warn({
78361
- kind: err2.busy.kind,
78362
- key: err2.busy.key,
78363
- label: err2.busy.label,
78364
- elapsedMs: err2.busy.elapsedMs
78365
- }, "lifecycle lock busy \u2014 request refused");
78366
- return reply.status(err2.status).header("Retry-After", String(retryAfter)).send({
78367
- ok: false,
78368
- error: err2.message,
78369
- code: "lifecycle-busy",
78370
- busy: err2.busy
78371
- });
79007
+ return replyLifecycleLockBusyError(err2, app.log, reply);
78372
79008
  }
78373
79009
  if (err2 instanceof RoutineError) {
78374
79010
  return reply.status(err2.status).send({ ok: false, error: err2.message });
@@ -78809,10 +79445,6 @@ async function startServer() {
78809
79445
  });
78810
79446
  return { ok: true, id, flow, started: true };
78811
79447
  });
78812
- app.get("/api/app/:id", async (req) => {
78813
- const a = readApp(req.params.id);
78814
- return { ok: true, app: a, contractState: appContractState(req.params.id, a) };
78815
- });
78816
79448
  const withTemplateId = (p, root4) => ({ ...p, templateId: root4(p.app) });
78817
79449
  const projectView = (p) => withTemplateId(p, resolveTemplateId);
78818
79450
  const projectViews = (list) => {
@@ -78840,6 +79472,7 @@ async function startServer() {
78840
79472
  return reply.status(404).send({ ok: false, error: `"${wanted}" is not installed`, code: "not-installed" });
78841
79473
  }
78842
79474
  const project = createProject({ name: req.body?.name, app: req.body?.app });
79475
+ broadcast({ type: "projects-changed", appId: project.app });
78843
79476
  let seeded = false;
78844
79477
  if (req.body?.seedFromApp) {
78845
79478
  const legacy = readAcceptedForRequest(project.app, void 0);
@@ -78881,7 +79514,12 @@ async function startServer() {
78881
79514
  projectExportsDir(req.params.id),
78882
79515
  { kind: "project", key: req.params.id }
78883
79516
  );
78884
- return { ok: true, project: projectView(duplicateProject(req.params.id, req.body?.name)) };
79517
+ const project = duplicateProject(
79518
+ req.params.id,
79519
+ req.body?.name,
79520
+ (created) => broadcast({ type: "projects-changed", appId: created.app })
79521
+ );
79522
+ return { ok: true, project: projectView(project) };
78885
79523
  });
78886
79524
  } catch (e) {
78887
79525
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
@@ -78895,7 +79533,9 @@ async function startServer() {
78895
79533
  projectExportsDir(req.params.id),
78896
79534
  { kind: "project", key: req.params.id }
78897
79535
  );
79536
+ const project = getProject(req.params.id);
78898
79537
  archiveProject(req.params.id);
79538
+ if (project) broadcast({ type: "projects-changed", appId: project.app });
78899
79539
  return { ok: true };
78900
79540
  });
78901
79541
  } catch (e) {
@@ -78906,7 +79546,11 @@ async function startServer() {
78906
79546
  app.get("/api/projects/archived", async () => ({ ok: true, projects: projectViews(listArchivedProjects()) }));
78907
79547
  app.post("/api/projects/:id/unarchive", async (req, reply) => {
78908
79548
  try {
78909
- return await withLifecycleLock("project", req.params.id, () => ({ ok: true, project: projectView(unarchiveProject(req.params.id)) }));
79549
+ return await withLifecycleLock("project", req.params.id, () => {
79550
+ const project = unarchiveProject(req.params.id);
79551
+ broadcast({ type: "projects-changed", appId: project.app });
79552
+ return { ok: true, project: projectView(project) };
79553
+ });
78910
79554
  } catch (e) {
78911
79555
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
78912
79556
  throw e;
@@ -78953,6 +79597,7 @@ async function startServer() {
78953
79597
  if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message, code: "invalid" });
78954
79598
  throw e;
78955
79599
  }
79600
+ broadcast({ type: "projects-changed", appId: project.app });
78956
79601
  return { ok: true, project: projectView(project), appInstalled: appExists(project.app) };
78957
79602
  }
78958
79603
  );
@@ -78960,34 +79605,51 @@ async function startServer() {
78960
79605
  const p = getProject(req.params.id);
78961
79606
  if (!p) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
78962
79607
  const versions = listVersions(req.params.id);
78963
- const diffSupported = appSupportsDiff(p.app);
79608
+ const kindSupportsDiff = appSupportsDiff(resolveTemplateId(p.app));
79609
+ let diffSupported = false;
79610
+ let diffEligibleVersions;
78964
79611
  let enriched = versions;
78965
- if (diffSupported) {
79612
+ if (kindSupportsDiff) {
79613
+ const support = await analyzeVersionDiffLedger(p.id, versions);
79614
+ diffSupported = support.diffSupported;
79615
+ diffEligibleVersions = support.eligibleVersions;
78966
79616
  const approvals = versions.filter((v) => v.kind === "approve").sort((a, b) => a.n - b.n);
78967
- const approvalBases = /* @__PURE__ */ new Map();
78968
- let previousApproval = null;
78969
- for (const version of approvals) {
78970
- approvalBases.set(version.n, previousApproval);
78971
- previousApproval = version.n;
78972
- }
79617
+ const approvalBases = new Map(
79618
+ approvals.map((version) => [version.n, support.rows.get(version.n)?.diffBase ?? null])
79619
+ );
79620
+ const summaryVersions = approvals.filter((version) => {
79621
+ const row = support.rows.get(version.n);
79622
+ return support.eligibility.get(version.n) === "eligible" && (row?.diffBase == null || row.diffSupported);
79623
+ }).map((version) => version.n);
78973
79624
  const summaries = await summarizeVersionChangesAsync(
78974
79625
  p.id,
78975
- approvals.map((v) => v.n),
79626
+ summaryVersions,
78976
79627
  approvalBases
78977
79628
  );
78978
79629
  enriched = versions.map((v) => {
78979
79630
  const changeSummary = summaries.get(v.n);
78980
- return v.kind === "approve" && changeSummary ? { ...v, changeSummary } : v;
79631
+ const row = support.rows.get(v.n) ?? { diffSupported: false, diffBase: null };
79632
+ return {
79633
+ ...v,
79634
+ ...row,
79635
+ ...v.kind === "approve" && changeSummary ? { changeSummary } : {}
79636
+ };
78981
79637
  });
78982
79638
  }
78983
- return { ok: true, versions: enriched, approvedAt: p.approvedAt ?? null, diffSupported };
79639
+ return {
79640
+ ok: true,
79641
+ versions: enriched,
79642
+ approvedAt: p.approvedAt ?? null,
79643
+ diffSupported,
79644
+ ...diffEligibleVersions ? { diffEligibleVersions } : {}
79645
+ };
78984
79646
  });
78985
79647
  app.get(
78986
79648
  "/api/projects/:id/versions/:n/diff",
78987
79649
  async (req, reply) => {
78988
79650
  const project = getProject(req.params.id);
78989
79651
  if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
78990
- if (!appSupportsDiff(project.app)) {
79652
+ if (!appSupportsDiff(resolveTemplateId(project.app))) {
78991
79653
  return reply.status(409).send({ ok: false, error: `the version diff is not supported for "${project.app}" projects` });
78992
79654
  }
78993
79655
  const n = Number(req.params.n);
@@ -79032,11 +79694,6 @@ async function startServer() {
79032
79694
  registerRevisionRoutes(app);
79033
79695
  registerSteelPrepassRoute(app, { getProject, clearApproval, broadcast });
79034
79696
  registerKnowledgeRoutes(app);
79035
- const projectPublicationBody = (what) => ({
79036
- ok: false,
79037
- error: `this workflow's model belongs to a project \u2014 open that project ${what} it`,
79038
- code: "project-publication"
79039
- });
79040
79697
  function projectAppMismatch(appId, project) {
79041
79698
  const p = getProject(project);
79042
79699
  if (!p) return `unknown project: ${project}`;
@@ -79050,7 +79707,58 @@ async function startServer() {
79050
79707
  if (!p.approvedAt) return { status: 409, error: "Approve this version before exporting \u2014 exports go out only after sign-off." };
79051
79708
  return null;
79052
79709
  }
79710
+ function genericBakeHostLabel(host) {
79711
+ return isGenericBakeHost(host) ? hostBakeDescriptor(host).label : null;
79712
+ }
79713
+ function projectPublicationStateForApp(appId) {
79714
+ return readProjectPublicationState(
79715
+ appId,
79716
+ listProjects,
79717
+ (error) => app.log.warn(
79718
+ { appId, err: error instanceof Error ? error.message : error },
79719
+ "could not read project availability for a baked publication"
79720
+ )
79721
+ );
79722
+ }
79723
+ function appContractStateForRoute(appId, loaded2) {
79724
+ return appContractState(appId, loaded2) ? projectPublicationStateForApp(appId) : null;
79725
+ }
79726
+ function appContractStateByIdForRoute(appId) {
79727
+ try {
79728
+ return appContractStateForRoute(appId, readApp(appId));
79729
+ } catch (error) {
79730
+ if (!(error instanceof AppNotFoundError)) {
79731
+ app.log.warn(
79732
+ { appId, err: error instanceof Error ? error.message : error },
79733
+ "could not inspect an absent app store for a baked project publication"
79734
+ );
79735
+ }
79736
+ return null;
79737
+ }
79738
+ }
79053
79739
  registerWorkspaceDataRoutes(app);
79740
+ registerContractAccessRoutes(app, {
79741
+ readApp,
79742
+ appContractState: appContractStateForRoute,
79743
+ projectPublicationState: projectPublicationStateForApp,
79744
+ projectAppMismatch,
79745
+ projectExportGate,
79746
+ currentApprovedSnapshot,
79747
+ workspaceSnapshotError: (error) => error instanceof WorkspaceSnapshotError ? { status: error.status, error: error.message } : null,
79748
+ readAcceptedForRequest,
79749
+ resolveAppContract,
79750
+ storeEtag,
79751
+ postProcessVector: (doc) => postProcess(doc),
79752
+ parseSelection: readSelectionFromBody,
79753
+ genericBakeHostLabel,
79754
+ withLifecycleLock,
79755
+ continueScene: continueContractScene,
79756
+ continueIfcExport,
79757
+ continueSvgExport,
79758
+ continueBomExport,
79759
+ continueTeklaExport,
79760
+ continueGenericHostExport
79761
+ });
79054
79762
  registerMigrationPreviewRoute(app, {
79055
79763
  // Reads bytes the policy has NOT accepted. Note what this does and does not currently buy: the
79056
79764
  // route validates its input as v1 (steel-model-migrate-route.ts), so a quarantined v2 still gets a
@@ -79060,31 +79768,6 @@ async function startServer() {
79060
79768
  projectAppMismatch
79061
79769
  });
79062
79770
  registerMigrationCommitRoute(app, { projectAppMismatch, broadcast });
79063
- app.get("/api/contract/:appId", async (req, reply) => {
79064
- const project = req.query.project || void 0;
79065
- if (project) {
79066
- const bad = projectAppMismatch(req.params.appId, project);
79067
- if (bad) return reply.status(404).send({ ok: false, error: bad });
79068
- }
79069
- let doc;
79070
- let publication = false;
79071
- if (project) {
79072
- doc = readAcceptedForRequest(req.params.appId, project);
79073
- } else {
79074
- const resolved = resolveAppContract(req.params.appId);
79075
- doc = resolvedDoc(resolved);
79076
- publication = resolved.kind === "project-publication";
79077
- }
79078
- if (doc == null && req.query.quietMissing === "1") return reply.status(204).send();
79079
- if (doc == null && publication) return reply.status(404).send(projectPublicationBody("to see"));
79080
- if (doc == null) return reply.status(404).send({ ok: false, error: "no contract for this app yet" });
79081
- const tag = storeEtag(req.params.appId, project);
79082
- if (tag) reply.header("ETag", tag);
79083
- if (doc && typeof doc === "object" && doc.type === "drawing.vector/v1") {
79084
- return postProcess(doc);
79085
- }
79086
- return doc;
79087
- });
79088
79771
  app.get(
79089
79772
  "/api/contract/:appId/detail/:sheet",
79090
79773
  async (req, reply) => {
@@ -79218,41 +79901,21 @@ async function startServer() {
79218
79901
  };
79219
79902
  }
79220
79903
  );
79221
- app.post(
79222
- "/api/contract/:appId/scene",
79223
- { bodyLimit: 25 * 1024 * 1024 },
79224
- // contracts embed rasters (matches PUT /api/contract) — the editor POSTs the live contract on every 3D rebuild
79225
- async (req, reply) => {
79226
- const project = req.query.project || void 0;
79227
- if (project) {
79228
- const bad = projectAppMismatch(req.params.appId, project);
79229
- if (bad) return reply.status(404).send({ ok: false, error: bad });
79230
- }
79231
- let candidate;
79232
- let publication = false;
79233
- if (req.body && "contract" in req.body) {
79234
- candidate = req.body.contract;
79235
- } else {
79236
- const resolved = resolveAppContract(req.params.appId);
79237
- candidate = resolvedDoc(resolved);
79238
- publication = resolved.kind === "project-publication";
79239
- }
79240
- if (candidate == null && publication) return reply.status(404).send(projectPublicationBody("to view"));
79241
- if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to render" });
79242
- if (candidate && typeof candidate === "object" && candidate.type === "drawing.vector/v1") {
79243
- const cleaned = postProcess(candidate);
79244
- const v = validateContract(cleaned);
79245
- if (!v.valid) {
79246
- const first = v.errors[0];
79247
- return reply.status(400).send({ ok: false, error: `contract failed schema validation \u2014 ${first ? `${first.path}: ${first.message}` : "invalid"}` });
79248
- }
79249
- return { ok: true, ...viewsToScene(cleaned) };
79904
+ async function continueContractScene(input, reply) {
79905
+ const { appId, project, candidate } = input;
79906
+ if (candidate && typeof candidate === "object" && candidate.type === "drawing.vector/v1") {
79907
+ const cleaned = postProcess(candidate);
79908
+ const v = validateContract(cleaned);
79909
+ if (!v.valid) {
79910
+ const first = v.errors[0];
79911
+ return reply.status(400).send({ ok: false, error: `contract failed schema validation \u2014 ${first ? `${first.path}: ${first.message}` : "invalid"}` });
79250
79912
  }
79251
- const steel = acceptSteelForRoute(candidate, { appId: req.params.appId, projectId: project }, "request-body", "v1-or-v2");
79252
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
79253
- return { ok: true, ...contractToScene(steel.doc) };
79913
+ return { ok: true, ...viewsToScene(cleaned) };
79254
79914
  }
79255
- );
79915
+ const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "request-body", "v1-or-v2");
79916
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
79917
+ return { ok: true, ...contractToScene(steel.doc) };
79918
+ }
79256
79919
  app.get("/api/contract/:appId/exports", async (req, reply) => {
79257
79920
  const project = req.query.project;
79258
79921
  if (!project) return reply.status(400).send({ ok: false, error: "project required" });
@@ -79333,7 +79996,20 @@ async function startServer() {
79333
79996
  throw error;
79334
79997
  }
79335
79998
  }
79336
- const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, void 0);
79999
+ let candidate;
80000
+ if (projectSnapshot) {
80001
+ candidate = projectSnapshot.contract;
80002
+ } else {
80003
+ candidate = readAcceptedForRequest(appId, void 0);
80004
+ if (candidate == null) {
80005
+ const publicationState = appContractStateByIdForRoute(appId);
80006
+ if (publicationState) {
80007
+ return reply.status(404).send(
80008
+ projectPublicationBody(publicationState, "to export")
80009
+ );
80010
+ }
80011
+ }
80012
+ }
79337
80013
  if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
79338
80014
  const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
79339
80015
  if (!steel.accepted) return reply.status(400).send(steel.refusal);
@@ -79385,139 +80061,117 @@ async function startServer() {
79385
80061
  const ownerId = project ? await getOrCreateProjectExportSourceId(project) : await getOrCreateWorkflowExportSourceId(appId);
79386
80062
  return deriveDropExportSourceId(project ? "project" : "workflow", ownerId, (0, import_node_crypto23.randomUUID)());
79387
80063
  }
79388
- app.post("/api/contract/:appId/export-ifc", async (req, reply) => {
79389
- const appId = req.params.appId;
79390
- const project = req.query.project || void 0;
79391
- return withLifecycleLock(project ? "project" : "app", project || appId, async () => {
79392
- let projectSnapshot;
79393
- if (project) {
79394
- const gate = projectExportGate(appId, project);
79395
- if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
79396
- try {
79397
- projectSnapshot = currentApprovedSnapshot(project);
79398
- } catch (error) {
79399
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
79400
- throw error;
79401
- }
79402
- }
79403
- let doc;
79404
- let publication = false;
79405
- if (projectSnapshot) {
79406
- doc = projectSnapshot.contract;
79407
- } else {
79408
- const resolved = resolveAppContract(appId);
79409
- doc = resolvedDoc(resolved);
79410
- publication = resolved.kind === "project-publication";
80064
+ async function continueIfcExport(input, reply) {
80065
+ const appId = input.appId;
80066
+ const project = input.kind === "project" ? input.project : void 0;
80067
+ const projectSnapshot = input.kind === "project" ? input.snapshot : void 0;
80068
+ const doc = input.kind === "app" ? input.doc : input.snapshot.contract;
80069
+ const sourceId = await stableExportSourceId(appId, project);
80070
+ const isVector2 = typeof doc === "object" && doc != null && doc.type === "drawing.vector/v1";
80071
+ let scene;
80072
+ let producerUnsupported = [];
80073
+ let skipped = [];
80074
+ let extrusionsSkipped = 0;
80075
+ let emptyError;
80076
+ if (isVector2) {
80077
+ const cleaned = postProcess(doc);
80078
+ const validation = validateContract(cleaned);
80079
+ if (!validation.valid) return reply.status(400).send({ ok: false, error: "stored contract is invalid \u2014 re-save it in the editor" });
80080
+ const built = viewsToScene(cleaned);
80081
+ extrusionsSkipped = built.scene.elements.filter((element) => element.kind === "extrusion").length;
80082
+ const elements = built.scene.elements.filter((element) => element.kind === "box").map((element) => ({ ...element, kind: "member" }));
80083
+ scene = {
80084
+ meta: { name: "Drawing IFC", units: "mm", sourceId, sceneHash: "" },
80085
+ elements,
80086
+ operations: [],
80087
+ referenceSystems: []
80088
+ };
80089
+ scene.meta.sceneHash = sceneHash(scene);
80090
+ skipped = built.skipped;
80091
+ emptyError = extrusionsSkipped ? `no member geometry to export \u2014 this model is ${extrusionsSkipped} extruded ${extrusionsSkipped === 1 ? "body" : "bodies"}, which don't export to IFC yet` : "no 3D to export \u2014 reconstruct a plan + elevation first";
80092
+ } else {
80093
+ const steel = acceptSteelForRoute(doc, { appId, projectId: project }, "stored", "v1-or-v2");
80094
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
80095
+ const built = contractToAwareScene(steel.doc, sourceId);
80096
+ scene = built.scene;
80097
+ skipped = built.skipped;
80098
+ producerUnsupported = built.producerUnsupported;
80099
+ emptyError = "no resolvable members to export \u2014 every member is an RFI (no AISC size yet)";
80100
+ }
80101
+ if (!hasExportableSceneRecords(scene)) return reply.status(422).send({ ok: false, error: emptyError, skipped });
80102
+ const filename = `${exportFileBase(project, appId)}.ifc`;
80103
+ const finalPath = (0, import_node_path46.join)(project ? projectExportsDir(project) : (0, import_node_path46.dirname)(bomExportPath(appId, "csv")), filename);
80104
+ const priorProjectIfc = project ? listProjectExportReceipts(project).find((row) => row.kind === "ifc") : void 0;
80105
+ const tempPath = requestIfcTempPath(finalPath);
80106
+ try {
80107
+ const rawReceipt = await aware.agentInvoke("ifc", "write", {
80108
+ scene,
80109
+ "output-path": tempPath
80110
+ });
80111
+ if (!(0, import_node_fs50.existsSync)(tempPath) || (0, import_node_fs50.statSync)(tempPath).size === 0) {
80112
+ throw new ReceiptReconciliationError("AWARE reported a successful export but wrote no IFC file.");
79411
80113
  }
79412
- if (doc == null && publication) return reply.status(404).send(projectPublicationBody("to export"));
79413
- if (doc == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
79414
- const sourceId = await stableExportSourceId(appId, project);
79415
- const isVector = typeof doc === "object" && doc != null && doc.type === "drawing.vector/v1";
79416
- let scene;
79417
- let producerUnsupported = [];
79418
- let skipped = [];
79419
- let extrusionsSkipped = 0;
79420
- let emptyError;
79421
- if (isVector) {
79422
- const cleaned = postProcess(doc);
79423
- const validation = validateContract(cleaned);
79424
- if (!validation.valid) return reply.status(400).send({ ok: false, error: "stored contract is invalid \u2014 re-save it in the editor" });
79425
- const built = viewsToScene(cleaned);
79426
- extrusionsSkipped = built.scene.elements.filter((element) => element.kind === "extrusion").length;
79427
- const elements = built.scene.elements.filter((element) => element.kind === "box").map((element) => ({ ...element, kind: "member" }));
79428
- scene = {
79429
- meta: { name: "Drawing IFC", units: "mm", sourceId, sceneHash: "" },
79430
- elements,
79431
- operations: [],
79432
- referenceSystems: []
79433
- };
79434
- scene.meta.sceneHash = sceneHash(scene);
79435
- skipped = built.skipped;
79436
- emptyError = extrusionsSkipped ? `no member geometry to export \u2014 this model is ${extrusionsSkipped} extruded ${extrusionsSkipped === 1 ? "body" : "bodies"}, which don't export to IFC yet` : "no 3D to export \u2014 reconstruct a plan + elevation first";
79437
- } else {
79438
- const steel = acceptSteelForRoute(doc, { appId, projectId: project }, "stored", "v1-or-v2");
79439
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
79440
- const built = contractToAwareScene(steel.doc, sourceId);
79441
- scene = built.scene;
79442
- skipped = built.skipped;
79443
- producerUnsupported = built.producerUnsupported;
79444
- emptyError = "no resolvable members to export \u2014 every member is an RFI (no AISC size yet)";
79445
- }
79446
- if (!hasExportableSceneRecords(scene)) return reply.status(422).send({ ok: false, error: emptyError, skipped });
79447
- const filename = `${exportFileBase(project, appId)}.ifc`;
79448
- const finalPath = (0, import_node_path46.join)(project ? projectExportsDir(project) : (0, import_node_path46.dirname)(bomExportPath(appId, "csv")), filename);
79449
- const priorProjectIfc = project ? listProjectExportReceipts(project).find((row) => row.kind === "ifc") : void 0;
79450
- const tempPath = requestIfcTempPath(finalPath);
79451
- try {
79452
- const rawReceipt = await aware.agentInvoke("ifc", "write", {
79453
- scene,
79454
- "output-path": tempPath
79455
- });
79456
- if (!(0, import_node_fs50.existsSync)(tempPath) || (0, import_node_fs50.statSync)(tempPath).size === 0) {
79457
- throw new ReceiptReconciliationError("AWARE reported a successful export but wrote no IFC file.");
79458
- }
79459
- const artifactBytes = (0, import_node_fs50.readFileSync)(tempPath);
79460
- const receipt = reconcileIfcExportReceipt(scene, rawReceipt, producerUnsupported, {
79461
- index: parseStepData(artifactBytes),
79462
- bytes: artifactBytes
79463
- });
79464
- const expectedContentSha256 = (0, import_node_crypto23.createHash)("sha256").update(artifactBytes).digest("hex");
79465
- const transition = project && projectSnapshot ? prepareProjectExport(project, {
79466
- kind: "ifc",
79467
- filename,
79468
- bytes: artifactBytes.length,
79469
- version: projectSnapshot.version.n,
79470
- contractHash: projectSnapshot.contractHash,
79471
- encoding: "utf8"
79472
- }) : void 0;
79473
- const publication2 = await publishIfcAtomically(tempPath, finalPath, {
79474
- resource: { kind: project ? "project" : "app", key: project || appId },
79475
- expectedContentSha256,
79476
- ...transition ? {
79477
- receipt: {
79478
- transition,
79479
- commit: () => commitProjectExportTransition(transition),
79480
- restore: () => restoreProjectExportTransition(transition)
79481
- }
79482
- } : {}
79483
- });
79484
- const bytes = publication2.bytes;
79485
- const content = bytes.toString("utf8");
79486
- if (publication2.cleanupPending) {
79487
- app.log.warn(
79488
- { appId, project, finalPath, error: publication2.cleanupError },
79489
- "IFC publication committed; cleanup deferred to recovery"
79490
- );
79491
- }
79492
- if (transition) cleanupSupersededProjectExport(transition);
79493
- return {
79494
- ok: true,
79495
- filename,
79496
- savedTo: finalPath,
79497
- content,
79498
- bytes: bytes.length,
79499
- skipped,
79500
- receipt,
79501
- counts: receipt.counts,
79502
- warnings: receipt.warnings,
79503
- ...publication2.cleanupPending ? { cleanupPending: true } : {},
79504
- ...extrusionsSkipped ? { extrusionsSkipped } : {}
79505
- };
79506
- } catch (error) {
79507
- const reason = awareStderr(error);
79508
- app.log.warn({ appId, project, error: error instanceof Error ? error.message : error, reason }, "IFC export failed before durable promotion");
79509
- const status = error instanceof ReceiptReconciliationError || error instanceof StepParseError ? 422 : error instanceof IfcPublicationError ? 500 : 502;
79510
- return reply.status(status).send({
79511
- ok: false,
79512
- error: awareFailureMessage(error, "IFC export failed"),
79513
- ...reason ? { reason } : {},
79514
- preservedPrevious: project && priorProjectIfc ? receiptHasFile(project, priorProjectIfc) : (0, import_node_fs50.existsSync)(finalPath)
79515
- });
79516
- } finally {
79517
- cleanupIfcTemp(tempPath);
80114
+ const artifactBytes = (0, import_node_fs50.readFileSync)(tempPath);
80115
+ const receipt = reconcileIfcExportReceipt(scene, rawReceipt, producerUnsupported, {
80116
+ index: parseStepData(artifactBytes),
80117
+ bytes: artifactBytes
80118
+ });
80119
+ const expectedContentSha256 = (0, import_node_crypto23.createHash)("sha256").update(artifactBytes).digest("hex");
80120
+ const transition = project && projectSnapshot ? prepareProjectExport(project, {
80121
+ kind: "ifc",
80122
+ filename,
80123
+ bytes: artifactBytes.length,
80124
+ version: projectSnapshot.version.n,
80125
+ contractHash: projectSnapshot.contractHash,
80126
+ encoding: "utf8"
80127
+ }) : void 0;
80128
+ const publication = await publishIfcAtomically(tempPath, finalPath, {
80129
+ resource: { kind: project ? "project" : "app", key: project || appId },
80130
+ expectedContentSha256,
80131
+ ...transition ? {
80132
+ receipt: {
80133
+ transition,
80134
+ commit: () => commitProjectExportTransition(transition),
80135
+ restore: () => restoreProjectExportTransition(transition)
80136
+ }
80137
+ } : {}
80138
+ });
80139
+ const bytes = publication.bytes;
80140
+ const content = bytes.toString("utf8");
80141
+ if (publication.cleanupPending) {
80142
+ app.log.warn(
80143
+ { appId, project, finalPath, error: publication.cleanupError },
80144
+ "IFC publication committed; cleanup deferred to recovery"
80145
+ );
79518
80146
  }
79519
- });
79520
- });
80147
+ if (transition) cleanupSupersededProjectExport(transition);
80148
+ return {
80149
+ ok: true,
80150
+ filename,
80151
+ savedTo: finalPath,
80152
+ content,
80153
+ bytes: bytes.length,
80154
+ skipped,
80155
+ receipt,
80156
+ counts: receipt.counts,
80157
+ warnings: receipt.warnings,
80158
+ ...publication.cleanupPending ? { cleanupPending: true } : {},
80159
+ ...extrusionsSkipped ? { extrusionsSkipped } : {}
80160
+ };
80161
+ } catch (error) {
80162
+ const reason = awareStderr(error);
80163
+ app.log.warn({ appId, project, error: error instanceof Error ? error.message : error, reason }, "IFC export failed before durable promotion");
80164
+ const status = error instanceof ReceiptReconciliationError || error instanceof StepParseError ? 422 : error instanceof IfcPublicationError ? 500 : 502;
80165
+ return reply.status(status).send({
80166
+ ok: false,
80167
+ error: awareFailureMessage(error, "IFC export failed"),
80168
+ ...reason ? { reason } : {},
80169
+ preservedPrevious: project && priorProjectIfc ? receiptHasFile(project, priorProjectIfc) : (0, import_node_fs50.existsSync)(finalPath)
80170
+ });
80171
+ } finally {
80172
+ cleanupIfcTemp(tempPath);
80173
+ }
80174
+ }
79521
80175
  app.get("/api/render/readiness", async () => ({ ok: true, readiness: await renderReadiness() }));
79522
80176
  app.post("/api/render/install-agent", async (_req, reply) => {
79523
80177
  try {
@@ -79713,213 +80367,174 @@ async function startServer() {
79713
80367
  expectedMs: renderExpectedMs(output, quality, viewpoints.length)
79714
80368
  });
79715
80369
  });
79716
- app.post("/api/contract/:appId/export-tekla", async (req, reply) => {
79717
- const appId = req.params.appId;
79718
- const project = req.query.project || void 0;
79719
- const parsed = readSelectionFromBody(req.body);
79720
- if (parsed === "invalid") {
79721
- return reply.status(400).send({
80370
+ async function continueTeklaExport(input, reply) {
80371
+ const { source, selection } = input;
80372
+ const appId = source.appId;
80373
+ const project = source.kind === "project" ? source.project : void 0;
80374
+ const readiness = await teklaReadiness();
80375
+ if (!readiness.ok) {
80376
+ return reply.status(409).send({
79722
80377
  ok: false,
79723
- error: "Could not read which members to send. Try again, and if it keeps happening, reload the editor."
80378
+ needsTekla: readiness.state === "host-closed" || readiness.state === "model-closed",
80379
+ error: readiness.message,
80380
+ readiness
79724
80381
  });
79725
80382
  }
79726
- const selection = parsed;
79727
- return withLifecycleLock(project ? "project" : "app", project || appId, async () => {
79728
- let projectSnapshot;
79729
- if (project) {
79730
- const gate = projectExportGate(appId, project);
79731
- if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
79732
- try {
79733
- projectSnapshot = currentApprovedSnapshot(project);
79734
- } catch (error) {
79735
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
79736
- throw error;
79737
- }
79738
- }
79739
- const readiness = await teklaReadiness();
79740
- if (!readiness.ok) {
79741
- return reply.status(409).send({
79742
- ok: false,
79743
- needsTekla: readiness.state === "host-closed" || readiness.state === "model-closed",
79744
- error: readiness.message,
79745
- readiness
79746
- });
79747
- }
79748
- const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, void 0);
79749
- if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to bake" });
79750
- const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
79751
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
79752
- const doc = steel.doc;
79753
- const sourceId = selection ? await dropExportSourceId(appId, project) : await stableExportSourceId(appId, project);
79754
- const scoped = selection ? contractForMemberSelection(doc, selection) : doc;
79755
- if (selection && selectionMemberCount(scoped) === 0) {
79756
- return reply.status(422).send({ ok: false, error: "those members aren\u2019t in the model any more \u2014 reload the editor and try again" });
79757
- }
79758
- const built = contractToAwareScene(scoped, sourceId);
79759
- if (!hasExportableSceneRecords(built.scene)) {
79760
- return reply.status(422).send({
79761
- ok: false,
79762
- error: selection ? "nothing to bake in that selection \u2014 every member you dragged is an RFI (no AISC size yet)" : "no resolvable members to bake \u2014 every member is an RFI (no AISC size yet)",
79763
- skipped: built.skipped
79764
- });
79765
- }
79766
- const companion = createExportCompanion(appId, "tekla");
80383
+ const candidate = source.kind === "project" ? source.snapshot.contract : source.doc;
80384
+ const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
80385
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
80386
+ const doc = steel.doc;
80387
+ const sourceId = selection ? await dropExportSourceId(appId, project) : await stableExportSourceId(appId, project);
80388
+ const scoped = selection ? contractForMemberSelection(doc, selection) : doc;
80389
+ if (selection && selectionMemberCount(scoped) === 0) {
80390
+ return reply.status(422).send({ ok: false, error: "those members aren\u2019t in the model any more \u2014 reload the editor and try again" });
80391
+ }
80392
+ const built = contractToAwareScene(scoped, sourceId);
80393
+ if (!hasExportableSceneRecords(built.scene)) {
80394
+ return reply.status(422).send({
80395
+ ok: false,
80396
+ error: selection ? "nothing to bake in that selection \u2014 every member you dragged is an RFI (no AISC size yet)" : "no resolvable members to bake \u2014 every member is an RFI (no AISC size yet)",
80397
+ skipped: built.skipped
80398
+ });
80399
+ }
80400
+ const companion = createExportCompanion(appId, "tekla");
80401
+ try {
80402
+ const flo = writeTeklaApp(companion.path, companion.id, built.scene, readiness.host.version || await teklaVersionToBake());
80403
+ stampExportCompanionLease(companion);
80404
+ await aware.compile(flo);
80405
+ let runResult;
79767
80406
  try {
79768
- const flo = writeTeklaApp(companion.path, companion.id, built.scene, readiness.host.version || await teklaVersionToBake());
79769
- stampExportCompanionLease(companion);
79770
- await aware.compile(flo);
79771
- let runResult;
79772
- try {
79773
- runResult = await aware.run(companion.id, {});
79774
- } catch (error) {
79775
- const recoverable = error instanceof AwareError && /timeout|timed out|lost response|connection reset/i.test(`${error.message} ${awareStderr(error) || ""}`);
79776
- if (!recoverable) throw error;
79777
- runResult = await aware.run(companion.id, {});
79778
- }
79779
- const events = runResult.traceText ? parseTrace(runResult.traceText) : [];
79780
- const output = [...events].reverse().find((event) => event.kind === "node-output" && event.node === "bake-tekla");
79781
- const envelope = output?.data && typeof output.data === "object" ? output.data : null;
79782
- const rawReceipt = envelope?.result && typeof envelope.result === "object" ? envelope.result : envelope;
79783
- const receipt = reconcileExportReceipt(built.scene, rawReceipt, built.producerUnsupported);
79784
- return {
79785
- ok: true,
79786
- message: `${receipt.counts.emitted} emitted${receipt.counts.native != null ? ` \xB7 ${receipt.counts.native} native` : ""}${receipt.counts.unsupported ? ` \xB7 ${receipt.counts.unsupported} unsupported` : ""}${receipt.counts.warnings ? ` \xB7 ${receipt.counts.warnings} warning${receipt.counts.warnings === 1 ? "" : "s"}` : ""}`,
79787
- elements: receipt.counts.emitted,
79788
- skipped: built.skipped,
79789
- receipt,
79790
- counts: receipt.counts,
79791
- warnings: receipt.warnings
79792
- };
80407
+ runResult = await aware.run(companion.id, {});
79793
80408
  } catch (error) {
79794
- const reason = error instanceof AwareError ? awareStderr(error) : void 0;
79795
- const message = error instanceof Error ? error.message : "Tekla export failed";
79796
- const needsTekla = /tekla|connect|model|open api|host-unavailable/i.test(`${message} ${reason || ""}`);
79797
- app.log.warn({ appId, project, error: message, reason }, "Tekla export failed");
79798
- return reply.status(error instanceof ReceiptReconciliationError ? 422 : 502).send({
79799
- ok: false,
79800
- needsTekla,
79801
- error: needsTekla ? "Tekla must be open with a model to receive this export." : message,
79802
- reason
79803
- });
79804
- } finally {
79805
- try {
79806
- companion.cleanup();
79807
- } catch (error) {
79808
- app.log.error({ companionId: companion.id, error: error instanceof Error ? error.message : error }, "could not remove Tekla export companion");
79809
- }
79810
- }
79811
- }, { label: "sending the model to Tekla" });
79812
- });
79813
- app.post(
79814
- "/api/contract/:appId/export-host/:host",
79815
- async (req, reply) => {
79816
- const { appId } = req.params;
79817
- const project = req.query.project || void 0;
79818
- if (!isGenericBakeHost(req.params.host)) {
79819
- return reply.status(404).send({ ok: false, error: `no bake target called "${req.params.host}"` });
80409
+ const recoverable = error instanceof AwareError && /timeout|timed out|lost response|connection reset/i.test(`${error.message} ${awareStderr(error) || ""}`);
80410
+ if (!recoverable) throw error;
80411
+ runResult = await aware.run(companion.id, {});
80412
+ }
80413
+ const events = runResult.traceText ? parseTrace(runResult.traceText) : [];
80414
+ const output = [...events].reverse().find((event) => event.kind === "node-output" && event.node === "bake-tekla");
80415
+ const envelope = output?.data && typeof output.data === "object" ? output.data : null;
80416
+ const rawReceipt = envelope?.result && typeof envelope.result === "object" ? envelope.result : envelope;
80417
+ const receipt = reconcileExportReceipt(built.scene, rawReceipt, built.producerUnsupported);
80418
+ return {
80419
+ ok: true,
80420
+ message: `${receipt.counts.emitted} emitted${receipt.counts.native != null ? ` \xB7 ${receipt.counts.native} native` : ""}${receipt.counts.unsupported ? ` \xB7 ${receipt.counts.unsupported} unsupported` : ""}${receipt.counts.warnings ? ` \xB7 ${receipt.counts.warnings} warning${receipt.counts.warnings === 1 ? "" : "s"}` : ""}`,
80421
+ elements: receipt.counts.emitted,
80422
+ skipped: built.skipped,
80423
+ receipt,
80424
+ counts: receipt.counts,
80425
+ warnings: receipt.warnings
80426
+ };
80427
+ } catch (error) {
80428
+ const reason = error instanceof AwareError ? awareStderr(error) : void 0;
80429
+ const message = error instanceof Error ? error.message : "Tekla export failed";
80430
+ const needsTekla = /tekla|connect|model|open api|host-unavailable/i.test(`${message} ${reason || ""}`);
80431
+ app.log.warn({ appId, project, error: message, reason }, "Tekla export failed");
80432
+ return reply.status(error instanceof ReceiptReconciliationError ? 422 : 502).send({
80433
+ ok: false,
80434
+ needsTekla,
80435
+ error: needsTekla ? "Tekla must be open with a model to receive this export." : message,
80436
+ reason
80437
+ });
80438
+ } finally {
80439
+ try {
80440
+ companion.cleanup();
80441
+ } catch (error) {
80442
+ app.log.error({ companionId: companion.id, error: error instanceof Error ? error.message : error }, "could not remove Tekla export companion");
79820
80443
  }
79821
- const target = hostBakeDescriptor(req.params.host);
79822
- const parsed = readSelectionFromBody(req.body);
79823
- if (parsed === "invalid") {
79824
- return reply.status(400).send({
79825
- ok: false,
79826
- error: "Could not read which members to send. Try again, and if it keeps happening, reload the editor."
79827
- });
80444
+ }
80445
+ }
80446
+ const RHINO_BAKE_RUN_TIMEOUT_MS = 20 * 6e4;
80447
+ async function continueGenericHostExport(input, reply) {
80448
+ const { source, selection, host, hostPid } = input;
80449
+ const appId = source.appId;
80450
+ const project = source.kind === "project" ? source.project : void 0;
80451
+ if (!isGenericBakeHost(host)) throw new Error(`unsupported generic bake host: ${host}`);
80452
+ const target = hostBakeDescriptor(host);
80453
+ const readiness = await hostReadiness(target.host, void 0, hostPid);
80454
+ if (!readiness.ok) {
80455
+ return reply.status(409).send({
80456
+ ok: false,
80457
+ needsHost: readiness.state === "host-closed" || readiness.state === "addin-missing",
80458
+ host: target.host,
80459
+ error: readiness.message,
80460
+ readiness
80461
+ });
80462
+ }
80463
+ const candidate = source.kind === "project" ? source.snapshot.contract : source.doc;
80464
+ const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
80465
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
80466
+ const doc = steel.doc;
80467
+ const sourceId = selection ? await dropExportSourceId(appId, project) : await stableExportSourceId(appId, project);
80468
+ const scoped = selection ? contractForMemberSelection(doc, selection) : doc;
80469
+ if (selection && selectionMemberCount(scoped) === 0) {
80470
+ return reply.status(422).send({ ok: false, error: "those members aren\u2019t in the model any more \u2014 reload the editor and try again" });
80471
+ }
80472
+ const built = contractToAwareScene(scoped, sourceId);
80473
+ if (!hasExportableSceneRecords(built.scene)) {
80474
+ return reply.status(422).send({
80475
+ ok: false,
80476
+ error: selection ? `nothing to bake in that selection \u2014 every member you dragged is an RFI (no AISC size yet)` : "no resolvable members to bake \u2014 every member is an RFI (no AISC size yet)",
80477
+ skipped: built.skipped
80478
+ });
80479
+ }
80480
+ const companion = createExportCompanion(appId, target.host);
80481
+ try {
80482
+ const flo = target.writeApp(
80483
+ companion.path,
80484
+ companion.id,
80485
+ built.scene,
80486
+ genericBakeTarget(hostPid, readiness.session)
80487
+ );
80488
+ stampExportCompanionLease(companion);
80489
+ await aware.compile(flo);
80490
+ const env2 = readiness.bakeEnv;
80491
+ const runOpts = target.host === "rhino" ? { env: env2, timeoutMs: RHINO_BAKE_RUN_TIMEOUT_MS } : { env: env2 };
80492
+ let runResult;
80493
+ try {
80494
+ runResult = await aware.run(companion.id, runOpts);
80495
+ } catch (error) {
80496
+ const failureText = error instanceof Error ? `${error.message} ${error instanceof AwareError ? awareStderr(error) || "" : ""}` : String(error);
80497
+ const uncertainRhinoCompletion = target.host === "rhino" && /timeout|timed out|lost response|connection reset|commit[-_ ]state|still (?:be )?applying|uncertain/i.test(failureText);
80498
+ const recoverable = !uncertainRhinoCompletion && error instanceof AwareError && /timeout|timed out|lost response|connection reset/i.test(failureText);
80499
+ if (!recoverable) throw error;
80500
+ runResult = await aware.run(companion.id, runOpts);
80501
+ }
80502
+ const events = runResult.traceText ? parseTrace(runResult.traceText) : [];
80503
+ const output = [...events].reverse().find((event) => event.kind === "node-output" && event.node === target.nodeId);
80504
+ const envelope = output?.data && typeof output.data === "object" ? output.data : null;
80505
+ const rawReceipt = envelope?.result && typeof envelope.result === "object" ? envelope.result : envelope;
80506
+ const receipt = reconcileHostExportReceipt(built.scene, rawReceipt, built.producerUnsupported);
80507
+ return {
80508
+ ok: true,
80509
+ host: target.host,
80510
+ message: `${receipt.counts.emitted} emitted${receipt.counts.native != null ? ` \xB7 ${receipt.counts.native} native` : ""}${receipt.counts.unsupported ? ` \xB7 ${receipt.counts.unsupported} unsupported` : ""}${receipt.counts.warnings ? ` \xB7 ${receipt.counts.warnings} warning${receipt.counts.warnings === 1 ? "" : "s"}` : ""}`,
80511
+ elements: receipt.counts.emitted,
80512
+ skipped: built.skipped,
80513
+ receipt,
80514
+ counts: receipt.counts,
80515
+ warnings: receipt.warnings
80516
+ };
80517
+ } catch (error) {
80518
+ const reason = error instanceof AwareError ? awareStderr(error) : void 0;
80519
+ const message = error instanceof Error ? error.message : `${target.label} export failed`;
80520
+ const actionable = awareFailureMessage(error, `${target.label} export failed`);
80521
+ const needsHost = looksLikeHostUnavailable(target.host, message, reason, actionable);
80522
+ app.log.warn({ appId, project, host: target.host, error: message, reason }, "host export failed");
80523
+ return reply.status(error instanceof ReceiptReconciliationError ? 422 : 502).send({
80524
+ ok: false,
80525
+ needsHost,
80526
+ host: target.host,
80527
+ error: needsHost ? target.unavailable : actionable,
80528
+ reason
80529
+ });
80530
+ } finally {
80531
+ try {
80532
+ companion.cleanup();
80533
+ } catch (error) {
80534
+ app.log.error({ companionId: companion.id, error: error instanceof Error ? error.message : error }, "could not remove host export companion");
79828
80535
  }
79829
- const selection = parsed;
79830
- const rawPid = (req.body ?? {}).hostPid;
79831
- const hostPid = typeof rawPid === "number" && Number.isInteger(rawPid) && rawPid > 0 ? rawPid : void 0;
79832
- return withLifecycleLock(project ? "project" : "app", project || appId, async () => {
79833
- let projectSnapshot;
79834
- if (project) {
79835
- const gate = projectExportGate(appId, project);
79836
- if (gate) return reply.status(gate.status).send({ ok: false, error: gate.error });
79837
- try {
79838
- projectSnapshot = currentApprovedSnapshot(project);
79839
- } catch (error) {
79840
- if (error instanceof WorkspaceSnapshotError) return reply.status(error.status).send({ ok: false, error: error.message });
79841
- throw error;
79842
- }
79843
- }
79844
- const readiness = await hostReadiness(target.host, void 0, hostPid);
79845
- if (!readiness.ok) {
79846
- return reply.status(409).send({
79847
- ok: false,
79848
- needsHost: readiness.state === "host-closed" || readiness.state === "addin-missing",
79849
- host: target.host,
79850
- error: readiness.message,
79851
- readiness
79852
- });
79853
- }
79854
- const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, void 0);
79855
- if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to bake" });
79856
- const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
79857
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
79858
- const doc = steel.doc;
79859
- const sourceId = selection ? await dropExportSourceId(appId, project) : await stableExportSourceId(appId, project);
79860
- const scoped = selection ? contractForMemberSelection(doc, selection) : doc;
79861
- if (selection && selectionMemberCount(scoped) === 0) {
79862
- return reply.status(422).send({ ok: false, error: "those members aren\u2019t in the model any more \u2014 reload the editor and try again" });
79863
- }
79864
- const built = contractToAwareScene(scoped, sourceId);
79865
- if (!hasExportableSceneRecords(built.scene)) {
79866
- return reply.status(422).send({
79867
- ok: false,
79868
- error: selection ? `nothing to bake in that selection \u2014 every member you dragged is an RFI (no AISC size yet)` : "no resolvable members to bake \u2014 every member is an RFI (no AISC size yet)",
79869
- skipped: built.skipped
79870
- });
79871
- }
79872
- const companion = createExportCompanion(appId, target.host);
79873
- try {
79874
- const flo = target.writeApp(companion.path, companion.id, built.scene, hostPid);
79875
- stampExportCompanionLease(companion);
79876
- await aware.compile(flo);
79877
- const env2 = readiness.bakeEnv;
79878
- let runResult;
79879
- try {
79880
- runResult = await aware.run(companion.id, { env: env2 });
79881
- } catch (error) {
79882
- const recoverable = error instanceof AwareError && /timeout|timed out|lost response|connection reset/i.test(`${error.message} ${awareStderr(error) || ""}`);
79883
- if (!recoverable) throw error;
79884
- runResult = await aware.run(companion.id, { env: env2 });
79885
- }
79886
- const events = runResult.traceText ? parseTrace(runResult.traceText) : [];
79887
- const output = [...events].reverse().find((event) => event.kind === "node-output" && event.node === target.nodeId);
79888
- const envelope = output?.data && typeof output.data === "object" ? output.data : null;
79889
- const rawReceipt = envelope?.result && typeof envelope.result === "object" ? envelope.result : envelope;
79890
- const receipt = reconcileHostExportReceipt(built.scene, rawReceipt, built.producerUnsupported);
79891
- return {
79892
- ok: true,
79893
- host: target.host,
79894
- message: `${receipt.counts.emitted} emitted${receipt.counts.native != null ? ` \xB7 ${receipt.counts.native} native` : ""}${receipt.counts.unsupported ? ` \xB7 ${receipt.counts.unsupported} unsupported` : ""}${receipt.counts.warnings ? ` \xB7 ${receipt.counts.warnings} warning${receipt.counts.warnings === 1 ? "" : "s"}` : ""}`,
79895
- elements: receipt.counts.emitted,
79896
- skipped: built.skipped,
79897
- receipt,
79898
- counts: receipt.counts,
79899
- warnings: receipt.warnings
79900
- };
79901
- } catch (error) {
79902
- const reason = error instanceof AwareError ? awareStderr(error) : void 0;
79903
- const message = error instanceof Error ? error.message : `${target.label} export failed`;
79904
- const needsHost = looksLikeHostUnavailable(target.host, message, reason);
79905
- app.log.warn({ appId, project, host: target.host, error: message, reason }, "host export failed");
79906
- return reply.status(error instanceof ReceiptReconciliationError ? 422 : 502).send({
79907
- ok: false,
79908
- needsHost,
79909
- host: target.host,
79910
- error: needsHost ? target.unavailable : message,
79911
- reason
79912
- });
79913
- } finally {
79914
- try {
79915
- companion.cleanup();
79916
- } catch (error) {
79917
- app.log.error({ companionId: companion.id, error: error instanceof Error ? error.message : error }, "could not remove host export companion");
79918
- }
79919
- }
79920
- }, { label: `sending the model to ${target.label}` });
79921
80536
  }
79922
- );
80537
+ }
79923
80538
  app.post("/api/host-at-point", async (req, reply) => {
79924
80539
  const body = req.body ?? {};
79925
80540
  const x = typeof body.screenX === "number" ? body.screenX : NaN;
@@ -79936,137 +80551,97 @@ async function startServer() {
79936
80551
  const [stack, running] = await Promise.all([hostWindowRects(), runningKnownHosts()]);
79937
80552
  return { ok: true, stack, running };
79938
80553
  });
79939
- app.post("/api/contract/:appId/export-bom/:format", async (req, reply) => {
79940
- const { appId, format } = req.params;
79941
- const project = req.query.project || void 0;
79942
- const execute = async () => {
79943
- if (format !== "csv" && format !== "xlsx") {
79944
- return reply.status(400).send({ ok: false, error: `unknown format "${format}" \u2014 use csv or xlsx` });
79945
- }
79946
- if (!/^[a-z0-9][a-z0-9._-]*$/i.test(appId)) {
79947
- return reply.status(400).send({ ok: false, error: `invalid appId: ${appId}` });
79948
- }
79949
- let projectSnapshot;
79950
- if (project) {
79951
- const g = projectExportGate(appId, project);
79952
- if (g) return reply.status(g.status).send({ ok: false, error: g.error });
79953
- try {
79954
- projectSnapshot = currentApprovedSnapshot(project);
79955
- } catch (e) {
79956
- if (e instanceof WorkspaceSnapshotError) return reply.status(e.status).send({ ok: false, error: e.message });
79957
- throw e;
79958
- }
79959
- await recoverIfcPublicationsInDirectory(
79960
- projectExportsDir(project),
79961
- { kind: "project", key: project }
79962
- );
79963
- }
79964
- const candidate = projectSnapshot ? projectSnapshot.contract : readAcceptedForRequest(appId, project ?? void 0);
79965
- if (candidate == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
79966
- const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
79967
- if (!steel.accepted) return reply.status(400).send(steel.refusal);
79968
- const bom = contractToBom(steel.doc);
79969
- if (bom.rows.filter((r) => r.Profile !== "TOTAL").length === 0) {
79970
- return reply.status(422).send({ ok: false, error: "no priced members to export \u2014 every member is an RFI (no AISC size / weight yet)" });
79971
- }
79972
- const preferredFilename = `${exportFileBase(project, appId)}-bom.${format}`;
79973
- const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
79974
- const outPath = project ? (0, import_node_path46.join)(projectExportsDir(project), filename) : bomExportPath(appId, format);
79975
- const dir = (0, import_node_path46.dirname)(outPath);
79976
- try {
79977
- (0, import_node_fs50.mkdirSync)(dir, { recursive: true });
79978
- if (format === "csv") {
79979
- const text3 = bomToCsv(bom);
79980
- if (project && projectSnapshot) {
79981
- publishProjectExportArtifact(project, {
79982
- kind: "bom-csv",
79983
- filename,
79984
- encoding: "utf8",
79985
- bytes: Buffer.byteLength(text3),
79986
- version: projectSnapshot.version.n,
79987
- contractHash: projectSnapshot.contractHash
79988
- }, Buffer.from(text3, "utf8"));
79989
- } else (0, import_node_fs50.writeFileSync)(outPath, text3, "utf8");
79990
- return { ok: true, filename, encoding: "utf8", content: text3, bytes: Buffer.byteLength(text3), savedTo: outPath };
79991
- }
79992
- const buf = await bomToXlsx(bom);
79993
- if (project && projectSnapshot) {
79994
- publishProjectExportArtifact(project, {
79995
- kind: "bom-xlsx",
79996
- filename,
79997
- encoding: "base64",
79998
- bytes: buf.length,
79999
- version: projectSnapshot.version.n,
80000
- contractHash: projectSnapshot.contractHash
80001
- }, buf);
80002
- } else (0, import_node_fs50.writeFileSync)(outPath, buf);
80003
- return { ok: true, filename, encoding: "base64", content: buf.toString("base64"), bytes: buf.length, savedTo: outPath };
80004
- } catch (e) {
80005
- app.log.error({ appId, format, err: e instanceof Error ? e.message : e }, "export-bom: generation failed");
80006
- return reply.status(500).send({ ok: false, error: `BOM ${format.toUpperCase()} export failed: ${e instanceof Error ? e.message : "write error"}` });
80007
- }
80008
- };
80009
- return project ? withLifecycleLock("project", project, execute) : execute();
80010
- });
80011
- app.post("/api/contract/:appId/export-svg", async (req, reply) => {
80012
- const project = req.query.project || void 0;
80013
- const execute = async () => {
80014
- if (!/^[a-z0-9][a-z0-9._-]*$/i.test(req.params.appId)) {
80015
- return reply.status(400).send({ ok: false, error: `invalid appId: ${req.params.appId}` });
80016
- }
80017
- let projectSnapshot;
80018
- if (project) {
80019
- const g = projectExportGate(req.params.appId, project);
80020
- if (g) return reply.status(g.status).send({ ok: false, error: g.error });
80021
- try {
80022
- projectSnapshot = currentApprovedSnapshot(project);
80023
- } catch (e) {
80024
- if (e instanceof WorkspaceSnapshotError) return reply.status(e.status).send({ ok: false, error: e.message });
80025
- throw e;
80026
- }
80027
- await recoverIfcPublicationsInDirectory(
80028
- projectExportsDir(project),
80029
- { kind: "project", key: project }
80030
- );
80031
- }
80032
- let doc;
80033
- let publication = false;
80034
- if (projectSnapshot) {
80035
- doc = projectSnapshot.contract;
80036
- } else {
80037
- const resolved = resolveAppContract(req.params.appId);
80038
- doc = resolvedDoc(resolved);
80039
- publication = resolved.kind === "project-publication";
80040
- }
80041
- if (doc == null && publication) return reply.status(404).send(projectPublicationBody("to export"));
80042
- if (doc == null) return reply.status(404).send({ ok: false, error: "no contract to export" });
80043
- const v = validateContract(doc);
80044
- if (!v.valid) return reply.status(400).send({ ok: false, error: "stored contract is invalid \u2014 re-save it in the editor" });
80045
- const cleaned = postProcess(doc);
80046
- const svg = contractToSvg(cleaned);
80047
- const preferredFilename = `${exportFileBase(project, req.params.appId)}.svg`;
80048
- const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
80049
- const outPath = project ? (0, import_node_path46.join)(projectExportsDir(project), filename) : (0, import_node_path46.join)(appPath(req.params.appId), filename);
80050
- try {
80051
- (0, import_node_fs50.mkdirSync)((0, import_node_path46.dirname)(outPath), { recursive: true });
80554
+ async function continueBomExport(input, reply) {
80555
+ const { source, format } = input;
80556
+ const appId = source.appId;
80557
+ const project = source.kind === "project" ? source.project : void 0;
80558
+ const projectSnapshot = source.kind === "project" ? source.snapshot : void 0;
80559
+ if (project) {
80560
+ await recoverIfcPublicationsInDirectory(
80561
+ projectExportsDir(project),
80562
+ { kind: "project", key: project }
80563
+ );
80564
+ }
80565
+ const candidate = source.kind === "project" ? source.snapshot.contract : source.doc;
80566
+ const steel = acceptSteelForRoute(candidate, { appId, projectId: project }, "stored", "v1-or-v2");
80567
+ if (!steel.accepted) return reply.status(400).send(steel.refusal);
80568
+ const bom = contractToBom(steel.doc);
80569
+ if (bom.rows.filter((r) => r.Profile !== "TOTAL").length === 0) {
80570
+ return reply.status(422).send({ ok: false, error: "no priced members to export \u2014 every member is an RFI (no AISC size / weight yet)" });
80571
+ }
80572
+ const preferredFilename = `${exportFileBase(project, appId)}-bom.${format}`;
80573
+ const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
80574
+ const outPath = project ? (0, import_node_path46.join)(projectExportsDir(project), filename) : bomExportPath(appId, format);
80575
+ const dir = (0, import_node_path46.dirname)(outPath);
80576
+ try {
80577
+ (0, import_node_fs50.mkdirSync)(dir, { recursive: true });
80578
+ if (format === "csv") {
80579
+ const text3 = bomToCsv(bom);
80052
80580
  if (project && projectSnapshot) {
80053
80581
  publishProjectExportArtifact(project, {
80054
- kind: "svg",
80582
+ kind: "bom-csv",
80055
80583
  filename,
80056
80584
  encoding: "utf8",
80057
- bytes: Buffer.byteLength(svg),
80585
+ bytes: Buffer.byteLength(text3),
80058
80586
  version: projectSnapshot.version.n,
80059
80587
  contractHash: projectSnapshot.contractHash
80060
- }, Buffer.from(svg, "utf8"));
80061
- } else (0, import_node_fs50.writeFileSync)(outPath, svg, "utf8");
80062
- return { ok: true, filename, encoding: "utf8", content: svg, bytes: Buffer.byteLength(svg), savedTo: outPath };
80063
- } catch (e) {
80064
- app.log.error({ appId: req.params.appId, err: e instanceof Error ? e.message : e }, "export-svg: write failed");
80065
- return reply.status(500).send({ ok: false, error: `SVG export failed: ${e instanceof Error ? e.message : "write error"}` });
80066
- }
80067
- };
80068
- return project ? withLifecycleLock("project", project, execute) : execute();
80069
- });
80588
+ }, Buffer.from(text3, "utf8"));
80589
+ } else (0, import_node_fs50.writeFileSync)(outPath, text3, "utf8");
80590
+ return { ok: true, filename, encoding: "utf8", content: text3, bytes: Buffer.byteLength(text3), savedTo: outPath };
80591
+ }
80592
+ const buf = await bomToXlsx(bom);
80593
+ if (project && projectSnapshot) {
80594
+ publishProjectExportArtifact(project, {
80595
+ kind: "bom-xlsx",
80596
+ filename,
80597
+ encoding: "base64",
80598
+ bytes: buf.length,
80599
+ version: projectSnapshot.version.n,
80600
+ contractHash: projectSnapshot.contractHash
80601
+ }, buf);
80602
+ } else (0, import_node_fs50.writeFileSync)(outPath, buf);
80603
+ return { ok: true, filename, encoding: "base64", content: buf.toString("base64"), bytes: buf.length, savedTo: outPath };
80604
+ } catch (e) {
80605
+ app.log.error({ appId, format, err: e instanceof Error ? e.message : e }, "export-bom: generation failed");
80606
+ return reply.status(500).send({ ok: false, error: `BOM ${format.toUpperCase()} export failed: ${e instanceof Error ? e.message : "write error"}` });
80607
+ }
80608
+ }
80609
+ async function continueSvgExport(input, reply) {
80610
+ const appId = input.appId;
80611
+ const project = input.kind === "project" ? input.project : void 0;
80612
+ const projectSnapshot = input.kind === "project" ? input.snapshot : void 0;
80613
+ if (project) {
80614
+ await recoverIfcPublicationsInDirectory(
80615
+ projectExportsDir(project),
80616
+ { kind: "project", key: project }
80617
+ );
80618
+ }
80619
+ const doc = input.kind === "app" ? input.doc : input.snapshot.contract;
80620
+ const v = validateContract(doc);
80621
+ if (!v.valid) return reply.status(400).send({ ok: false, error: "stored contract is invalid \u2014 re-save it in the editor" });
80622
+ const cleaned = postProcess(doc);
80623
+ const svg = contractToSvg(cleaned);
80624
+ const preferredFilename = `${exportFileBase(project, appId)}.svg`;
80625
+ const filename = project ? uniqueProjectExportFilename(project, preferredFilename) : preferredFilename;
80626
+ const outPath = project ? (0, import_node_path46.join)(projectExportsDir(project), filename) : (0, import_node_path46.join)(appPath(appId), filename);
80627
+ try {
80628
+ (0, import_node_fs50.mkdirSync)((0, import_node_path46.dirname)(outPath), { recursive: true });
80629
+ if (project && projectSnapshot) {
80630
+ publishProjectExportArtifact(project, {
80631
+ kind: "svg",
80632
+ filename,
80633
+ encoding: "utf8",
80634
+ bytes: Buffer.byteLength(svg),
80635
+ version: projectSnapshot.version.n,
80636
+ contractHash: projectSnapshot.contractHash
80637
+ }, Buffer.from(svg, "utf8"));
80638
+ } else (0, import_node_fs50.writeFileSync)(outPath, svg, "utf8");
80639
+ return { ok: true, filename, encoding: "utf8", content: svg, bytes: Buffer.byteLength(svg), savedTo: outPath };
80640
+ } catch (e) {
80641
+ app.log.error({ appId, err: e instanceof Error ? e.message : e }, "export-svg: write failed");
80642
+ return reply.status(500).send({ ok: false, error: `SVG export failed: ${e instanceof Error ? e.message : "write error"}` });
80643
+ }
80644
+ }
80070
80645
  async function stopForegroundSession(id) {
80071
80646
  try {
80072
80647
  const sid = foregroundSessionId(id);