@mulmoclaude/core 7.4.0 → 7.5.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 (54) hide show
  1. package/dist/{root-CqxPNSyK.js → atomic-C3NMg6-j.js} +2 -20
  2. package/dist/atomic-C3NMg6-j.js.map +1 -0
  3. package/dist/{root-9lRFeXbm.cjs → atomic-cqafMWEI.cjs} +1 -25
  4. package/dist/atomic-cqafMWEI.cjs.map +1 -0
  5. package/dist/collection/registry/server/index.cjs +4 -4
  6. package/dist/collection/registry/server/index.cjs.map +1 -1
  7. package/dist/collection/registry/server/index.js +3 -3
  8. package/dist/collection/server/index.cjs +3 -3
  9. package/dist/collection/server/index.js +3 -3
  10. package/dist/collection-watchers/index.cjs +3 -3
  11. package/dist/collection-watchers/index.js +3 -3
  12. package/dist/{discovery-RyuhNKjx.js → discovery-CImpaG95.js} +3 -2
  13. package/dist/{discovery-RyuhNKjx.js.map → discovery-CImpaG95.js.map} +1 -1
  14. package/dist/{discovery-DxmMcpFo.cjs → discovery-CY4pvgo9.cjs} +4 -3
  15. package/dist/{discovery-DxmMcpFo.cjs.map → discovery-CY4pvgo9.cjs.map} +1 -1
  16. package/dist/feeds/server/index.cjs +3 -3
  17. package/dist/feeds/server/index.js +3 -3
  18. package/dist/files/index.cjs +8 -13
  19. package/dist/files/index.cjs.map +1 -1
  20. package/dist/files/index.js +3 -8
  21. package/dist/files/index.js.map +1 -1
  22. package/dist/google/index.cjs +3 -3
  23. package/dist/google/index.cjs.map +1 -1
  24. package/dist/google/index.js +2 -2
  25. package/dist/json-BGdV2cz6.cjs +16 -0
  26. package/dist/json-BGdV2cz6.cjs.map +1 -0
  27. package/dist/json-BizOSThv.js +11 -0
  28. package/dist/json-BizOSThv.js.map +1 -0
  29. package/dist/root-Ccgd3H5S.cjs +29 -0
  30. package/dist/root-Ccgd3H5S.cjs.map +1 -0
  31. package/dist/root-s0MUUMQU.js +22 -0
  32. package/dist/root-s0MUUMQU.js.map +1 -0
  33. package/dist/runtime-plugins/containment.d.ts +5 -0
  34. package/dist/runtime-plugins/download.d.ts +12 -0
  35. package/dist/runtime-plugins/fetchPackage.d.ts +52 -0
  36. package/dist/runtime-plugins/index.cjs +735 -4
  37. package/dist/runtime-plugins/index.cjs.map +1 -1
  38. package/dist/runtime-plugins/index.d.ts +7 -0
  39. package/dist/runtime-plugins/index.js +711 -7
  40. package/dist/runtime-plugins/index.js.map +1 -1
  41. package/dist/runtime-plugins/inspect.d.ts +18 -0
  42. package/dist/runtime-plugins/install.d.ts +48 -0
  43. package/dist/runtime-plugins/installSource.d.ts +34 -0
  44. package/dist/runtime-plugins/ledger.d.ts +3 -0
  45. package/dist/runtime-plugins/ledgerWrite.d.ts +17 -0
  46. package/dist/runtime-plugins/load.d.ts +2 -2
  47. package/dist/runtime-plugins/npmBuiltinNames.d.ts +1 -0
  48. package/dist/{server-xdXBsiba.js → server-B5TZjZN9.js} +3 -3
  49. package/dist/{server-xdXBsiba.js.map → server-B5TZjZN9.js.map} +1 -1
  50. package/dist/{server-ZKTtI8_W.cjs → server-BXtSbL-b.cjs} +6 -6
  51. package/dist/{server-ZKTtI8_W.cjs.map → server-BXtSbL-b.cjs.map} +1 -1
  52. package/package.json +1 -1
  53. package/dist/root-9lRFeXbm.cjs.map +0 -1
  54. package/dist/root-CqxPNSyK.js.map +0 -1
@@ -2,14 +2,20 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
3
  const require_dist = require("../dist-734JaRYi.cjs");
4
4
  const require_containment = require("../containment-Dc3gO4wD.cjs");
5
+ const require_json = require("../json-BGdV2cz6.cjs");
6
+ const require_atomic = require("../atomic-cqafMWEI.cjs");
5
7
  let gui_chat_protocol = require("gui-chat-protocol");
6
8
  let node_fs = require("node:fs");
7
9
  let node_path = require("node:path");
8
10
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
11
+ let node_crypto = require("node:crypto");
12
+ let node_fs_promises = require("node:fs/promises");
9
13
  let node_child_process = require("node:child_process");
10
14
  let node_url = require("node:url");
15
+ let node_zlib = require("node:zlib");
11
16
  // src/runtime-plugins/ledger.ts
12
- var isLedgerEntry = (value) => require_dist.hasStringProp(value, "name") && require_dist.hasStringProp(value, "version") && require_dist.hasStringProp(value, "tgz") && require_dist.hasStringProp(value, "installedAt");
17
+ var hasValidSource = (value) => !Object.hasOwn(value, "source") || typeof value.source === "string";
18
+ var isLedgerEntry = (value) => require_dist.hasStringProp(value, "name") && require_dist.hasStringProp(value, "version") && require_dist.hasStringProp(value, "tgz") && require_dist.hasStringProp(value, "installedAt") && hasValidSource(value);
13
19
  /** The well-formed entries of a parsed ledger; anything that is not an array reads as empty. */
