@firstdraft.com/cli 0.1.0-alpha.2

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.
@@ -0,0 +1,717 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ mkdtempSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import path from "node:path";
14
+
15
+ import { isFileSystemError } from "./file-system.js";
16
+ import { isUuidV7 } from "./plan-state.js";
17
+
18
+ export const ARTIFACT_MEDIA_TYPE =
19
+ "application/vnd.firstdraft.compilation-artifact+json";
20
+ export const ARTIFACT_FORMAT = "firstdraft.compilation-artifact/1";
21
+ export const FOUNDATION_PLAN_FORMAT = "firstdraft.foundation-plan.sketch/0.19";
22
+ export const MAX_ARTIFACT_BYTES = 16 * 1024 * 1024;
23
+
24
+ const ARTIFACT_KEYS = ["format", "provenance", "manifest_sha256", "files"];
25
+ const PROVENANCE_KEYS = [
26
+ "compilation_id",
27
+ "project_id",
28
+ "graph_version",
29
+ "head_source_sha256",
30
+ "foundation_plan",
31
+ "analysis",
32
+ "compiler_release",
33
+ "target",
34
+ "core",
35
+ ];
36
+ const FOUNDATION_PLAN_KEYS = ["format", "sha256"];
37
+ const ANALYSIS_KEYS = ["id", "release"];
38
+ const TARGET_KEYS = ["id", "profile"];
39
+ const CORE_KEYS = ["repository", "revision", "sha256"];
40
+ const FILE_KEYS = [
41
+ "path",
42
+ "sha256",
43
+ "mode",
44
+ "owner",
45
+ "source_subject_uuids",
46
+ "contents_base64",
47
+ ];
48
+ const SHA1_PATTERN = /^[0-9a-f]{40}$/;
49
+ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
50
+ const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
51
+ const REPOSITORY_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
52
+ const OWNER_PATTERN = /^[A-Za-z][A-Za-z0-9_.:-]*$/;
53
+ const COMPONENT_PATTERN = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/;
54
+ const WINDOWS_DEVICE_PATTERN = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
55
+ const STRICT_BASE64_PATTERN =
56
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
57
+ const MAX_PATH_BYTES = 1_024;
58
+ const MAX_COMPONENT_BYTES = 255;
59
+ const MAX_IDENTIFIER_BYTES = 256;
60
+ const DIRECTORY_MODE = 0o755;
61
+ const POSIX_MODE_BITS_SUPPORTED = process.platform !== "win32";
62
+
63
+ export class CompilationArtifactInvalidError extends Error {}
64
+ export class CompilationMaterializationError extends Error {}
65
+ export class CompilationOutputPathError extends Error {}
66
+
67
+ /**
68
+ * @typedef {object} ValidatedCompilationProvenance
69
+ * @property {string} compilation_id
70
+ * @property {string} project_id
71
+ * @property {number} graph_version
72
+ * @property {string} head_source_sha256
73
+ * @property {{format: string, sha256: string}} foundation_plan
74
+ * @property {{id: string, release: string}} analysis
75
+ * @property {string} compiler_release
76
+ * @property {{id: string, profile: string}} target
77
+ * @property {{repository: string, revision: string, sha256: string}} core
78
+ */
79
+
80
+ /**
81
+ * @typedef {object} CompilationArtifactExpectations
82
+ * @property {string} projectId
83
+ * @property {string} compilationId
84
+ * @property {number} graphVersion
85
+ * @property {string} headSourceSha256
86
+ * @property {string} analysisRunId
87
+ * @property {string} compilerRelease
88
+ * @property {{id: string, profile: string}} target
89
+ */
90
+
91
+ /**
92
+ * @typedef {object} ValidatedArtifactFile
93
+ * @property {string} path
94
+ * @property {string} sha256
95
+ * @property {420 | 493} mode
96
+ * @property {string} owner
97
+ * @property {string[]} source_subject_uuids
98
+ * @property {Buffer} contents
99
+ */
100
+
101
+ /**
102
+ * @typedef {object} ValidatedCompilationArtifact
103
+ * @property {string} manifest_sha256
104
+ * @property {ValidatedCompilationProvenance} provenance
105
+ * @property {ValidatedArtifactFile[]} files
106
+ */
107
+
108
+ /**
109
+ * @param {Buffer} source
110
+ * @param {CompilationArtifactExpectations} expected
111
+ * @returns {ValidatedCompilationArtifact}
112
+ */
113
+ export function parseCompilationArtifact(source, expected) {
114
+ let text;
115
+ let parsed;
116
+
117
+ try {
118
+ text = new TextDecoder("utf-8", { fatal: true }).decode(source);
119
+ parsed = JSON.parse(text);
120
+ } catch (error) {
121
+ if (!(error instanceof SyntaxError || error instanceof TypeError)) {
122
+ throw error;
123
+ }
124
+
125
+ throw new CompilationArtifactInvalidError(
126
+ "The compilation artifact is not valid UTF-8 JSON.",
127
+ { cause: error },
128
+ );
129
+ }
130
+
131
+ if (
132
+ !Buffer.from(JSON.stringify(parsed), "utf8").equals(source) ||
133
+ !hasExactKeys(parsed, ARTIFACT_KEYS) ||
134
+ parsed.format !== ARTIFACT_FORMAT ||
135
+ typeof parsed.manifest_sha256 !== "string" ||
136
+ !SHA256_PATTERN.test(parsed.manifest_sha256) ||
137
+ !Array.isArray(parsed.files)
138
+ ) {
139
+ throw new CompilationArtifactInvalidError(
140
+ "The compilation artifact envelope is invalid.",
141
+ );
142
+ }
143
+
144
+ const manifestSha256 = /** @type {string} */ (parsed.manifest_sha256);
145
+ const provenance = parseProvenance(parsed.provenance, expected);
146
+ const files = parsed.files.map(parseArtifactFile);
147
+ validateManifest(files, manifestSha256);
148
+
149
+ return {
150
+ manifest_sha256: manifestSha256,
151
+ provenance,
152
+ files,
153
+ };
154
+ }
155
+
156
+ /**
157
+ * @param {object} options
158
+ * @param {string} options.cwd
159
+ * @param {string} options.output
160
+ */
161
+ export function resolveOutputTarget({ cwd, output }) {
162
+ if (
163
+ typeof output !== "string" ||
164
+ output.length === 0 ||
165
+ output.includes("\0")
166
+ ) {
167
+ throw new CompilationOutputPathError(
168
+ "The compilation output path is invalid.",
169
+ );
170
+ }
171
+
172
+ const target = path.resolve(cwd, output);
173
+ const parent = path.dirname(target);
174
+ if (
175
+ target === parent ||
176
+ path.basename(target).length === 0 ||
177
+ !isInitiallyAbsent(target)
178
+ ) {
179
+ throw new CompilationOutputPathError(
180
+ "The compilation output path must be absent.",
181
+ );
182
+ }
183
+
184
+ let parentStat;
185
+ try {
186
+ parentStat = lstatSync(parent);
187
+ } catch (error) {
188
+ if (!isFileSystemError(error)) throw error;
189
+
190
+ throw new CompilationOutputPathError(
191
+ "The compilation output parent could not be read.",
192
+ { cause: error },
193
+ );
194
+ }
195
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
196
+ throw new CompilationOutputPathError(
197
+ "The compilation output parent must be a real directory.",
198
+ );
199
+ }
200
+
201
+ return target;
202
+ }
203
+
204
+ /**
205
+ * @param {ValidatedCompilationArtifact} artifact
206
+ * @param {string} target
207
+ */
208
+ export function materializeCompilationArtifact(artifact, target) {
209
+ const parent = path.dirname(target);
210
+ const prefix = path.join(parent, `.firstdraft-${path.basename(target)}-`);
211
+ let temporaryDirectory = null;
212
+
213
+ try {
214
+ assertTargetStillAvailable(target, parent);
215
+ temporaryDirectory = mkdtempSync(prefix);
216
+ assertOwnedTemporaryDirectory(temporaryDirectory, parent, prefix);
217
+
218
+ writeArtifactTree(artifact.files, temporaryDirectory);
219
+ applyMode(temporaryDirectory, DIRECTORY_MODE);
220
+ verifyArtifactTree(artifact.files, temporaryDirectory);
221
+ assertTargetStillAvailable(target, parent);
222
+ renameSync(temporaryDirectory, target);
223
+ temporaryDirectory = null;
224
+ } catch (error) {
225
+ if (
226
+ error instanceof CompilationMaterializationError ||
227
+ isFileSystemError(error)
228
+ ) {
229
+ throw new CompilationMaterializationError(
230
+ "The compilation artifact could not be materialized.",
231
+ { cause: error },
232
+ );
233
+ }
234
+
235
+ throw error;
236
+ } finally {
237
+ if (temporaryDirectory !== null) {
238
+ removeOwnedTemporaryDirectory(temporaryDirectory, parent, prefix);
239
+ }
240
+ }
241
+
242
+ return {
243
+ path: target,
244
+ file_count: artifact.files.length,
245
+ manifest_sha256: artifact.manifest_sha256,
246
+ };
247
+ }
248
+
249
+ /**
250
+ * @param {unknown} value
251
+ * @param {CompilationArtifactExpectations} expected
252
+ * @returns {ValidatedCompilationProvenance}
253
+ */
254
+ function parseProvenance(value, expected) {
255
+ // The outer artifact digest authenticates the canonical Plan digest, which
256
+ // need not equal the digest of the exact submitted Head bytes.
257
+ if (
258
+ !hasExactKeys(value, PROVENANCE_KEYS) ||
259
+ value.compilation_id !== expected.compilationId ||
260
+ value.project_id !== expected.projectId ||
261
+ value.graph_version !== expected.graphVersion ||
262
+ value.head_source_sha256 !== expected.headSourceSha256 ||
263
+ !hasExactKeys(value.foundation_plan, FOUNDATION_PLAN_KEYS) ||
264
+ value.foundation_plan.format !== FOUNDATION_PLAN_FORMAT ||
265
+ typeof value.foundation_plan.sha256 !== "string" ||
266
+ !SHA256_PATTERN.test(value.foundation_plan.sha256) ||
267
+ !hasExactKeys(value.analysis, ANALYSIS_KEYS) ||
268
+ value.analysis.id !== expected.analysisRunId ||
269
+ !isRelease(value.analysis.release) ||
270
+ value.compiler_release !== expected.compilerRelease ||
271
+ !hasExactKeys(value.target, TARGET_KEYS) ||
272
+ value.target.id !== expected.target.id ||
273
+ value.target.profile !== expected.target.profile ||
274
+ !hasExactKeys(value.core, CORE_KEYS) ||
275
+ !isRepository(value.core.repository) ||
276
+ typeof value.core.revision !== "string" ||
277
+ !SHA1_PATTERN.test(value.core.revision) ||
278
+ typeof value.core.sha256 !== "string" ||
279
+ !SHA256_PATTERN.test(value.core.sha256)
280
+ ) {
281
+ throw new CompilationArtifactInvalidError(
282
+ "The compilation artifact provenance is invalid.",
283
+ );
284
+ }
285
+
286
+ return {
287
+ compilation_id: /** @type {string} */ (value.compilation_id),
288
+ project_id: /** @type {string} */ (value.project_id),
289
+ graph_version: /** @type {number} */ (value.graph_version),
290
+ head_source_sha256: /** @type {string} */ (value.head_source_sha256),
291
+ foundation_plan: {
292
+ format: /** @type {string} */ (value.foundation_plan.format),
293
+ sha256: /** @type {string} */ (value.foundation_plan.sha256),
294
+ },
295
+ analysis: {
296
+ id: /** @type {string} */ (value.analysis.id),
297
+ release: /** @type {string} */ (value.analysis.release),
298
+ },
299
+ compiler_release: /** @type {string} */ (value.compiler_release),
300
+ target: {
301
+ id: /** @type {string} */ (value.target.id),
302
+ profile: /** @type {string} */ (value.target.profile),
303
+ },
304
+ core: {
305
+ repository: /** @type {string} */ (value.core.repository),
306
+ revision: /** @type {string} */ (value.core.revision),
307
+ sha256: /** @type {string} */ (value.core.sha256),
308
+ },
309
+ };
310
+ }
311
+
312
+ /**
313
+ * @param {unknown} value
314
+ * @param {number} index
315
+ * @returns {ValidatedArtifactFile}
316
+ */
317
+ function parseArtifactFile(value, index) {
318
+ if (
319
+ !hasExactKeys(value, FILE_KEYS) ||
320
+ !isArtifactPath(value.path) ||
321
+ typeof value.sha256 !== "string" ||
322
+ !SHA256_PATTERN.test(value.sha256) ||
323
+ (value.mode !== 0o644 && value.mode !== 0o755) ||
324
+ !isOwner(value.owner) ||
325
+ !isSourceSubjectUuids(value.source_subject_uuids) ||
326
+ typeof value.contents_base64 !== "string" ||
327
+ !STRICT_BASE64_PATTERN.test(value.contents_base64)
328
+ ) {
329
+ throw new CompilationArtifactInvalidError(
330
+ `Compilation artifact file ${index} is invalid.`,
331
+ );
332
+ }
333
+
334
+ const pathValue = /** @type {string} */ (value.path);
335
+ const digest = /** @type {string} */ (value.sha256);
336
+ const mode = /** @type {420 | 493} */ (value.mode);
337
+ const owner = /** @type {string} */ (value.owner);
338
+ const sourceSubjectUuids = /** @type {string[]} */ (
339
+ value.source_subject_uuids
340
+ );
341
+ const contentsBase64 = /** @type {string} */ (value.contents_base64);
342
+ const contents = Buffer.from(contentsBase64, "base64");
343
+ if (
344
+ contents.toString("base64") !== contentsBase64 ||
345
+ sha256(contents) !== digest
346
+ ) {
347
+ throw new CompilationArtifactInvalidError(
348
+ `Compilation artifact file ${index} has invalid contents.`,
349
+ );
350
+ }
351
+
352
+ return {
353
+ path: pathValue,
354
+ sha256: digest,
355
+ mode,
356
+ owner,
357
+ source_subject_uuids: [...sourceSubjectUuids],
358
+ contents,
359
+ };
360
+ }
361
+
362
+ /**
363
+ * @param {ValidatedArtifactFile[]} files
364
+ * @param {string} expectedManifestSha256
365
+ */
366
+ function validateManifest(files, expectedManifestSha256) {
367
+ const claims = new Map();
368
+ let previousPath = null;
369
+
370
+ for (const file of files) {
371
+ if (previousPath !== null && file.path <= previousPath) {
372
+ throw new CompilationArtifactInvalidError(
373
+ "Compilation artifact files are not in manifest order.",
374
+ );
375
+ }
376
+ previousPath = file.path;
377
+
378
+ const components = file.path.split("/");
379
+ for (let index = 0; index < components.length; index += 1) {
380
+ const spelling = components.slice(0, index + 1).join("/");
381
+ const collisionKey = spelling.toLowerCase();
382
+ const kind = index === components.length - 1 ? "file" : "directory";
383
+ const existing = claims.get(collisionKey);
384
+ if (
385
+ existing !== undefined &&
386
+ (existing.kind === "file" ||
387
+ kind === "file" ||
388
+ existing.spelling !== spelling)
389
+ ) {
390
+ throw new CompilationArtifactInvalidError(
391
+ "Compilation artifact paths conflict.",
392
+ );
393
+ }
394
+ claims.set(collisionKey, { spelling, kind });
395
+ }
396
+ }
397
+
398
+ const metadata = files.map((file) => ({
399
+ path: file.path,
400
+ sha256: file.sha256,
401
+ mode: file.mode,
402
+ owner: file.owner,
403
+ source_subject_uuids: file.source_subject_uuids,
404
+ }));
405
+ const manifestSha256 = sha256(
406
+ Buffer.from(JSON.stringify({ files: metadata }), "utf8"),
407
+ );
408
+ if (manifestSha256 !== expectedManifestSha256) {
409
+ throw new CompilationArtifactInvalidError(
410
+ "The compilation artifact manifest digest is invalid.",
411
+ );
412
+ }
413
+ }
414
+
415
+ /** @param {unknown} value @returns {value is string} */
416
+ function isArtifactPath(value) {
417
+ if (
418
+ typeof value !== "string" ||
419
+ !isAscii(value) ||
420
+ Buffer.byteLength(value) === 0 ||
421
+ Buffer.byteLength(value) > MAX_PATH_BYTES
422
+ ) {
423
+ return false;
424
+ }
425
+
426
+ const components = value.split("/");
427
+ return components.every((component) => {
428
+ if (
429
+ component.length === 0 ||
430
+ component === "." ||
431
+ component === ".." ||
432
+ Buffer.byteLength(component) > MAX_COMPONENT_BYTES ||
433
+ !COMPONENT_PATTERN.test(component) ||
434
+ component.endsWith(".") ||
435
+ component.toLowerCase() === ".git"
436
+ ) {
437
+ return false;
438
+ }
439
+
440
+ return !WINDOWS_DEVICE_PATTERN.test(component.split(".", 1)[0] ?? "");
441
+ });
442
+ }
443
+
444
+ /** @param {unknown} value */
445
+ function isOwner(value) {
446
+ return (
447
+ typeof value === "string" &&
448
+ Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
449
+ OWNER_PATTERN.test(value)
450
+ );
451
+ }
452
+
453
+ /** @param {unknown} value */
454
+ function isSourceSubjectUuids(value) {
455
+ if (!Array.isArray(value) || !value.every(isUuidV7)) return false;
456
+
457
+ const canonical = [...new Set(value)].sort();
458
+ return arraysEqual(value, canonical);
459
+ }
460
+
461
+ /** @param {unknown} value */
462
+ function isRelease(value) {
463
+ return (
464
+ typeof value === "string" &&
465
+ Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
466
+ RELEASE_PATTERN.test(value)
467
+ );
468
+ }
469
+
470
+ /** @param {unknown} value */
471
+ function isRepository(value) {
472
+ return (
473
+ typeof value === "string" &&
474
+ Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
475
+ REPOSITORY_PATTERN.test(value)
476
+ );
477
+ }
478
+
479
+ /** @param {ValidatedArtifactFile[]} files @param {string} root */
480
+ function writeArtifactTree(files, root) {
481
+ const createdDirectories = new Set([""]);
482
+
483
+ for (const file of files) {
484
+ const components = file.path.split("/");
485
+ for (let index = 1; index < components.length; index += 1) {
486
+ const relativeDirectory = components.slice(0, index).join("/");
487
+ if (createdDirectories.has(relativeDirectory)) continue;
488
+
489
+ mkdirSync(path.join(root, ...components.slice(0, index)), {
490
+ mode: DIRECTORY_MODE,
491
+ });
492
+ applyMode(path.join(root, ...components.slice(0, index)), DIRECTORY_MODE);
493
+ createdDirectories.add(relativeDirectory);
494
+ }
495
+
496
+ const destination = path.join(root, ...components);
497
+ writeFileSync(destination, file.contents, {
498
+ flag: "wx",
499
+ mode: file.mode,
500
+ });
501
+ applyMode(destination, file.mode);
502
+ }
503
+ }
504
+
505
+ /** @param {ValidatedArtifactFile[]} files @param {string} root */
506
+ function verifyArtifactTree(files, root) {
507
+ const expectedFiles = new Map(files.map((file) => [file.path, file]));
508
+ const expectedDirectories = new Set();
509
+ for (const file of files) {
510
+ const components = file.path.split("/");
511
+ for (let index = 1; index < components.length; index += 1) {
512
+ expectedDirectories.add(components.slice(0, index).join("/"));
513
+ }
514
+ }
515
+
516
+ const actualFiles = new Set();
517
+ const actualDirectories = new Set();
518
+ const rootStat = lstatSync(root);
519
+ if (
520
+ !rootStat.isDirectory() ||
521
+ rootStat.isSymbolicLink() ||
522
+ !hasExpectedMode(rootStat.mode, DIRECTORY_MODE)
523
+ ) {
524
+ throw new CompilationMaterializationError(
525
+ "The materialized compilation root is invalid.",
526
+ );
527
+ }
528
+ walkTree(root, "", actualFiles, actualDirectories);
529
+ if (
530
+ !setsEqual(actualFiles, new Set(expectedFiles.keys())) ||
531
+ !setsEqual(actualDirectories, expectedDirectories)
532
+ ) {
533
+ throw new CompilationMaterializationError(
534
+ "The materialized compilation tree is invalid.",
535
+ );
536
+ }
537
+
538
+ for (const relativePath of expectedDirectories) {
539
+ const stat = lstatSync(path.join(root, ...relativePath.split("/")));
540
+ if (
541
+ !stat.isDirectory() ||
542
+ stat.isSymbolicLink() ||
543
+ !hasExpectedMode(stat.mode, DIRECTORY_MODE)
544
+ ) {
545
+ throw new CompilationMaterializationError(
546
+ "A materialized compilation directory is invalid.",
547
+ );
548
+ }
549
+ }
550
+
551
+ for (const [relativePath, expected] of expectedFiles) {
552
+ const fullPath = path.join(root, ...relativePath.split("/"));
553
+ const stat = lstatSync(fullPath);
554
+ const contents = readFileSync(fullPath);
555
+ if (
556
+ !stat.isFile() ||
557
+ stat.isSymbolicLink() ||
558
+ !hasExpectedMode(stat.mode, expected.mode) ||
559
+ !contents.equals(expected.contents) ||
560
+ sha256(contents) !== expected.sha256
561
+ ) {
562
+ throw new CompilationMaterializationError(
563
+ "A materialized compilation file is invalid.",
564
+ );
565
+ }
566
+ }
567
+ }
568
+
569
+ /** @param {string} target @param {number} mode */
570
+ function applyMode(target, mode) {
571
+ if (POSIX_MODE_BITS_SUPPORTED) chmodSync(target, mode);
572
+ }
573
+
574
+ /** @param {number} actual @param {number} expected */
575
+ function hasExpectedMode(actual, expected) {
576
+ return !POSIX_MODE_BITS_SUPPORTED || (actual & 0o777) === expected;
577
+ }
578
+
579
+ /**
580
+ * @param {string} root
581
+ * @param {string} relative
582
+ * @param {Set<string>} files
583
+ * @param {Set<string>} directories
584
+ */
585
+ function walkTree(root, relative, files, directories) {
586
+ const directory = relative ? path.join(root, ...relative.split("/")) : root;
587
+ const entries = readdirSync(directory, { withFileTypes: true });
588
+
589
+ for (const entry of entries) {
590
+ const entryRelative = relative ? `${relative}/${entry.name}` : entry.name;
591
+ if (entry.isDirectory()) {
592
+ directories.add(entryRelative);
593
+ walkTree(root, entryRelative, files, directories);
594
+ } else if (entry.isFile()) {
595
+ files.add(entryRelative);
596
+ } else {
597
+ throw new CompilationMaterializationError(
598
+ "The materialized compilation tree contains a special file.",
599
+ );
600
+ }
601
+ }
602
+ }
603
+
604
+ /** @param {string} target @param {string} parent */
605
+ function assertTargetStillAvailable(target, parent) {
606
+ if (!isAbsent(target)) {
607
+ throw new CompilationMaterializationError(
608
+ "The compilation output path is no longer absent.",
609
+ );
610
+ }
611
+
612
+ const parentStat = lstatSync(parent);
613
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
614
+ throw new CompilationMaterializationError(
615
+ "The compilation output parent is no longer a real directory.",
616
+ );
617
+ }
618
+ }
619
+
620
+ /** @param {string} temporaryDirectory @param {string} parent @param {string} prefix */
621
+ function assertOwnedTemporaryDirectory(temporaryDirectory, parent, prefix) {
622
+ const stat = lstatSync(temporaryDirectory);
623
+ if (
624
+ path.dirname(temporaryDirectory) !== parent ||
625
+ !temporaryDirectory.startsWith(prefix) ||
626
+ temporaryDirectory === prefix ||
627
+ !stat.isDirectory() ||
628
+ stat.isSymbolicLink()
629
+ ) {
630
+ throw new CompilationMaterializationError(
631
+ "The compilation temporary directory is invalid.",
632
+ );
633
+ }
634
+ }
635
+
636
+ /** @param {string} temporaryDirectory @param {string} parent @param {string} prefix */
637
+ function removeOwnedTemporaryDirectory(temporaryDirectory, parent, prefix) {
638
+ try {
639
+ assertOwnedTemporaryDirectory(temporaryDirectory, parent, prefix);
640
+ rmSync(temporaryDirectory, { recursive: true, force: true });
641
+ } catch (error) {
642
+ if (!isFileSystemError(error)) throw error;
643
+ }
644
+ }
645
+
646
+ /** @param {string} candidate */
647
+ function isAbsent(candidate) {
648
+ try {
649
+ lstatSync(candidate);
650
+ return false;
651
+ } catch (error) {
652
+ if (!isFileSystemError(error)) throw error;
653
+ if (error.code === "ENOENT") return true;
654
+
655
+ throw new CompilationMaterializationError(
656
+ "The compilation output path could not be inspected.",
657
+ { cause: error },
658
+ );
659
+ }
660
+ }
661
+
662
+ /** @param {string} candidate */
663
+ function isInitiallyAbsent(candidate) {
664
+ try {
665
+ lstatSync(candidate);
666
+ return false;
667
+ } catch (error) {
668
+ if (!isFileSystemError(error)) throw error;
669
+ if (error.code === "ENOENT") return true;
670
+
671
+ throw new CompilationOutputPathError(
672
+ "The compilation output path could not be inspected.",
673
+ { cause: error },
674
+ );
675
+ }
676
+ }
677
+
678
+ /** @param {Buffer} value */
679
+ function sha256(value) {
680
+ return createHash("sha256").update(value).digest("hex");
681
+ }
682
+
683
+ /** @param {string} value */
684
+ function isAscii(value) {
685
+ return [...value].every(
686
+ (character) => (character.codePointAt(0) ?? 0) <= 0x7f,
687
+ );
688
+ }
689
+
690
+ /**
691
+ * @param {unknown} value
692
+ * @param {string[]} keys
693
+ * @returns {value is Record<string, unknown>}
694
+ */
695
+ function hasExactKeys(value, keys) {
696
+ return isRecord(value) && arraysEqual(Object.keys(value), keys);
697
+ }
698
+
699
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
700
+ function isRecord(value) {
701
+ return typeof value === "object" && value !== null && !Array.isArray(value);
702
+ }
703
+
704
+ /** @param {unknown[]} left @param {unknown[]} right */
705
+ function arraysEqual(left, right) {
706
+ return (
707
+ left.length === right.length &&
708
+ left.every((value, index) => value === right[index])
709
+ );
710
+ }
711
+
712
+ /** @param {Set<string>} left @param {Set<string>} right */
713
+ function setsEqual(left, right) {
714
+ return (
715
+ left.size === right.size && [...left].every((value) => right.has(value))
716
+ );
717
+ }