farna-bootstrapper 0.0.0-stage → 0.1.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 (80) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +65 -0
  6. package/dist/cli/commands/check.d.ts +58 -0
  7. package/dist/cli/commands/check.js +198 -0
  8. package/dist/cli/commands/generate.d.ts +75 -0
  9. package/dist/cli/commands/generate.js +218 -0
  10. package/dist/cli/commands/init.d.ts +52 -0
  11. package/dist/cli/commands/init.js +271 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +51 -0
  14. package/dist/cli/program.d.ts +23 -0
  15. package/dist/cli/program.js +183 -0
  16. package/dist/compose/resolve.d.ts +154 -0
  17. package/dist/compose/resolve.js +545 -0
  18. package/dist/config/load.d.ts +4 -0
  19. package/dist/config/load.js +45 -0
  20. package/dist/config/schema.d.ts +22 -0
  21. package/dist/config/schema.js +46 -0
  22. package/dist/core/constants.d.ts +268 -0
  23. package/dist/core/constants.js +336 -0
  24. package/dist/core/errors.d.ts +44 -0
  25. package/dist/core/errors.js +75 -0
  26. package/dist/core/fs.d.ts +31 -0
  27. package/dist/core/fs.js +169 -0
  28. package/dist/core/json.d.ts +22 -0
  29. package/dist/core/json.js +174 -0
  30. package/dist/core/paths.d.ts +45 -0
  31. package/dist/core/paths.js +110 -0
  32. package/dist/core/text.d.ts +10 -0
  33. package/dist/core/text.js +27 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.js +1 -0
  36. package/dist/lock/lockfile.d.ts +229 -0
  37. package/dist/lock/lockfile.js +333 -0
  38. package/dist/materialise/source-tree.d.ts +77 -0
  39. package/dist/materialise/source-tree.js +264 -0
  40. package/dist/permissions/permissions.d.ts +128 -0
  41. package/dist/permissions/permissions.js +452 -0
  42. package/dist/render/commit.d.ts +59 -0
  43. package/dist/render/commit.js +279 -0
  44. package/dist/render/generate-lock.d.ts +9 -0
  45. package/dist/render/generate-lock.js +203 -0
  46. package/dist/render/identity.d.ts +23 -0
  47. package/dist/render/identity.js +396 -0
  48. package/dist/render/orphans.d.ts +59 -0
  49. package/dist/render/orphans.js +234 -0
  50. package/dist/render/port.d.ts +96 -0
  51. package/dist/render/port.js +1 -0
  52. package/dist/render/prepare.d.ts +33 -0
  53. package/dist/render/prepare.js +139 -0
  54. package/dist/render/root-cleanliness.d.ts +28 -0
  55. package/dist/render/root-cleanliness.js +76 -0
  56. package/dist/render/stage.d.ts +36 -0
  57. package/dist/render/stage.js +92 -0
  58. package/dist/render/staging.d.ts +16 -0
  59. package/dist/render/staging.js +94 -0
  60. package/dist/render/structured.d.ts +35 -0
  61. package/dist/render/structured.js +258 -0
  62. package/dist/render/upstream.d.ts +41 -0
  63. package/dist/render/upstream.js +179 -0
  64. package/dist/report/format.d.ts +7 -0
  65. package/dist/report/format.js +97 -0
  66. package/dist/report/warnings.d.ts +21 -0
  67. package/dist/report/warnings.js +24 -0
  68. package/dist/source/digest.d.ts +18 -0
  69. package/dist/source/digest.js +77 -0
  70. package/dist/source/frontmatter.d.ts +12 -0
  71. package/dist/source/frontmatter.js +29 -0
  72. package/dist/source/load.d.ts +103 -0
  73. package/dist/source/load.js +676 -0
  74. package/dist/source/schema.d.ts +149 -0
  75. package/dist/source/schema.js +283 -0
  76. package/dist/source/yaml.d.ts +10 -0
  77. package/dist/source/yaml.js +49 -0
  78. package/dist/verify/containment.d.ts +22 -0
  79. package/dist/verify/containment.js +753 -0
  80. package/package.json +79 -4