14
20
  var parseLedger = (raw) => {
15
21
  if (!Array.isArray(raw)) return [];
@@ -93,6 +99,13 @@ var EXTRACT_MARKER = ".extract-complete";
93
99
  function isCacheValid(cachePath) {
94
100
  return (0, node_fs.existsSync)(node_path.default.join(cachePath, EXTRACT_MARKER));
95
101
  }
102
+ function writeMarker(markerPath) {
103
+ (0, node_fs.rmSync)(markerPath, {
104
+ recursive: true,
105
+ force: true
106
+ });
107
+ (0, node_fs.writeFileSync)(markerPath, "", { flag: "wx" });
108
+ }
96
109
  /** Run `tar xzf` to extract a tgz into the version-keyed cache slot.
97
110
  * `--strip-components=1` drops the `package/` prefix that npm packs
98
111
  * add. `execFileSync` (not `execSync`) so paths bypass shell parsing
@@ -118,7 +131,7 @@ function extractTgz(tgzAbs, destDir) {
118
131
  destDir,
119
132
  "--strip-components=1"
120
133
  ], { stdio: "pipe" });
121
- (0, node_fs.writeFileSync)(node_path.default.join(destDir, EXTRACT_MARKER), "");
134
+ writeMarker(node_path.default.join(destDir, EXTRACT_MARKER));
122
135
  } catch (err) {
123
136
  try {
124
137
  (0, node_fs.rmSync)(destDir, {
@@ -129,6 +142,24 @@ function extractTgz(tgzAbs, destDir) {
129
142
  throw err;
130
143
  }
131
144
  }
145
+ // src/runtime-plugins/containment.ts
146
+ /** True when `file` exists and, with every link followed, is inside `root`. */
147
+ function resolvesInside(file, root) {
148
+ const rootReal = require_containment.realpathSyncOrNull(root);
149
+ const fileReal = require_containment.realpathSyncOrNull(file);
150
+ return rootReal !== null && fileReal !== null && require_containment.isInsideRoot(rootReal, fileReal);
151
+ }
152
+ /** The first symlink under `root` that leads outside it (or nowhere), relative to `root`; null when
153
+ * every link stays inside. */
154
+ function linkLeadingOut(root, dir = root) {
155
+ for (const item of (0, node_fs.readdirSync)(dir, { withFileTypes: true })) {
156
+ const full = node_path.default.join(dir, item.name);
157
+ if (item.isSymbolicLink() && !resolvesInside(full, root)) return node_path.default.relative(root, full);
158
+ const nested = item.isDirectory() ? linkLeadingOut(root, full) : null;
159
+ if (nested !== null) return nested;
160
+ }
161
+ return null;
162
+ }
132
163
  // src/runtime-plugins/load.ts
133
164
  var isToolDefinition = (value) => {
134
165
  if (!require_dist.isRecord(value)) return false;
@@ -220,6 +251,13 @@ async function loadPluginFromCacheDir(name, version, cachePath, deps) {
220
251
  return null;
221
252
  }
222
253
  const entryAbs = node_path.default.join(cachePath, entrySpec);
254
+ if (!resolvesInside(entryAbs, cachePath)) {
255
+ log.warn("plugin entry is missing or leads outside its folder — skipping", {
256
+ name,
257
+ entrySpec
258
+ });
259
+ return null;
260
+ }
223
261
  try {
224
262
  const mod = await import((0, node_url.pathToFileURL)(entryAbs).href);
225
263
  if (!require_dist.isRecord(mod)) {
@@ -267,8 +305,8 @@ async function loadPluginFromCacheDir(name, version, cachePath, deps) {
267
305
  * touch the disk. The asset route trusts registry membership, so a
268
306
  * registered cachePath that escaped the base would expose arbitrary
269
307
  * files via the unauthenticated GET — this check is the first
270
- * line of defence (defence-in-depth: realpath after extract is the
271
- * symlink-escape backstop). */
308
+ * line of defence; `loadPluginFromCacheDir` checks the entry's realpath
309
+ * after extraction as the symlink-escape backstop. */
272
310
  function ensureInsideBase(candidate, base) {
273
311
  return require_containment.isWithinRoot(node_path.default.resolve(base), node_path.default.resolve(candidate));
274
312
  }
@@ -314,16 +352,709 @@ function prepareLedgerEntry(entry, roots, log) {
314
352
  }
315
353
  return cachePath;
316
354
  }
355
+ // src/runtime-plugins/npmBuiltinNames.ts
356
+ var NPM_BUILTIN_MODULE_NAMES = /* @__PURE__ */ new Set([
357
+ "_http_agent",
358
+ "_http_client",
359
+ "_http_common",
360
+ "_http_incoming",
361
+ "_http_outgoing",
362
+ "_http_server",
363
+ "_stream_duplex",
364
+ "_stream_passthrough",
365
+ "_stream_readable",
366
+ "_stream_transform",
367
+ "_stream_wrap",
368
+ "_stream_writable",
369
+ "_tls_common",
370
+ "_tls_wrap",
371
+ "assert",
372
+ "assert/strict",
373
+ "async_hooks",
374
+ "buffer",
375
+ "child_process",
376
+ "cluster",
377
+ "console",
378
+ "constants",
379
+ "crypto",
380
+ "dgram",
381
+ "diagnostics_channel",
382
+ "dns",
383
+ "dns/promises",
384
+ "domain",
385
+ "events",
386
+ "fs",
387
+ "fs/promises",
388
+ "http",
389
+ "http2",
390
+ "https",
391
+ "inspector",
392
+ "inspector/promises",
393
+ "module",
394
+ "net",
395
+ "os",
396
+ "path",
397
+ "path/posix",
398
+ "path/win32",
399
+ "perf_hooks",
400
+ "process",
401
+ "punycode",
402
+ "querystring",
403
+ "readline",
404
+ "readline/promises",
405
+ "repl",
406
+ "stream",
407
+ "stream/consumers",
408
+ "stream/promises",
409
+ "stream/web",
410
+ "string_decoder",
411
+ "sys",
412
+ "timers",
413
+ "timers/promises",
414
+ "tls",
415
+ "trace_events",
416
+ "tty",
417
+ "url",
418
+ "util",
419
+ "util/types",
420
+ "v8",
421
+ "vm",
422
+ "wasi",
423
+ "worker_threads",
424
+ "zlib",
425
+ "node:sea",
426
+ "node:sqlite",
427
+ "node:test",
428
+ "node:test/reporters"
429
+ ]);
430
+ // src/runtime-plugins/installSource.ts
431
+ var MAX_NPM_NAME_LENGTH = 214;
432
+ var MAX_TAG_LENGTH = 255;
433
+ var NPM_UNSCOPED_NAME = /^[a-z0-9][a-z0-9\-._]*$/;
434
+ var NPM_SCOPED_SEGMENT = /^[a-z0-9\-_][a-z0-9\-._]*$/;
435
+ var NUMERIC_IDENTIFIER = /^(?:0|[1-9]\d*)$/;
436
+ var ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/;
437
+ var ALL_DIGITS = /^\d+$/;
438
+ var DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]*$/;
439
+ var GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
440
+ var GITHUB_REPO = /^[A-Za-z0-9._-]{1,100}$/;
441
+ var GITHUB_TAG = /^[A-Za-z0-9._+/-]+$/;
442
+ var GITHUB_PREFIX = "github:";
443
+ var refuse$1 = (error) => ({
444
+ ok: false,
445
+ error
446
+ });
447
+ function isNpmNameShape(name) {
448
+ if (!name.startsWith("@")) return NPM_UNSCOPED_NAME.test(name);
449
+ const slash = name.indexOf("/");
450
+ return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1));
451
+ }
452
+ var NPM_EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", "favicon.ico"]);
453
+ var isNpmReservedName = (name) => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name);
454
+ var isNpmPackageName = (name) => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name);
455
+ var isVersionCore = (core) => {
456
+ const parts = core.split(".");
457
+ return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part));
458
+ };
459
+ var isLabel = (label, prerelease) => label.split(".").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part)));
460
+ /** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */
461
+ function isSemverShape(version) {
462
+ const plus = version.indexOf("+");
463
+ const build = plus === -1 ? null : version.slice(plus + 1);
464
+ const withoutBuild = plus === -1 ? version : version.slice(0, plus);
465
+ const dash = withoutBuild.indexOf("-");
466
+ const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash);
467
+ const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1);
468
+ return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false));
469
+ }
470
+ /** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because
471
+ * what it resolves to would change between the confirmation and the next install. */
472
+ var isNpmVersionSpec = (spec) => isSemverShape(spec) || DIST_TAG.test(spec);
473
+ /** An exact version — what a package's own `version` must be, since it becomes part of a file name
474
+ * and a cache folder. */
475
+ var isExactVersion = (version) => isSemverShape(version);
476
+ function parseNpm(input) {
477
+ const specAt = input.lastIndexOf("@");
478
+ const hasSpec = specAt > 0;
479
+ const name = hasSpec ? input.slice(0, specAt) : input;
480
+ const spec = hasSpec ? input.slice(specAt + 1) : null;
481
+ if (!isNpmPackageName(name)) return refuse$1(`not an npm package name: ${JSON.stringify(name)}`);
482
+ if (spec !== null && !isNpmVersionSpec(spec)) return refuse$1(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`);
483
+ return {
484
+ ok: true,
485
+ source: {
486
+ kind: "npm",
487
+ name,
488
+ spec
489
+ }
490
+ };
491
+ }
492
+ var isGithubTag = (tag) => tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split("/").some((part) => part === "" || part === "." || part === "..");
493
+ function parseGithub(rest) {
494
+ const hash = rest.indexOf("#");
495
+ const path = hash === -1 ? rest : rest.slice(0, hash);
496
+ const tag = hash === -1 ? null : rest.slice(hash + 1);
497
+ const [owner = "", repo = "", ...extra] = path.split("/");
498
+ if (extra.length > 0 || !GITHUB_OWNER.test(owner)) return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(path)}`);
499
+ if (!GITHUB_REPO.test(repo) || repo === "." || repo === "..") return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(path)}`);
500
+ if (tag !== null && !isGithubTag(tag)) return refuse$1(`not a release tag: ${JSON.stringify(tag)}`);
501
+ return {
502
+ ok: true,
503
+ source: {
504
+ kind: "github",
505
+ owner,
506
+ repo,
507
+ tag
508
+ }
509
+ };
510
+ }
511
+ function parseInstallSource(input) {
512
+ if (typeof input !== "string") return refuse$1("an install source is a string");
513
+ const trimmed = input.trim();
514
+ if (trimmed === "") return refuse$1("an install source is empty");
515
+ return trimmed.startsWith(GITHUB_PREFIX) ? parseGithub(trimmed.slice(7)) : parseNpm(trimmed);
516
+ }
517
+ /** The ledger's `source` field for what was actually installed: the resolved version or tag. */
518
+ function sourceLabel(source, resolved) {
519
+ return source.kind === "npm" ? `npm:${source.name}@${resolved}` : `github:${source.owner}/${source.repo}#${resolved}`;
520
+ }
521
+ /** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */
522
+ var packageFileName = (name, version) => `${name.replace(/^@/, "").replaceAll("/", "-")}-${version}.tgz`;
523
+ var CONTENT_ID_LENGTH = 12;
524
+ /** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`.
525
+ * Two different packages with one name and version (a GitHub tag published again) then get different
526
+ * files. The hash is short, so the install also refuses to write over an existing file whose bytes
527
+ * differ: that is what keeps a file an entry points at from changing. */
528
+ var installedFileName = (name, version, sha256Hex) => packageFileName(name, version).replace(/\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);
529
+ // src/runtime-plugins/ledgerWrite.ts
530
+ var isEntryNamed = (value, name) => require_dist.isRecord(value) && Object.hasOwn(value, "name") && value.name === name;
531
+ /** The ledger with `entry` in it, exactly once: it takes the place of the first entry of the same
532
+ * name, any further ones are dropped (each would load another copy), and with none it is appended. */
533
+ function withLedgerEntry(raw, entry) {
534
+ const first = raw.findIndex((value) => isEntryNamed(value, entry.name));
535
+ if (first === -1) return [...raw, entry];
536
+ return raw.flatMap((value, index) => {
537
+ if (index === first) return [entry];
538
+ return isEntryNamed(value, entry.name) ? [] : [value];
539
+ });
540
+ }
541
+ /** The ledger without any entry named `name`; everything else is kept as it was. */
542
+ var withoutLedgerEntry = (raw, name) => raw.filter((value) => !isEntryNamed(value, name));
543
+ async function readLedgerText(ledgerPath) {
544
+ try {
545
+ return {
546
+ ok: true,
547
+ text: await (0, node_fs_promises.readFile)(ledgerPath, "utf-8")
548
+ };
549
+ } catch (err) {
550
+ if (require_dist.isRecord(err) && err.code === "ENOENT") return {
551
+ ok: true,
552
+ text: null
553
+ };
554
+ return {
555
+ ok: false,
556
+ error: `cannot read the plugin ledger ${ledgerPath}: ${String(err)}`
557
+ };
558
+ }
559
+ }
560
+ function parseLedgerText(ledgerPath, text) {
561
+ try {
562
+ const parsed = JSON.parse(text);
563
+ return Array.isArray(parsed) ? {
564
+ ok: true,
565
+ raw: parsed
566
+ } : {
567
+ ok: false,
568
+ error: `the plugin ledger ${ledgerPath} is not a JSON array; fix it before installing`
569
+ };
570
+ } catch (err) {
571
+ return {
572
+ ok: false,
573
+ error: `the plugin ledger ${ledgerPath} is not valid JSON; fix it before installing: ${String(err)}`
574
+ };
575
+ }
576
+ }
577
+ /** The ledger as an array to edit: a missing file is an empty ledger; a file that is not a JSON
578
+ * array is refused rather than overwritten, since writing over it would lose what the user wrote. */
579
+ async function readLedgerForWrite(ledgerPath) {
580
+ const read = await readLedgerText(ledgerPath);
581
+ if (!read.ok) return read;
582
+ return read.text === null ? {
583
+ ok: true,
584
+ raw: []
585
+ } : parseLedgerText(ledgerPath, read.text);
586
+ }
587
+ var writeLedger = (ledgerPath, raw) => require_json.writeJsonAtomic(ledgerPath, raw);
588
+ // src/runtime-plugins/download.ts
589
+ var DownloadError = class extends Error {};
590
+ async function readCapped(body, url, maxBytes, signal) {
591
+ const reader = body.getReader();
592
+ const onAbort = () => {
593
+ reader.cancel(signal.reason).catch(() => void 0);
594
+ };
595
+ signal.addEventListener("abort", onAbort, { once: true });
596
+ try {
597
+ return await collectChunks(reader, url, maxBytes, signal);
598
+ } finally {
599
+ signal.removeEventListener("abort", onAbort);
600
+ }
601
+ }
602
+ async function collectChunks(reader, url, maxBytes, signal) {
603
+ const chunks = [];
604
+ let received = 0;
605
+ for (;;) {
606
+ const { done, value } = await reader.read();
607
+ if (signal.aborted) throw signal.reason;
608
+ if (done) return Buffer.concat(chunks);
609
+ received += value.byteLength;
610
+ if (received > maxBytes) {
611
+ reader.cancel().catch(() => void 0);
612
+ throw new DownloadError(`${url} is larger than ${maxBytes} bytes`);
613
+ }
614
+ chunks.push(value);
615
+ }
616
+ }
617
+ /** The response's body once it is known to be a success within the cap. */
618
+ function refuseResponse(res, message) {
619
+ res.body?.cancel().catch(() => void 0);
620
+ throw new DownloadError(message);
621
+ }
622
+ function acceptedBody(res, url, maxBytes) {
623
+ if (!res.ok) refuseResponse(res, `${url} answered HTTP ${res.status}`);
624
+ const declared = Number(res.headers.get("content-length"));
625
+ if (Number.isFinite(declared) && declared > maxBytes) refuseResponse(res, `${url} is ${declared} bytes, more than ${maxBytes}`);
626
+ if (!res.body) throw new DownloadError(`${url} answered with no body`);
627
+ return res.body;
628
+ }
629
+ function settlesByDeadline(pending, signal) {
630
+ return new Promise((resolve, reject) => {
631
+ const onAbort = () => reject(signal.reason);
632
+ if (signal.aborted) onAbort();
633
+ signal.addEventListener("abort", onAbort, { once: true });
634
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
635
+ });
636
+ }
637
+ async function downloadBytes(fetchFn, url, headers, limits) {
638
+ const controller = new AbortController();
639
+ const timer = setTimeout(() => controller.abort(new DownloadError(`${url} did not finish within ${limits.timeoutMs}ms`)), limits.timeoutMs);
640
+ try {
641
+ return await readCapped(acceptedBody(await settlesByDeadline(fetchFn(url, {
642
+ headers,
643
+ signal: controller.signal,
644
+ redirect: "follow"
645
+ }), controller.signal), url, limits.maxBytes), url, limits.maxBytes, controller.signal);
646
+ } catch (err) {
647
+ if (err instanceof DownloadError) throw err;
648
+ const reason = controller.signal.aborted ? controller.signal.reason : err;
649
+ throw reason instanceof DownloadError ? reason : new DownloadError(`${url} could not be downloaded: ${String(reason)}`);
650
+ } finally {
651
+ clearTimeout(timer);
652
+ }
653
+ }
654
+ async function downloadJson(fetchFn, url, headers, limits) {
655
+ const bytes = await downloadBytes(fetchFn, url, headers, limits);
656
+ try {
657
+ return JSON.parse(bytes.toString("utf-8"));
658
+ } catch {
659
+ throw new DownloadError(`${url} did not answer with JSON`);
660
+ }
661
+ }
662
+ var SRI = /^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/;
663
+ /** Whether `bytes` match an npm `dist.integrity` (Subresource Integrity, possibly several space-
664
+ * separated hashes) — the strongest algorithm present must match. False when none is recognised. */
665
+ function matchesIntegrity(bytes, integrity) {
666
+ const hashes = integrity.split(/\s+/).map((part) => SRI.exec(part)).filter((match) => match !== null);
667
+ const strongest = [
668
+ "sha512",
669
+ "sha384",
670
+ "sha256"
671
+ ].find((algorithm) => hashes.some((match) => match[1] === algorithm));
672
+ if (strongest === void 0) return false;
673
+ const actual = (0, node_crypto.createHash)(strongest).update(bytes).digest("base64");
674
+ return hashes.some((match) => match[1] === strongest && match[2] === actual);
675
+ }
676
+ // src/runtime-plugins/fetchPackage.ts
677
+ var NPM_REGISTRY = "https://registry.npmjs.org";
678
+ var GITHUB_API = "https://api.github.com";
679
+ var ONE_SECOND_MS = 1e3;
680
+ var ONE_MIB$1 = 1048576;
681
+ var METADATA_LIMITS = {
682
+ timeoutMs: 30 * ONE_SECOND_MS,
683
+ maxBytes: 32 * ONE_MIB$1
684
+ };
685
+ var PACKAGE_LIMITS = {
686
+ timeoutMs: 120 * ONE_SECOND_MS,
687
+ maxBytes: 50 * ONE_MIB$1
688
+ };
689
+ var USER_AGENT = "mulmo-runtime-plugins";
690
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
691
+ var fail = (error) => ({
692
+ ok: false,
693
+ error
694
+ });
695
+ var isHttpsUrl = (value) => value.startsWith("https://");
696
+ function resolveNpmVersion(packument, versions, spec) {
697
+ const tags = require_dist.isRecord(packument["dist-tags"]) ? packument["dist-tags"] : {};
698
+ if (spec !== null && Object.hasOwn(versions, spec)) return {
699
+ ok: true,
700
+ value: spec
701
+ };
702
+ const tag = spec ?? "latest";
703
+ const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null;
704
+ if (fromTag !== null) return {
705
+ ok: true,
706
+ value: fromTag
707
+ };
708
+ return fail(spec === null ? "the package has no latest version" : `no version or dist-tag ${JSON.stringify(spec)}`);
709
+ }
710
+ function releaseOf(versions, version) {
711
+ const entry = Object.hasOwn(versions, version) ? versions[version] : void 0;
712
+ const dist = require_dist.isRecord(entry) && require_dist.isRecord(entry.dist) ? entry.dist : null;
713
+ const tarball = dist ? stringOrNull(dist.tarball) : null;
714
+ if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`);
715
+ return {
716
+ ok: true,
717
+ value: {
718
+ version,
719
+ tarball,
720
+ integrity: stringOrNull(dist.integrity)
721
+ }
722
+ };
723
+ }
724
+ /** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */
725
+ function resolveNpmRelease(packument, spec) {
726
+ if (!require_dist.isRecord(packument) || !require_dist.isRecord(packument.versions)) return fail("the registry did not answer with a package");
727
+ const version = resolveNpmVersion(packument, packument.versions, spec);
728
+ return version.ok ? releaseOf(packument.versions, version.value) : version;
729
+ }
730
+ /** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */
731
+ function verifyNpmBytes(bytes, release) {
732
+ if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`;
733
+ return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`;
734
+ }
735
+ var assetsOf = (release) => Array.isArray(release.assets) ? release.assets.filter(require_dist.isRecord) : [];
736
+ /** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin
737
+ * is exactly what a user should not have to trust. */
738
+ function resolveGithubAsset(release) {
739
+ if (!require_dist.isRecord(release) || typeof release.tag_name !== "string") return fail("GitHub did not answer with a release");
740
+ const assets = assetsOf(release);
741
+ const tgz = assets.filter((asset) => typeof asset.name === "string" && asset.name.endsWith(".tgz"));
742
+ const names = assets.map((asset) => String(asset.name)).join(", ") || "none";
743
+ if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`);
744
+ const [asset] = tgz;
745
+ const downloadUrl = stringOrNull(asset?.browser_download_url);
746
+ const apiUrl = stringOrNull(asset?.url);
747
+ if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl)) return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`);
748
+ return {
749
+ ok: true,
750
+ value: {
751
+ tag: release.tag_name,
752
+ name: String(asset?.name),
753
+ downloadUrl,
754
+ apiUrl,
755
+ digest: stringOrNull(asset?.digest)
756
+ }
757
+ };
758
+ }
759
+ var SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/;
760
+ /** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older
761
+ * uploads carry none, and the bytes still came over https from GitHub — but a digest that is present
762
+ * must be a sha256 and must match. */
763
+ function verifyGithubBytes(bytes, asset) {
764
+ if (asset.digest === null) return null;
765
+ const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1];
766
+ if (expected === void 0) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`;
767
+ return (0, node_crypto.createHash)("sha256").update(bytes).digest("hex") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`;
768
+ }
769
+ function httpsBase(base, what) {
770
+ if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`);
771
+ return base.endsWith("/") ? base.slice(0, -1) : base;
772
+ }
773
+ var packumentUrl = (registry, name) => `${registry}/${name.replaceAll("/", "%2f")}`;
774
+ async function fetchNpm(source, deps) {
775
+ const accept = {
776
+ accept: "application/vnd.npm.install-v1+json",
777
+ "user-agent": USER_AGENT
778
+ };
779
+ const resolved = resolveNpmRelease(await downloadJson(deps.fetch, packumentUrl(httpsBase(deps.npmRegistry ?? "https://registry.npmjs.org", "the npm registry"), source.name), accept, METADATA_LIMITS), source.spec);
780
+ if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`);
781
+ const release = resolved.value;
782
+ const bytes = await downloadBytes(deps.fetch, release.tarball, { "user-agent": USER_AGENT }, PACKAGE_LIMITS);
783
+ const mismatch = verifyNpmBytes(bytes, release);
784
+ if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`);
785
+ return {
786
+ bytes,
787
+ resolved: release.version
788
+ };
789
+ }
790
+ function githubHeaders(deps, accept) {
791
+ const headers = {
792
+ accept,
793
+ "user-agent": USER_AGENT
794
+ };
795
+ if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`;
796
+ return headers;
797
+ }
798
+ function assetUrl(asset, deps, apiBase) {
799
+ if (!deps.githubToken) return asset.downloadUrl;
800
+ if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`);
801
+ return asset.apiUrl;
802
+ }
803
+ async function fetchGithub(source, deps) {
804
+ const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`;
805
+ const which = source.tag === null ? "latest" : `tags/${encodeURIComponent(source.tag)}`;
806
+ const apiBase = httpsBase(deps.githubApi ?? "https://api.github.com", "the GitHub API");
807
+ const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`;
808
+ const resolved = resolveGithubAsset(await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, "application/vnd.github+json"), METADATA_LIMITS));
809
+ if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`);
810
+ const asset = resolved.value;
811
+ const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, "application/octet-stream"), PACKAGE_LIMITS);
812
+ const mismatch = verifyGithubBytes(bytes, asset);
813
+ if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`);
814
+ return {
815
+ bytes,
816
+ resolved: asset.tag
817
+ };
818
+ }
819
+ var fetchPackage = (source, deps) => source.kind === "npm" ? fetchNpm(source, deps) : fetchGithub(source, deps);
820
+ // src/runtime-plugins/inspect.ts
821
+ var TEMP_PREFIX = ".inspect-";
822
+ var MAX_UNPACKED_BYTES = 268435456;
823
+ /** Whether the gzip stream expands to at most `maxBytes`, counted while it is inflated so a hostile
824
+ * archive is stopped at the limit rather than after it has been written out. */
825
+ function inflatesWithin(bytes, maxBytes) {
826
+ return new Promise((resolve, reject) => {
827
+ const gunzip = (0, node_zlib.createGunzip)();
828
+ let inflated = 0;
829
+ gunzip.on("data", (chunk) => {
830
+ inflated += chunk.length;
831
+ if (inflated <= maxBytes) return;
832
+ gunzip.destroy();
833
+ resolve(false);
834
+ });
835
+ gunzip.on("end", () => resolve(true));
836
+ gunzip.on("error", reject);
837
+ gunzip.end(bytes);
838
+ });
839
+ }
840
+ var UNPARSABLE = Symbol("unparsable");
841
+ function parseJsonFile(file) {
842
+ try {
843
+ return JSON.parse((0, node_fs.readFileSync)(file, "utf-8"));
844
+ } catch {
845
+ return UNPARSABLE;
846
+ }
847
+ }
848
+ var refuse = (error) => ({
849
+ ok: false,
850
+ error
851
+ });
852
+ function readPackage(dir) {
853
+ const outward = linkLeadingOut(dir);
854
+ if (outward !== null) return refuse(`the package holds a link that leads outside it: ${outward}`);
855
+ const pkgPath = node_path.default.join(dir, "package.json");
856
+ if (!(0, node_fs.existsSync)(pkgPath)) return refuse("the package has no package.json");
857
+ const parsed = parseJsonFile(pkgPath);
858
+ if (parsed === UNPARSABLE) return refuse("the package's package.json is not valid JSON");
859
+ const pkg = toPackageJson(parsed);
860
+ if (pkg?.name === void 0 || pkg.version === void 0) return refuse("the package's package.json has no name or version");
861
+ const entrySpec = resolveEntrySpecifier(pkg);
862
+ if (entrySpec === null) return refuse("the package's package.json names no server entry (exports, module or main)");
863
+ const entryAbs = node_path.default.join(dir, entrySpec);
864
+ if (!ensureInsideBase(entryAbs, dir) || !resolvesInside(entryAbs, dir)) return refuse(`the package's server entry ${entrySpec} is not in it`);
865
+ if (!(0, node_fs.statSync)(entryAbs).isFile()) return refuse(`the package's server entry ${entrySpec} is not a file`);
866
+ return {
867
+ ok: true,
868
+ value: {
869
+ name: pkg.name,
870
+ version: pkg.version,
871
+ entrySpec
872
+ }
873
+ };
874
+ }
875
+ /** What the package file says it is, or why it is not a package this loader can use. */
876
+ async function inspectPackage(bytes, pluginsDir) {
877
+ const withinLimit = await inflatesWithin(bytes, MAX_UNPACKED_BYTES).catch(() => null);
878
+ if (withinLimit === null) return refuse("the file is not a gzip package");
879
+ if (!withinLimit) return refuse(`the package expands to more than ${MAX_UNPACKED_BYTES} bytes`);
880
+ const work = await (0, node_fs_promises.mkdtemp)(node_path.default.join(pluginsDir, TEMP_PREFIX));
881
+ try {
882
+ const tgz = node_path.default.join(work, "package.tgz");
883
+ await (0, node_fs_promises.writeFile)(tgz, bytes);
884
+ const unpacked = node_path.default.join(work, "unpacked");
885
+ try {
886
+ extractTgz(tgz, unpacked);
887
+ } catch (err) {
888
+ return refuse(`the file could not be unpacked as a package: ${String(err)}`);
889
+ }
890
+ return readPackage(unpacked);
891
+ } finally {
892
+ await (0, node_fs_promises.rm)(work, {
893
+ recursive: true,
894
+ force: true
895
+ });
896
+ }
897
+ }
898
+ // src/runtime-plugins/install.ts
899
+ var InstallError = class extends Error {};
900
+ function checkIdentity(source, resolved, name, version) {
901
+ if (!isNpmPackageName(name)) throw new InstallError(`the package's name ${JSON.stringify(name)} is not an npm package name`);
902
+ if (!isExactVersion(version)) throw new InstallError(`the package's version ${JSON.stringify(version)} is not an exact version`);
903
+ if (source.kind !== "npm") return;
904
+ if (name !== source.name) throw new InstallError(`asked for ${source.name}, but the package is ${name}`);
905
+ if (version !== resolved) throw new InstallError(`asked for ${source.name}@${resolved}, but the package is version ${version}`);
906
+ }
907
+ async function preparePlan(source, deps) {
908
+ await (0, node_fs_promises.mkdir)(deps.paths.pluginsDir, { recursive: true });
909
+ const ledger = await readLedgerForWrite(deps.paths.ledgerPath);
910
+ if (!ledger.ok) throw new InstallError(ledger.error);
911
+ const fetched = await fetchPackage(source, deps);
912
+ const inspection = await inspectPackage(fetched.bytes, deps.paths.pluginsDir);
913
+ if (!inspection.ok) throw new InstallError(inspection.error);
914
+ const inspected = inspection.value;
915
+ checkIdentity(source, fetched.resolved, inspected.name, inspected.version);
916
+ const replaces = parseLedger(ledger.raw).find((entry) => entry.name === inspected.name) ?? null;
917
+ const tgz = installedFileName(inspected.name, inspected.version, (0, node_crypto.createHash)("sha256").update(fetched.bytes).digest("hex"));
918
+ return {
919
+ plan: {
920
+ name: inspected.name,
921
+ version: inspected.version,
922
+ source: sourceLabel(source, fetched.resolved),
923
+ tgz,
924
+ replaces
925
+ },
926
+ bytes: fetched.bytes,
927
+ raw: ledger.raw
928
+ };
929
+ }
930
+ async function dropStaleCache(plan, raw, paths) {
931
+ const sameVersion = parseLedger(raw).filter((entry) => entry.name === plan.name && entry.version === plan.version);
932
+ if (sameVersion.length > 0 && sameVersion.every((entry) => entry.tgz === plan.tgz)) return;
933
+ const cacheDir = paths.cacheDir ?? node_path.default.join(paths.pluginsDir, ".cache");
934
+ const stale = node_path.default.join(cacheDir, plan.name, plan.version);
935
+ if (ensureInsideBase(stale, cacheDir)) await (0, node_fs_promises.rm)(stale, {
936
+ recursive: true,
937
+ force: true
938
+ });
939
+ }
940
+ async function writePackageFile(plan, bytes, pluginsDir) {
941
+ const tgzPath = node_path.default.join(pluginsDir, plan.tgz);
942
+ const fileWasThere = (0, node_fs.existsSync)(tgzPath);
943
+ if (fileWasThere && !(await (0, node_fs_promises.readFile)(tgzPath)).equals(bytes)) throw new InstallError(`${plan.tgz} already exists with different bytes; not overwritten`);
944
+ if (!fileWasThere) await require_atomic.writeFileAtomic(tgzPath, bytes);
945
+ return {
946
+ tgzPath,
947
+ fileWasThere
948
+ };
949
+ }
950
+ async function commit(plan, bytes, raw, deps) {
951
+ const { tgzPath, fileWasThere } = await writePackageFile(plan, bytes, deps.paths.pluginsDir);
952
+ const installedAt = (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
953
+ const entry = {
954
+ name: plan.name,
955
+ version: plan.version,
956
+ tgz: plan.tgz,
957
+ installedAt,
958
+ source: plan.source
959
+ };
960
+ try {
961
+ await dropStaleCache(plan, raw, deps.paths);
962
+ await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));
963
+ } catch (err) {
964
+ if (!fileWasThere) await (0, node_fs_promises.rm)(tgzPath, { force: true });
965
+ throw err;
966
+ }
967
+ return entry;
968
+ }
969
+ var failure = (err, action) => {
970
+ if (err instanceof InstallError || err instanceof DownloadError) return {
971
+ status: "failed",
972
+ error: err.message
973
+ };
974
+ return {
975
+ status: "failed",
976
+ error: `${action} failed: ${err instanceof Error ? err.message : String(err)}`
977
+ };
978
+ };
979
+ /** Install what `input` names (`<npm name>[@<version or dist-tag>]` or `github:<owner>/<repo>[#<tag>]`). */
980
+ async function installRuntimePlugin(input, deps) {
981
+ const parsed = parseInstallSource(input);
982
+ if (!parsed.ok) return {
983
+ status: "failed",
984
+ error: parsed.error
985
+ };
986
+ try {
987
+ const { plan, bytes, raw } = await preparePlan(parsed.source, deps);
988
+ if (!await deps.confirm(plan)) return {
989
+ status: "cancelled",
990
+ plan
991
+ };
992
+ return {
993
+ status: "installed",
994
+ entry: await commit(plan, bytes, raw, deps),
995
+ replaced: plan.replaces
996
+ };
997
+ } catch (err) {
998
+ return failure(err, "install");
999
+ }
1000
+ }
1001
+ /** Take `name` out of the ledger. Its package file, unpacked copy and data folders are left in place. */
1002
+ async function uninstallRuntimePlugin(name, paths) {
1003
+ const ledger = await readLedgerForWrite(paths.ledgerPath);
1004
+ if (!ledger.ok) return {
1005
+ status: "failed",
1006
+ error: ledger.error
1007
+ };
1008
+ const entry = parseLedger(ledger.raw).find((candidate) => candidate.name === name) ?? null;
1009
+ const remaining = withoutLedgerEntry(ledger.raw, name);
1010
+ if (remaining.length === ledger.raw.length) return { status: "not-installed" };
1011
+ try {
1012
+ await writeLedger(paths.ledgerPath, remaining);
1013
+ } catch (err) {
1014
+ return failure(err, "uninstall");
1015
+ }
1016
+ return {
1017
+ status: "removed",
1018
+ entry
1019
+ };
1020
+ }
1021
+ exports.DownloadError = DownloadError;
317
1022
  exports.EXTRACT_MARKER = EXTRACT_MARKER;
