@arcadia-eternity/content-sdk 4.3.4 → 4.4.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 (121) hide show
  1. package/README.md +3 -3
  2. package/bin/arcadia-content-mcp.mjs +2 -0
  3. package/bin/arcadia-content.mjs +2 -0
  4. package/dist/asset-inspect.d.ts +30 -0
  5. package/dist/asset-inspect.js +84 -0
  6. package/dist/author-api.d.ts +48 -0
  7. package/dist/author-api.js +128 -0
  8. package/dist/author-reference.d.ts +61 -0
  9. package/dist/author-reference.js +130 -0
  10. package/dist/build-content.d.ts +2 -0
  11. package/dist/build-content.js +29 -0
  12. package/dist/cli.d.ts +2 -0
  13. package/dist/cli.js +81 -0
  14. package/dist/content-query.d.ts +30 -0
  15. package/dist/content-query.js +326 -0
  16. package/dist/content-workspace.d.ts +204 -0
  17. package/dist/content-workspace.js +981 -0
  18. package/dist/debug-environments.d.ts +96 -0
  19. package/dist/debug-environments.js +135 -0
  20. package/dist/demo.d.ts +1 -0
  21. package/dist/demo.js +18 -0
  22. package/dist/effect-build.d.ts +3 -0
  23. package/dist/effect-build.js +44 -0
  24. package/dist/environment-rules.d.ts +7 -0
  25. package/dist/environment-rules.js +94 -0
  26. package/dist/environment.d.ts +48 -0
  27. package/dist/environment.js +184 -0
  28. package/dist/job-journal.d.ts +19 -0
  29. package/dist/job-journal.js +110 -0
  30. package/dist/jobs.d.ts +103 -0
  31. package/dist/jobs.js +626 -0
  32. package/dist/lib/content.d.ts +24 -0
  33. package/dist/lib/content.js +106 -0
  34. package/dist/lib/presentation.d.ts +26 -0
  35. package/dist/lib/presentation.js +252 -0
  36. package/dist/lib/yaml-sharing.d.ts +16 -0
  37. package/dist/lib/yaml-sharing.js +130 -0
  38. package/dist/managed-projects.d.ts +37 -0
  39. package/dist/managed-projects.js +305 -0
  40. package/dist/managed-sources.d.ts +28 -0
  41. package/dist/managed-sources.js +541 -0
  42. package/dist/mcp-contracts.d.ts +420 -0
  43. package/dist/mcp-contracts.js +146 -0
  44. package/dist/mcp.d.ts +2 -0
  45. package/dist/mcp.js +228 -0
  46. package/dist/module-path.d.ts +1 -0
  47. package/dist/module-path.js +8 -0
  48. package/dist/pack-project.d.ts +10 -0
  49. package/dist/pack-project.js +178 -0
  50. package/dist/preview-control.d.ts +17 -0
  51. package/dist/preview-control.js +273 -0
  52. package/dist/preview.d.ts +24 -0
  53. package/dist/preview.js +332 -0
  54. package/dist/project-teams.d.ts +51 -0
  55. package/dist/project-teams.js +106 -0
  56. package/dist/project.d.ts +18 -0
  57. package/dist/project.js +146 -0
  58. package/dist/rename.d.ts +2 -0
  59. package/dist/rename.js +128 -0
  60. package/dist/setup.d.ts +2 -0
  61. package/dist/setup.js +117 -0
  62. package/dist/source-lock.d.ts +9 -0
  63. package/dist/source-lock.js +117 -0
  64. package/dist/template/README.md +2 -0
  65. package/dist/template/docs/presentation.md +3 -3
  66. package/dist/template/package.json +3 -7
  67. package/dist/template/test/pack.test.mjs +10 -7
  68. package/dist/testing.d.ts +58 -0
  69. package/dist/testing.js +205 -0
  70. package/dist/types.d.ts +5 -0
  71. package/dist/types.js +14 -0
  72. package/dist/workbench-context.d.ts +10 -0
  73. package/dist/workbench-context.js +27 -0
  74. package/dist/workspace-cli.d.ts +1 -0
  75. package/dist/workspace-cli.js +66 -0
  76. package/dist/workspace-materials.d.ts +19 -0
  77. package/dist/workspace-materials.js +165 -0
  78. package/dist/workspace.d.ts +190 -0
  79. package/dist/workspace.js +726 -0
  80. package/package.json +34 -27
  81. package/dist/asset-inspect.mjs +0 -67
  82. package/dist/author-api.mjs +0 -112
  83. package/dist/author-reference.mjs +0 -121
  84. package/dist/build-content.mjs +0 -30
  85. package/dist/cli.mjs +0 -76
  86. package/dist/content-query.mjs +0 -283
  87. package/dist/content-workspace.d.mts +0 -161
  88. package/dist/content-workspace.mjs +0 -936
  89. package/dist/debug-environments.mjs +0 -154
  90. package/dist/demo.mjs +0 -22
  91. package/dist/effect-build.d.mts +0 -2
  92. package/dist/effect-build.mjs +0 -46
  93. package/dist/environment-rules.d.mts +0 -5
  94. package/dist/environment-rules.mjs +0 -92
  95. package/dist/environment.mjs +0 -183
  96. package/dist/job-journal.mjs +0 -94
  97. package/dist/jobs.mjs +0 -579
  98. package/dist/lib/content.mjs +0 -95
  99. package/dist/lib/presentation.mjs +0 -240
  100. package/dist/lib/yaml-sharing.mjs +0 -101
  101. package/dist/managed-projects.d.mts +0 -35
  102. package/dist/managed-projects.mjs +0 -303
  103. package/dist/managed-sources.d.mts +0 -19
  104. package/dist/managed-sources.mjs +0 -503
  105. package/dist/mcp-contracts.mjs +0 -153
  106. package/dist/mcp.mjs +0 -369
  107. package/dist/pack-project.mjs +0 -157
  108. package/dist/preview-control.mjs +0 -260
  109. package/dist/preview.mjs +0 -313
  110. package/dist/project-teams.mjs +0 -98
  111. package/dist/project.mjs +0 -140
  112. package/dist/rename.mjs +0 -112
  113. package/dist/setup.mjs +0 -134
  114. package/dist/source-lock.mjs +0 -103
  115. package/dist/testing.mjs +0 -204
  116. package/dist/workbench-context.mjs +0 -18
  117. package/dist/workspace-cli.mjs +0 -60
  118. package/dist/workspace-materials.mjs +0 -153
  119. package/dist/workspace.mjs +0 -684
  120. /package/dist/{index.d.mts → index.d.ts} +0 -0
  121. /package/dist/{index.mjs → index.js} +0 -0
