farseer-cli 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +328 -0
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/index.js +16 -0
  5. package/dist/index.js.map +2 -2
  6. package/dist/pipeline/service.js +1 -1
  7. package/dist/pipeline/service.js.map +2 -2
  8. package/dist/services/codefirst/api.js +269 -0
  9. package/dist/services/codefirst/api.js.map +7 -0
  10. package/dist/services/codefirst/binaryDisk.js +67 -0
  11. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  12. package/dist/services/codefirst/byteHashes.js +129 -0
  13. package/dist/services/codefirst/byteHashes.js.map +7 -0
  14. package/dist/services/codefirst/documents.js +563 -0
  15. package/dist/services/codefirst/documents.js.map +7 -0
  16. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  17. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  18. package/dist/services/codefirst/layoutCompose.js +593 -0
  19. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  20. package/dist/services/codefirst/layoutCore.js +260 -0
  21. package/dist/services/codefirst/layoutCore.js.map +7 -0
  22. package/dist/services/codefirst/layoutPaths.js +492 -0
  23. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  24. package/dist/services/codefirst/layoutProjection.js +995 -0
  25. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  26. package/dist/services/codefirst/layoutReadback.js +2552 -0
  27. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  28. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  29. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  30. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  31. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  32. package/dist/services/codefirst/layoutScan.js +882 -0
  33. package/dist/services/codefirst/layoutScan.js.map +7 -0
  34. package/dist/services/codefirst/output.js +179 -0
  35. package/dist/services/codefirst/output.js.map +7 -0
  36. package/dist/services/codefirst/types.js +17 -0
  37. package/dist/services/codefirst/types.js.map +7 -0
  38. package/dist/services/codefirst/workflow.js +581 -0
  39. package/dist/services/codefirst/workflow.js.map +7 -0
  40. package/dist/services/codefirst/workspace.js +310 -0
  41. package/dist/services/codefirst/workspace.js.map +7 -0
  42. package/dist/services/codefirst/workspaceLock.js +148 -0
  43. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  44. package/dist/services/codefirst/workspaceRoot.js +147 -0
  45. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  46. package/dist/utils/logger.js +9 -3
  47. package/dist/utils/logger.js.map +2 -2
  48. package/package.json +3 -2