1023
+ exports.GITHUB_API = GITHUB_API;
1024
+ exports.NPM_REGISTRY = NPM_REGISTRY;
1025
+ exports.downloadBytes = downloadBytes;
1026
+ exports.downloadJson = downloadJson;
318
1027
  exports.ensureInsideBase = ensureInsideBase;
319
1028
  exports.extractTgz = extractTgz;
1029
+ exports.fetchPackage = fetchPackage;
1030
+ exports.inspectPackage = inspectPackage;
1031
+ exports.installRuntimePlugin = installRuntimePlugin;
1032
+ exports.installedFileName = installedFileName;
320
1033
  exports.isCacheValid = isCacheValid;
1034
+ exports.isExactVersion = isExactVersion;
321
1035
  exports.isLedgerEntry = isLedgerEntry;
1036
+ exports.isNpmPackageName = isNpmPackageName;
1037
+ exports.isNpmVersionSpec = isNpmVersionSpec;
1038
+ exports.linkLeadingOut = linkLeadingOut;
322
1039
  exports.loadPluginFromCacheDir = loadPluginFromCacheDir;
1040
+ exports.matchesIntegrity = matchesIntegrity;
1041
+ exports.packageFileName = packageFileName;
1042
+ exports.parseInstallSource = parseInstallSource;
323
1043
  exports.parseLedger = parseLedger;
324
1044
  exports.prepareLedgerEntry = prepareLedgerEntry;
1045
+ exports.readLedgerForWrite = readLedgerForWrite;
325
1046
  exports.resolveEntrySpecifier = resolveEntrySpecifier;
326
1047
  exports.resolveExecute = resolveExecute;
1048
+ exports.resolveGithubAsset = resolveGithubAsset;
1049
+ exports.resolveNpmRelease = resolveNpmRelease;
1050
+ exports.resolvesInside = resolvesInside;
1051
+ exports.sourceLabel = sourceLabel;
327
1052
  exports.toPackageJson = toPackageJson;
1053
+ exports.uninstallRuntimePlugin = uninstallRuntimePlugin;
1054
+ exports.verifyGithubBytes = verifyGithubBytes;
1055
+ exports.verifyNpmBytes = verifyNpmBytes;
1056
+ exports.withLedgerEntry = withLedgerEntry;
1057
+ exports.withoutLedgerEntry = withoutLedgerEntry;
1058
+ exports.writeLedger = writeLedger;
328
1059
 
329
1060
  //# sourceMappingURL=index.cjs.map