farseer-cli 1.15.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 (55) 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/commands/model.js +14 -4
  5. package/dist/commands/model.js.map +2 -2
  6. package/dist/index.js +16 -0
  7. package/dist/index.js.map +2 -2
  8. package/dist/pipeline/generated-reference.json +30 -30
  9. package/dist/pipeline/service.js +2 -2
  10. package/dist/pipeline/service.js.map +2 -2
  11. package/dist/services/codefirst/api.js +269 -0
  12. package/dist/services/codefirst/api.js.map +7 -0
  13. package/dist/services/codefirst/binaryDisk.js +67 -0
  14. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  15. package/dist/services/codefirst/byteHashes.js +129 -0
  16. package/dist/services/codefirst/byteHashes.js.map +7 -0
  17. package/dist/services/codefirst/documents.js +563 -0
  18. package/dist/services/codefirst/documents.js.map +7 -0
  19. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  20. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  21. package/dist/services/codefirst/layoutCompose.js +593 -0
  22. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  23. package/dist/services/codefirst/layoutCore.js +260 -0
  24. package/dist/services/codefirst/layoutCore.js.map +7 -0
  25. package/dist/services/codefirst/layoutPaths.js +492 -0
  26. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  27. package/dist/services/codefirst/layoutProjection.js +995 -0
  28. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  29. package/dist/services/codefirst/layoutReadback.js +2552 -0
  30. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  31. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  32. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  33. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  34. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  35. package/dist/services/codefirst/layoutScan.js +882 -0
  36. package/dist/services/codefirst/layoutScan.js.map +7 -0
  37. package/dist/services/codefirst/output.js +179 -0
  38. package/dist/services/codefirst/output.js.map +7 -0
  39. package/dist/services/codefirst/types.js +17 -0
  40. package/dist/services/codefirst/types.js.map +7 -0
  41. package/dist/services/codefirst/workflow.js +581 -0
  42. package/dist/services/codefirst/workflow.js.map +7 -0
  43. package/dist/services/codefirst/workspace.js +310 -0
  44. package/dist/services/codefirst/workspace.js.map +7 -0
  45. package/dist/services/codefirst/workspaceLock.js +148 -0
  46. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  47. package/dist/services/codefirst/workspaceRoot.js +147 -0
  48. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  49. package/dist/utils/logger.js +9 -3
  50. package/dist/utils/logger.js.map +2 -2
  51. package/docs/pipeline-client-guide.md +2 -2
  52. package/docs/pipeline-reference.md +156 -99
  53. package/package.json +3 -2
  54. package/skills/pipeline-authoring/SKILL.md +10 -8
  55. package/skills/pipeline-authoring/practices.md +39 -25