@@ -0,0 +1,541 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { constants, createReadStream } from 'node:fs';
4
+ import { mkdir, open, readdir, lstat, realpath, rm, writeFile } from 'node:fs/promises';
5
+ import { dirname, isAbsolute, join, relative } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { Parser } from 'tar';
8
+ import yauzl from 'yauzl';
9
+ import { errorCode, errorMessage, isRecord } from './types.js';
10
+ const exec = promisify(execFile);
11
+ function fail(code) {
12
+ throw Object.assign(new Error(code), { code });
13
+ }
14
+ const forbidden = (name) => ['.git', '.ssh', '.aws', '.npmrc', '.netrc', 'node_modules'].includes(name.toLowerCase()) ||
15
+ /^\.env(?:\.|$)/i.test(name);
16
+ const safePath = (value) => {
17
+ if (typeof value !== 'string' ||
18
+ !value ||
19
+ value.length > 2048 ||
20
+ value.includes('\\') ||
21
+ /[\p{Cc}:]/u.test(value) ||
22
+ isAbsolute(value))
23
+ throw fail('SOURCE_PATH_INVALID');
24
+ const clean = value.replace(/\/$/, '').replace(/^\.\//, '');
25
+ if (!clean ||
26
+ clean
27
+ .split('/')
28
+ .some(part => !part ||
29
+ part === '.' ||
30
+ part === '..' ||
31
+ /[. ]$/.test(part) ||
32
+ /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)))
33
+ throw fail('SOURCE_PATH_INVALID');
34
+ return clean;
35
+ };
36
+ const httpsUrl = (value) => {
37
+ const url = new URL(value);
38
+ if (url.protocol !== 'https:' || url.username || url.password || url.hash)
39
+ throw fail('SOURCE_URL_INVALID');
40
+ return url;
41
+ };
42
+ const publicUrl = (value) => {
43
+ const url = httpsUrl(value);
44
+ url.search = '';
45
+ return url.href;
46
+ };
47
+ function boundedFiles(options) {
48
+ const names = new Set();
49
+ const files = [];
50
+ let size = 0;
51
+ let entries = 0;
52
+ function track(name) {
53
+ options.signal.throwIfAborted();
54
+ name = safePath(name);
55
+ if (++entries > options.maxFiles)
56
+ throw fail('SOURCE_LIMIT');
57
+ const key = name.normalize('NFC').toLowerCase();
58
+ if (names.has(key))
59
+ throw fail('SOURCE_PATH_DUPLICATE');
60
+ names.add(key);
61
+ return name;
62
+ }
63
+ return {
64
+ files,
65
+ directory: track,
66
+ add(name, bytes) {
67
+ name = track(name);
68
+ if ((size += bytes.length) > options.maxBytes)
69
+ throw fail('SOURCE_LIMIT');
70
+ if (!name.split('/').some(forbidden))
71
+ files.push({ name, bytes });
72
+ },
73
+ checkSize(size) {
74
+ if (!Number.isSafeInteger(size) || size < 0 || size > options.maxBytes)
75
+ throw fail('SOURCE_LIMIT');
76
+ },
77
+ };
78
+ }
79
+ async function readBounded(stream, expectedSize, options) {
80
+ if (!Number.isSafeInteger(expectedSize) || expectedSize < 0 || expectedSize > options.maxBytes)
81
+ throw fail('SOURCE_LIMIT');
82
+ return new Promise((resolve, reject) => {
83
+ const chunks = [];
84
+ let size = 0, settled = false;
85
+ const finish = (error) => {
86
+ if (settled)
87
+ return;
88
+ settled = true;
89
+ options.signal.removeEventListener('abort', abort);
90
+ if (error) {
91
+ reject(error);
92
+ stream.destroy();
93
+ }
94
+ else
95
+ resolve(Buffer.concat(chunks, size));
96
+ };
97
+ const abort = () => finish(options.signal.reason ?? fail('SOURCE_CANCELLED'));
98
+ options.signal.addEventListener('abort', abort, { once: true });
99
+ stream.on('error', finish);
100
+ stream.on('data', (chunk) => {
101
+ if (settled)
102
+ return;
103
+ size += chunk.length;
104
+ if (size > expectedSize || size > options.maxBytes)
105
+ return finish(fail('SOURCE_LIMIT'));
106
+ chunks.push(Buffer.from(chunk));
107
+ });
108
+ stream.on('end', () => finish(size === expectedSize ? undefined : fail('SOURCE_SIZE_CHANGED')));
109
+ stream.on('close', () => {
110
+ if (!settled)
111
+ finish(fail('SOURCE_STREAM_CLOSED'));
112
+ });
113
+ if (options.signal.aborted)
114
+ abort();
115
+ });
116
+ }
117
+ async function tarFiles(file, options) {
118
+ const output = boundedFiles(options);
119
+ await new Promise((resolve, reject) => {
120
+ const input = createReadStream(file);
121
+ const parser = new Parser({ strict: true, maxMetaEntrySize: 64 * 1024, maxDecompressionRatio: 1000 });
122
+ let failed = false;
123
+ const stop = (error) => {
124
+ if (failed)
125
+ return;
126
+ failed = true;
127
+ options.signal.removeEventListener('abort', abort);
128
+ input.destroy();
129
+ parser.abort(error instanceof Error ? error : new Error(errorMessage(error)));
130
+ reject(error);
131
+ };
132
+ const abort = () => stop(options.signal.reason ?? fail('SOURCE_CANCELLED'));
133
+ options.signal.addEventListener('abort', abort, { once: true });
134
+ parser.on('entry', (entry) => {
135
+ try {
136
+ if (entry.type === 'Directory' && ['.', './'].includes(entry.path)) {
137
+ entry.resume();
138
+ return;
139
+ }
140
+ const name = safePath(entry.path);
141
+ if (entry.type === 'Directory') {
142
+ output.directory(name);
143
+ entry.resume();
144
+ return;
145
+ }
146
+ if (!['File', 'OldFile', 'ContiguousFile'].includes(entry.type))
147
+ throw fail('SOURCE_LINK_FORBIDDEN');
148
+ output.checkSize(entry.size);
149
+ const chunks = [];
150
+ let size = 0;
151
+ entry.on('data', (chunk) => {
152
+ if (failed)
153
+ return;
154
+ size += chunk.length;
155
+ if (size > entry.size || size > options.maxBytes)
156
+ return stop(fail('SOURCE_LIMIT'));
157
+ chunks.push(Buffer.from(chunk));
158
+ });
159
+ entry.on('end', () => {
160
+ if (failed)
161
+ return;
162
+ try {
163
+ if (size !== entry.size)
164
+ throw fail('SOURCE_SIZE_CHANGED');
165
+ output.add(name, Buffer.concat(chunks, size));
166
+ }
167
+ catch (error) {
168
+ stop(error);
169
+ }
170
+ });
171
+ entry.on('error', stop);
172
+ entry.resume();
173
+ }
174
+ catch (error) {
175
+ stop(error);
176
+ }
177
+ });
178
+ input.on('error', stop);
179
+ parser.on('error', stop);
180
+ parser.on('end', () => {
181
+ options.signal.removeEventListener('abort', abort);
182
+ if (!failed)
183
+ resolve();
184
+ });
185
+ input.pipe(parser);
186
+ });
187
+ return output.files;
188
+ }
189
+ async function zipFiles(file, options) {
190
+ const output = boundedFiles(options);
191
+ const zip = await new Promise((resolve, reject) => yauzl.open(file, { lazyEntries: true, validateEntrySizes: true, strictFileNames: true }, (error, value) => error ? reject(error) : resolve(value)));
192
+ let abort;
193
+ try {
194
+ await new Promise((resolve, reject) => {
195
+ const onAbort = () => {
196
+ zip.close();
197
+ reject(options.signal.reason ?? fail('SOURCE_CANCELLED'));
198
+ };
199
+ abort = onAbort;
200
+ options.signal.addEventListener('abort', onAbort, { once: true });
201
+ zip.on('error', reject);
202
+ zip.on('end', () => {
203
+ options.signal.removeEventListener('abort', onAbort);
204
+ resolve();
205
+ });
206
+ zip.on('entry', (entry) => {
207
+ void (async () => {
208
+ const name = safePath(entry.fileName);
209
+ const kind = (entry.externalFileAttributes >>> 16) & 0o170000;
210
+ if (kind !== 0 && kind !== 0o100000 && kind !== 0o040000)
211
+ throw fail('SOURCE_LINK_FORBIDDEN');
212
+ if (entry.generalPurposeBitFlag & 1)
213
+ throw fail('SOURCE_ENCRYPTED_ARCHIVE');
214
+ if (entry.fileName.endsWith('/')) {
215
+ output.directory(name);
216
+ zip.readEntry();
217
+ return;
218
+ }
219
+ output.checkSize(entry.uncompressedSize);
220
+ const stream = await new Promise((resolve, reject) => zip.openReadStream(entry, (error, value) => (error ? reject(error) : resolve(value))));
221
+ output.add(name, await readBounded(stream, entry.uncompressedSize, options));
222
+ zip.readEntry();
223
+ })().catch(error => {
224
+ zip.close();
225
+ reject(error);
226
+ });
227
+ });
228
+ zip.readEntry();
229
+ });
230
+ }
231
+ finally {
232
+ if (abort)
233
+ options.signal.removeEventListener('abort', abort);
234
+ zip.close();
235
+ }
236
+ return output.files;
237
+ }
238
+ async function directoryFiles(directory, options) {
239
+ const root = await realpath(directory);
240
+ const output = boundedFiles(options);
241
+ async function walk(path, prefix = '') {
242
+ options.signal.throwIfAborted();
243
+ const resolved = await realpath(path);
244
+ const rel = relative(root, resolved);
245
+ if ((rel && (isAbsolute(rel) || rel === '..' || rel.startsWith('../'))) || (await lstat(path)).isSymbolicLink())
246
+ throw fail('SOURCE_LINK_FORBIDDEN');
247
+ for (const entry of await readdir(path, { withFileTypes: true })) {
248
+ const name = prefix ? prefix + '/' + entry.name : entry.name;
249
+ safePath(name);
250
+ if (forbidden(entry.name)) {
251
+ output.directory(name);
252
+ continue;
253
+ }
254
+ const file = join(path, entry.name);
255
+ if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile()))
256
+ throw fail('SOURCE_LINK_FORBIDDEN');
257
+ if (entry.isDirectory()) {
258
+ output.directory(name);
259
+ await walk(file, name);
260
+ }
261
+ else {
262
+ const before = await lstat(file);
263
+ if (!before.isFile())
264
+ throw fail('SOURCE_LINK_FORBIDDEN');
265
+ output.checkSize(before.size);
266
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
267
+ try {
268
+ const actualPath = await realpath(file);
269
+ const rel = relative(root, actualPath);
270
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('../'))
271
+ throw fail('SOURCE_LINK_FORBIDDEN');
272
+ const bytes = await readBounded(handle.createReadStream({ autoClose: false }), before.size, options);
273
+ const after = await handle.stat();
274
+ if (before.ino !== after.ino || before.size !== bytes.length || before.mtimeMs !== after.mtimeMs)
275
+ throw fail('SOURCE_CHANGED');
276
+ output.add(name, bytes);
277
+ }
278
+ finally {
279
+ await handle.close();
280
+ }
281
+ }
282
+ }
283
+ }
284
+ await walk(root);
285
+ return output.files;
286
+ }
287
+ async function download(source, file, options) {
288
+ let url = httpsUrl(source.url);
289
+ for (let redirects = 0; redirects <= 5; redirects++) {
290
+ const response = await fetch(url, { redirect: 'manual', signal: options.signal });
291
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
292
+ await response.body?.cancel();
293
+ const location = response.headers.get('location');
294
+ if (redirects === 5 || !location)
295
+ throw fail('SOURCE_REDIRECT_LIMIT');
296
+ url = httpsUrl(new URL(location, url).href);
297
+ continue;
298
+ }
299
+ if (!response.ok || !response.body) {
300
+ await response.body?.cancel();
301
+ throw fail('SOURCE_DOWNLOAD_FAILED');
302
+ }
303
+ const declared = response.headers.get('content-length');
304
+ if (declared && Number(declared) > options.maxBytes) {
305
+ await response.body.cancel();
306
+ throw fail('SOURCE_LIMIT');
307
+ }
308
+ const chunks = [];
309
+ let total = 0;
310
+ for await (const chunk of response.body) {
311
+ total += chunk.length;
312
+ if (total > options.maxBytes) {
313
+ await response.body.cancel().catch(() => { });
314
+ throw fail('SOURCE_LIMIT');
315
+ }
316
+ chunks.push(Buffer.from(chunk));
317
+ }
318
+ const bytes = Buffer.concat(chunks, total);
319
+ if (source.integrity) {
320
+ const tokens = source.integrity.trim().split(/\s+/);
321
+ if (!tokens.length || tokens.some((token) => !/^sha(?:256|384|512)-[A-Za-z0-9+/]+={0,2}$/.test(token)))
322
+ throw fail('SOURCE_INTEGRITY_INVALID');
323
+ if (!tokens.some((token) => {
324
+ const [algorithm, expected] = token.split('-');
325
+ return createHash(algorithm).update(bytes).digest('base64') === expected;
326
+ }))
327
+ throw fail('SOURCE_INTEGRITY_MISMATCH');
328
+ }
329
+ await writeFile(file, bytes, { flag: 'wx', mode: 0o600 });
330
+ return {
331
+ kind: 'url',
332
+ url: publicUrl(source.url),
333
+ resolvedUrl: publicUrl(url.href),
334
+ ...(source.integrity ? { integrity: source.integrity } : {}),
335
+ };
336
+ }
337
+ throw fail('SOURCE_REDIRECT_LIMIT');
338
+ }
339
+ async function gitArchive(source, root, options) {
340
+ const url = httpsUrl(source.url).href;
341
+ if (typeof source.commit !== 'string' || !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i.test(source.commit))
342
+ throw fail('SOURCE_GIT_COMMIT_REQUIRED');
343
+ const artifactPath = source.artifactPath === undefined ? undefined : safePath(source.artifactPath);
344
+ const gitRoot = join(root, 'git');
345
+ const config = [
346
+ '-c',
347
+ 'core.hooksPath=' + join(root, 'no-hooks'),
348
+ '-c',
349
+ 'protocol.allow=never',
350
+ '-c',
351
+ 'protocol.https.allow=always',
352
+ '-c',
353
+ 'credential.helper=',
354
+ '-c',
355
+ 'http.followRedirects=false',
356
+ ];
357
+ const env = {
358
+ PATH: process.env.PATH ?? '',
359
+ SystemRoot: process.env.SystemRoot,
360
+ HOME: root,
361
+ GIT_CONFIG_NOSYSTEM: '1',
362
+ GIT_CONFIG_GLOBAL: join(root, 'no-config'),
363
+ GIT_TERMINAL_PROMPT: '0',
364
+ };
365
+ const budget = new AbortController();
366
+ const signal = AbortSignal.any([options.signal, budget.signal]);
367
+ let scanning = false;
368
+ async function checkBudget() {
369
+ let size = 0, count = 0;
370
+ async function walk(directory) {
371
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
372
+ const file = join(directory, entry.name);
373
+ let info;
374
+ try {
375
+ info = await lstat(file);
376
+ }
377
+ catch (error) {
378
+ if (errorCode(error) === 'ENOENT')
379
+ continue;
380
+ throw error;
381
+ }
382
+ if (++count > options.maxFiles || (size += info.size) > options.maxBytes)
383
+ throw fail('SOURCE_LIMIT');
384
+ if (info.isDirectory())
385
+ await walk(file);
386
+ }
387
+ }
388
+ await walk(root);
389
+ }
390
+ const timer = setInterval(() => {
391
+ if (scanning)
392
+ return;
393
+ scanning = true;
394
+ void checkBudget()
395
+ .catch(error => budget.abort(error))
396
+ .finally(() => {
397
+ scanning = false;
398
+ });
399
+ }, 100);
400
+ timer.unref();
401
+ const run = (args) => exec('git', [...config, ...args], {
402
+ env,
403
+ signal,
404
+ timeout: options.timeoutMs,
405
+ killSignal: 'SIGKILL',
406
+ maxBuffer: 1024 * 1024,
407
+ windowsHide: true,
408
+ });
409
+ try {
410
+ await run(['init', '--bare', '--initial-branch=main', gitRoot]);
411
+ await run(['--git-dir=' + gitRoot, 'fetch', '--no-tags', '--depth=1', '--', url, source.commit]);
412
+ await checkBudget();
413
+ const actual = (await run(['--git-dir=' + gitRoot, 'rev-parse', 'FETCH_HEAD^{commit}'])).stdout.trim();
414
+ if (actual.toLowerCase() !== source.commit.toLowerCase())
415
+ throw fail('SOURCE_GIT_COMMIT_MISMATCH');
416
+ const file = join(root, 'git.tar');
417
+ await run([
418
+ '--git-dir=' + gitRoot,
419
+ 'archive',
420
+ '--format=tar',
421
+ '--output=' + file,
422
+ artifactPath ? actual + ':' + artifactPath : actual,
423
+ ]);
424
+ await checkBudget();
425
+ return {
426
+ file,
427
+ provenance: { kind: 'git', url: publicUrl(url), commit: actual, ...(artifactPath ? { artifactPath } : {}) },
428
+ };
429
+ }
430
+ catch (error) {
431
+ if (budget.signal.aborted)
432
+ throw budget.signal.reason;
433
+ if (options.signal.aborted)
434
+ throw options.signal.reason;
435
+ const code = errorCode(error);
436
+ if (typeof code === 'string' && code.startsWith('SOURCE_'))
437
+ throw error;
438
+ throw fail('SOURCE_GIT_FAILED');
439
+ }
440
+ finally {
441
+ clearInterval(timer);
442
+ }
443
+ }
444
+ /** Only trusted host configuration supplies descriptors. HTTP callers select registered source IDs. */
445
+ export async function acquireSource(source, input) {
446
+ if (!source ||
447
+ typeof source !== 'object' ||
448
+ !input ||
449
+ typeof input.destination !== 'string' ||
450
+ !isAbsolute(input.destination))
451
+ throw fail('SOURCE_INVALID');
452
+ const timeoutMs = input.timeoutMs ?? 120000;
453
+ const options = {
454
+ maxBytes: input.maxBytes ?? 256 * 1024 * 1024,
455
+ maxFiles: input.maxFiles ?? 50000,
456
+ timeoutMs,
457
+ signal: AbortSignal.any([...(input.signal ? [input.signal] : []), AbortSignal.timeout(timeoutMs)]),
458
+ };
459
+ if (!Number.isSafeInteger(options.maxBytes) ||
460
+ options.maxBytes < 1 ||
461
+ !Number.isSafeInteger(options.maxFiles) ||
462
+ options.maxFiles < 1)
463
+ throw fail('SOURCE_LIMIT_INVALID');
464
+ options.signal.throwIfAborted();
465
+ await mkdir(input.destination, { mode: 0o700 });
466
+ try {
467
+ const scratch = join(input.destination, '.source');
468
+ await mkdir(scratch);
469
+ let files, provenance;
470
+ if (source.kind === 'directory') {
471
+ if (typeof source.directory !== 'string' || !isAbsolute(source.directory))
472
+ throw fail('SOURCE_PATH_INVALID');
473
+ files = await directoryFiles(source.directory, options);
474
+ provenance = { kind: 'directory' };
475
+ }
476
+ else {
477
+ let file;
478
+ if (source.kind === 'archive') {
479
+ if (typeof source.file !== 'string' || !isAbsolute(source.file) || !(await lstat(source.file)).isFile())
480
+ throw fail('SOURCE_ARCHIVE_INVALID');
481
+ file = source.file;
482
+ provenance = { kind: 'archive' };
483
+ }
484
+ else if (source.kind === 'url') {
485
+ file = join(scratch, 'download');
486
+ provenance = await download(source, file, options);
487
+ }
488
+ else if (source.kind === 'git') {
489
+ const result = await gitArchive(source, scratch, options);
490
+ file = result.file;
491
+ provenance = result.provenance;
492
+ }
493
+ else
494
+ throw fail('SOURCE_KIND_UNSUPPORTED');
495
+ if ((await lstat(file)).size > options.maxBytes)
496
+ throw fail('SOURCE_LIMIT');
497
+ const handle = await open(file, 'r');
498
+ const magic = Buffer.alloc(4);
499
+ try {
500
+ await handle.read(magic, 0, 4, 0);
501
+ }
502
+ finally {
503
+ await handle.close();
504
+ }
505
+ files = magic.readUInt32LE(0) === 0x04034b50 ? await zipFiles(file, options) : await tarFiles(file, options);
506
+ }
507
+ const packageFiles = files.filter(file => file.name === 'package.json' || file.name.endsWith('/package.json'));
508
+ const rootManifest = packageFiles.find(file => file.name === 'package.json');
509
+ const shortest = rootManifest ?? [...packageFiles].sort((a, b) => a.name.split('/').length - b.name.split('/').length)[0];
510
+ if (!shortest)
511
+ throw fail('SOURCE_PACKAGE_MISSING');
512
+ const prefix = shortest.name.slice(0, -'package.json'.length);
513
+ if (!rootManifest && files.some(file => !file.name.startsWith(prefix)))
514
+ throw fail('SOURCE_PACKAGE_AMBIGUOUS');
515
+ const manifest = JSON.parse(shortest.bytes.toString('utf8'));
516
+ if (!isRecord(manifest) || typeof manifest.name !== 'string' || typeof manifest.version !== 'string')
517
+ throw fail('SOURCE_PACKAGE_INVALID');
518
+ const directory = join(input.destination, 'package');
519
+ await mkdir(directory);
520
+ for (const file of files) {
521
+ options.signal.throwIfAborted();
522
+ const name = safePath(file.name.slice(prefix.length));
523
+ const output = join(directory, name);
524
+ if (relative(directory, output).startsWith('..'))
525
+ throw fail('SOURCE_PATH_INVALID');
526
+ await mkdir(dirname(output), { recursive: true });
527
+ await writeFile(output, file.bytes, { flag: 'wx', mode: 0o600 });
528
+ }
529
+ await rm(scratch, { recursive: true, force: true });
530
+ return { directory, provenance: { ...provenance, name: manifest.name, version: manifest.version } };
531
+ }
532
+ catch (error) {
533
+ await rm(input.destination, { recursive: true, force: true });
534
+ const code = errorCode(error);
535
+ if (typeof code === 'string' && code.startsWith('SOURCE_'))
536
+ throw error;
537
+ if (options.signal.aborted)
538
+ throw options.signal.reason;
539
+ throw fail('SOURCE_ACQUISITION_FAILED');
540
+ }
541
+ }