@@ -0,0 +1,974 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var layoutBinaryProjection_exports = {};
20
+ __export(layoutBinaryProjection_exports, {
21
+ composeBinaryLayout: () => composeBinaryLayout,
22
+ decomposeBinaryLayout: () => decomposeBinaryLayout
23
+ });
24
+ module.exports = __toCommonJS(layoutBinaryProjection_exports);
25
+ var import_layoutPaths = require("./layoutPaths");
26
+ var import_layoutCore = require("./layoutCore");
27
+ const RAW_NORMAL_FIELDS = /* @__PURE__ */ new Set(["kind", "id", "key", "order", "type", "category", "name", "shares"]);
28
+ const RAW_DETACHED_FIELDS = /* @__PURE__ */ new Set([...RAW_NORMAL_FIELDS, "folder"]);
29
+ const BINARY_TOKEN_NAMESPACE = "binary-submission";
30
+ function rawIdentity(source) {
31
+ if (source.type === "transient") return { transient: source.token };
32
+ if (source.type !== "resource") throw new Error("A raw file requires a resource or transient source");
33
+ return "id" in source.resource ? { id: source.resource.id } : { key: source.resource.key };
34
+ }
35
+ function selectorKey(selector) {
36
+ return selector.sidecar;
37
+ }
38
+ function proofEvidence(entryHash, byteHash) {
39
+ return typeof entryHash === "string" && entryHash.length > 0 && typeof byteHash === "string" && byteHash.length > 0 ? (0, import_layoutCore.canonicalFragmentHash)({ entryHash, byteHash }) : void 0;
40
+ }
41
+ function selectorLocation(left, right) {
42
+ if (left.slot !== right.slot) return false;
43
+ if (left.slot === "file-entry" && right.slot === "file-entry") return left.sidecar === right.sidecar;
44
+ return left.slot === "owner-attachment" && right.slot === "owner-attachment" && left.field === right.field && left.ownerFile === right.ownerFile;
45
+ }
46
+ function observationState(currentHash, prior) {
47
+ if (!prior) return "new";
48
+ return prior.priorCleanHash === currentHash ? "clean" : "dirty";
49
+ }
50
+ function provesRepresentationFallback(proof, candidate) {
51
+ const source = candidate.source;
52
+ const direct = proof.request !== void 0 || proof.existingClaims !== void 0;
53
+ const inherited = proof.inheritedFrom !== void 0;
54
+ if (source?.type !== "resource" || proof.sourceKey !== (0, import_layoutCore.sourceIdentityKey)(source) || direct === inherited)
55
+ return false;
56
+ if (inherited) {
57
+ if (typeof candidate.name !== "string" || candidate.name.length === 0 || !Array.isArray(candidate.folder) || candidate.folder.length === 0 || candidate.folder.some((part) => typeof part !== "string" || part.length === 0))
58
+ return false;
59
+ try {
60
+ (0, import_layoutPaths.encodeLayoutSegment)(candidate.name);
61
+ for (const part of candidate.folder) (0, import_layoutPaths.encodeLayoutSegment)(part);
62
+ } catch {
63
+ return false;
64
+ }
65
+ return proof.request === void 0 && proof.existingClaims === void 0 && proof.inheritedFrom.sourceKey.length > 0 && proof.inheritedFrom.sourceKey !== proof.sourceKey && import_layoutCore.SHA256.test(proof.inheritedFrom.semanticPathHash) && proof.inheritedFrom.semanticPathHash === (0, import_layoutCore.canonicalFragmentHash)(candidate.folder);
66
+ }
67
+ const request = proof.request;
68
+ const existingClaims = proof.existingClaims;
69
+ if (!request || !existingClaims || request.role !== "raw" || request.kind !== void 0 && request.kind !== "file" || request.extension !== void 0 && request.extension !== "" || request.requiredChildren !== void 0 || !(request.directory === "tree" || request.directory.startsWith("tree/")) || request.name !== candidate.name || request.identity !== ("id" in source.resource ? source.resource.id : source.resource.key))
70
+ return false;
71
+ return (0, import_layoutPaths.provesUnrepresentableRequest)(request, existingClaims);
72
+ }
73
+ function currentObservationHash(observations, source, selector) {
74
+ return (observations.get((0, import_layoutCore.sourceIdentityKey)(source)) ?? []).find(
75
+ (observation) => selectorLocation(observation.selector, selector)
76
+ )?.currentHash;
77
+ }
78
+ function composeBinaryLayout(input) {
79
+ const priorRoutes = input.priorRoutes ?? [];
80
+ const submissionProofs = input.submissionProofs ?? [];
81
+ const rawDocuments = [];
82
+ const rawSources = [];
83
+ const rawObservations = [];
84
+ const ownerFields = [];
85
+ const attachmentObservations = [];
86
+ const navigation = [];
87
+ const submissions = [];
88
+ const diagnostics = [];
89
+ const diagnostic = (code, path, message, sourcePath, relatedPath) => diagnostics.push({
90
+ code,
91
+ path,
92
+ message,
93
+ ...sourcePath ? { sourcePath } : {},
94
+ ...relatedPath ? { relatedPath } : {}
95
+ });
96
+ const authoritativeBaselines = /* @__PURE__ */ new Map();
97
+ for (const baseline of input.authoritativeBaselines ?? []) {
98
+ const key = (0, import_layoutCore.sourceIdentityKey)(baseline.source);
99
+ if (authoritativeBaselines.has(key) || baseline.canonicalHash.length === 0) {
100
+ diagnostic("invalid-authoritative-baseline", key, "Authoritative binary baseline is invalid or duplicated");
101
+ continue;
102
+ }
103
+ authoritativeBaselines.set(key, baseline.canonicalHash);
104
+ }
105
+ const facts = /* @__PURE__ */ new Map();
106
+ for (const fact of input.bytes) {
107
+ if (facts.has(fact.path)) throw new Error(`More than one byte fact describes ${JSON.stringify(fact.path)}`);
108
+ (0, import_layoutPaths.parseWorkspacePointer)(fact.path);
109
+ facts.set(fact.path, fact);
110
+ }
111
+ const rawPathClaims = /* @__PURE__ */ new Map();
112
+ for (const raw of input.rawFiles) rawPathClaims.set(raw.bytes, [...rawPathClaims.get(raw.bytes) ?? [], raw]);
113
+ const attachmentPathClaims = /* @__PURE__ */ new Map();
114
+ for (const attachment of input.attachments) {
115
+ const value = attachment.ownerDocument[attachment.field];
116
+ const pointer = (0, import_layoutCore.attachmentPointer)(value);
117
+ if (pointer !== void 0 && pointer !== null)
118
+ attachmentPathClaims.set(pointer, [...attachmentPathClaims.get(pointer) ?? [], attachment]);
119
+ }
120
+ const conflictingPaths = /* @__PURE__ */ new Set();
121
+ for (const [path, claims] of rawPathClaims) {
122
+ if (claims.length > 1 || attachmentPathClaims.has(path)) {
123
+ conflictingPaths.add(path);
124
+ diagnostic("conflicting-byte-claim", path, "More than one managed component claims this byte path");
125
+ }
126
+ }
127
+ for (const [path, claims] of attachmentPathClaims) {
128
+ if (claims.length > 1 && !conflictingPaths.has(path)) {
129
+ conflictingPaths.add(path);
130
+ diagnostic("conflicting-byte-claim", path, "More than one attachment claims this byte path");
131
+ }
132
+ }
133
+ const candidates = input.rawFiles.map((raw) => {
134
+ const detached = raw.detached !== void 0 || raw.sidecar.startsWith("detached/files/");
135
+ const candidate = {
136
+ input: raw,
137
+ detached,
138
+ metadata: raw.metadata,
139
+ semanticEntry: (0, import_layoutCore.without)(raw.metadata, ["shares"]),
140
+ invalid: conflictingPaths.has(raw.bytes)
141
+ };
142
+ for (const path of [raw.sidecar, raw.bytes]) (0, import_layoutPaths.parseWorkspacePointer)(path);
143
+ if (raw.sidecar !== (0, import_layoutPaths.rawSidecarPath)(raw.bytes) || !raw.bytes.includes("/")) {
144
+ diagnostic("invalid-raw-pair", raw.sidecar, "The sidecar and byte path do not form one raw file");
145
+ candidate.invalid = true;
146
+ }
147
+ if (raw.metadata.kind !== "file") {
148
+ diagnostic("invalid-raw-kind", raw.sidecar, 'A raw sidecar requires kind "file"', ["kind"]);
149
+ candidate.invalid = true;
150
+ }
151
+ const allowed = detached ? RAW_DETACHED_FIELDS : RAW_NORMAL_FIELDS;
152
+ const forbidden = Object.keys(raw.metadata).find((field) => !allowed.has(field));
153
+ if (forbidden) {
154
+ diagnostic("invalid-raw-field", raw.sidecar, `Raw sidecar cannot contain ${forbidden}`, [forbidden]);
155
+ candidate.invalid = true;
156
+ }
157
+ if (!(0, import_layoutCore.own)(raw.metadata, "order") || !(0, import_layoutCore.own)(raw.metadata, "type") || !(0, import_layoutCore.own)(raw.metadata, "category")) {
158
+ diagnostic("incomplete-raw-metadata", raw.sidecar, "A raw sidecar requires order, type, and category");
159
+ candidate.invalid = true;
160
+ }
161
+ if (raw.metadata.order !== null && (typeof raw.metadata.order !== "number" || !Number.isFinite(raw.metadata.order)) || typeof raw.metadata.type !== "string" || raw.metadata.type.length === 0 || typeof raw.metadata.category !== "string" || raw.metadata.category.length === 0) {
162
+ diagnostic("invalid-raw-metadata", raw.sidecar, "Raw metadata fields have invalid values");
163
+ candidate.invalid = true;
164
+ }
165
+ const hasId = (0, import_layoutCore.own)(raw.metadata, "id");
166
+ const hasKey = (0, import_layoutCore.own)(raw.metadata, "key");
167
+ if (hasId && hasKey) {
168
+ diagnostic("ambiguous-raw-identity", raw.sidecar, "A raw sidecar cannot contain both id and key");
169
+ candidate.invalid = true;
170
+ } else if (hasId) {
171
+ if (typeof raw.metadata.id !== "string" || !import_layoutCore.RESOURCE_ID.test(raw.metadata.id)) {
172
+ diagnostic("invalid-raw-id", raw.sidecar, "Raw sidecar id is invalid", ["id"]);
173
+ candidate.invalid = true;
174
+ } else {
175
+ candidate.source = { type: "resource", resource: { kind: "file", id: raw.metadata.id } };
176
+ }
177
+ } else if (hasKey) {
178
+ if (typeof raw.metadata.key !== "string" || raw.metadata.key.length === 0) {
179
+ diagnostic("invalid-raw-key", raw.sidecar, "Raw sidecar key is invalid", ["key"]);
180
+ candidate.invalid = true;
181
+ } else {
182
+ candidate.source = { type: "resource", resource: { kind: "file", key: raw.metadata.key } };
183
+ }
184
+ }
185
+ if (candidate.source) candidate.sourceKey = (0, import_layoutCore.sourceIdentityKey)(candidate.source);
186
+ if (detached) {
187
+ if (!hasId && !hasKey) {
188
+ diagnostic("detached-raw-identity", raw.sidecar, "A detached raw sidecar requires id or key");
189
+ candidate.invalid = true;
190
+ }
191
+ if (typeof raw.metadata.name !== "string" || !(0, import_layoutCore.own)(raw.metadata, "folder")) {
192
+ diagnostic(
193
+ "detached-raw-placement",
194
+ raw.sidecar,
195
+ "A detached raw sidecar requires explicit name and folder"
196
+ );
197
+ candidate.invalid = true;
198
+ } else {
199
+ candidate.name = raw.metadata.name;
200
+ candidate.folder = raw.metadata.folder;
201
+ }
202
+ const bucket = raw.sidecar.split("/").at(-2);
203
+ const expectedBucket = candidate.source?.type === "resource" ? "id" in candidate.source.resource ? candidate.source.resource.id : candidate.source.resource.key : void 0;
204
+ let encodedBucket;
205
+ try {
206
+ encodedBucket = expectedBucket === void 0 ? void 0 : (0, import_layoutPaths.encodeLayoutSegment)(expectedBucket);
207
+ } catch {
208
+ encodedBucket = void 0;
209
+ }
210
+ if (!raw.sidecar.startsWith("detached/files/") || expectedBucket === void 0 || encodedBucket === void 0 || bucket !== encodedBucket) {
211
+ diagnostic("detached-raw-bucket", raw.sidecar, "Detached bucket does not match the raw source");
212
+ candidate.invalid = true;
213
+ }
214
+ } else {
215
+ if ((0, import_layoutCore.own)(raw.metadata, "name")) {
216
+ if (typeof raw.metadata.name !== "string" || raw.metadata.name !== raw.name) {
217
+ diagnostic(
218
+ "invalid-raw-name-override",
219
+ raw.sidecar,
220
+ "Raw name override must equal the decoded semantic name",
221
+ ["name"]
222
+ );
223
+ candidate.invalid = true;
224
+ }
225
+ }
226
+ candidate.name = typeof raw.metadata.name === "string" ? raw.metadata.name : raw.name;
227
+ candidate.folder = raw.folder;
228
+ }
229
+ candidate.entryHash = (0, import_layoutCore.canonicalFragmentHash)({
230
+ entry: candidate.semanticEntry,
231
+ name: candidate.name ?? null,
232
+ folder: candidate.folder ?? null
233
+ });
234
+ return candidate;
235
+ });
236
+ const bucketCounts = /* @__PURE__ */ new Map();
237
+ const identityCandidates = /* @__PURE__ */ new Map();
238
+ const selectorCandidates = /* @__PURE__ */ new Map();
239
+ for (const candidate of candidates) {
240
+ const bucket = candidate.input.sidecar.slice(0, candidate.input.sidecar.lastIndexOf("/"));
241
+ bucketCounts.set(bucket, (bucketCounts.get(bucket) ?? 0) + 1);
242
+ if (candidate.sourceKey)
243
+ identityCandidates.set(candidate.sourceKey, [
244
+ ...identityCandidates.get(candidate.sourceKey) ?? [],
245
+ candidate
246
+ ]);
247
+ const key = selectorKey({ sidecar: candidate.input.sidecar });
248
+ selectorCandidates.set(key, [...selectorCandidates.get(key) ?? [], candidate]);
249
+ }
250
+ for (const [key, duplicates] of identityCandidates)
251
+ if (duplicates.length > 1) {
252
+ for (const candidate of duplicates) candidate.invalid = true;
253
+ diagnostic(
254
+ "duplicate-raw-identity",
255
+ duplicates[0].input.sidecar,
256
+ `More than one raw sidecar uses ${key}`,
257
+ void 0,
258
+ duplicates[1].input.sidecar
259
+ );
260
+ }
261
+ for (const duplicates of selectorCandidates.values())
262
+ if (duplicates.length > 1) {
263
+ for (const candidate of duplicates) candidate.invalid = true;
264
+ diagnostic("duplicate-raw-entry", duplicates[0].input.sidecar, "More than one raw input uses this sidecar");
265
+ }
266
+ for (const candidate of candidates)
267
+ if (candidate.detached && bucketCounts.get(candidate.input.sidecar.slice(0, candidate.input.sidecar.lastIndexOf("/"))) !== 1) {
268
+ diagnostic("detached-file-count", candidate.input.sidecar, "A detached file bucket must hold one raw file");
269
+ candidate.invalid = true;
270
+ }
271
+ for (const proof of submissionProofs)
272
+ if (!proof.source.token.startsWith(`${BINARY_TOKEN_NAMESPACE}:`))
273
+ throw new Error(`Binary proof token ${JSON.stringify(proof.source.token)} uses the wrong namespace`);
274
+ const normalizedProofs = submissionProofs.map((proof) => ({
275
+ token: proof.source.token,
276
+ scopeKey: selectorKey(proof.selector),
277
+ sourcePath: proof.sourcePath,
278
+ evidenceHash: proofEvidence(proof.entryHash, proof.byteHash)
279
+ }));
280
+ const usedTokens = /* @__PURE__ */ new Set([
281
+ ...submissionProofs.map((proof) => proof.source.token),
282
+ ...input.reservedTransientTokens ?? []
283
+ ]);
284
+ let tokenSequence = 0;
285
+ const newTransient = () => {
286
+ const allocated = (0, import_layoutCore.allocateSubmissionToken)(usedTokens, tokenSequence, BINARY_TOKEN_NAMESPACE);
287
+ tokenSequence = allocated.sequence;
288
+ return { type: "transient", token: allocated.token };
289
+ };
290
+ const priorRawRoutes = priorRoutes.filter(
291
+ (route) => route.selector.slot === "file-entry" && typeof route.bytes === "string"
292
+ );
293
+ const claimedRawSources = /* @__PURE__ */ new Set();
294
+ const pushRawObservation = (candidate, source, selector, prior, state) => {
295
+ rawObservations.push({
296
+ source,
297
+ selector,
298
+ sourcePath: [],
299
+ bytes: candidate.input.bytes,
300
+ priorCleanHash: prior?.priorCleanHash,
301
+ state,
302
+ contributor: true,
303
+ entryHash: candidate.entryHash
304
+ });
305
+ };
306
+ for (const candidate of candidates) {
307
+ const { input: raw } = candidate;
308
+ const fact = facts.get(raw.bytes);
309
+ if (candidate.sourceKey) claimedRawSources.add(candidate.sourceKey);
310
+ if (candidate.invalid || !candidate.name || candidate.folder === void 0 || !candidate.entryHash) {
311
+ if (candidate.source) {
312
+ const selector2 = {
313
+ sidecar: raw.sidecar,
314
+ slot: "file-entry",
315
+ identity: rawIdentity(candidate.source)
316
+ };
317
+ const prior2 = priorRawRoutes.find(
318
+ (route) => (0, import_layoutCore.sourceIdentityKey)(route.source) === (0, import_layoutCore.sourceIdentityKey)(candidate.source)
319
+ );
320
+ const identityIsUnique = candidate.sourceKey !== void 0 && identityCandidates.get(candidate.sourceKey)?.length === 1;
321
+ const entryIsUnique = selectorCandidates.get(selectorKey({ sidecar: raw.sidecar }))?.length === 1;
322
+ pushRawObservation(
323
+ candidate,
324
+ candidate.source,
325
+ selector2,
326
+ prior2,
327
+ prior2 && fact?.state === "absent" && identityIsUnique && entryIsUnique ? "absent" : "present-unclassified"
328
+ );
329
+ }
330
+ continue;
331
+ }
332
+ if (!candidate.source) {
333
+ if (!fact || fact.state !== "present") {
334
+ diagnostic("incomplete-raw-upload", raw.bytes, "A new raw file requires present byte evidence");
335
+ continue;
336
+ }
337
+ const byteHash2 = (0, import_layoutCore.canonicalFragmentHash)(fact.content);
338
+ const match = (0, import_layoutCore.matchExactSubmissionProof)(normalizedProofs, [
339
+ {
340
+ scopeKey: selectorKey({ sidecar: raw.sidecar }),
341
+ sourcePath: [],
342
+ evidenceHash: proofEvidence(candidate.entryHash, byteHash2)
343
+ }
344
+ ]);
345
+ if (match.status === "matched") candidate.source = { type: "transient", token: match.token };
346
+ else {
347
+ if (match.status === "ambiguous")
348
+ diagnostic(
349
+ "ambiguous-source-correspondence",
350
+ raw.sidecar,
351
+ "Multiple transient routes match this raw file"
352
+ );
353
+ else if (match.status === "lost")
354
+ diagnostic(
355
+ "lost-source-correspondence",
356
+ raw.sidecar,
357
+ "The unchanged transient raw source can no longer be located"
358
+ );
359
+ candidate.source = newTransient();
360
+ }
361
+ candidate.sourceKey = (0, import_layoutCore.sourceIdentityKey)(candidate.source);
362
+ claimedRawSources.add(candidate.sourceKey);
363
+ }
364
+ const source = candidate.source;
365
+ const identity = rawIdentity(source);
366
+ candidate.identity = identity;
367
+ const selector = { sidecar: raw.sidecar, slot: "file-entry", identity };
368
+ const prior = priorRawRoutes.find((route) => (0, import_layoutCore.sourceIdentityKey)(route.source) === (0, import_layoutCore.sourceIdentityKey)(source));
369
+ if (!prior && candidate.folder === null && (source.type === "transient" || source.type === "resource" && "key" in source.resource)) {
370
+ diagnostic("incomplete-raw-placement", raw.sidecar, "A new raw file requires a folder");
371
+ continue;
372
+ }
373
+ if (candidate.detached) {
374
+ const proof = raw.detached;
375
+ const placementHash = (0, import_layoutCore.canonicalFragmentHash)({ name: candidate.name, folder: candidate.folder });
376
+ const validProof = proof?.sourceKey === (0, import_layoutCore.sourceIdentityKey)(source) && (proof.reason === "representation-fallback" ? provesRepresentationFallback(proof, candidate) : source.type === "resource" && "id" in source.resource && proof.placementHash === placementHash && proof.baselineHash.length > 0 && authoritativeBaselines.get((0, import_layoutCore.sourceIdentityKey)(source)) === proof.baselineHash && prior !== void 0);
377
+ if (!validProof) {
378
+ diagnostic("invalid-detached-proof", raw.sidecar, "Detached raw placement lacks caller proof");
379
+ continue;
380
+ }
381
+ }
382
+ if (!fact) {
383
+ diagnostic("unobserved-byte-path", raw.bytes, "Raw byte path was not observed");
384
+ pushRawObservation(candidate, source, selector, prior, "present-unclassified");
385
+ continue;
386
+ }
387
+ if (fact.state === "unreadable") {
388
+ diagnostic("unreadable-byte-path", raw.bytes, fact.message);
389
+ pushRawObservation(candidate, source, selector, prior, "present-unclassified");
390
+ continue;
391
+ }
392
+ if (fact.state === "absent") {
393
+ const stranded = prior !== void 0 && prior.bytes !== raw.bytes && facts.get(prior.bytes)?.state === "present" && !rawPathClaims.has(prior.bytes);
394
+ if (stranded)
395
+ diagnostic(
396
+ "missing-raw-metadata",
397
+ raw.sidecar,
398
+ `sidecar moved without its bytes; move ${prior.bytes} beside it or restore the sidecar`,
399
+ void 0,
400
+ prior.bytes
401
+ );
402
+ else if (!prior)
403
+ diagnostic("incomplete-raw-upload", raw.bytes, "A new raw file requires present byte evidence");
404
+ pushRawObservation(
405
+ candidate,
406
+ source,
407
+ selector,
408
+ prior,
409
+ prior && !stranded ? "absent" : "present-unclassified"
410
+ );
411
+ continue;
412
+ }
413
+ const byteHash = (0, import_layoutCore.canonicalFragmentHash)(fact.content);
414
+ const document = {
415
+ ...source.type === "resource" ? "id" in source.resource ? { id: source.resource.id } : {} : {},
416
+ kind: "file",
417
+ name: candidate.name,
418
+ folder: candidate.folder,
419
+ order: candidate.metadata.order,
420
+ type: candidate.metadata.type,
421
+ category: candidate.metadata.category,
422
+ content: fact.content
423
+ };
424
+ const currentHash = (0, import_layoutCore.canonicalFragmentHash)(document);
425
+ const documentIndex = rawDocuments.push(document) - 1;
426
+ rawSources.push({
427
+ documentIndex,
428
+ source,
429
+ selector,
430
+ sourcePath: [],
431
+ bytes: raw.bytes,
432
+ detached: candidate.detached,
433
+ nameOverride: (0, import_layoutCore.own)(candidate.metadata, "name")
434
+ });
435
+ rawObservations.push({
436
+ source,
437
+ selector,
438
+ sourcePath: [],
439
+ bytes: raw.bytes,
440
+ currentHash,
441
+ priorCleanHash: prior?.priorCleanHash,
442
+ state: observationState(currentHash, prior),
443
+ contributor: true,
444
+ entryHash: candidate.entryHash,
445
+ byteHash
446
+ });
447
+ if (source.type === "transient")
448
+ submissions.push({
449
+ source,
450
+ selector,
451
+ sourcePath: [],
452
+ entryHash: candidate.entryHash,
453
+ byteHash
454
+ });
455
+ if ((0, import_layoutCore.own)(candidate.metadata, "shares")) {
456
+ const shares = (0, import_layoutCore.object)(candidate.metadata.shares);
457
+ const groupFile = shares && Object.keys(shares).length === 1 ? shares.file : void 0;
458
+ if (typeof groupFile !== "string")
459
+ diagnostic("invalid-file-share-pointer", raw.sidecar, "Raw shares requires one file pointer", [
460
+ "shares"
461
+ ]);
462
+ else {
463
+ try {
464
+ (0, import_layoutPaths.parseWorkspacePointer)(groupFile);
465
+ navigation.push({
466
+ source,
467
+ selector: { sidecar: raw.sidecar, slot: "file-share-pointer", identity },
468
+ sourcePath: ["shares"],
469
+ groupFile,
470
+ currentHash: (0, import_layoutCore.canonicalFragmentHash)(groupFile)
471
+ });
472
+ } catch (error) {
473
+ diagnostic("invalid-file-share-pointer", raw.sidecar, error.message, ["shares"]);
474
+ }
475
+ }
476
+ }
477
+ }
478
+ for (const route of priorRawRoutes) {
479
+ const key = (0, import_layoutCore.sourceIdentityKey)(route.source);
480
+ if (claimedRawSources.has(key)) continue;
481
+ const fact = facts.get(route.bytes);
482
+ if (fact?.state === "absent") {
483
+ rawObservations.push({ ...route, state: "absent" });
484
+ continue;
485
+ }
486
+ if (!fact) diagnostic("unobserved-byte-path", route.bytes, "Tracked raw byte path was not observed");
487
+ else if (fact.state === "unreadable") diagnostic("unreadable-byte-path", route.bytes, fact.message);
488
+ else
489
+ diagnostic(
490
+ "missing-raw-metadata",
491
+ route.selector.sidecar,
492
+ "Tracked raw bytes remain without their sidecar",
493
+ void 0,
494
+ route.bytes
495
+ );
496
+ rawObservations.push({ ...route, state: "present-unclassified" });
497
+ }
498
+ const priorAttachmentRoutes = priorRoutes.filter(
499
+ (route) => route.selector.slot === "owner-attachment"
500
+ );
501
+ const explicitOwnerByPath = /* @__PURE__ */ new Map();
502
+ for (const [path, claims] of attachmentPathClaims)
503
+ if (claims.length === 1 && !conflictingPaths.has(path)) explicitOwnerByPath.set(path, claims[0]);
504
+ for (const attachment of input.attachments) {
505
+ const { field, ownerDocument, ownerFile, ownerSource } = attachment;
506
+ const sourcePath = [field];
507
+ const expectedKind = field === "icon" ? "remote_job" : "export_configuration";
508
+ const selector = { ownerFile, slot: "owner-attachment", field };
509
+ const prior = priorAttachmentRoutes.find(
510
+ (route) => (0, import_layoutCore.sourceIdentityKey)(route.source) === (0, import_layoutCore.sourceIdentityKey)(ownerSource) && route.selector.field === field
511
+ );
512
+ const projectInvalid = () => {
513
+ ownerFields.push({ ownerSource, ownerFile, field, sourcePath, status: "invalid" });
514
+ if (prior) attachmentObservations.push({ ...prior, state: "present-unclassified" });
515
+ };
516
+ const assignedOwnerId = typeof ownerDocument.id === "string" && import_layoutCore.RESOURCE_ID.test(ownerDocument.id);
517
+ const ownerIdentityValid = ownerSource.type !== "group" && (ownerSource.type === "transient" || ownerSource.resource.kind === ownerDocument.kind) && (ownerDocument.id === void 0 || ownerSource.type === "resource" && "id" in ownerSource.resource && ownerSource.resource.id === ownerDocument.id || attachment.origin === "authoritative" && assignedOwnerId && (ownerSource.type === "transient" || ownerSource.type === "resource" && "key" in ownerSource.resource)) && (ownerDocument.key === void 0 || typeof ownerDocument.key === "string" && ownerSource.type === "resource" && "key" in ownerSource.resource && ownerSource.resource.key === ownerDocument.key);
518
+ if (ownerDocument.kind !== expectedKind || !ownerIdentityValid) {
519
+ diagnostic(
520
+ "invalid-attachment-owner",
521
+ ownerFile,
522
+ `${field} does not belong to ${ownerDocument.kind}`,
523
+ sourcePath
524
+ );
525
+ projectInvalid();
526
+ continue;
527
+ }
528
+ const authored = ownerDocument[field];
529
+ const authoritativeDescriptor = attachment.origin === "authoritative" && (0, import_layoutCore.object)(authored) && (0, import_layoutCore.validBlob)(authored) ? authored : void 0;
530
+ const pointer = (0, import_layoutCore.attachmentPointer)(authored);
531
+ if (authored !== void 0 && authored !== null && pointer === void 0 && authoritativeDescriptor === void 0) {
532
+ diagnostic("invalid-attachment-pointer", ownerFile, `${field} requires one file pointer`, sourcePath);
533
+ projectInvalid();
534
+ continue;
535
+ }
536
+ let value;
537
+ let bytes;
538
+ if (authoritativeDescriptor) {
539
+ value = authoritativeDescriptor;
540
+ bytes = prior?.bytes;
541
+ } else if (authored === null || authored === void 0 && attachment.origin === "authoritative" && field === "icon") {
542
+ value = null;
543
+ } else if (authored === void 0) {
544
+ if (attachment.origin === "authoritative") {
545
+ diagnostic(
546
+ "incomplete-attachment-input",
547
+ ownerFile,
548
+ `${field} omission has no authoritative value`,
549
+ sourcePath
550
+ );
551
+ projectInvalid();
552
+ continue;
553
+ }
554
+ if (!prior) {
555
+ if (field === "template") {
556
+ diagnostic(
557
+ "incomplete-attachment-input",
558
+ ownerFile,
559
+ `${field} omission has no retained route`,
560
+ sourcePath
561
+ );
562
+ projectInvalid();
563
+ continue;
564
+ }
565
+ ownerFields.push({ ownerSource, ownerFile, field, sourcePath, status: "omitted" });
566
+ continue;
567
+ }
568
+ if (!prior.contributor) {
569
+ value = null;
570
+ } else if (!prior.bytes) {
571
+ diagnostic(
572
+ "incomplete-attachment-input",
573
+ ownerFile,
574
+ `${field} retained contribution has no byte route`,
575
+ sourcePath
576
+ );
577
+ projectInvalid();
578
+ continue;
579
+ } else {
580
+ const displaced = explicitOwnerByPath.get(prior.bytes);
581
+ if (rawPathClaims.has(prior.bytes) || displaced && (0, import_layoutCore.sourceIdentityKey)(displaced.ownerSource) !== (0, import_layoutCore.sourceIdentityKey)(ownerSource)) {
582
+ diagnostic(
583
+ "attachment-route-displaced",
584
+ ownerFile,
585
+ "Another owner claims this omitted attachment route",
586
+ sourcePath,
587
+ prior.bytes
588
+ );
589
+ projectInvalid();
590
+ continue;
591
+ }
592
+ const fact = facts.get(prior.bytes);
593
+ if (!fact) {
594
+ diagnostic("unobserved-byte-path", prior.bytes, "Retained attachment path was not observed");
595
+ projectInvalid();
596
+ continue;
597
+ }
598
+ if (fact.state === "unreadable") {
599
+ diagnostic("unreadable-byte-path", prior.bytes, fact.message);
600
+ projectInvalid();
601
+ continue;
602
+ }
603
+ if (fact.state === "absent") value = null;
604
+ else {
605
+ value = fact.content;
606
+ bytes = prior.bytes;
607
+ }
608
+ }
609
+ } else {
610
+ bytes = pointer;
611
+ try {
612
+ (0, import_layoutPaths.parseWorkspacePointer)(bytes);
613
+ } catch (error) {
614
+ diagnostic("invalid-attachment-pointer", ownerFile, error.message, sourcePath);
615
+ projectInvalid();
616
+ continue;
617
+ }
618
+ if (conflictingPaths.has(bytes)) {
619
+ projectInvalid();
620
+ continue;
621
+ }
622
+ const fact = facts.get(bytes);
623
+ if (!fact) {
624
+ diagnostic("unobserved-byte-path", bytes, "Attachment byte path was not observed");
625
+ projectInvalid();
626
+ continue;
627
+ }
628
+ if (fact.state === "unreadable") {
629
+ diagnostic("unreadable-byte-path", bytes, fact.message);
630
+ projectInvalid();
631
+ continue;
632
+ }
633
+ if (fact.state === "absent") {
634
+ if (prior?.bytes === bytes) {
635
+ value = null;
636
+ bytes = void 0;
637
+ } else {
638
+ diagnostic("missing-attachment-bytes", bytes, "A new or changed attachment pointer requires bytes");
639
+ projectInvalid();
640
+ continue;
641
+ }
642
+ } else value = fact.content;
643
+ }
644
+ const currentHash = (0, import_layoutCore.canonicalFragmentHash)(value ?? null);
645
+ const state = observationState(currentHash, prior);
646
+ ownerFields.push({
647
+ ownerSource,
648
+ ownerFile,
649
+ field,
650
+ sourcePath,
651
+ status: "value",
652
+ value: value ?? null,
653
+ ...bytes ? { bytes } : {},
654
+ currentHash,
655
+ ...prior ? { priorCleanHash: prior.priorCleanHash } : {},
656
+ state
657
+ });
658
+ attachmentObservations.push({
659
+ source: ownerSource,
660
+ selector,
661
+ sourcePath,
662
+ ...bytes ? { bytes } : {},
663
+ currentHash,
664
+ priorCleanHash: prior?.priorCleanHash,
665
+ state,
666
+ contributor: value !== null,
667
+ ...value ? { byteHash: (0, import_layoutCore.canonicalFragmentHash)(value) } : {}
668
+ });
669
+ }
670
+ return {
671
+ rawDocuments,
672
+ rawSources,
673
+ rawObservations,
674
+ ownerFields,
675
+ attachmentObservations,
676
+ navigation,
677
+ submissions,
678
+ diagnostics
679
+ };
680
+ }
681
+ function decomposeBinaryLayout(input) {
682
+ const diagnostics = [...input.current.diagnostics];
683
+ const rawPatches = [];
684
+ const ownerPatches = [];
685
+ const diagnostic = (code, path, message, sourcePath) => diagnostics.push({ code, path, message, ...sourcePath ? { sourcePath } : {} });
686
+ const observations = (0, import_layoutCore.groupBySource)(
687
+ [...input.current.rawObservations, ...input.current.attachmentObservations],
688
+ (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)
689
+ );
690
+ const rawObservationsBySource = (0, import_layoutCore.groupBySource)(
691
+ input.current.rawObservations,
692
+ (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)
693
+ );
694
+ const attachmentObservationsBySource = (0, import_layoutCore.groupBySource)(
695
+ input.current.attachmentObservations,
696
+ (observation) => (0, import_layoutCore.sourceIdentityKey)(observation.source)
697
+ );
698
+ const vacating = new Set((input.vacating ?? []).map(import_layoutCore.sourceIdentityKey));
699
+ const patchedRawTargets = /* @__PURE__ */ new Set();
700
+ const pushRawPatch = (patch) => {
701
+ const key = `${selectorKey(patch.selector)}/${(0, import_layoutCore.sourceIdentityKey)(patch.source)}`;
702
+ if (patchedRawTargets.has(key)) {
703
+ diagnostic("duplicate-patch-target", patch.selector.sidecar, "More than one patch targets this raw file");
704
+ return;
705
+ }
706
+ patchedRawTargets.add(key);
707
+ rawPatches.push(patch);
708
+ };
709
+ const transientMatchesCurrent = (mapping) => {
710
+ if (mapping.source.type !== "transient") return true;
711
+ const token = mapping.source.token;
712
+ const proofs = (input.submissionProofs ?? []).filter(
713
+ (proof2) => proof2.source.token === token && selectorLocation(proof2.selector, mapping.selector) && (0, import_layoutCore.samePath)(proof2.sourcePath, mapping.sourcePath)
714
+ );
715
+ if (proofs.length !== 1) return false;
716
+ const proof = proofs[0];
717
+ const match = (0, import_layoutCore.matchExactSubmissionProof)(
718
+ [
719
+ {
720
+ token: proof.source.token,
721
+ scopeKey: "mapping",
722
+ sourcePath: proof.sourcePath,
723
+ evidenceHash: proofEvidence(proof.entryHash, proof.byteHash)
724
+ }
725
+ ],
726
+ input.current.submissions.filter(
727
+ (candidate) => candidate.source.token === proof.source.token && selectorLocation(candidate.selector, proof.selector)
728
+ ).map((candidate) => ({
729
+ scopeKey: "mapping",
730
+ sourcePath: candidate.sourcePath,
731
+ evidenceHash: proofEvidence(candidate.entryHash, candidate.byteHash)
732
+ }))
733
+ );
734
+ return match.status === "matched" && match.token === token && match.exactMatchCount === 1;
735
+ };
736
+ const documentUses = /* @__PURE__ */ new Map();
737
+ const sourceUses = /* @__PURE__ */ new Map();
738
+ const targetUses = /* @__PURE__ */ new Map();
739
+ for (const mapping of input.rawSources) {
740
+ documentUses.set(mapping.documentIndex, (documentUses.get(mapping.documentIndex) ?? 0) + 1);
741
+ const sourceKey = (0, import_layoutCore.sourceIdentityKey)(mapping.source);
742
+ sourceUses.set(sourceKey, (sourceUses.get(sourceKey) ?? 0) + 1);
743
+ if (vacating.has(sourceKey)) continue;
744
+ const targetKey = selectorKey(mapping.selector);
745
+ targetUses.set(targetKey, (targetUses.get(targetKey) ?? 0) + 1);
746
+ }
747
+ input.rawDocuments.forEach((_document, index) => {
748
+ if ((documentUses.get(index) ?? 0) === 0) throw new Error(`Raw wire document ${index} has no source mapping`);
749
+ });
750
+ for (const mapping of input.rawSources) {
751
+ const mappingSourceKey = (0, import_layoutCore.sourceIdentityKey)(mapping.source);
752
+ const mappingTargetKey = selectorKey(mapping.selector);
753
+ if (documentUses.get(mapping.documentIndex) > 1 || sourceUses.get(mappingSourceKey) > 1 || (targetUses.get(mappingTargetKey) ?? 0) > 1) {
754
+ diagnostic(
755
+ "duplicate-wire-source",
756
+ mapping.selector.sidecar,
757
+ "Raw documents, sources, and patch targets must be one-to-one",
758
+ mapping.sourcePath
759
+ );
760
+ continue;
761
+ }
762
+ const document = input.rawDocuments[mapping.documentIndex];
763
+ const currentSource = rawObservationsBySource.get(mappingSourceKey) ?? [];
764
+ const currentTarget = input.current.rawObservations.filter(
765
+ (observation) => selectorLocation(observation.selector, mapping.selector) && !vacating.has((0, import_layoutCore.sourceIdentityKey)(observation.source))
766
+ );
767
+ const exactCurrent = currentSource.filter(
768
+ (observation) => selectorLocation(observation.selector, mapping.selector)
769
+ );
770
+ const currentHash = exactCurrent.length === 1 ? exactCurrent[0].currentHash : void 0;
771
+ const safeInsertion = mapping.source.type === "resource" && (exactCurrent.length === 1 && exactCurrent[0].state === "absent" || currentSource.length === 0 && currentTarget.length === 0);
772
+ const validWireIdentity = document?.kind === "file" && !(0, import_layoutCore.own)(document, "key") && (document.id === void 0 || typeof document.id === "string" && import_layoutCore.RESOURCE_ID.test(document.id)) && mapping.source.type !== "group" && (mapping.source.type !== "resource" || !("id" in mapping.source.resource) || document.id === mapping.source.resource.id);
773
+ if (!validWireIdentity || !currentHash && !safeInsertion || !transientMatchesCurrent(mapping)) {
774
+ diagnostic(
775
+ "stale-wire-source",
776
+ mapping.selector.sidecar,
777
+ "The raw wire source is no longer current",
778
+ mapping.sourcePath
779
+ );
780
+ continue;
781
+ }
782
+ const content = (0, import_layoutCore.object)(document.content);
783
+ if (!content || !(0, import_layoutCore.validBlob)(content)) {
784
+ diagnostic("invalid-raw-content", mapping.selector.sidecar, "Raw file content requires a byte descriptor");
785
+ continue;
786
+ }
787
+ const assignedId = typeof document.id === "string" ? document.id : void 0;
788
+ const metadata = {
789
+ kind: "file",
790
+ ...assignedId ? { id: assignedId } : mapping.source.type === "resource" && "key" in mapping.source.resource ? { key: mapping.source.resource.key } : {},
791
+ ...mapping.detached || mapping.nameOverride ? { name: document.name } : {},
792
+ order: document.order,
793
+ type: document.type,
794
+ category: document.category,
795
+ ...mapping.detached ? { folder: document.folder } : {}
796
+ };
797
+ pushRawPatch({
798
+ source: mapping.source,
799
+ selector: mapping.selector,
800
+ action: "set",
801
+ document,
802
+ metadata,
803
+ bytes: mapping.bytes,
804
+ content,
805
+ placement: {
806
+ mode: "allocate-from-document",
807
+ name: document.name,
808
+ folder: document.folder
809
+ },
810
+ ...assignedId && (mapping.source.type !== "resource" || !("id" in mapping.source.resource) || mapping.source.resource.id !== assignedId) ? { assignedId } : {},
811
+ ...assignedId && mapping.source.type === "resource" && "key" in mapping.source.resource ? { removeKey: true } : {},
812
+ ...currentHash ? { expectedCurrentHash: currentHash } : {}
813
+ });
814
+ }
815
+ for (const removal of input.removals ?? []) {
816
+ const currentHash = currentObservationHash(observations, removal.source, removal.selector);
817
+ if (!currentHash) {
818
+ diagnostic("stale-wire-source", removal.selector.sidecar, "The raw removal source is no longer current");
819
+ continue;
820
+ }
821
+ pushRawPatch({
822
+ source: removal.source,
823
+ selector: removal.selector,
824
+ action: "remove",
825
+ expectedCurrentHash: currentHash
826
+ });
827
+ }
828
+ const ownerInsertions = input.ownerInsertions ?? [];
829
+ const insertionSourceUses = /* @__PURE__ */ new Map();
830
+ const insertionTargetUses = /* @__PURE__ */ new Map();
831
+ const ownerTargetKey = (ownerFile, field) => JSON.stringify([ownerFile, field]);
832
+ for (const insertion of ownerInsertions) {
833
+ const source = (0, import_layoutCore.sourceIdentityKey)(insertion.source);
834
+ const target = ownerTargetKey(insertion.ownerFile, insertion.field);
835
+ insertionSourceUses.set(source, (insertionSourceUses.get(source) ?? 0) + 1);
836
+ insertionTargetUses.set(target, (insertionTargetUses.get(target) ?? 0) + 1);
837
+ }
838
+ const existingOwnerSources = new Set(
839
+ (input.ownerFields ?? []).map((field) => (0, import_layoutCore.sourceIdentityKey)(field.ownerSource))
840
+ );
841
+ const existingOwnerTargets = new Set(
842
+ (input.ownerFields ?? []).map((field) => ownerTargetKey(field.ownerFile, field.field))
843
+ );
844
+ const mixedInsertionSources = new Set(
845
+ ownerInsertions.map((insertion) => (0, import_layoutCore.sourceIdentityKey)(insertion.source)).filter((source) => existingOwnerSources.has(source))
846
+ );
847
+ const mixedInsertionTargets = new Set(
848
+ ownerInsertions.map((insertion) => ownerTargetKey(insertion.ownerFile, insertion.field)).filter((target) => existingOwnerTargets.has(target))
849
+ );
850
+ for (const mapping of input.ownerFields ?? []) {
851
+ if (mapping.status !== "value") continue;
852
+ if (mixedInsertionSources.has((0, import_layoutCore.sourceIdentityKey)(mapping.ownerSource)) || mixedInsertionTargets.has(ownerTargetKey(mapping.ownerFile, mapping.field)))
853
+ continue;
854
+ const owner = (input.ownerDocuments ?? []).find(
855
+ (candidate) => (0, import_layoutCore.sourceIdentityKey)(candidate.source) === (0, import_layoutCore.sourceIdentityKey)(mapping.ownerSource) && candidate.ownerFile === mapping.ownerFile
856
+ );
857
+ const selector = {
858
+ ownerFile: mapping.ownerFile,
859
+ slot: "owner-attachment",
860
+ field: mapping.field
861
+ };
862
+ const currentMatches = (attachmentObservationsBySource.get((0, import_layoutCore.sourceIdentityKey)(mapping.ownerSource)) ?? []).filter((observation) => selectorLocation(observation.selector, selector));
863
+ const current = currentMatches.length === 1 ? currentMatches[0] : void 0;
864
+ const routeChanged = mapping.value !== null && mapping.bytes !== void 0 && current?.bytes !== mapping.bytes;
865
+ if (!owner || !current?.currentHash || current.currentHash !== mapping.currentHash || routeChanged) {
866
+ diagnostic("stale-wire-source", mapping.ownerFile, "The attachment owner source is no longer current", [
867
+ mapping.field
868
+ ]);
869
+ continue;
870
+ }
871
+ const authoredValue = owner.document[mapping.field];
872
+ const value = authoredValue === void 0 && owner.document.kind === "remote_job" ? null : authoredValue;
873
+ ownerPatches.push({
874
+ origin: "current-observation",
875
+ source: mapping.ownerSource,
876
+ ownerFile: mapping.ownerFile,
877
+ field: mapping.field,
878
+ action: value === null ? "clear" : "set",
879
+ ownerDocument: owner.document,
880
+ value,
881
+ ...mapping.bytes ? { bytes: mapping.bytes } : {},
882
+ expectedCurrentHash: current.currentHash
883
+ });
884
+ }
885
+ for (const insertion of ownerInsertions) {
886
+ const sourceKey = (0, import_layoutCore.sourceIdentityKey)(insertion.source);
887
+ const targetKey = ownerTargetKey(insertion.ownerFile, insertion.field);
888
+ if ((insertionSourceUses.get(sourceKey) ?? 0) > 1 || (insertionTargetUses.get(targetKey) ?? 0) > 1) {
889
+ diagnostic(
890
+ "duplicate-attachment-candidate",
891
+ insertion.ownerFile,
892
+ "Authoritative attachment insertions must have unique sources and targets",
893
+ [insertion.field]
894
+ );
895
+ continue;
896
+ }
897
+ if (mixedInsertionSources.has(sourceKey) || mixedInsertionTargets.has(targetKey)) {
898
+ diagnostic(
899
+ "duplicate-attachment-candidate",
900
+ insertion.ownerFile,
901
+ "Authoritative insertion cannot mix with a current-observation candidate",
902
+ [insertion.field]
903
+ );
904
+ continue;
905
+ }
906
+ const validField = insertion.field === "icon" || insertion.field === "template";
907
+ const expectedKind = insertion.field === "icon" ? "remote_job" : "export_configuration";
908
+ const resource = insertion.source.type === "resource" ? insertion.source.resource : void 0;
909
+ const stableId = resource && "id" in resource && typeof resource.id === "string" && import_layoutCore.RESOURCE_ID.test(resource.id) ? resource.id : void 0;
910
+ const identityValid = validField && stableId !== void 0 && resource?.kind === expectedKind && insertion.documentKey === `${expectedKind}/${stableId}` && insertion.ownerDocument.kind === expectedKind && insertion.ownerDocument.id === stableId && !(0, import_layoutCore.own)(insertion.ownerDocument, "key") && insertion.groupedSelector.slot === "document" && insertion.groupedSelector.file === insertion.ownerFile;
911
+ if (!identityValid) {
912
+ diagnostic(
913
+ "invalid-authoritative-attachment-insertion",
914
+ insertion.ownerFile,
915
+ "Authoritative attachment insertion identity is inconsistent",
916
+ [insertion.field]
917
+ );
918
+ continue;
919
+ }
920
+ const selector = {
921
+ ownerFile: insertion.ownerFile,
922
+ slot: "owner-attachment",
923
+ field: insertion.field
924
+ };
925
+ if (attachmentObservationsBySource.has(sourceKey) || input.current.attachmentObservations.some((observation) => selectorLocation(observation.selector, selector))) {
926
+ diagnostic(
927
+ "stale-wire-source",
928
+ insertion.ownerFile,
929
+ "Authoritative attachment insertion already has a current binary association",
930
+ [insertion.field]
931
+ );
932
+ continue;
933
+ }
934
+ const value = insertion.ownerDocument[insertion.field];
935
+ if (value === void 0) {
936
+ if (insertion.field === "template")
937
+ diagnostic(
938
+ "incomplete-attachment-input",
939
+ insertion.ownerFile,
940
+ "template omission has no authoritative value",
941
+ [insertion.field]
942
+ );
943
+ continue;
944
+ }
945
+ if (value === null) continue;
946
+ const descriptor = (0, import_layoutCore.object)(value);
947
+ if (!descriptor || !(0, import_layoutCore.validBlob)(descriptor)) {
948
+ diagnostic(
949
+ "invalid-attachment-content",
950
+ insertion.ownerFile,
951
+ "Authoritative attachment insertion requires a byte descriptor or null",
952
+ [insertion.field]
953
+ );
954
+ continue;
955
+ }
956
+ ownerPatches.push({
957
+ origin: "authoritative-insertion",
958
+ source: insertion.source,
959
+ ownerFile: insertion.ownerFile,
960
+ field: insertion.field,
961
+ action: "set",
962
+ ownerDocument: insertion.ownerDocument,
963
+ value: descriptor,
964
+ groupedSelector: insertion.groupedSelector
965
+ });
966
+ }
967
+ return { rawPatches, ownerPatches, diagnostics };
968
+ }
969
+ // Annotate the CommonJS export names for ESM import in node:
970
+ 0 && (module.exports = {
971
+ composeBinaryLayout,
972
+ decomposeBinaryLayout
973
+ });
974
+ //# sourceMappingURL=layoutBinaryProjection.js.map