@@ -0,0 +1,563 @@
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 documents_exports = {};
20
+ __export(documents_exports, {
21
+ canonicalEqual: () => canonicalEqual,
22
+ canonicalText: () => canonicalText,
23
+ documentKey: () => documentKey,
24
+ emptyState: () => emptyState,
25
+ headDocuments: () => headDocuments,
26
+ parseState: () => parseState,
27
+ peekState: () => peekState,
28
+ readByteHashes: () => readByteHashes,
29
+ serializeState: () => serializeState,
30
+ validBinarySubmissionProof: () => validBinarySubmissionProof,
31
+ validGroupedSubmissionProof: () => validGroupedSubmissionProof,
32
+ validateDocumentKeys: () => validateDocumentKeys
33
+ });
34
+ module.exports = __toCommonJS(documents_exports);
35
+ var import_crypto = require("crypto");
36
+ var import_farseer_client = require("farseer-client");
37
+ var import_layoutPaths = require("./layoutPaths");
38
+ const emptyState = (identity) => ({
39
+ ...identity,
40
+ revisionId: null,
41
+ baseline: {},
42
+ layout: {
43
+ evidence: {
44
+ groupedRoutes: [],
45
+ binaryRoutes: [],
46
+ derivedSourceProofs: [],
47
+ rawNavigationRoutes: [],
48
+ detachedFileProofs: {},
49
+ detachedDocumentProofs: {}
50
+ },
51
+ tracked: [],
52
+ receipts: {}
53
+ }
54
+ });
55
+ const quotedKeys = /* @__PURE__ */ new Map();
56
+ const QUOTED_KEY_LIMIT = 1e4;
57
+ function quotedKey(key) {
58
+ let quoted = quotedKeys.get(key);
59
+ if (quoted === void 0) {
60
+ quoted = JSON.stringify(key);
61
+ if (quotedKeys.size < QUOTED_KEY_LIMIT) quotedKeys.set(key, quoted);
62
+ }
63
+ return quoted;
64
+ }
65
+ function canonicalText(value) {
66
+ switch (typeof value) {
67
+ case "string":
68
+ return JSON.stringify(value);
69
+ case "boolean":
70
+ return value ? "true" : "false";
71
+ case "number":
72
+ if (Number.isFinite(value)) return JSON.stringify(value);
73
+ break;
74
+ case "object": {
75
+ if (value === null) return "null";
76
+ if (Array.isArray(value)) {
77
+ let text2 = "[";
78
+ for (let index = 0; index < value.length; index++) {
79
+ if (index > 0) text2 += ",";
80
+ if (index in value) text2 += canonicalText(value[index]);
81
+ }
82
+ return `${text2}]`;
83
+ }
84
+ if (Object.getPrototypeOf(value) !== Object.prototype) break;
85
+ const keys = Object.keys(value).sort();
86
+ let text = "{";
87
+ for (let index = 0; index < keys.length; index++) {
88
+ if (index > 0) text += ",";
89
+ text += `${quotedKey(keys[index])}:${canonicalText(value[keys[index]])}`;
90
+ }
91
+ return `${text}}`;
92
+ }
93
+ }
94
+ throw new Error("Expected finite plain JSON");
95
+ }
96
+ function structurallyEqual(left, right) {
97
+ if (typeof left === "string" || typeof left === "boolean") return left === right;
98
+ if (typeof left === "number") return Number.isFinite(left) ? left === right : void 0;
99
+ if (left === null) return right === null;
100
+ if (typeof left !== "object" || right === null || typeof right !== "object") return void 0;
101
+ if (Array.isArray(left)) {
102
+ if (!Array.isArray(right) || left.length !== right.length) return false;
103
+ for (let index = 0; index < left.length; index++) {
104
+ if (!(index in left) || !(index in right)) return void 0;
105
+ const equal = structurallyEqual(left[index], right[index]);
106
+ if (equal !== true) return equal;
107
+ }
108
+ return true;
109
+ }
110
+ if (Array.isArray(right) || Object.getPrototypeOf(left) !== Object.prototype) return void 0;
111
+ if (Object.getPrototypeOf(right) !== Object.prototype) return void 0;
112
+ const leftRecord = left;
113
+ const rightRecord = right;
114
+ const keys = Object.keys(leftRecord);
115
+ if (keys.length !== Object.keys(rightRecord).length) return false;
116
+ for (const key of keys) {
117
+ if (!Object.prototype.hasOwnProperty.call(rightRecord, key)) return false;
118
+ const equal = structurallyEqual(leftRecord[key], rightRecord[key]);
119
+ if (equal !== true) return equal;
120
+ }
121
+ return true;
122
+ }
123
+ function canonicalEqual(left, right) {
124
+ return structurallyEqual(left, right) === true || canonicalText(left) === canonicalText(right);
125
+ }
126
+ function parseDocument(text, file = "document") {
127
+ let value;
128
+ try {
129
+ value = JSON.parse(text);
130
+ } catch {
131
+ throw new Error(`Invalid JSON in ${file}`);
132
+ }
133
+ if (!value || typeof value !== "object" || Array.isArray(value) || ![
134
+ "folder",
135
+ "variable",
136
+ "dimension_table",
137
+ "dimension_members",
138
+ "sheet",
139
+ "dashboard",
140
+ "share",
141
+ "user_group",
142
+ "user_permissions",
143
+ "label",
144
+ "settings",
145
+ "dataset",
146
+ "file",
147
+ "export_configuration",
148
+ "remote_job"
149
+ ].includes(value.kind))
150
+ throw new Error(`Invalid model document in ${file}`);
151
+ canonicalText(value);
152
+ return value;
153
+ }
154
+ function documentKey(document, documents) {
155
+ if (document.kind !== "dimension_members")
156
+ return typeof document.id === "string" ? `${document.kind}/${document.id}` : void 0;
157
+ const owner = document.table;
158
+ if (owner && typeof owner === "object" && !Array.isArray(owner) && typeof owner.dangling === "string")
159
+ return `dimension_members/${owner.dangling}`;
160
+ const matches = documents.filter(
161
+ (d) => d.kind === "dimension_table" && d.name === owner && typeof d.id === "string"
162
+ );
163
+ const ids = [...new Set(matches.map((d) => d.id))];
164
+ return ids.length === 1 ? `dimension_members/${ids[0]}` : void 0;
165
+ }
166
+ function validateDocumentKeys(documents, keys, allowNew = false) {
167
+ if (!Array.isArray(keys) || keys.length !== documents.length || new Set(keys).size !== keys.length)
168
+ throw new Error("Document keys are missing, duplicated or not aligned with documents");
169
+ documents.forEach((document, index) => {
170
+ const key = keys[index], id = typeof key === "string" ? key.slice(key.indexOf("/") + 1) : "";
171
+ if (typeof key !== "string" || !key.startsWith(document.kind + "/") || !(/^(0|[1-9][0-9]*)$/.test(id) || allowNew && /^new:[1-9][0-9]*$/.test(id)) || document.id !== void 0 && key !== `${document.kind}/${document.id}`)
172
+ throw new Error("Document identity does not match its server key");
173
+ const derived = documentKey(document, documents);
174
+ if (derived !== void 0 && derived !== key)
175
+ throw new Error("Document identity does not match its server key");
176
+ });
177
+ }
178
+ function headDocuments(head) {
179
+ validateDocumentKeys(head.documents, head.documentKeys);
180
+ const result = /* @__PURE__ */ new Map();
181
+ for (const [index, document] of head.documents.entries()) {
182
+ const key = head.documentKeys[index];
183
+ if (!key || !head.manifest[key] || result.has(key))
184
+ throw new Error("Head document identities do not match its manifest");
185
+ result.set(key, document);
186
+ }
187
+ if (result.size !== Object.keys(head.manifest).length) throw new Error("Head manifest has missing documents");
188
+ return result;
189
+ }
190
+ function plain(value) {
191
+ return value !== null && typeof value === "object" && !Array.isArray(value);
192
+ }
193
+ function hash(value) {
194
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
195
+ }
196
+ function optionalHash(value) {
197
+ return value === void 0 || hash(value);
198
+ }
199
+ function blobContent(value) {
200
+ return plain(value) && hash(value.sha256) && Number.isSafeInteger(value.size) && Number(value.size) >= 0;
201
+ }
202
+ function workspacePath(value) {
203
+ if (typeof value !== "string") return false;
204
+ try {
205
+ (0, import_layoutPaths.parseWorkspacePointer)(value);
206
+ return true;
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+ function resource(value) {
212
+ return plain(value) && typeof value.kind === "string" && typeof value.id === "string" && /^(0|[1-9][0-9]*)$/.test(value.id);
213
+ }
214
+ function resourceReference(value) {
215
+ return plain(value) && typeof value.kind === "string" && typeof value.id === "string" && /^(0|[1-9][0-9]*|new:[1-9][0-9]*)$/.test(value.id);
216
+ }
217
+ function groupOwner(value) {
218
+ if (!plain(value) || typeof value.kind !== "string") return false;
219
+ const variants = ["id", "key", "dangling"].filter((field) => Object.prototype.hasOwnProperty.call(value, field));
220
+ if (variants.length !== 1) return false;
221
+ const selected = variants[0];
222
+ if (selected === "key") return typeof value.key === "string" && value.key.length > 0;
223
+ return typeof value[selected] === "string" && /^(0|[1-9][0-9]*)$/.test(value[selected]);
224
+ }
225
+ function selectorIdentity(value) {
226
+ if (!plain(value)) return false;
227
+ const variants = ["id", "key", "transient"].filter((field) => Object.prototype.hasOwnProperty.call(value, field));
228
+ if (variants.length !== 1) return false;
229
+ const selected = variants[0];
230
+ if (selected === "id") return typeof value.id === "string" && /^(0|[1-9][0-9]*)$/.test(value.id);
231
+ return typeof value[selected] === "string" && value[selected].length > 0;
232
+ }
233
+ function sourceIdentity(value) {
234
+ if (!plain(value) || typeof value.type !== "string") return false;
235
+ if (value.type === "transient")
236
+ return !Object.prototype.hasOwnProperty.call(value, "owner") && !Object.prototype.hasOwnProperty.call(value, "resource") && typeof value.token === "string" && value.token.length > 0;
237
+ if (value.type === "group")
238
+ return !Object.prototype.hasOwnProperty.call(value, "token") && !Object.prototype.hasOwnProperty.call(value, "resource") && groupOwner(value.owner);
239
+ if (value.type !== "resource" || !plain(value.resource) || typeof value.resource.kind !== "string") return false;
240
+ if (Object.prototype.hasOwnProperty.call(value, "token") || Object.prototype.hasOwnProperty.call(value, "owner"))
241
+ return false;
242
+ const variants = ["id", "key"].filter((field) => Object.prototype.hasOwnProperty.call(value.resource, field));
243
+ if (variants.length !== 1) return false;
244
+ return variants[0] === "id" ? typeof value.resource.id === "string" && /^(0|[1-9][0-9]*)$/.test(value.resource.id) : typeof value.resource.key === "string" && value.resource.key.length > 0;
245
+ }
246
+ function sourcePath(value) {
247
+ return Array.isArray(value) && value.every(
248
+ (part) => typeof part === "string" || typeof part === "number" && Number.isSafeInteger(part) && part >= 0
249
+ );
250
+ }
251
+ function selector(value) {
252
+ if (!plain(value) || typeof value.slot !== "string") return false;
253
+ if (value.slot === "file-entry" || value.slot === "file-share-pointer")
254
+ return typeof value.sidecar === "string" && (0, import_layoutPaths.isRawSidecarPath)(value.sidecar) && workspacePath(value.sidecar) && selectorIdentity(value.identity) && !Object.prototype.hasOwnProperty.call(value, "manifest") && !Object.prototype.hasOwnProperty.call(value, "entry");
255
+ if (value.slot === "owner-attachment")
256
+ return workspacePath(value.ownerFile) && ["icon", "template"].includes(String(value.field));
257
+ if (!workspacePath(value.file)) return false;
258
+ const valid = [
259
+ "document",
260
+ "table-definition",
261
+ "member-set",
262
+ "owner-navigation",
263
+ "share-group-owner",
264
+ "share-entry"
265
+ ].includes(value.slot);
266
+ return valid && (value.slot !== "share-entry" || selectorIdentity(value.identity));
267
+ }
268
+ function rawNavigationSelector(value) {
269
+ return plain(value) && value.slot === "file-share-pointer" && selector(value);
270
+ }
271
+ function groupedSelector(value) {
272
+ return plain(value) && ["document", "table-definition", "member-set", "owner-navigation", "share-group-owner", "share-entry"].includes(
273
+ String(value.slot)
274
+ ) && selector(value);
275
+ }
276
+ function binarySelector(value) {
277
+ return plain(value) && ["file-entry", "owner-attachment"].includes(String(value.slot)) && selector(value);
278
+ }
279
+ function transientProofSource(value, namespace) {
280
+ return plain(value) && value.type === "transient" && typeof value.token === "string" && new RegExp(`^${namespace}:[1-9][0-9]*$`).test(value.token) && !Object.prototype.hasOwnProperty.call(value, "resource") && !Object.prototype.hasOwnProperty.call(value, "owner");
281
+ }
282
+ function validGroupedSubmissionProof(value) {
283
+ const proofSelector = plain(value) && plain(value.selector) ? value.selector : void 0;
284
+ const proofSource = plain(value) && plain(value.source) ? value.source : void 0;
285
+ const identity = proofSelector && plain(proofSelector.identity) ? proofSelector.identity : void 0;
286
+ return plain(value) && transientProofSource(value.source, "submission") && groupedSelector(proofSelector) && typeof proofSelector?.slot === "string" && ["document", "table-definition", "member-set", "share-entry"].includes(proofSelector.slot) && !Object.prototype.hasOwnProperty.call(proofSelector, "sidecar") && !Object.prototype.hasOwnProperty.call(proofSelector, "ownerFile") && !Object.prototype.hasOwnProperty.call(proofSelector, "field") && (proofSelector?.slot === "share-entry" ? identity !== void 0 && Object.keys(identity).length === 1 && identity.transient === proofSource?.token : !Object.prototype.hasOwnProperty.call(proofSelector, "identity")) && sourcePath(value.sourcePath) && hash(value.fragmentHash) && hash(value.containerHash) && !Object.prototype.hasOwnProperty.call(value, "entryHash") && !Object.prototype.hasOwnProperty.call(value, "byteHash");
287
+ }
288
+ function validBinarySubmissionProof(value) {
289
+ const proofSelector = plain(value) && plain(value.selector) ? value.selector : void 0;
290
+ const proofSource = plain(value) && plain(value.source) ? value.source : void 0;
291
+ const identity = proofSelector && plain(proofSelector.identity) ? proofSelector.identity : void 0;
292
+ return plain(value) && transientProofSource(value.source, "binary-submission") && proofSelector?.slot === "file-entry" && binarySelector(proofSelector) && !Object.prototype.hasOwnProperty.call(proofSelector, "file") && !Object.prototype.hasOwnProperty.call(proofSelector, "ownerFile") && !Object.prototype.hasOwnProperty.call(proofSelector, "field") && identity !== void 0 && Object.keys(identity).length === 1 && identity.transient === proofSource?.token && sourcePath(value.sourcePath) && hash(value.entryHash) && hash(value.byteHash) && !Object.prototype.hasOwnProperty.call(value, "fragmentHash") && !Object.prototype.hasOwnProperty.call(value, "containerHash");
293
+ }
294
+ function rawNavigationSourcePath(value) {
295
+ return Array.isArray(value) && value.length === 1 && value[0] === "shares";
296
+ }
297
+ function route(value, binary) {
298
+ if (!plain(value) || !sourceIdentity(value.source) || !selector(value.selector) || !sourcePath(value.sourcePath) || !hash(value.priorCleanHash) || typeof value.contributor !== "boolean" || !optionalHash(value.derivedSelectorHash) || !optionalHash(value.entryHash) || !optionalHash(value.byteHash))
299
+ return false;
300
+ if (binary ? !binarySelector(value.selector) : !groupedSelector(value.selector)) return false;
301
+ if (binary && value.derivedSelectorHash !== void 0) return false;
302
+ if (!binary && (value.bytes !== void 0 || value.entryHash !== void 0 || value.byteHash !== void 0))
303
+ return false;
304
+ if (binary && plain(value.selector) && value.selector.slot === "file-entry")
305
+ return value.bytes === void 0 || workspacePath(value.bytes);
306
+ if (binary && plain(value.selector) && value.selector.slot === "owner-attachment")
307
+ return value.bytes === void 0 || workspacePath(value.bytes);
308
+ return true;
309
+ }
310
+ function detachedProofMap(value) {
311
+ if (!plain(value)) return false;
312
+ return Object.entries(value).every(([file, proof]) => {
313
+ if (!workspacePath(file) || !plain(proof) || typeof proof.sourceKey !== "string") return false;
314
+ if (proof.reason === "damage-proof") return hash(proof.placementHash) && hash(proof.baselineHash);
315
+ if (proof.reason !== "representation-fallback") return false;
316
+ if (plain(proof.inheritedFrom))
317
+ return proof.request === void 0 && proof.existingClaims === void 0 && typeof proof.inheritedFrom.sourceKey === "string" && hash(proof.inheritedFrom.semanticPathHash);
318
+ if (!plain(proof.request) || !Array.isArray(proof.existingClaims)) return false;
319
+ const requestValid = (proof.request.directory === "" || workspacePath(proof.request.directory)) && typeof proof.request.name === "string" && (proof.request.extension === void 0 || typeof proof.request.extension === "string") && (proof.request.kind === void 0 || ["file", "directory"].includes(String(proof.request.kind))) && ["directory", "raw", "attachment", "document"].includes(String(proof.request.role)) && typeof proof.request.identity === "string" && (proof.request.requiredChildren === void 0 || Array.isArray(proof.request.requiredChildren) && proof.request.requiredChildren.every((child) => child === "_folder.json"));
320
+ return requestValid && proof.existingClaims.every(
321
+ (claim) => plain(claim) && workspacePath(claim.path) && ["file", "directory"].includes(String(claim.kind)) && ["control", "directory", "raw", "attachment", "document"].includes(String(claim.role)) && typeof claim.identity === "string"
322
+ );
323
+ });
324
+ }
325
+ function observation(value, binary) {
326
+ if (!plain(value) || !sourceIdentity(value.source) || !selector(value.selector) || !sourcePath(value.sourcePath) || !["clean", "dirty", "absent", "new", "present-unclassified"].includes(String(value.state)) || typeof value.contributor !== "boolean" || !optionalHash(value.currentHash) || !optionalHash(value.priorCleanHash) || !optionalHash(value.derivedSelectorHash))
327
+ return false;
328
+ if (binary ? !binarySelector(value.selector) : !groupedSelector(value.selector)) return false;
329
+ return !binary || (value.bytes === void 0 || workspacePath(value.bytes)) && optionalHash(value.entryHash) && optionalHash(value.byteHash);
330
+ }
331
+ function groupedNavigation(value) {
332
+ return plain(value) && sourceIdentity(value.source) && selector(value.selector) && plain(value.selector) && value.selector.slot === "owner-navigation" && sourcePath(value.sourcePath) && workspacePath(value.groupFile) && groupOwner(value.owner);
333
+ }
334
+ function ownerField(value) {
335
+ return plain(value) && sourceIdentity(value.ownerSource) && workspacePath(value.ownerFile) && ["icon", "template"].includes(String(value.field)) && Array.isArray(value.sourcePath) && value.sourcePath.length === 1 && value.sourcePath[0] === value.field && ["value", "omitted", "invalid"].includes(String(value.status)) && (value.value === void 0 || value.value === null || blobContent(value.value)) && (value.bytes === void 0 || workspacePath(value.bytes)) && optionalHash(value.currentHash) && optionalHash(value.priorCleanHash) && (value.state === void 0 || ["clean", "dirty", "absent", "new", "present-unclassified"].includes(String(value.state)));
336
+ }
337
+ function rawNavigationObservation(value) {
338
+ return plain(value) && sourceIdentity(value.source) && plain(value.source) && value.source.type === "resource" && rawNavigationSelector(value.selector) && rawNavigationSourcePath(value.sourcePath) && (value.groupFile === void 0 || workspacePath(value.groupFile)) && optionalHash(value.currentHash) && optionalHash(value.priorCleanHash) && ["clean", "dirty", "absent", "new"].includes(String(value.state));
339
+ }
340
+ function persistedLayoutEvidence(value) {
341
+ if (!plain(value)) return false;
342
+ const groupedRoutes = value.groupedRoutes;
343
+ const binaryRoutes = value.binaryRoutes;
344
+ const derived = value.derivedSourceProofs;
345
+ const rawNavigation = value.rawNavigationRoutes;
346
+ return Array.isArray(groupedRoutes) && groupedRoutes.every((item) => route(item, false)) && Array.isArray(binaryRoutes) && binaryRoutes.every((item) => route(item, true)) && Array.isArray(derived) && derived.every(
347
+ (item) => plain(item) && sourceIdentity(item.source) && plain(item.source) && item.source.type === "resource" && plain(item.source.resource) && item.source.resource.kind === "user_permissions" && typeof item.source.resource.id === "string" && hash(item.selectorHash)
348
+ ) && Array.isArray(rawNavigation) && rawNavigation.every(
349
+ (item) => plain(item) && sourceIdentity(item.source) && plain(item.source) && item.source.type === "resource" && rawNavigationSelector(item.selector) && rawNavigationSourcePath(item.sourcePath) && workspacePath(item.groupFile) && hash(item.priorCleanHash)
350
+ ) && detachedProofMap(value.detachedFileProofs) && detachedProofMap(value.detachedDocumentProofs);
351
+ }
352
+ const enumValue = (values, value) => Object.values(values).includes(value);
353
+ function receiptValue(value) {
354
+ if (!plain(value) || typeof value.revisionId !== "string" || !enumValue(import_farseer_client.ReceiptStatusEnum, value.status) || !plain(value.assignments) || !plain(value.outcomes) || !plain(value.baseline) || !plain(value.baseline.set) || !Array.isArray(value.baseline.deleted))
355
+ return false;
356
+ return (value.warnings === void 0 || Array.isArray(value.warnings) && value.warnings.every(
357
+ (warning) => plain(warning) && typeof warning.key === "string" && typeof warning.code === "string" && typeof warning.message === "string"
358
+ )) && Object.values(value.assignments).every(resource) && Object.values(value.outcomes).every((outcome) => {
359
+ if (!plain(outcome) || !enumValue(import_farseer_client.OperationOutcomeOutcomeEnum, outcome.outcome)) return false;
360
+ if (outcome.error !== void 0 && (!plain(outcome.error) || typeof outcome.error.message !== "string" || outcome.error.code !== void 0 && typeof outcome.error.code !== "string"))
361
+ return false;
362
+ if (outcome.reason !== void 0 && !enumValue(import_farseer_client.OperationOutcomeReasonEnum, outcome.reason)) return false;
363
+ return outcome.blockedBy === void 0 || Array.isArray(outcome.blockedBy) && outcome.blockedBy.every(resourceReference);
364
+ }) && Object.values(value.baseline.set).every(hash) && value.baseline.deleted.every((key) => typeof key === "string");
365
+ }
366
+ function layoutSubmission(value, planId) {
367
+ if (!plain(value) || value.planId !== planId || !Array.isArray(value.documentKeys) || !value.documentKeys.every((key) => typeof key === "string") || new Set(value.documentKeys).size !== value.documentKeys.length || !Array.isArray(value.operations) || !plain(value.handles) || !plain(value.composition))
368
+ return false;
369
+ const composition = value.composition;
370
+ const arrays = [
371
+ composition.documents,
372
+ composition.sources,
373
+ composition.groupedObservations,
374
+ composition.groupedNavigation,
375
+ composition.rawObservations,
376
+ composition.ownerFields,
377
+ composition.attachmentObservations,
378
+ composition.rawNavigation
379
+ ];
380
+ if (!arrays.every(Array.isArray) || value.documentKeys.length !== composition.documents.length)
381
+ return false;
382
+ try {
383
+ for (const document of composition.documents) parseDocument(JSON.stringify(document));
384
+ } catch {
385
+ return false;
386
+ }
387
+ if (!composition.sources.every(
388
+ (item) => plain(item) && ["grouped", "raw"].includes(String(item.codec)) && plain(item.mapping) && Number.isInteger(item.mapping.documentIndex) && Number(item.mapping.documentIndex) >= 0 && Number(item.mapping.documentIndex) < composition.documents.length && sourceIdentity(item.mapping.source) && plain(item.mapping.selector) && sourcePath(item.mapping.sourcePath) && (item.mapping.derivedSelectorHash === void 0 || hash(item.mapping.derivedSelectorHash)) && (item.mapping.groupOwner === void 0 || groupOwner(item.mapping.groupOwner)) && (item.mapping.ownerDocument === void 0 || plain(item.mapping.ownerDocument) && workspacePath(item.mapping.ownerDocument.file) && typeof item.mapping.ownerDocument.kind === "string" && (item.mapping.ownerDocument.folderLength === void 0 || Number.isSafeInteger(item.mapping.ownerDocument.folderLength) && Number(item.mapping.ownerDocument.folderLength) >= 0)) && (item.mapping.externalOwnerLocation === void 0 || plain(item.mapping.externalOwnerLocation) && workspacePath(item.mapping.externalOwnerLocation.file) && sourcePath(item.mapping.externalOwnerLocation.path)) && (item.mapping.wireOwner === void 0 || plain(item.mapping.wireOwner)) && (item.codec === "raw" ? binarySelector(item.mapping.selector) && item.mapping.selector.slot === "file-entry" && workspacePath(item.mapping.bytes) && typeof item.mapping.detached === "boolean" && typeof item.mapping.nameOverride === "boolean" : groupedSelector(item.mapping.selector))
389
+ ) || !composition.groupedObservations.every((item) => observation(item, false)) || !composition.groupedNavigation.every(groupedNavigation) || !composition.rawObservations.every(
390
+ (item) => observation(item, true) && plain(item) && plain(item.selector) && item.selector.slot === "file-entry"
391
+ ) || !composition.ownerFields.every(ownerField) || !composition.attachmentObservations.every(
392
+ (item) => observation(item, true) && plain(item) && plain(item.selector) && item.selector.slot === "owner-attachment"
393
+ ) || !composition.rawNavigation.every(rawNavigationObservation) || composition.groupedSubmissions !== void 0 && (!Array.isArray(composition.groupedSubmissions) || !composition.groupedSubmissions.every(validGroupedSubmissionProof)) || composition.binarySubmissions !== void 0 && (!Array.isArray(composition.binarySubmissions) || !composition.binarySubmissions.every(validBinarySubmissionProof)))
394
+ return false;
395
+ return value.operations.every(
396
+ (item) => plain(item) && enumValue(import_farseer_client.PlanOperationActionEnum, item.action) && typeof item.kind === "string" && typeof item.name === "string" && (item.key === void 0 || typeof item.key === "string") && (item.handle === void 0 || typeof item.handle === "string") && (item.reason === void 0 || typeof item.reason === "string") && (item.by === void 0 || Array.isArray(item.by) && item.by.every(resourceReference)) && (item.inducedBy === void 0 || resourceReference(item.inducedBy)) && Array.isArray(item.fieldDiff) && item.fieldDiff.every(
397
+ (diff) => plain(diff) && Array.isArray(diff.path) && diff.path.every((part) => typeof part === "string") && "before" in diff && "after" in diff
398
+ )
399
+ ) && Object.values(value.handles).every(
400
+ (item) => plain(item) && typeof item.kind === "string" && Number.isInteger(item.documentIndex) && Number(item.documentIndex) >= 0 && Number(item.documentIndex) < composition.documents.length && sourcePath(item.path)
401
+ );
402
+ }
403
+ function validateLayoutStateQuarantiningDrafts(state) {
404
+ const layout = state.layout;
405
+ if (!plain(layout) || !persistedLayoutEvidence(layout.evidence) || !Array.isArray(layout.tracked) || !plain(layout.receipts))
406
+ throw new Error("Invalid layout workspace state");
407
+ const routes = /* @__PURE__ */ new Set();
408
+ for (const tracked of layout.tracked) {
409
+ if (!plain(tracked) || typeof tracked.route !== "string" || tracked.route.length === 0 || routes.has(tracked.route) || !workspacePath(tracked.path) || !["file", "directory"].includes(String(tracked.kind)) || !["folder-control", "raw-metadata", "document", "raw", "attachment"].includes(String(tracked.role)))
410
+ throw new Error("Invalid tracked layout path");
411
+ routes.add(tracked.route);
412
+ }
413
+ if (layout.unreadableReceipts !== void 0 && !plain(layout.unreadableReceipts))
414
+ throw new Error("Invalid layout workspace state");
415
+ const readable = {};
416
+ const unreadable = { ...layout.unreadableReceipts ?? {} };
417
+ for (const [planId, draft] of Object.entries(layout.receipts)) {
418
+ if (plain(draft) && layoutSubmission(draft.submission, planId) && (draft.applying === void 0 || typeof draft.applying === "boolean") && (draft.unanswered === void 0 || typeof draft.unanswered === "boolean") && (draft.revisionId === void 0 || typeof draft.revisionId === "string") && (draft.receipt === void 0 || receiptValue(draft.receipt))) {
419
+ readable[planId] = draft;
420
+ continue;
421
+ }
422
+ unreadable[planId] = draft;
423
+ }
424
+ state.layout.receipts = readable;
425
+ if (Object.keys(unreadable).length > 0) state.layout.unreadableReceipts = unreadable;
426
+ const byteHashes = readByteHashes(layout.byteHashes);
427
+ if (byteHashes) state.layout.byteHashes = byteHashes;
428
+ else delete state.layout.byteHashes;
429
+ }
430
+ const RETIRED_SIDECAR_STATE = "This workspace was pulled before the .meta sidecar layout; delete the workspace directory, then run farseer code checkout <tenant>";
431
+ function retiredBinarySelector(value) {
432
+ if (Array.isArray(value)) return value.some(retiredBinarySelector);
433
+ if (!plain(value)) return false;
434
+ if ((value.slot === "file-entry" || value.slot === "file-share-pointer") && Object.prototype.hasOwnProperty.call(value, "manifest") && !Object.prototype.hasOwnProperty.call(value, "sidecar"))
435
+ return true;
436
+ return Object.values(value).some(retiredBinarySelector);
437
+ }
438
+ function retiredLayoutState(layout) {
439
+ if (!plain(layout)) return false;
440
+ if (Array.isArray(layout.tracked) && layout.tracked.some((item) => plain(item) && item.role === "file-manifest"))
441
+ return true;
442
+ return retiredBinarySelector(layout.evidence) || retiredBinarySelector(layout.receipts);
443
+ }
444
+ const RETIRED_STATE = "This workspace uses the retired prototype layout; delete the workspace directory, then run farseer code checkout <tenant>";
445
+ const identityName = (value) => typeof value === "string" && value.length > 0;
446
+ const UNPINNED_STATE = "This workspace does not record the server it was checked out from; delete the workspace directory, then run farseer code checkout <tenant>";
447
+ function internDraftDocuments(layout) {
448
+ const objects = {};
449
+ const receipts = Object.fromEntries(
450
+ Object.entries(layout.receipts ?? {}).map(([planId, draft]) => {
451
+ const submission = draft.submission;
452
+ const composition = submission?.composition;
453
+ if (!composition || !Array.isArray(composition.documents)) return [planId, draft];
454
+ const documentHashes = composition.documents.map((document) => {
455
+ const hash2 = (0, import_crypto.createHash)("sha256").update(canonicalText(document)).digest("hex");
456
+ objects[hash2] = document;
457
+ return hash2;
458
+ });
459
+ const { documents: _documents, ...rest } = composition;
460
+ return [planId, { ...draft, submission: { ...submission, composition: { ...rest, documentHashes } } }];
461
+ })
462
+ );
463
+ return { ...layout, receipts, objects };
464
+ }
465
+ function resolveDraftDocuments(layout) {
466
+ const objects = plain(layout.objects) ? layout.objects : {};
467
+ delete layout.objects;
468
+ if (!plain(layout.receipts)) return;
469
+ for (const draft of Object.values(layout.receipts)) {
470
+ if (!plain(draft) || !plain(draft.submission) || !plain(draft.submission.composition)) continue;
471
+ const composition = draft.submission.composition;
472
+ if (!Array.isArray(composition.documentHashes)) continue;
473
+ const documents = composition.documentHashes.map(
474
+ (hash2) => typeof hash2 === "string" && Object.prototype.hasOwnProperty.call(objects, hash2) ? objects[hash2] : void 0
475
+ );
476
+ delete composition.documentHashes;
477
+ if (documents.every((document) => document !== void 0)) composition.documents = documents;
478
+ }
479
+ }
480
+ function validEntry(value) {
481
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
482
+ const entry = value;
483
+ return typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256) && Number.isSafeInteger(entry.size) && entry.size >= 0 && typeof entry.mtimeNs === "string" && /^[0-9]+$/.test(entry.mtimeNs) && typeof entry.ctimeNs === "string" && /^[0-9]+$/.test(entry.ctimeNs) && typeof entry.ino === "string" && /^[0-9]+$/.test(entry.ino);
484
+ }
485
+ function readByteHashes(value) {
486
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
487
+ const entries = Object.entries(value).filter(
488
+ (pair) => validEntry(pair[1])
489
+ );
490
+ return entries.length ? Object.fromEntries(entries) : void 0;
491
+ }
492
+ const PARSED_STATE_CACHE_SIZE = 4;
493
+ const parsedStates = /* @__PURE__ */ new Map();
494
+ function copyState(value, copies = /* @__PURE__ */ new Map()) {
495
+ if (value === null || typeof value !== "object") return value;
496
+ const known = copies.get(value);
497
+ if (known !== void 0) return known;
498
+ if (Array.isArray(value)) {
499
+ const copy2 = new Array(value.length);
500
+ copies.set(value, copy2);
501
+ for (let index = 0; index < value.length; index++) copy2[index] = copyState(value[index], copies);
502
+ return copy2;
503
+ }
504
+ const copy = {};
505
+ copies.set(value, copy);
506
+ for (const key of Object.keys(value)) {
507
+ const item = copyState(value[key], copies);
508
+ if (key === "__proto__")
509
+ Object.defineProperty(copy, key, { value: item, enumerable: true, writable: true, configurable: true });
510
+ else copy[key] = item;
511
+ }
512
+ return copy;
513
+ }
514
+ function peekState(text) {
515
+ const cached = parsedStates.get(text);
516
+ if (cached) {
517
+ parsedStates.delete(text);
518
+ parsedStates.set(text, cached);
519
+ return cached;
520
+ }
521
+ const state = parseStateText(text);
522
+ parsedStates.set(text, state);
523
+ if (parsedStates.size > PARSED_STATE_CACHE_SIZE) parsedStates.delete(parsedStates.keys().next().value);
524
+ return state;
525
+ }
526
+ function parseState(text) {
527
+ return copyState(peekState(text));
528
+ }
529
+ function parseStateText(text) {
530
+ const value = JSON.parse(text);
531
+ if (!plain(value)) throw new Error("Invalid code-first state file");
532
+ if (plain(value.layout)) resolveDraftDocuments(value.layout);
533
+ for (const retired of ["documents", "documentHashes", "fileContents", "documentKeys", "receipts"])
534
+ if (Object.prototype.hasOwnProperty.call(value, retired)) throw new Error(RETIRED_STATE);
535
+ if (!plain(value.layout)) throw new Error(RETIRED_STATE);
536
+ if (retiredLayoutState(value.layout)) throw new Error(RETIRED_SIDECAR_STATE);
537
+ if (!identityName(value.tenant) || !identityName(value.organisation)) throw new Error(RETIRED_STATE);
538
+ if (typeof value.baseUrl !== "string" || !/^https?:\/\/\S+$/.test(value.baseUrl)) throw new Error(UNPINNED_STATE);
539
+ if (!plain(value.baseline) || value.revisionId !== null && typeof value.revisionId !== "string")
540
+ throw new Error("Invalid code-first state file");
541
+ for (const hashValue of Object.values(value.baseline))
542
+ if (!hash(hashValue)) throw new Error("Invalid code-first baseline");
543
+ const state = value;
544
+ validateLayoutStateQuarantiningDrafts(state);
545
+ return state;
546
+ }
547
+ const serializeState = (state) => JSON.stringify({ ...state, layout: internDraftDocuments(state.layout) }) + "\n";
548
+ // Annotate the CommonJS export names for ESM import in node:
549
+ 0 && (module.exports = {
550
+ canonicalEqual,
551
+ canonicalText,
552
+ documentKey,
553
+ emptyState,
554
+ headDocuments,
555
+ parseState,
556
+ peekState,
557
+ readByteHashes,
558
+ serializeState,
559
+ validBinarySubmissionProof,
560
+ validGroupedSubmissionProof,
561
+ validateDocumentKeys
562
+ });
563
+ //# sourceMappingURL=documents.js.map