@floless/app 0.130.1 → 0.131.1

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.
@@ -54980,7 +54980,7 @@ function appVersion() {
54980
54980
  return resolveVersion({
54981
54981
  isSea: isSea2(),
54982
54982
  sqVersionXml: readSqVersionXml(),
54983
- define: true ? "0.130.1" : void 0,
54983
+ define: true ? "0.131.1" : void 0,
54984
54984
  pkgVersion: readPkgVersion()
54985
54985
  });
54986
54986
  }
@@ -54996,7 +54996,7 @@ function resolveChannel(s) {
54996
54996
  function appChannel() {
54997
54997
  return resolveChannel({
54998
54998
  isSea: isSea2(),
54999
- define: true ? "0.130.1" : void 0,
54999
+ define: true ? "0.131.1" : void 0,
55000
55000
  // argv[1] is the entry the runtime actually loaded (…/dist/floless-server.cjs), which is what
55001
55001
  // carries the npx cache prefix. Absent under the SEA exe, which never reaches the npx branch.
55002
55002
  modulePath: process.argv[1]
@@ -55413,7 +55413,6 @@ var parseInches = (raw) => {
55413
55413
  }
55414
55414
  return NaN;
55415
55415
  };
55416
- var mmPerPx = (ptPerFt) => FT_MM / (ptPerFt > 0 ? ptPerFt : 1);
55417
55416
  function parseLen(tok) {
55418
55417
  let s = String(tok == null ? "" : tok).trim();
55419
55418
  if (!s) return NaN;
@@ -55532,9 +55531,6 @@ function labelsFor(override, style, n) {
55532
55531
  const auto = autoLabels(style, n);
55533
55532
  return auto.map((a, i) => own2[i] != null ? own2[i] : a);
55534
55533
  }
55535
- function sane(g) {
55536
- return !!(g && Array.isArray(g.origin) && g.origin.length >= 2 && isFinite(g.origin[0]) && isFinite(g.origin[1]));
55537
- }
55538
55534
  var pt2 = (p) => Array.isArray(p) && p.length >= 2 && isFinite(p[0]) && isFinite(p[1]) ? [+p[0], +p[1]] : null;
55539
55535
  function gridLines(g) {
55540
55536
  const out = [], used = /* @__PURE__ */ new Set();
@@ -55550,59 +55546,6 @@ function gridLines(g) {
55550
55546
  }
55551
55547
  return out;
55552
55548
  }
55553
- function gridGeometry(g, ptPerFt, opts = {}) {
55554
- const yUp = !!opts.yUp;
55555
- const k = mmPerPx(ptPerFt);
55556
- const px = (mm) => mm / k;
55557
- const X = parseSpacings(g && g.x), Y = parseSpacings(g && g.y);
55558
- const ok = sane(g);
55559
- const ox = ok ? g.origin[0] : 0, oy = ok ? g.origin[1] : 0;
55560
- const lx = labelsFor(g && g.labels_x, "num", X.offsets.length);
55561
- const ly = labelsFor(g && g.labels_y, "alpha", Y.offsets.length);
55562
- const v = X.offsets.map((off, i) => ({ x: ox + px(off), label: lx[i] }));
55563
- const h = Y.offsets.map((off, i) => ({ y: yUp ? oy + px(off) : oy - px(off), label: ly[i] }));
55564
- const resolvedZ = parseLevels(g && g.z, g && g.labels_z);
55565
- const levelsZ = resolvedZ.err ? [] : resolvedZ.levels;
55566
- const ext = px(g && isFinite(g.ext) ? g.ext : 5 * FT_MM);
55567
- const xs = v.map((l) => l.x), ys = h.map((l) => l.y);
55568
- const lines = gridLines(g);
55569
- const lx0 = lines.length ? Math.min(...lines.flatMap((l) => [l.a[0], l.b[0]])) : ox;
55570
- const lx1 = lines.length ? Math.max(...lines.flatMap((l) => [l.a[0], l.b[0]])) : ox;
55571
- const ly0 = lines.length ? Math.min(...lines.flatMap((l) => [l.a[1], l.b[1]])) : oy;
55572
- const ly1 = lines.length ? Math.max(...lines.flatMap((l) => [l.a[1], l.b[1]])) : oy;
55573
- const geo = {
55574
- v,
55575
- h,
55576
- lines,
55577
- zs: levelsZ,
55578
- errX: X.err,
55579
- errY: Y.err,
55580
- errZ: resolvedZ.err,
55581
- warningsZ: resolvedZ.warnings,
55582
- ext,
55583
- x0: Math.min(xs.length ? Math.min(...xs) : ox, lx0) - ext,
55584
- x1: Math.max(xs.length ? Math.max(...xs) : ox, lx1) + ext,
55585
- y0: Math.min(ys.length ? Math.min(...ys) : oy, ly0) - ext,
55586
- y1: Math.max(ys.length ? Math.max(...ys) : oy, ly1) + ext
55587
- };
55588
- const axisIds = (dir) => yUp && g && Array.isArray(g.axes) ? g.axes.filter((a) => a && a.dir === dir).map((a) => a.id) : [];
55589
- const override = (dir, i, legacy) => {
55590
- if (!yUp) return g && g[legacy] && g[legacy][i] || [];
55591
- const id = axisIds(dir)[i];
55592
- return id != null && g && g.ends && g.ends[id] || [];
55593
- };
55594
- for (const [i, l] of v.entries()) {
55595
- const o = override("x", i, "ends_x");
55596
- l.lo = o[0] != null && isFinite(o[0]) ? +o[0] : geo.y0;
55597
- l.hi = o[1] != null && isFinite(o[1]) ? +o[1] : geo.y1;
55598
- }
55599
- for (const [i, l] of h.entries()) {
55600
- const o = override("y", i, "ends_y");
55601
- l.lo = o[0] != null && isFinite(o[0]) ? +o[0] : geo.x0;
55602
- l.hi = o[1] != null && isFinite(o[1]) ? +o[1] : geo.x1;
55603
- }
55604
- return geo;
55605
- }
55606
55549
 
55607
55550
  // steel-model-v2.ts
55608
55551
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -65931,58 +65874,6 @@ function planeOffset(positionH, ax, ay, bx, by, dims, rotDeg) {
65931
65874
  const signed = pos2 === "left" ? -half : half;
65932
65875
  return { dx: -(by - ay) / planLen * signed, dy: (bx - ax) / planLen * signed, signed };
65933
65876
  }
65934
- function contractWithExportScopedMemberIds(contract) {
65935
- const occurrences = /* @__PURE__ */ new Map();
65936
- (contract.plans ?? []).forEach((plan, planIndex) => {
65937
- (plan.members ?? []).forEach((member, memberIndex) => {
65938
- const id = typeof member.id === "string" ? member.id : "";
65939
- if (!id) return;
65940
- const rows2 = occurrences.get(id) ?? [];
65941
- rows2.push({ planIndex, memberIndex, scopedId: id });
65942
- occurrences.set(id, rows2);
65943
- });
65944
- });
65945
- const reserved = new Set([...occurrences.entries()].filter(([, rows2]) => rows2.length === 1).map(([id]) => id));
65946
- for (const [id, rows2] of occurrences) {
65947
- if (rows2.length === 1) continue;
65948
- const plans2 = new Set(rows2.map((row) => row.planIndex));
65949
- if (plans2.size !== rows2.length) {
65950
- throw new SceneContractError(`Member id "${id}" is duplicated within one plan and cannot be exported safely.`);
65951
- }
65952
- for (const row of rows2) {
65953
- const readable = `plan:${row.planIndex + 1}:${id}`;
65954
- let candidate = Buffer.byteLength(readable, "utf8") <= 256 ? readable : `plan:${row.planIndex + 1}:member:${row.memberIndex + 1}`;
65955
- let suffix = 2;
65956
- while (reserved.has(candidate)) candidate = `plan:${row.planIndex + 1}:member:${row.memberIndex + 1}:${suffix++}`;
65957
- reserved.add(candidate);
65958
- row.scopedId = candidate;
65959
- }
65960
- }
65961
- const resolveMemberRef = (id, jointId) => {
65962
- if (!id) return id;
65963
- const rows2 = occurrences.get(id);
65964
- if (!rows2 || rows2.length === 0) return id;
65965
- if (rows2.length > 1) {
65966
- throw new SceneContractError(
65967
- `Joint "${jointId}" references sheet-ambiguous member id "${id}"; use model-unique member ids before export.`
65968
- );
65969
- }
65970
- return rows2[0].scopedId;
65971
- };
65972
- const plans = (contract.plans ?? []).map((plan, planIndex) => ({
65973
- ...plan,
65974
- members: (plan.members ?? []).map((member, memberIndex) => {
65975
- const row = occurrences.get(member.id)?.find((item) => item.planIndex === planIndex && item.memberIndex === memberIndex);
65976
- return row ? { ...member, id: row.scopedId } : { ...member };
65977
- })
65978
- }));
65979
- const joints = (contract.joints ?? []).map((joint) => ({
65980
- ...joint,
65981
- main: resolveMemberRef(joint.main, joint.id),
65982
- secondaries: joint.secondaries?.map((id) => resolveMemberRef(id, joint.id) ?? id)
65983
- }));
65984
- return { ...contract, plans, joints };
65985
- }
65986
65877
  function foldedWeight(weights, profile) {
65987
65878
  const target = canonProfile(profile);
65988
65879
  const hit = Object.entries(weights).find(([k]) => canonProfile(k) === target);
@@ -66213,97 +66104,6 @@ function canonicalConnectionElement(part) {
66213
66104
  meta: { ...part.meta, name: part.meta.label, connectionId: part.conn, connectionKind: part.connKind }
66214
66105
  };
66215
66106
  }
66216
- function structuralGridRecords(contract) {
66217
- const referenceSystems = [];
66218
- const unsupported = [];
66219
- const logical = /* @__PURE__ */ new Map();
66220
- const equivalent = /* @__PURE__ */ new Set();
66221
- (contract.plans ?? []).forEach((plan, planIndex) => {
66222
- const grid = plan.grid;
66223
- if (!grid || grid.on === false) return;
66224
- const ptPerFt = plan.pt_per_ft && plan.pt_per_ft > 0 ? plan.pt_per_ft : 1;
66225
- const geometry = gridGeometry(grid, ptPerFt);
66226
- const where = plan.sheet || plan.title || `plan ${planIndex + 1}`;
66227
- if (geometry.errX || geometry.errY || geometry.errZ) {
66228
- throw new SceneContractError(`Grid on ${where} is invalid: ${geometry.errX || geometry.errY || geometry.errZ}`);
66229
- }
66230
- if (!geometry.v.length || !geometry.h.length) {
66231
- throw new SceneContractError(`Grid on ${where} must contain at least one X axis and one Y axis.`);
66232
- }
66233
- if (!geometry.zs.length) throw new SceneContractError(`Grid on ${where} must contain at least one elevation level.`);
66234
- if (!Array.isArray(grid.origin) || grid.origin.length < 2 || !grid.origin.every((n) => typeof n === "number" && isFinite(n))) {
66235
- throw new SceneContractError(`Grid on ${where} has an invalid origin.`);
66236
- }
66237
- const root6 = `grid:${planIndex + 1}:${String(plan.sheet || plan.title || "main").trim().replace(/\s+/g, "-")}`;
66238
- const k = mmPerPx(ptPerFt);
66239
- const [ox, oy] = grid.origin;
66240
- const toX = (x) => (x - ox) * k;
66241
- const toY = (y) => -(y - oy) * k;
66242
- const bounds = {
66243
- minX: Math.min(toX(geometry.x0), toX(geometry.x1)),
66244
- maxX: Math.max(toX(geometry.x0), toX(geometry.x1)),
66245
- minY: Math.min(toY(geometry.y0), toY(geometry.y1)),
66246
- maxY: Math.max(toY(geometry.y0), toY(geometry.y1))
66247
- };
66248
- const axes = [];
66249
- geometry.v.forEach((axis, index) => {
66250
- if (!String(axis.label || "").trim()) throw new SceneContractError(`Grid on ${where} has a blank X-axis label.`);
66251
- const start2 = Math.min(toY(axis.lo), toY(axis.hi));
66252
- const end = Math.max(toY(axis.lo), toY(axis.hi));
66253
- axes.push({
66254
- id: `${root6}:x:${index + 1}`,
66255
- direction: "x",
66256
- offsetMm: toX(axis.x),
66257
- label: String(axis.label).trim(),
66258
- ...Math.abs(start2 - bounds.minY) > 0.5 ? { startMm: start2 } : {},
66259
- ...Math.abs(end - bounds.maxY) > 0.5 ? { endMm: end } : {}
66260
- });
66261
- });
66262
- geometry.h.forEach((axis, index) => {
66263
- if (!String(axis.label || "").trim()) throw new SceneContractError(`Grid on ${where} has a blank Y-axis label.`);
66264
- const start2 = Math.min(toX(axis.lo), toX(axis.hi));
66265
- const end = Math.max(toX(axis.lo), toX(axis.hi));
66266
- axes.push({
66267
- id: `${root6}:y:${index + 1}`,
66268
- direction: "y",
66269
- offsetMm: toY(axis.y),
66270
- label: String(axis.label).trim(),
66271
- ...Math.abs(start2 - bounds.minX) > 0.5 ? { startMm: start2 } : {},
66272
- ...Math.abs(end - bounds.maxX) > 0.5 ? { endMm: end } : {}
66273
- });
66274
- });
66275
- const levels = geometry.zs.map((level, index) => {
66276
- if (!String(level.label || "").trim()) throw new SceneContractError(`Grid on ${where} has a blank elevation label.`);
66277
- return { id: `${root6}:level:${level.sourceIndex ?? index}`, elevationMm: level.mm, label: String(level.label).trim() };
66278
- });
66279
- const record3 = {
66280
- id: root6,
66281
- kind: "structural-grid",
66282
- name: String(plan.title || plan.sheet || `Grid ${planIndex + 1}`).trim(),
66283
- origin: [ox * k, -oy * k, 0],
66284
- axes,
66285
- levels,
66286
- bounds
66287
- };
66288
- const signature = JSON.stringify({ ...record3, id: "", name: "", axes: axes.map(({ id: _id, ...axis }) => axis), levels: levels.map(({ id: _id, ...level }) => level) });
66289
- const logicalKey = String(plan.sheet || plan.title || `plan-${planIndex + 1}`).trim().toLowerCase();
66290
- const prior = logical.get(logicalKey);
66291
- if (prior && prior !== signature) throw new SceneContractError(`Conflicting structural grids share the identity "${logicalKey}".`);
66292
- logical.set(logicalKey, signature);
66293
- if (!equivalent.has(signature)) {
66294
- equivalent.add(signature);
66295
- referenceSystems.push(record3);
66296
- }
66297
- geometry.lines.forEach((line) => unsupported.push({
66298
- id: `${root6}:free:${line.id}`,
66299
- kind: "grid-axis",
66300
- status: "unsupported",
66301
- code: "free-angle-grid-axis-unrepresentable",
66302
- message: `Free-angle grid line "${line.label}" cannot be represented by the AWARE v0.90.0 structural-grid contract.`
66303
- }));
66304
- });
66305
- return { referenceSystems, unsupported };
66306
- }
66307
66107
  function contractForMemberSelection(contractInput, memberIds) {
66308
66108
  const { view, issues } = readModelOrIssues(contractInput);
66309
66109
  if (!view) throw new InvalidModelV2Error(`selection export requires a valid steel.model/v2 contract: ${issues[0] ?? "unknown"}`, issues);
@@ -66382,24 +66182,6 @@ function contractToAwareScene(contractInput, sourceId) {
66382
66182
  if (!sourceId.trim()) throw new SceneContractError("A stable export sourceId is required.");
66383
66183
  if (isModelV2(contractInput)) return awareSceneFromModel(contractInput, sourceId);
66384
66184
  throw new InvalidModelV2Error("export requires a valid steel.model/v2 contract", ["$.type: expected steel.model/v2"]);
66385
- const contract = contractWithExportScopedMemberIds(contractInput ?? {});
66386
- const legacy = contractToScene(contract);
66387
- const { elements, producerUnsupported } = canonicalExportElements(legacy);
66388
- const grids = structuralGridRecords(contract);
66389
- producerUnsupported.push(...grids.unsupported);
66390
- const scene = {
66391
- meta: {
66392
- name: contract.title || "Steel Model",
66393
- units: "mm",
66394
- sourceId,
66395
- sceneHash: ""
66396
- },
66397
- elements,
66398
- operations: legacy.operations,
66399
- referenceSystems: grids.referenceSystems
66400
- };
66401
- scene.meta.sceneHash = sceneHash(scene);
66402
- return { scene, skipped: legacy.skipped, producerUnsupported, coverage: legacy.coverage };
66403
66185
  }
66404
66186
  function sceneFromModel(view) {
66405
66187
  const blocked = membersBlockingExport(view.doc);
@@ -71154,7 +70936,8 @@ function selectedPopulation(probe, filter) {
71154
70936
  function emittedFilter(filter) {
71155
70937
  const storeys = filter?.storeys?.length ? filter.storeys : void 0;
71156
70938
  const ifcTypes = filter?.ifcTypes?.length ? filter.ifcTypes : void 0;
71157
- return storeys || ifcTypes ? { ...storeys ? { storeys } : {}, ...ifcTypes ? { ifcTypes } : {} } : null;
70939
+ const ids = filter?.ids?.length ? filter.ids : void 0;
70940
+ return storeys || ifcTypes || ids ? { ...storeys ? { storeys } : {}, ...ifcTypes ? { ifcTypes } : {}, ...ids ? { ids } : {} } : null;
71158
70941
  }
71159
70942
  function assertSelectionConfirmed(selected2, filter) {
71160
70943
  const asked = emittedFilter(filter);
@@ -71165,7 +70948,7 @@ function assertSelectionConfirmed(selected2, filter) {
71165
70948
  "reference-filter-unconfirmed"
71166
70949
  );
71167
70950
  }
71168
- for (const axis of ["storeys", "ifcTypes"]) {
70951
+ for (const axis of ["storeys", "ifcTypes", "ids"]) {
71169
70952
  if (asked[axis]?.length && !selected2[axis]?.length) {
71170
70953
  throw new ReferenceImportError(
71171
70954
  "the reader confirmed only part of what you chose, so FloLess stopped rather than show you more of the model than you asked for.",
@@ -71436,6 +71219,7 @@ function readerInvocation(command, ifcPath, filter, progressive = false) {
71436
71219
  const emit = emittedFilter(filter);
71437
71220
  if (emit?.storeys) config.storeys = emit.storeys;
71438
71221
  if (emit?.ifcTypes) config["ifc-types"] = emit.ifcTypes;
71222
+ if (emit?.ids) config.ids = emit.ids;
71439
71223
  if (progressive && wantsSegments(command, filter)) config["batch-size"] = PREVIEW_BATCH_SIZE;
71440
71224
  }
71441
71225
  return { command, description: READER_DESCRIPTION[command], config };
@@ -71948,6 +71732,9 @@ function sidesDiffer(base, revised) {
71948
71732
  }
71949
71733
  var statedBaseSide = (opts) => Object.hasOwn(opts, "baseFilter");
71950
71734
  function compareInvocation(basePath, revisedPath, opts = {}) {
71735
+ for (const [which, f] of [["filter", opts.filter], ["baseFilter", opts.baseFilter]]) {
71736
+ if (f?.ids?.length) throw new ReferenceImportError(`compare does not select by object id \u2014 ${which}.ids cannot be honoured`);
71737
+ }
71951
71738
  const config = {
71952
71739
  "base-ifc-path": basePath,
71953
71740
  "revised-ifc-path": revisedPath
@@ -72047,6 +71834,27 @@ function appendVersion(e, version, opts = {}) {
72047
71834
  const next = [...versions, version];
72048
71835
  return withMirror(base, version, next);
72049
71836
  }
71837
+ function rollbackTo(e, versionId, opts = {}) {
71838
+ const versions = chain(e);
71839
+ const target = versions.find((v) => v.id === versionId);
71840
+ if (!target) throw new Error(`version '${versionId}' is not one of this reference's versions`);
71841
+ if (currentVersionId(e) === versionId) return e;
71842
+ const id = opts.mintId?.() ?? cryptoId();
71843
+ refuseCollision(versions, id);
71844
+ const restored = {
71845
+ id,
71846
+ file: target.file,
71847
+ name: target.name,
71848
+ // THE CALLER MAY SUPPLY THE HASH OF THE BYTES IT ACTUALLY READ, and the route does. Copying
71849
+ // `target.sha256` unconditionally records a value that is knowably false whenever the file behind a
71850
+ // version has drifted on disk — and it propagates, because every later rollback to the restored row
71851
+ // copies it again. Absent, the old behaviour stands, which is what the pure-function tests pin.
71852
+ sha256: opts.sha256 ?? target.sha256,
71853
+ importedAt: opts.at ?? target.importedAt,
71854
+ ...target.filter === void 0 ? {} : { filter: target.filter }
71855
+ };
71856
+ return withMirror(e, restored, [...versions, restored]);
71857
+ }
72050
71858
  var newVersionId = () => `v-${globalThis.crypto.randomUUID()}`;
72051
71859
  var cryptoId = newVersionId;
72052
71860
 
@@ -72072,6 +71880,7 @@ function watchDisconnect(reply, onGone) {
72072
71880
  // reference-routes.ts
72073
71881
  var APPID = /^[a-z0-9][a-z0-9._-]*$/i;
72074
71882
  var REFERENCE_BODY_LIMIT = 210 * 1024 * 1024;
71883
+ var GHOST_ID_CAP = 200;
72075
71884
  function runScope(deps, reply, opts = {}) {
72076
71885
  let current = null;
72077
71886
  const signal = opts.detachOnDisconnect ? { gone: () => false, finish: () => {
@@ -72180,29 +71989,29 @@ var PreconditionError = class extends Error {
72180
71989
  status;
72181
71990
  body;
72182
71991
  };
72183
- function precondition(entry2, body, expect) {
71992
+ function precondition(entry2, body, expect, act = { verb: "load a new version of it", noun: "a new version" }) {
72184
71993
  const refuse = (status, error, code, extra = {}) => ({ status, body: { ok: false, error, code, ...extra } });
72185
71994
  if (entry2.display?.locked) {
72186
- return refuse(409, `"${entry2.name}" is locked \u2014 unlock it in the Reference models panel to load a new version of it`, "reference-locked");
71995
+ return refuse(409, `"${entry2.name}" is locked \u2014 unlock it in the Reference models panel to ${act.verb}`, "reference-locked");
72187
71996
  }
72188
71997
  if (!mirrorIsIntact(entry2)) {
72189
- return refuse(409, `"${entry2.name}" records a version history that disagrees with the file it currently points at, so a new version cannot safely be added to it`, "reference-mirror-diverged");
71998
+ return refuse(409, `"${entry2.name}" records a version history that disagrees with the file it currently points at, so ${act.noun} cannot safely be applied to it`, "reference-mirror-diverged");
72190
71999
  }
72191
72000
  if (!versionIdsAreUnique(entry2)) {
72192
- return refuse(409, `"${entry2.name}" records two versions under the same id, so a new version cannot safely be added to it`, "reference-versions-ambiguous");
72001
+ return refuse(409, `"${entry2.name}" records two versions under the same id, so ${act.noun} cannot safely be applied to it`, "reference-versions-ambiguous");
72193
72002
  }
72194
72003
  if (!("expectedVersionId" in body)) {
72195
- return refuse(400, "a new version must say which version it believes is current", "reference-version-expected-missing");
72004
+ return refuse(400, `${act.noun} must say which version it believes is current`, "reference-version-expected-missing");
72196
72005
  }
72197
72006
  const expected = body.expectedVersionId ?? null;
72198
72007
  if (expected !== null && typeof expected !== "string") {
72199
- return refuse(400, "a new version must say which version it believes is current", "reference-version-expected-missing");
72008
+ return refuse(400, `${act.noun} must say which version it believes is current`, "reference-version-expected-missing");
72200
72009
  }
72201
72010
  const actual = currentVersionId(entry2);
72202
72011
  if (expected !== actual) {
72203
72012
  return refuse(
72204
72013
  409,
72205
- actual === null ? `"${entry2.name}" has no version history yet, but this upload expected one \u2014 reload the project and try again` : `"${entry2.name}" moved on to another version while this one was being prepared \u2014 reload the project and try again`,
72014
+ actual === null ? `"${entry2.name}" has no version history yet, but ${act.noun} expected one \u2014 reload the project and try again` : `"${entry2.name}" moved on to another version while this was being prepared \u2014 reload the project and try again`,
72206
72015
  "reference-version-stale",
72207
72016
  { currentVersionId: actual }
72208
72017
  );
@@ -72217,6 +72026,7 @@ function precondition(entry2, body, expect) {
72217
72026
  }
72218
72027
  return null;
72219
72028
  }
72029
+ var ROLLBACK_ACT = { verb: "roll it back", noun: "a rollback" };
72220
72030
  function sameEmittedFilter(a, b) {
72221
72031
  const key = (f) => {
72222
72032
  const e = emittedFilter(f);
@@ -72806,6 +72616,342 @@ function registerReferenceRoutes(app, deps) {
72806
72616
  }
72807
72617
  }
72808
72618
  );
72619
+ app.post(
72620
+ "/api/steel/:appId/reference/:id/rollback",
72621
+ async (req, reply) => {
72622
+ const scope = runScope(deps, reply, { detachOnDisconnect: true });
72623
+ const g = gate2(deps, req.params.appId, req.query.project);
72624
+ if (!g.ok) return reply.status(g.refusal.status).send(g.refusal.body);
72625
+ const entry2 = referencesOf(g.doc).find((r) => r.id === req.params.id);
72626
+ if (!entry2) return reply.status(404).send({ ok: false, error: "no such reference model" });
72627
+ const pre = precondition(entry2, req.body ?? {}, void 0, ROLLBACK_ACT);
72628
+ if (pre) return reply.status(pre.status).send(pre.body);
72629
+ const versionId = req.body?.versionId;
72630
+ if (typeof versionId !== "string" || !versionId.trim()) {
72631
+ return reply.status(400).send({
72632
+ ok: false,
72633
+ code: "reference-rollback-version-missing",
72634
+ error: "say which version to go back to"
72635
+ });
72636
+ }
72637
+ const target = (entry2.versions ?? []).find((v) => v.id === versionId);
72638
+ if (!target) {
72639
+ return reply.status(409).send({
72640
+ ok: false,
72641
+ code: "reference-rollback-version-unknown",
72642
+ error: `"${entry2.name}" has no version by that name any more \u2014 reopen its history and try again`
72643
+ });
72644
+ }
72645
+ if (currentVersionId(entry2) === versionId) {
72646
+ scope.finish();
72647
+ return { ok: true, unchanged: true, reference: entry2, versions: entry2.versions ?? [], rolledBackTo: versionId };
72648
+ }
72649
+ if (target.filter && !emittedFilter(target.filter)) {
72650
+ return reply.status(409).send({
72651
+ ok: false,
72652
+ code: "reference-filter-unreadable",
72653
+ error: `Version "${target.name}" of "${entry2.name}" records which part of the file to load, but not in a form FloLess can read, so it cannot be restored.`
72654
+ });
72655
+ }
72656
+ const filter = target.filter;
72657
+ let abs;
72658
+ try {
72659
+ abs = originalPath(g.project, target.file);
72660
+ } catch (e) {
72661
+ const r = importRefusal(e);
72662
+ if (r) return reply.status(r.status).send(r.body);
72663
+ throw e;
72664
+ }
72665
+ if (!abs) {
72666
+ return reply.status(409).send({
72667
+ ok: false,
72668
+ code: "reference-rollback-file-missing",
72669
+ error: `The file behind version "${target.name}" is no longer in this project, so "${entry2.name}" cannot be rolled back to it.`
72670
+ });
72671
+ }
72672
+ try {
72673
+ const sourceHash = await hashFile(abs);
72674
+ const shaUnknown = target.sha256 === "0".repeat(64);
72675
+ const fileChanged = !shaUnknown && target.sha256 !== sourceHash;
72676
+ if (fileChanged) {
72677
+ app.log.warn(
72678
+ { project: g.project, id: entry2.id, versionId, recorded: target.sha256, actual: sourceHash },
72679
+ "the file behind a reference version no longer hashes to what the chain recorded"
72680
+ );
72681
+ }
72682
+ const geometry = await deps.reader.readModel(companion(g.appId), abs, { ticket: scope.ticket(), ...filter ? { filter } : {} });
72683
+ if (scope.gone()) throw new ReferenceImportError("cancelled");
72684
+ if (!geometry.objects.length && hasUnmatched(geometry.selected)) {
72685
+ return reply.status(409).send({
72686
+ ok: false,
72687
+ code: "reference-filter-unmatched",
72688
+ error: unmatchedMessage(entry2.name, unmatchedNames(geometry.selected), "remove the reference and add it again to pick from the current list.")
72689
+ });
72690
+ }
72691
+ if (!geometry.objects.length) {
72692
+ return reply.status(409).send({
72693
+ ok: false,
72694
+ code: "reference-empty",
72695
+ error: `Version "${target.name}" of "${entry2.name}" was re-read, but produced nothing we can draw` + (geometry.dropped ? ` (${geometry.dropped} object${geometry.dropped === 1 ? "" : "s"} had no usable mesh)` : "") + ", so it has not been restored."
72696
+ });
72697
+ }
72698
+ if (objectVerdict(geometry.objects.length) === "refuse") {
72699
+ return reply.status(409).send({
72700
+ ok: false,
72701
+ code: "reference-too-many-objects",
72702
+ error: `Version "${target.name}" now reads ${geometry.objects.length.toLocaleString("en-US")} objects, and the limit is ${MAX_OBJECTS.toLocaleString("en-US")}. The file behind it has grown since it was loaded.`
72703
+ });
72704
+ }
72705
+ writeCache2(g.project, entry2.id, { v: REFERENCE_CACHE_VERSION, sourceHash, dropped: geometry.dropped, colorsAvailable: geometry.colorsAvailable, colorsDropped: geometry.colorsDropped, propertySetsAvailable: geometry.propertySetsAvailable, ...filter ? { filter } : {}, objects: geometry.objects });
72706
+ let next;
72707
+ let restored;
72708
+ const etag = await withLifecycleLock("project", g.project, async () => {
72709
+ if (scope.gone()) throw new ReferenceImportError("cancelled");
72710
+ const current = readAcceptedForRequest(g.appId, g.project);
72711
+ if (current == null) throw new ReferenceImportError("this project has no model to roll a reference back in");
72712
+ const now = referencesOf(current).find((r) => r.id === entry2.id);
72713
+ if (!now) throw new ReferenceImportError(`"${entry2.name}" was removed while it was being rolled back`);
72714
+ const late = precondition(now, req.body ?? {}, { file: entry2.file, filter: entry2.filter }, ROLLBACK_ACT);
72715
+ if (late) throw new PreconditionError(late.status, late.body);
72716
+ const lateTarget = (now.versions ?? []).find((v) => v.id === versionId);
72717
+ if (!lateTarget) {
72718
+ throw new PreconditionError(409, {
72719
+ ok: false,
72720
+ code: "reference-rollback-version-unknown",
72721
+ error: `"${entry2.name}" has no version by that name any more \u2014 reopen its history and try again`
72722
+ });
72723
+ }
72724
+ if (lateTarget.file !== target.file || !sameEmittedFilter(lateTarget.filter, target.filter) || lateTarget.sha256 !== target.sha256) {
72725
+ throw new PreconditionError(409, {
72726
+ ok: false,
72727
+ code: "reference-rollback-version-changed",
72728
+ error: `Version "${target.name}" of "${entry2.name}" was rewritten while it was being restored, so what FloLess just read is no longer what that version says it is \u2014 reopen its history and try again.`
72729
+ });
72730
+ }
72731
+ next = rollbackTo(now, versionId, { at: (/* @__PURE__ */ new Date()).toISOString(), sha256: sourceHash });
72732
+ restored = next.versions[next.versions.length - 1];
72733
+ const written = await writeContractChecked(g.appId, {
72734
+ ...current,
72735
+ reference_models: referencesOf(current).map((r) => r.id === entry2.id ? next : r)
72736
+ }, g.project, {
72737
+ origin: "internal",
72738
+ why: "rolling a reference back rewrites one entry by id under a precondition the route re-checks inside this lock"
72739
+ });
72740
+ return written.etag;
72741
+ });
72742
+ deps.broadcast(contractChangedEvent(g.appId, g.project, etag, req.headers["x-floless-mutation-id"]));
72743
+ return {
72744
+ ok: true,
72745
+ etag,
72746
+ reference: next,
72747
+ version: restored,
72748
+ versions: next.versions,
72749
+ rolledBackTo: versionId,
72750
+ // SAID, not just logged. Whatever is now on screen is not the bytes this version was recorded
72751
+ // under, and the panel would otherwise assert "back on version 2" about a file the server has
72752
+ // already proved is not version 2's.
72753
+ ...fileChanged ? { fileChanged: true } : {},
72754
+ objects: geometry.objects,
72755
+ dropped: geometry.dropped,
72756
+ colorsAvailable: geometry.colorsAvailable,
72757
+ colorsDropped: geometry.colorsDropped,
72758
+ propertySetsAvailable: geometry.propertySetsAvailable,
72759
+ spanMm: spanOf(geometry.objects),
72760
+ ...hasUnmatched(geometry.selected) ? { unmatched: unmatchedNames(geometry.selected) } : {}
72761
+ };
72762
+ } catch (e) {
72763
+ if (e instanceof PreconditionError) return reply.status(e.status).send(e.body);
72764
+ const r = importRefusal(e);
72765
+ if (r) return reply.status(r.status).send(r.body);
72766
+ if (e instanceof ContractError) {
72767
+ return reply.status(400).send({ ok: false, error: e.message, ...e.code ? { code: e.code } : {} });
72768
+ }
72769
+ app.log.error({ appId: g.appId, id: entry2.id, versionId, expectedVersionId: req.body?.expectedVersionId, err: e }, "reference rollback failed");
72770
+ return reply.status(500).send({ ok: false, error: `could not roll "${entry2.name}" back to that version` });
72771
+ } finally {
72772
+ scope.finish();
72773
+ }
72774
+ }
72775
+ );
72776
+ app.post(
72777
+ "/api/steel/:appId/reference/:id/compare",
72778
+ async (req, reply) => {
72779
+ const scope = runScope(deps, reply);
72780
+ const g = gate2(deps, req.params.appId, req.query.project);
72781
+ if (!g.ok) return reply.status(g.refusal.status).send(g.refusal.body);
72782
+ const entry2 = referencesOf(g.doc).find((r) => r.id === req.params.id);
72783
+ if (!entry2) return reply.status(404).send({ ok: false, error: "no such reference model" });
72784
+ if (!versionIdsAreUnique(entry2)) {
72785
+ return reply.status(409).send({
72786
+ ok: false,
72787
+ code: "reference-versions-ambiguous",
72788
+ error: `"${entry2.name}" records two versions under the same id, so FloLess cannot tell which two you asked to compare`
72789
+ });
72790
+ }
72791
+ const pick = (id) => typeof id === "string" && id ? (entry2.versions ?? []).find((v) => v.id === id) : void 0;
72792
+ const base = pick(req.body?.baseVersionId);
72793
+ const revised = pick(req.body?.revisedVersionId);
72794
+ const unknownSide = !base ? "earlier" : !revised ? "later" : null;
72795
+ if (unknownSide) {
72796
+ return reply.status(409).send({
72797
+ ok: false,
72798
+ code: "reference-compare-version-unknown",
72799
+ error: `"${entry2.name}" has no ${unknownSide} version by that name any more \u2014 reopen its history and try again`
72800
+ });
72801
+ }
72802
+ for (const side2 of [base, revised]) {
72803
+ if (side2.filter && !emittedFilter(side2.filter)) {
72804
+ return reply.status(409).send({
72805
+ ok: false,
72806
+ code: "reference-filter-unreadable",
72807
+ error: `Version "${side2.name}" of "${entry2.name}" records which part of the file to load, but not in a form FloLess can read, so it cannot be compared.`
72808
+ });
72809
+ }
72810
+ }
72811
+ if (base.id === revised.id) {
72812
+ return reply.status(400).send({
72813
+ ok: false,
72814
+ code: "reference-compare-same-version",
72815
+ error: "choose two different versions to compare"
72816
+ });
72817
+ }
72818
+ try {
72819
+ const basePath = originalPath(g.project, base.file);
72820
+ const revisedPath = originalPath(g.project, revised.file);
72821
+ const goneSide = !basePath ? base : !revisedPath ? revised : null;
72822
+ if (goneSide) {
72823
+ return reply.status(409).send({
72824
+ ok: false,
72825
+ code: "reference-compare-file-missing",
72826
+ error: `The file behind version "${goneSide.name}" is no longer in this project, so there is nothing to compare it with.`
72827
+ });
72828
+ }
72829
+ let comparison;
72830
+ try {
72831
+ comparison = await deps.reader.compare(companion(g.appId), basePath, revisedPath, {
72832
+ ticket: scope.ticket(),
72833
+ // EACH SIDE UNDER THE FILTER IT WAS ACTUALLY READ WITH. Applying one side's filter to the
72834
+ // other asks a file for a storey it may never have had, resolves nothing, and reports every
72835
+ // object on the far side as added — the version route records the same reasoning.
72836
+ ...revised.filter ? { filter: revised.filter } : {},
72837
+ baseFilter: base.filter
72838
+ });
72839
+ } catch (e) {
72840
+ if (e instanceof CompareRefusedError) {
72841
+ return reply.status(409).send({
72842
+ ok: false,
72843
+ code: "reference-compare-refused",
72844
+ error: e.reason,
72845
+ refused: {
72846
+ reason: e.reason,
72847
+ baseObjects: e.baseObjects,
72848
+ revisedObjects: e.revisedObjects,
72849
+ skipped: e.skipped,
72850
+ uncomparable: e.uncomparable,
72851
+ baseName: base.name,
72852
+ revisedName: revised.name
72853
+ }
72854
+ });
72855
+ }
72856
+ throw e;
72857
+ }
72858
+ return {
72859
+ ok: true,
72860
+ comparison,
72861
+ base: { id: base.id, name: base.name, importedAt: base.importedAt },
72862
+ revised: { id: revised.id, name: revised.name, importedAt: revised.importedAt }
72863
+ };
72864
+ } catch (e) {
72865
+ const r = importRefusal(e);
72866
+ if (r) return reply.status(r.status).send(r.body);
72867
+ let goneNow = null;
72868
+ try {
72869
+ goneNow = !originalPath(g.project, base.file) ? base : !originalPath(g.project, revised.file) ? revised : null;
72870
+ } catch (probe) {
72871
+ app.log.error({ appId: g.appId, id: entry2.id, err: probe }, "could not re-check a reference version\u2019s original after a failed comparison");
72872
+ }
72873
+ if (goneNow) {
72874
+ return reply.status(409).send({
72875
+ ok: false,
72876
+ code: "reference-compare-file-missing",
72877
+ error: `The file behind version "${goneNow.name}" was removed while the two versions were being compared, so there is nothing to compare it with.`
72878
+ });
72879
+ }
72880
+ app.log.error({ appId: g.appId, id: entry2.id, base: base.id, revised: revised.id, err: e }, "reference version compare failed");
72881
+ return reply.status(500).send({ ok: false, code: "reference-compare-failed", error: `could not compare those two versions of "${entry2.name}"` });
72882
+ } finally {
72883
+ scope.finish();
72884
+ }
72885
+ }
72886
+ );
72887
+ app.post(
72888
+ "/api/steel/:appId/reference/:id/ghosts",
72889
+ async (req, reply) => {
72890
+ const scope = runScope(deps, reply);
72891
+ const g = gate2(deps, req.params.appId, req.query.project);
72892
+ if (!g.ok) return reply.status(g.refusal.status).send(g.refusal.body);
72893
+ const entry2 = referencesOf(g.doc).find((r) => r.id === req.params.id);
72894
+ if (!entry2) return reply.status(404).send({ ok: false, error: "no such reference model" });
72895
+ if (!versionIdsAreUnique(entry2)) {
72896
+ return reply.status(409).send({
72897
+ ok: false,
72898
+ code: "reference-versions-ambiguous",
72899
+ error: `"${entry2.name}" records two versions under the same id, so the objects that were removed cannot be drawn where they used to be`
72900
+ });
72901
+ }
72902
+ const versionId = req.body?.versionId;
72903
+ const version = typeof versionId === "string" && versionId ? (entry2.versions ?? []).find((v) => v.id === versionId) : void 0;
72904
+ if (!version) {
72905
+ return reply.status(409).send({
72906
+ ok: false,
72907
+ code: "reference-ghost-version-unknown",
72908
+ error: `"${entry2.name}" has no version by that name any more, so the objects that were removed cannot be drawn where they used to be`
72909
+ });
72910
+ }
72911
+ const asked = Array.isArray(req.body?.ids) ? req.body.ids : [];
72912
+ const ids = [...new Set(asked.filter((s) => typeof s === "string" && !!s.trim()))];
72913
+ if (!ids.length) {
72914
+ return reply.status(400).send({ ok: false, code: "reference-ghost-ids-missing", error: "say which objects to draw" });
72915
+ }
72916
+ if (ids.length > GHOST_ID_CAP) {
72917
+ return reply.status(400).send({
72918
+ ok: false,
72919
+ code: "reference-ghost-too-many",
72920
+ error: `FloLess draws at most ${GHOST_ID_CAP} removed objects at a time, and this asked for ${ids.length.toLocaleString("en-US")}`,
72921
+ cap: GHOST_ID_CAP
72922
+ });
72923
+ }
72924
+ try {
72925
+ const abs = originalPath(g.project, version.file);
72926
+ if (!abs) {
72927
+ return reply.status(409).send({
72928
+ ok: false,
72929
+ code: "reference-ghost-file-missing",
72930
+ error: `The file behind version "${version.name}" is no longer in this project, so the objects that were removed cannot be drawn where they used to be. The change list below is unaffected.`
72931
+ });
72932
+ }
72933
+ const geometry = await deps.reader.readModel(companion(g.appId), abs, { ticket: scope.ticket(), filter: { ids } });
72934
+ const unmatched = geometry.selected?.unmatched ?? [];
72935
+ const missing = unmatched.map((u) => typeof u.id === "string" ? u.id : null).filter((s) => !!s);
72936
+ const unresolved = hasUnmatched(geometry.selected ?? null) ? unmatched.length : 0;
72937
+ return {
72938
+ ok: true,
72939
+ versionId: version.id,
72940
+ objects: geometry.objects,
72941
+ dropped: geometry.dropped,
72942
+ ...missing.length ? { missing } : {},
72943
+ ...unresolved ? { unresolved } : {}
72944
+ };
72945
+ } catch (e) {
72946
+ const r = importRefusal(e);
72947
+ if (r) return reply.status(r.status).send(r.body);
72948
+ app.log.error({ appId: g.appId, id: entry2.id, versionId: version.id, ids: ids.length, err: e }, "reference ghost read failed");
72949
+ return reply.status(500).send({ ok: false, code: "reference-ghost-failed", error: `could not read the removed objects of "${entry2.name}"` });
72950
+ } finally {
72951
+ scope.finish();
72952
+ }
72953
+ }
72954
+ );
72809
72955
  app.delete(
72810
72956
  "/api/steel/:appId/reference/:id",
72811
72957
  async (req, reply) => {