@@ -0,0 +1,279 @@
1
+ import { chmod, mkdir, rename, rm, rmdir, writeFile } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, posix } from 'node:path';
3
+ import { MANAGED_FILE_MAX_BYTES, OUTPUT_DIR_MODE, OUTPUT_FILE_MODE } from '../core/constants.js';
4
+ import { pathUnsafe, writeFailed } from '../core/errors.js';
5
+ import { describeFsError, readBoundedBytes } from '../core/fs.js';
6
+ import { containedTarget, lstatOrUndefined } from '../core/paths.js';
7
+ import { hasControlCharacters } from '../core/text.js';
8
+ import { stagingName, sweepStaging } from './staging.js';
9
+ /**
10
+ * A managed path is relative, POSIX-spelled, control-character-free, and cannot
11
+ * escape the root. The control-character refusal is not cosmetic: the path is
12
+ * printed on a human line and reaches a filesystem call, so a carriage return
13
+ * or an escape introducer must never pass through.
14
+ */
15
+ export function assertSafeRelativePath(path) {
16
+ if (path === '' || path.includes('\\') || isAbsolute(path)) {
17
+ throw pathUnsafe('managed path is not relative', { subject: path });
18
+ }
19
+ if (hasControlCharacters(path)) {
20
+ throw pathUnsafe('managed path contains a control character', { subject: path });
21
+ }
22
+ const normalised = posix.normalize(path);
23
+ if (normalised !== path ||
24
+ normalised.startsWith('../') ||
25
+ normalised === '..' ||
26
+ normalised === '.') {
27
+ throw pathUnsafe('managed path escapes the repository root', { subject: path });
28
+ }
29
+ }
30
+ const defaultOperations = {
31
+ // One level at a time. A recursive mkdir can create ancestors and then throw,
32
+ // leaving directories the rollback has no record of; the caller records each
33
+ // successful level instead. The mode is set explicitly and then re-asserted:
34
+ // `mkdir`'s mode is masked by the process umask, so a umask of 000 would
35
+ // otherwise leave a world-writable managed directory.
36
+ mkdir: async (path) => {
37
+ await mkdir(path, { mode: OUTPUT_DIR_MODE });
38
+ await chmod(path, OUTPUT_DIR_MODE);
39
+ },
40
+ writeFile: async (path, data) => {
41
+ // The raw bytes are written as-is: a restore must not round-trip a
42
+ // repository file through a lossy text encoding. The mode is explicit for
43
+ // the same reason as `mkdir`: a generated file is always 0644, never 0666.
44
+ await writeFile(path, data, { mode: OUTPUT_FILE_MODE });
45
+ await chmod(path, OUTPUT_FILE_MODE);
46
+ },
47
+ rename: async (from, to) => {
48
+ await rename(from, to);
49
+ },
50
+ remove: async (path) => {
51
+ await rm(path, { force: true });
52
+ },
53
+ removeDirectory: async (path) => {
54
+ await rmdir(path);
55
+ },
56
+ };
57
+ /**
58
+ * Resolve one managed path and read its current bytes, refusing a symlinked
59
+ * ancestor, a symlink at the target, a directory in the way, or any other
60
+ * non-regular file. Shared by the write path and by `--dry-run`, so the plan
61
+ * cannot report a state the write path would refuse.
62
+ *
63
+ * The read returns bytes, never decoded text: a managed file holding an invalid
64
+ * byte decodes to U+FFFD, which can equal a rule that legitimately contains
65
+ * U+FFFD. Comparing the text would call such a file clean and never repair it.
66
+ */
67
+ export async function inspectManagedTarget(repoRoot, path) {
68
+ assertSafeRelativePath(path);
69
+ const target = await containedTarget(repoRoot, path);
70
+ const stats = await lstatOrUndefined(target, path);
71
+ if (stats?.isSymbolicLink()) {
72
+ throw pathUnsafe(`refusing to write through a symbolic link: ${path}`, {
73
+ subject: path,
74
+ action: 'replace the symbolic link with a real file',
75
+ });
76
+ }
77
+ if (stats?.isDirectory()) {
78
+ throw writeFailed(`cannot write ${path}: a directory is in the way`, {
79
+ subject: path,
80
+ action: 'remove the directory and re-run generate',
81
+ });
82
+ }
83
+ if (stats !== undefined && !stats.isFile()) {
84
+ throw writeFailed(`cannot write ${path}: the path is not a regular file`, {
85
+ subject: path,
86
+ });
87
+ }
88
+ return {
89
+ path,
90
+ target,
91
+ existing: stats === undefined
92
+ ? undefined
93
+ : await readBoundedBytes(target, path, {
94
+ action: 'make the managed file readable and re-run generate',
95
+ maxBytes: MANAGED_FILE_MAX_BYTES,
96
+ }),
97
+ };
98
+ }
99
+ async function removeTemporaryFiles(staged, operations) {
100
+ for (const item of staged) {
101
+ try {
102
+ await operations.remove(item.temporary);
103
+ }
104
+ catch {
105
+ // A leftover temp file is harmless and never a managed path.
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Write the verified managed set atomically. Callers must have verified first;
111
+ * this function never renders and never decides whether the output is correct.
112
+ *
113
+ * The whole set is preflighted (no symlinked ancestor, no directory in the way)
114
+ * and the tool's own staging namespace is swept before anything is staged, so a
115
+ * killed earlier run cannot leave a permanent red `check`. A failure while
116
+ * staging removes the temporaries and the directories this call created; the
117
+ * diagnostic names any directory it could not remove rather than claiming a
118
+ * clean tree. A rename failure restores the files this call already replaced and
119
+ * reports any file it could not restore by name.
120
+ */
121
+ export async function commitFiles(repoRoot, files, overrides = {}) {
122
+ const operations = { ...defaultOperations, ...overrides };
123
+ const planned = [];
124
+ for (const file of files) {
125
+ planned.push({ ...(await inspectManagedTarget(repoRoot, file.path)), bytes: file.bytes });
126
+ }
127
+ // Sweep our own namespace in every managed directory. Only directories the
128
+ // plan already validated are touched, and only names matching this tool's
129
+ // staging shape.
130
+ const stagingDirectories = new Map();
131
+ for (const item of planned) {
132
+ stagingDirectories.set(dirname(item.target), posix.dirname(item.path));
133
+ }
134
+ for (const directory of stagingDirectories.keys()) {
135
+ await sweepStaging(directory);
136
+ }
137
+ const statuses = planned.map((item) => ({
138
+ path: item.path,
139
+ status: item.existing?.equals(Buffer.from(item.bytes, 'utf8')) === true ? 'unchanged' : 'written',
140
+ }));
141
+ const writes = planned.filter((item) => item.existing === undefined || !item.existing.equals(Buffer.from(item.bytes, 'utf8')));
142
+ const staged = [];
143
+ const createdDirectories = [];
144
+ const ensureDirectory = async (directory, subject) => {
145
+ const missing = [];
146
+ let current = directory;
147
+ for (;;) {
148
+ if ((await lstatOrUndefined(current, subject)) !== undefined) {
149
+ break;
150
+ }
151
+ missing.push(current);
152
+ const parent = dirname(current);
153
+ if (parent === current) {
154
+ break;
155
+ }
156
+ current = parent;
157
+ }
158
+ // Parent first, recording each level the moment it is created: a failure on
159
+ // a deeper level leaves the earlier levels known to the rollback. A
160
+ // concurrent process may create one of these levels first; `EEXIST` for a
161
+ // directory that is now present is success, never a failure to roll back.
162
+ for (const level of [...missing].reverse()) {
163
+ try {
164
+ await operations.mkdir(level);
165
+ }
166
+ catch (error) {
167
+ const stats = describeFsError(error) === 'EEXIST' ? await lstatOrUndefined(level, subject) : undefined;
168
+ if (stats?.isDirectory() !== true) {
169
+ throw error;
170
+ }
171
+ continue;
172
+ }
173
+ createdDirectories.push({ path: level, subject });
174
+ }
175
+ };
176
+ const removeCreatedDirectories = async () => {
177
+ const failed = [];
178
+ for (const directory of [...createdDirectories].sort((a, b) => b.path.length - a.path.length)) {
179
+ try {
180
+ await operations.removeDirectory(directory.path);
181
+ }
182
+ catch {
183
+ // A non-empty directory means something other than generate wrote to
184
+ // it; name it rather than claiming the tree is clean.
185
+ failed.push(directory.subject);
186
+ }
187
+ }
188
+ return failed;
189
+ };
190
+ let stagingPath = writes[0]?.path ?? '';
191
+ try {
192
+ for (const item of writes) {
193
+ stagingPath = item.path;
194
+ await ensureDirectory(dirname(item.target), posix.dirname(item.path));
195
+ const temporary = join(dirname(item.target), stagingName(item.target));
196
+ // Record before writing, so a write that creates then fails is still
197
+ // removed by the catch below.
198
+ staged.push({ ...item, temporary });
199
+ await operations.writeFile(temporary, item.bytes);
200
+ }
201
+ }
202
+ catch (error) {
203
+ await removeTemporaryFiles(staged, operations);
204
+ const leftBehind = await removeCreatedDirectories();
205
+ const outcome = leftBehind.length === 0
206
+ ? 'nothing was written'
207
+ : `no managed file was written, but these directories could not be removed: ${leftBehind.join(', ')}`;
208
+ throw writeFailed(`cannot stage ${stagingPath}; ${outcome}`, {
209
+ subject: stagingPath,
210
+ action: leftBehind.length === 0
211
+ ? 'fix the filesystem and re-run generate'
212
+ : 'remove the named directories and re-run generate',
213
+ cause: error,
214
+ });
215
+ }
216
+ const replaced = [];
217
+ const restoreFailures = [];
218
+ const changedByAnotherWriter = [];
219
+ let renamePath = staged[0]?.path ?? '';
220
+ try {
221
+ for (const item of staged) {
222
+ renamePath = item.path;
223
+ await operations.rename(item.temporary, item.target);
224
+ replaced.push(item);
225
+ }
226
+ }
227
+ catch (error) {
228
+ await removeTemporaryFiles(staged.filter((item) => !replaced.includes(item)), operations);
229
+ for (const item of [...replaced].reverse()) {
230
+ try {
231
+ // Re-check the target before restoring it. Another process may have
232
+ // written its own (newer) bytes since this call renamed: overwriting
233
+ // them would undo a concurrent winner. Only restore a file that still
234
+ // holds exactly the bytes this call put there; a missing target needs
235
+ // no restore.
236
+ const stats = await lstatOrUndefined(item.target, item.path);
237
+ if (stats === undefined) {
238
+ continue;
239
+ }
240
+ const current = await readBoundedBytes(item.target, item.path, {
241
+ action: 'make the managed file readable and re-run generate',
242
+ maxBytes: MANAGED_FILE_MAX_BYTES,
243
+ });
244
+ if (!current.equals(Buffer.from(item.bytes, 'utf8'))) {
245
+ changedByAnotherWriter.push(item.path);
246
+ continue;
247
+ }
248
+ if (item.existing === undefined) {
249
+ await operations.remove(item.target);
250
+ }
251
+ else {
252
+ await operations.writeFile(item.target, item.existing);
253
+ }
254
+ }
255
+ catch (restoreError) {
256
+ restoreFailures.push(`${item.path} (${describeFsError(restoreError)})`);
257
+ }
258
+ }
259
+ const leftBehind = await removeCreatedDirectories();
260
+ const outcome = restoreFailures.length > 0
261
+ ? `${restoreFailures.length} earlier file(s) could NOT be restored: ${restoreFailures.join(', ')}`
262
+ : changedByAnotherWriter.length > 0
263
+ ? `earlier files were left as another writer left them: ${changedByAnotherWriter.join(', ')}`
264
+ : replaced.length > 0
265
+ ? 'earlier files were restored'
266
+ : 'no earlier file was replaced';
267
+ const directories = leftBehind.length === 0
268
+ ? ''
269
+ : `; these directories could not be removed: ${leftBehind.join(', ')}`;
270
+ throw writeFailed(`cannot write ${renamePath}; ${outcome}${directories}`, {
271
+ subject: renamePath,
272
+ action: restoreFailures.length > 0
273
+ ? `inspect and re-run generate; restore failed for ${restoreFailures.join(', ')}`
274
+ : 're-run generate after fixing the filesystem',
275
+ cause: error,
276
+ });
277
+ }
278
+ return { statuses };
279
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Run `body` while holding `.farna/.generate.lock`.
3
+ *
4
+ * The source root is validated **before** the lock is taken, so a `.farna` that
5
+ * is a symlink, a file or absent reports the source problem rather than a lock
6
+ * error the user cannot act on. A missing `.farna` skips the lock and runs
7
+ * `body`, which reports the real problem.
8
+ */
9
+ export declare function withGenerateLock<T>(repoRoot: string, body: () => Promise<T>, staleMs?: number): Promise<T>;
@@ -0,0 +1,203 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { basename, join } from 'node:path';
4
+ import { GENERATE_LOCK_PATH, GENERATE_LOCK_STALE_MS, ROOT_DIR } from '../core/constants.js';
5
+ import { invalidConfig } from '../core/errors.js';
6
+ import { describeFsError } from '../core/fs.js';
7
+ import { assertRealDirectory, lstatOrUndefined } from '../core/paths.js';
8
+ /**
9
+ * The exclusive run lock that makes two concurrent `generate` runs impossible.
10
+ *
11
+ * Both runs would read the same lockfile, plan from it, remove its orphans and
12
+ * rewrite it; the second could delete a file the first had just written, or
13
+ * commit a plan computed before the first changed the tree. The lock covers the
14
+ * whole read → plan → remove → commit sequence, and a second live run is a typed
15
+ * `F001` ("lock held"), never a silent interleave.
16
+ *
17
+ * The lock is a **directory**, because `mkdir` is atomic on every supported
18
+ * filesystem, including network shares where an exclusive create is not
19
+ * reliable. Its owner writes `pid` inside it. The lock is local-only state: it
20
+ * is never committed, never a managed output, and is released in a `finally`
21
+ * even when the run fails.
22
+ */
23
+ /** The file inside the lock directory that records the owning process. */
24
+ const PID_FILE = 'pid';
25
+ const RECLAIM_INFIX = '.reclaim.';
26
+ const RELEASE_INFIX = '.release.';
27
+ function errorCode(error) {
28
+ return error instanceof Error && 'code' in error && typeof error.code === 'string'
29
+ ? error.code
30
+ : undefined;
31
+ }
32
+ function isProcessAlive(pid) {
33
+ try {
34
+ process.kill(pid, 0);
35
+ return true;
36
+ }
37
+ catch (error) {
38
+ // EPERM means the process exists but is not ours: still alive.
39
+ return errorCode(error) === 'EPERM';
40
+ }
41
+ }
42
+ function heldError(action, cause) {
43
+ return invalidConfig('another generate is already running', {
44
+ subject: GENERATE_LOCK_PATH,
45
+ action,
46
+ ...(cause === undefined ? {} : { cause }),
47
+ });
48
+ }
49
+ /**
50
+ * Inspect an existing lock directory. `held` when its owner is alive and the
51
+ * lock is younger than the age bound; `stale` when the pid is dead or the lock
52
+ * is older; `unknown` when the pid file is not readable yet (a concurrent
53
+ * create may still be writing it).
54
+ *
55
+ * A path that is not a directory is a typed error, never "another generate is
56
+ * running": the reader must not have to guess whether a file at the lock path
57
+ * is a live holder or a broken tree.
58
+ */
59
+ async function readLockState(path, staleMs) {
60
+ const stats = await lstatOrUndefined(path, GENERATE_LOCK_PATH);
61
+ if (stats === undefined) {
62
+ // The holder released it between the failed `mkdir` and this read.
63
+ return 'stale';
64
+ }
65
+ if (!stats.isDirectory()) {
66
+ throw invalidConfig(`${GENERATE_LOCK_PATH} is not a directory`, {
67
+ subject: GENERATE_LOCK_PATH,
68
+ action: 'remove the file at that path; the generate lock is a directory',
69
+ });
70
+ }
71
+ let pid;
72
+ try {
73
+ const text = await readFile(join(path, PID_FILE), 'utf8');
74
+ const parsed = Number.parseInt(text.trim(), 10);
75
+ pid = Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;
76
+ }
77
+ catch {
78
+ pid = undefined;
79
+ }
80
+ if (pid === undefined) {
81
+ // The owner may be between creating the directory and writing its pid. A
82
+ // lock with no readable pid is only stale once it is older than the grace
83
+ // window, so a concurrent create is never mistaken for a crash.
84
+ return Date.now() - stats.mtimeMs > Math.min(staleMs, 60_000) ? 'stale' : 'unknown';
85
+ }
86
+ if (!isProcessAlive(pid)) {
87
+ return 'stale';
88
+ }
89
+ return Date.now() - stats.mtimeMs > staleMs ? 'stale' : 'held';
90
+ }
91
+ /**
92
+ * Move a stale lock aside and delete it. Only one reclaimer can succeed: the
93
+ * `rename` of one source to one destination is atomic, so every other racer
94
+ * fails with `ENOENT` and retries the `mkdir` instead of deleting a lock the
95
+ * winner has already replaced.
96
+ */
97
+ async function reclaim(path) {
98
+ const aside = `${path}${RECLAIM_INFIX}${randomUUID()}`;
99
+ try {
100
+ await rename(path, aside);
101
+ }
102
+ catch (error) {
103
+ if (errorCode(error) === 'ENOENT') {
104
+ return;
105
+ }
106
+ throw invalidConfig('cannot reclaim a stale generate lock', {
107
+ subject: GENERATE_LOCK_PATH,
108
+ action: 'remove the stale lock directory deliberately, then re-run generate',
109
+ cause: error,
110
+ });
111
+ }
112
+ await rm(aside, { recursive: true, force: true }).catch(() => undefined);
113
+ }
114
+ async function acquire(path, staleMs) {
115
+ try {
116
+ await mkdir(path, { mode: 0o755 });
117
+ return;
118
+ }
119
+ catch (error) {
120
+ const code = errorCode(error);
121
+ if (code === 'ENOENT') {
122
+ // `.farna` is validated before the lock is taken, so this is a race that
123
+ // removed it; the caller's body reports the missing source.
124
+ return;
125
+ }
126
+ if (code !== 'EEXIST') {
127
+ throw invalidConfig(`cannot create the generate lock (${code ?? 'unknown error'})`, {
128
+ subject: GENERATE_LOCK_PATH,
129
+ action: 'make .farna writable and re-run generate',
130
+ cause: error,
131
+ });
132
+ }
133
+ }
134
+ const state = await readLockState(path, staleMs);
135
+ if (state === 'held') {
136
+ throw heldError('wait for it to finish and re-run generate; delete the lock only when no generate is running');
137
+ }
138
+ if (state === 'unknown') {
139
+ throw heldError('wait for it to finish and re-run generate');
140
+ }
141
+ await reclaim(path);
142
+ try {
143
+ await mkdir(path, { mode: 0o755 });
144
+ }
145
+ catch (retry) {
146
+ if (errorCode(retry) === 'EEXIST') {
147
+ throw heldError('wait for it to finish and re-run generate', retry);
148
+ }
149
+ throw invalidConfig(`cannot create the generate lock (${errorCode(retry) ?? 'unknown error'})`, {
150
+ subject: GENERATE_LOCK_PATH,
151
+ action: 'make .farna writable and re-run generate',
152
+ cause: retry,
153
+ });
154
+ }
155
+ }
156
+ /**
157
+ * Release the lock by renaming it aside and deleting the renamed directory. A
158
+ * rename that fails because the path is already gone is the normal already-
159
+ * released case; any other cleanup failure is reported on stderr rather than
160
+ * replacing the body's own diagnostic or claiming the lock is still held.
161
+ */
162
+ async function release(path) {
163
+ const aside = `${path}${RELEASE_INFIX}${randomUUID()}`;
164
+ try {
165
+ await rename(path, aside);
166
+ }
167
+ catch (error) {
168
+ if (errorCode(error) !== 'ENOENT') {
169
+ process.stderr.write(`farna-bootstrapper: warning: could not release ${GENERATE_LOCK_PATH} (${describeFsError(error)})\n`);
170
+ }
171
+ return;
172
+ }
173
+ try {
174
+ await rm(aside, { recursive: true, force: true });
175
+ }
176
+ catch (error) {
177
+ process.stderr.write(`farna-bootstrapper: warning: could not remove the released lock (${describeFsError(error)})\n`);
178
+ }
179
+ }
180
+ /**
181
+ * Run `body` while holding `.farna/.generate.lock`.
182
+ *
183
+ * The source root is validated **before** the lock is taken, so a `.farna` that
184
+ * is a symlink, a file or absent reports the source problem rather than a lock
185
+ * error the user cannot act on. A missing `.farna` skips the lock and runs
186
+ * `body`, which reports the real problem.
187
+ */
188
+ export async function withGenerateLock(repoRoot, body, staleMs = GENERATE_LOCK_STALE_MS) {
189
+ const rootStats = await assertRealDirectory(join(repoRoot, ROOT_DIR), ROOT_DIR);
190
+ if (rootStats === undefined) {
191
+ // No `.farna` directory: nothing to hold, and the body reports why.
192
+ return await body();
193
+ }
194
+ const path = join(repoRoot, ROOT_DIR, basename(GENERATE_LOCK_PATH));
195
+ await acquire(path, staleMs);
196
+ try {
197
+ await writeFile(join(path, PID_FILE), `${process.pid}\n`, 'utf8');
198
+ return await body();
199
+ }
200
+ finally {
201
+ await release(path);
202
+ }
203
+ }
@@ -0,0 +1,23 @@
1
+ import type { RecordedIntegrity, RendererIdentity } from './port.js';
2
+ /**
3
+ * The structured integrity record for an identity. The real target attaches the
4
+ * npm lookup directly; an injected target that only supplied `integrity` has a
5
+ * present value treated as verified and a missing one as no record. This keeps
6
+ * the warning decision in one place instead of re-deriving it at each caller.
7
+ */
8
+ export declare function integrityRecordOf(identity: RendererIdentity): RecordedIntegrity;
9
+ /** Read the installed renderer's own package manifest and recorded integrity. */
10
+ export declare function installedRendererIdentity(name: string): RendererIdentity;
11
+ /**
12
+ * Compare the renderer recorded in the lockfile with the one that is installed.
13
+ *
14
+ * A differing name or version always fails, and so does a lockfile that records
15
+ * no integrity: the committed bytes must be tied to a pinned renderer. An
16
+ * installed package whose npm lock record supplied no string integrity is not a
17
+ * mismatch: its version has already been enforced, and the caller reports the
18
+ * unverified digest as `W114_RENDERER_INTEGRITY_UNVERIFIED` rather than
19
+ * refusing a normal global or linked install. When an integrity was read, it is
20
+ * compared exactly; the check never degrades a known integrity to a
21
+ * version-only comparison.
22
+ */
23
+ export declare function verifyRendererIdentity(recorded: RendererIdentity, installed: RendererIdentity, subject?: string): void;