@jini-ai/platform 0.7.2 → 0.7.3-next.1

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 (169) hide show
  1. package/CHANGELOG.md +2 -8
  2. package/README.md +16 -4
  3. package/dist/asset-cache.d.ts +13 -3
  4. package/dist/asset-cache.js +163 -154
  5. package/dist/blob-storage.d.ts +3 -32
  6. package/dist/blob-storage.js +1 -9
  7. package/dist/child-environment.d.ts +0 -16
  8. package/dist/child-environment.js +0 -25
  9. package/dist/command.d.ts +6 -11
  10. package/dist/command.js +8 -54
  11. package/dist/download-lock.d.ts +4 -0
  12. package/dist/download-lock.js +82 -0
  13. package/dist/download-maintenance.d.ts +5 -0
  14. package/dist/download-maintenance.js +82 -0
  15. package/dist/download-state.d.ts +8 -0
  16. package/dist/download-state.js +126 -0
  17. package/dist/download-store.d.ts +22 -0
  18. package/dist/download-store.js +174 -0
  19. package/dist/download-target.d.ts +10 -0
  20. package/dist/download-target.js +102 -0
  21. package/dist/download-transfer.d.ts +12 -0
  22. package/dist/download-transfer.js +174 -0
  23. package/dist/download-types.d.ts +162 -0
  24. package/dist/download-types.js +31 -0
  25. package/dist/download.d.ts +1 -89
  26. package/dist/download.js +8 -738
  27. package/dist/fetch-with-timeout.d.ts +7 -32
  28. package/dist/fetch-with-timeout.js +1 -77
  29. package/dist/fs/app-data-root.d.ts +28 -0
  30. package/dist/fs/app-data-root.js +35 -0
  31. package/dist/fs/atomic-write.js +1 -1
  32. package/dist/fs/boot-identity.d.ts +1 -4
  33. package/dist/fs/directory-delete-guard.d.ts +93 -0
  34. package/dist/fs/directory-delete-guard.js +148 -0
  35. package/dist/fs/directory-registry.js +45 -35
  36. package/dist/fs/directory-relocation.d.ts +82 -0
  37. package/dist/fs/directory-relocation.js +99 -0
  38. package/dist/fs/directory-running-lock.d.ts +1 -1
  39. package/dist/fs/directory-running-lock.js +24 -21
  40. package/dist/fs/directory-sync.js +1 -1
  41. package/dist/fs/directory-user-config.js +30 -3
  42. package/dist/fs/directory-workspace.d.ts +34 -30
  43. package/dist/fs/directory-workspace.js +70 -29
  44. package/dist/fs/durable-json.d.ts +6 -15
  45. package/dist/fs/durable-json.js +38 -35
  46. package/dist/fs/errno.d.ts +12 -3
  47. package/dist/fs/errno.js +5 -3
  48. package/dist/fs/file-lock.d.ts +3 -87
  49. package/dist/fs/file-lock.js +16 -30
  50. package/dist/fs/guarded-reader.js +335 -315
  51. package/dist/fs/index.d.ts +5 -0
  52. package/dist/fs/index.js +5 -0
  53. package/dist/fs/recent-directories.d.ts +46 -0
  54. package/dist/fs/recent-directories.js +68 -0
  55. package/dist/fs/remove-directory-tree.d.ts +20 -0
  56. package/dist/fs/remove-directory-tree.js +28 -0
  57. package/dist/fs/user-data-directories.js +2 -2
  58. package/dist/fs/workspace-directory.js +2 -1
  59. package/dist/fs.d.ts +16 -4
  60. package/dist/fs.js +4 -4
  61. package/dist/home-expansion.d.ts +7 -2
  62. package/dist/home-expansion.js +3 -3
  63. package/dist/http/guarded/client.d.ts +1 -2
  64. package/dist/http/guarded/client.js +2 -1
  65. package/dist/http/guarded/index.d.ts +0 -3
  66. package/dist/http/guarded/node-ports.d.ts +1 -1
  67. package/dist/http/guarded/transport.fetch.d.ts +2 -3
  68. package/dist/http/guarded/transport.fetch.js +64 -58
  69. package/dist/http.d.ts +3 -1
  70. package/dist/http.js +2 -2
  71. package/dist/index.d.ts +10 -11
  72. package/dist/index.js +7 -6
  73. package/dist/mail/activity/activity.d.ts +136 -0
  74. package/dist/mail/activity/activity.js +172 -0
  75. package/dist/mail/activity/ports.d.ts +113 -0
  76. package/dist/mail/activity/suppressions.d.ts +82 -0
  77. package/dist/mail/activity/suppressions.js +119 -0
  78. package/dist/mail/activity/vocabulary.d.ts +10 -0
  79. package/dist/mail/activity/vocabulary.js +8 -0
  80. package/dist/mail/builtin-providers.d.ts +12 -6
  81. package/dist/mail/builtin-providers.js +14 -11
  82. package/dist/mail/delivery-wrapper.js +2 -1
  83. package/dist/mail/email-sender-registry.d.ts +1 -1
  84. package/dist/mail/email-sender-registry.js +1 -1
  85. package/dist/mail/email-template-operations.d.ts +186 -0
  86. package/dist/mail/email-template-operations.js +226 -0
  87. package/dist/mail/email-template.d.ts +120 -0
  88. package/dist/mail/email-template.js +243 -0
  89. package/dist/mail/index.d.ts +4 -0
  90. package/dist/mail/index.js +3 -0
  91. package/dist/mail/prepare-sender-email.d.ts +1 -10
  92. package/dist/mail/prepare-sender-email.js +1 -11
  93. package/dist/mail/resolve-mailer.d.ts +2 -1
  94. package/dist/mail/resolve-mailer.js +5 -2
  95. package/dist/mail/senders.d.ts +0 -1
  96. package/dist/mail/senders.js +0 -1
  97. package/dist/mail/smtp.d.ts +1 -31
  98. package/dist/net/address.d.ts +1 -8
  99. package/dist/net/address.js +1 -18
  100. package/dist/net/index.d.ts +1 -1
  101. package/dist/net/index.js +1 -1
  102. package/dist/net/local-http-probe.js +1 -1
  103. package/dist/net/local-http-request.js +1 -1
  104. package/dist/process-probes.d.ts +36 -0
  105. package/dist/process-probes.js +151 -0
  106. package/dist/process-top-footprint.d.ts +7 -0
  107. package/dist/process-top-footprint.js +30 -0
  108. package/dist/process.d.ts +29 -31
  109. package/dist/process.js +18 -196
  110. package/dist/proxy-env.d.ts +12 -3
  111. package/dist/proxy-env.js +9 -8
  112. package/dist/resource-paths.d.ts +15 -3
  113. package/dist/resource-paths.js +7 -5
  114. package/dist/sandbox-env.d.ts +26 -5
  115. package/dist/sandbox-env.js +7 -7
  116. package/dist/secrets/credential-sets/contracts.d.ts +0 -1
  117. package/dist/secrets/credential-sets/contracts.js +0 -1
  118. package/dist/secrets/credential-sets/index.d.ts +2 -3
  119. package/dist/secrets/credential-sets/index.js +1 -1
  120. package/dist/secrets/credential-sets/provider-matches.d.ts +1 -1
  121. package/dist/secrets/credential-sets/provider-matches.js +1 -1
  122. package/dist/secrets/credential-sets/vault-archive.d.ts +1 -1
  123. package/dist/secrets/credential-sets/vault-archive.js +14 -8
  124. package/dist/secrets/credential-sets/vault.aad.d.ts +1 -1
  125. package/dist/secrets/credential-sets/vault.meta.d.ts +1 -1
  126. package/dist/secrets/credential-sets/vault.meta.js +1 -1
  127. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -1
  128. package/dist/secrets/credential-sets/vault.repo.memory.js +1 -1
  129. package/dist/secrets/credential-sets/vault.reseal-refused.d.ts +23 -0
  130. package/dist/secrets/credential-sets/vault.reseal-refused.js +36 -0
  131. package/dist/secrets/credential-sets/vault.service.d.ts +25 -5
  132. package/dist/secrets/credential-sets/vault.service.js +42 -8
  133. package/dist/secrets/index.d.ts +0 -3
  134. package/dist/secrets/index.js +5 -0
  135. package/dist/secrets/keyring.env.d.ts +1 -1
  136. package/dist/secrets/legacy-owner.d.ts +61 -0
  137. package/dist/secrets/legacy-owner.js +196 -0
  138. package/dist/secrets/root-key/decide.d.ts +89 -0
  139. package/dist/secrets/root-key/decide.js +60 -0
  140. package/dist/secrets/sealer-contract.d.ts +19 -0
  141. package/dist/secrets/sealer-contract.js +37 -0
  142. package/dist/secrets/secret-sealer.aesgcm.d.ts +1 -1
  143. package/dist/secrets/testing.d.ts +1 -0
  144. package/dist/secrets/testing.js +1 -0
  145. package/dist/shell.d.ts +4 -1
  146. package/dist/shell.js +1 -1
  147. package/dist/system.d.ts +6 -0
  148. package/dist/system.js +9 -0
  149. package/dist/terminal.d.ts +11 -96
  150. package/dist/terminal.js +80 -56
  151. package/dist/web/agent-tools.d.ts +107 -0
  152. package/dist/web/agent-tools.js +49 -0
  153. package/dist/web/index.d.ts +1 -0
  154. package/dist/web/index.js +1 -0
  155. package/package.json +38 -12
  156. package/dist/http/guarded/ports.d.ts +0 -56
  157. package/dist/http/guarded/types.d.ts +0 -8
  158. package/dist/http/guarded/types.js +0 -2
  159. package/dist/mail/email-sender.d.ts +0 -109
  160. package/dist/mail/email-sender.js +0 -10
  161. package/dist/net/endpoint-policy.d.ts +0 -39
  162. package/dist/net/endpoint-policy.js +0 -218
  163. package/dist/secrets/credential-sets/aad.d.ts +0 -7
  164. package/dist/secrets/credential-sets/aad.js +0 -7
  165. package/dist/secrets/credential-sets/repo.memory.d.ts +0 -44
  166. package/dist/secrets/credential-sets/repo.memory.js +0 -80
  167. package/dist/secrets/credential-sets/vault.types.d.ts +0 -27
  168. package/dist/secrets/credential-sets/vault.types.js +0 -49
  169. /package/dist/{http/guarded → mail/activity}/ports.js +0 -0
package/dist/command.js CHANGED
@@ -11,54 +11,7 @@
11
11
  * itself.
12
12
  */
13
13
  import { extname } from "node:path";
14
- import { trimCharsEnd } from "@jini-ai/core/primitives";
15
- // `cmd.exe /s /c "..."` runs percent-expansion on the inner line *regardless*
16
- // of whether the `%name%` pair sits inside a `"..."` quoted segment, so a
17
- // `.cmd` / `.bat` shim spawn with an attacker-influenced argv (e.g. an LLM
18
- // adapter that ships the user prompt as a positional argument) lets a stray
19
- // `%DEEPSEEK_API_KEY%` substring substitute live env values into the line
20
- // before the child sees it. Plain quote-doubling is not enough on its own.
21
- //
22
- // The fix is to break each potential `%var%` pair by toggling out of the
23
- // outer quote with `"^%"`: cmd treats the `^` as the standard escape for the
24
- // next char (here, `%`), making it literal and skipping percent-expansion;
25
- // `CommandLineToArgvW` then concatenates the surrounding quote segments back
26
- // into one literal arg with the `%` preserved. The two layers cancel, so the
27
- // child receives the original arg byte-for-byte while cmd never has a chance
28
- // to expand anything inside it.
29
- function quoteWindowsCommandArg({ value }, _options = {}) {
30
- if (/[\r\n]/.test(value))
31
- throw new Error("Windows command shim arguments cannot contain line breaks");
32
- if (value !== "" && !/[\s"&<>|^%=,;()]/.test(value))
33
- return value;
34
- // Backslashes before the closing quote must survive the child's argv parser.
35
- const quoted = value.replace(/"/g, '""').replace(/%/g, '"^%"');
36
- const trailingBackslashes = quoted.slice(trimCharsEnd({ text: quoted, chars: '\\' }).length);
37
- const escaped = quoted + trailingBackslashes;
38
- return `"${escaped}"`;
39
- }
40
- // Build the `cmd.exe /d /s /c "<line>"` invocation Node uses internally for
41
- // `shell: true`. The outer `"..."` plus `windowsVerbatimArguments: true` is
42
- // the only shape that survives both layers of quoting:
43
- //
44
- // 1. Node would otherwise escape each argv element with CommandLineToArgvW
45
- // rules (turning `"path with space"` into `\"path with space\"`), which
46
- // cmd.exe does not understand.
47
- // 2. cmd.exe with `/s /c` strips exactly one leading and one trailing `"`
48
- // from the rest of the command line. The outer wrap absorbs that strip
49
- // so any inner per-arg quoting stays intact.
50
- //
51
- // Without this, paths containing spaces (`C:\Users\First Last\...\foo.cmd`)
52
- // get split on the first space and cmd.exe reports "not recognized as an
53
- // internal or external command" — see issue #315.
54
- function buildCmdShimInvocation({ command, args, env }, _options = {}) {
55
- const inner = [command, ...args].map((value) => quoteWindowsCommandArg({ value })).join(" ");
56
- return {
57
- args: ["/d", "/s", "/c", `"${inner}"`],
58
- command: env.ComSpec ?? process.env.ComSpec ?? "cmd.exe",
59
- windowsVerbatimArguments: true,
60
- };
61
- }
14
+ import { planCmdShimInvocation, planCommandInvocation } from "@jini-ai/core/contracts/runtime";
62
15
  const nodeLoadablePackageManagerExtensions = new Set([".js", ".cjs", ".mjs"]);
63
16
  /**
64
17
  * Resolve a command request into the concrete invocation to spawn. On Windows,
@@ -70,10 +23,11 @@ const nodeLoadablePackageManagerExtensions = new Set([".js", ".cjs", ".mjs"]);
70
23
  * @returns The `{ command, args }` (plus `windowsVerbatimArguments` when a shim is used) to spawn.
71
24
  */
72
25
  export function createCommandInvocation({ args = [], command, env = process.env }, _options = {}) {
73
- if (process.platform === "win32" && /\.(bat|cmd)$/i.test(command)) {
74
- return buildCmdShimInvocation({ command, args, env });
75
- }
76
- return { args, command };
26
+ return planCommandInvocation({ command, platform: process.platform, env }, { args, fallbackComSpec: ambientComSpec() });
27
+ }
28
+ /** The process's own `ComSpec`, the fallback when a caller-supplied `env` carries none; `ambient` is injectable. */
29
+ function ambientComSpec(ambient = process.env) {
30
+ return ambient.ComSpec;
77
31
  }
78
32
  /**
79
33
  * Build the invocation for re-entering the repo-pinned package manager. Prefers
@@ -85,7 +39,7 @@ export function createCommandInvocation({ args = [], command, env = process.env
85
39
  * @param env - Environment to read `npm_execpath` / `ComSpec` from (defaults to `process.env`).
86
40
  * @returns The `{ command, args }` invocation that runs the package manager.
87
41
  */
88
- export function createPackageManagerInvocation(args, env = process.env) {
42
+ export function createPackageManagerInvocation({ args }, { env = process.env } = {}) {
89
43
  const execPath = env.npm_execpath;
90
44
  if (execPath) {
91
45
  if (nodeLoadablePackageManagerExtensions.has(extname(execPath).toLowerCase())) {
@@ -100,7 +54,7 @@ export function createPackageManagerInvocation(args, env = process.env) {
100
54
  // package manager out of the box, while a bare `pnpm` only resolves when a
101
55
  // separate global install or a `corepack enable` shim is present. See #2438.
102
56
  if (process.platform === "win32") {
103
- return buildCmdShimInvocation({ command: "corepack", args: ["pnpm", ...args], env });
57
+ return planCmdShimInvocation({ command: "corepack", args: ["pnpm", ...args], env }, { fallbackComSpec: ambientComSpec() });
104
58
  }
105
59
  return { args: ["pnpm", ...args], command: "corepack" };
106
60
  }
@@ -0,0 +1,4 @@
1
+ import { type NormalizedTarget, type AcquiredLock } from './download-types.js';
2
+ export declare function acquireLock(target: NormalizedTarget): Promise<AcquiredLock>;
3
+ export declare function releaseLock(lock: AcquiredLock | null): Promise<void>;
4
+ //# sourceMappingURL=download-lock.d.ts.map
@@ -0,0 +1,82 @@
1
+ import { mkdir, rm, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { isProcessAlive } from "./process.js";
4
+ import { ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES } from './download-types.js';
5
+ import { isPlainObject, errorCode, readJson } from './download-store.js';
6
+ const PID_REUSE_GRACE_MS = 1000;
7
+ const PROCESS_STARTED_AT_MS = Date.now() - process.uptime() * 1000;
8
+ function isDownloadLockFile(value) {
9
+ if (!isPlainObject(value))
10
+ return false;
11
+ const record = value;
12
+ const validPid = typeof record.pid === "number" && Number.isInteger(record.pid) && record.pid > 0;
13
+ const validStartedAt = record.processStartedAt == null || typeof record.processStartedAt === "string";
14
+ return typeof record.createdAt === "string" && validPid && validStartedAt;
15
+ }
16
+ function parseTimeMs(value) {
17
+ if (value == null)
18
+ return null;
19
+ const parsed = Date.parse(value);
20
+ return Number.isFinite(parsed) ? parsed : null;
21
+ }
22
+ function lockBelongsToCurrentProcess(lock) {
23
+ // Its only caller (`isLockProcessAlive`) already gates this call behind
24
+ // `lock.pid === process.pid`, so that comparison can never be true here —
25
+ // no redundant re-check.
26
+ const ownerStartedAtMs = parseTimeMs(lock.processStartedAt);
27
+ if (ownerStartedAtMs != null)
28
+ return ownerStartedAtMs >= PROCESS_STARTED_AT_MS - PID_REUSE_GRACE_MS;
29
+ // Older locks only carried a pid. If Windows reuses that pid for this
30
+ // process, a lock that predates this process start is definitely stale.
31
+ const lockCreatedAtMs = parseTimeMs(lock.createdAt);
32
+ return lockCreatedAtMs == null || lockCreatedAtMs >= PROCESS_STARTED_AT_MS - PID_REUSE_GRACE_MS;
33
+ }
34
+ function isLockProcessAlive(lock) {
35
+ if (!isProcessAlive(lock.pid))
36
+ return false;
37
+ if (lock.pid === process.pid)
38
+ return lockBelongsToCurrentProcess(lock);
39
+ return true;
40
+ }
41
+ export async function acquireLock(target) {
42
+ await mkdir(dirname(target.lockPath), { recursive: true });
43
+ // At most two create attempts: the second only after the first hit an
44
+ // existing lock that `clearStaleLock` proved stale and removed; a second
45
+ // EEXIST is real contention. (This was formerly a `for (;;)` loop whose
46
+ // fall-through branch V8 instrumented but no path could take — see archived
47
+ // provenance ledger's 2026-07-22 entry; the straight-line form has none.)
48
+ if (await tryCreateLockFile(target))
49
+ return { path: target.lockPath };
50
+ if (await clearStaleLock(target) && await tryCreateLockFile(target))
51
+ return { path: target.lockPath };
52
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.TARGET_LOCKED, `download target is locked: ${target.bucket}/${target.fileName}`);
53
+ }
54
+ /** Exclusively create the lock file; `false` when one already exists, any other failure is rethrown. */
55
+ async function tryCreateLockFile(target) {
56
+ try {
57
+ await writeFile(target.lockPath, `${JSON.stringify({
58
+ createdAt: new Date().toISOString(),
59
+ pid: process.pid,
60
+ processStartedAt: new Date(PROCESS_STARTED_AT_MS).toISOString(),
61
+ })}\n`, { flag: "wx" });
62
+ return true;
63
+ }
64
+ catch (error) {
65
+ if (errorCode(error) === "EEXIST")
66
+ return false;
67
+ throw error;
68
+ }
69
+ }
70
+ async function clearStaleLock(target) {
71
+ const lock = await readJson(target.lockPath);
72
+ if (!isDownloadLockFile(lock) || isLockProcessAlive(lock))
73
+ return false;
74
+ await rm(target.lockPath, { force: true }).catch(() => undefined);
75
+ return true;
76
+ }
77
+ export async function releaseLock(lock) {
78
+ if (lock == null)
79
+ return;
80
+ await rm(lock.path, { force: true }).catch(() => undefined);
81
+ }
82
+ //# sourceMappingURL=download-lock.js.map
@@ -0,0 +1,5 @@
1
+ import { type RemoveManagedDownloadOptions, type ManagedDownloadInspection, type RemoveManagedDownloadResult, type PruneManagedDownloadsOptions, type PruneManagedDownloadsResult } from './download-types.js';
2
+ export declare function inspectManagedDownload(options: RemoveManagedDownloadOptions): Promise<ManagedDownloadInspection>;
3
+ export declare function removeManagedDownload(options: RemoveManagedDownloadOptions): Promise<RemoveManagedDownloadResult>;
4
+ export declare function pruneManagedDownloads(options: PruneManagedDownloadsOptions): Promise<PruneManagedDownloadsResult>;
5
+ //# sourceMappingURL=download-maintenance.d.ts.map
@@ -0,0 +1,82 @@
1
+ import { readdir, rm, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { removePathBestEffort } from "./fs.js";
4
+ import { ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES, STATE_DIR, PARTIAL_DIR, LOCK_DIR } from './download-types.js';
5
+ import { targetWithoutPayload, activeTargets, targetActiveKey, normalizeBasePath } from './download-target.js';
6
+ import { ensureManagedBase, readManifest, pathExists } from './download-store.js';
7
+ const DEFAULT_PRUNE_OLDER_THAN_MS = 24 * 60 * 60 * 1000;
8
+ export async function inspectManagedDownload(options) {
9
+ const target = targetWithoutPayload(options);
10
+ await ensureManagedBase(target.basePath);
11
+ const rawManifest = await readManifest(target.manifestPath);
12
+ const manifest = rawManifest === "invalid" ? "unreadable" : rawManifest?.state ?? "missing";
13
+ return {
14
+ bucket: target.bucket,
15
+ complete: await pathExists(target.finalPath),
16
+ fileName: target.fileName,
17
+ manifest,
18
+ path: target.finalPath,
19
+ };
20
+ }
21
+ export async function removeManagedDownload(options) {
22
+ const target = targetWithoutPayload(options);
23
+ if (activeTargets.has(targetActiveKey(target))) {
24
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.TARGET_LOCKED, `download target is active: ${target.bucket}/${target.fileName}`);
25
+ }
26
+ await ensureManagedBase(target.basePath);
27
+ await Promise.all([
28
+ removePathBestEffort({ path: target.finalPath }),
29
+ removePathBestEffort({ path: target.partialPath }, { recursive: false }),
30
+ removePathBestEffort({ path: target.manifestPath }, { recursive: false }),
31
+ removePathBestEffort({ path: target.lockPath }, { recursive: false }),
32
+ ]);
33
+ const bucketPath = join(target.basePath, target.bucket);
34
+ const entries = await readdir(bucketPath).catch(() => null);
35
+ if (entries != null && entries.length === 0)
36
+ await rm(bucketPath, { force: true, recursive: true }).catch(() => undefined);
37
+ return { removed: true };
38
+ }
39
+ async function removeEntriesOlderThan(root, olderThan) {
40
+ const warnings = [];
41
+ let removed = 0;
42
+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
43
+ for (const entry of entries) {
44
+ const path = join(root, entry.name);
45
+ const info = await stat(path).catch(() => null);
46
+ if (info == null || info.mtimeMs > olderThan)
47
+ continue;
48
+ const result = await removePathBestEffort({ path });
49
+ // A successful removal never carries an error, so the two checks are exclusive.
50
+ if (result.removed)
51
+ removed += 1;
52
+ if (result.error != null)
53
+ warnings.push(result.error);
54
+ }
55
+ return { removed, warnings };
56
+ }
57
+ export async function pruneManagedDownloads(options) {
58
+ const basePath = normalizeBasePath(options.basePath);
59
+ await ensureManagedBase(basePath);
60
+ const olderThan = (options.now?.getTime() ?? Date.now()) - (options.olderThanMs ?? DEFAULT_PRUNE_OLDER_THAN_MS);
61
+ const roots = [join(basePath, STATE_DIR), join(basePath, PARTIAL_DIR), join(basePath, LOCK_DIR)];
62
+ let removed = 0;
63
+ const warnings = [];
64
+ for (const root of roots) {
65
+ const result = await removeEntriesOlderThan(root, olderThan);
66
+ removed += result.removed;
67
+ warnings.push(...result.warnings);
68
+ }
69
+ const bucketEntries = await readdir(basePath, { withFileTypes: true }).catch(() => []);
70
+ for (const entry of bucketEntries) {
71
+ if (!entry.isDirectory() || entry.name.startsWith("."))
72
+ continue;
73
+ const result = await removeEntriesOlderThan(join(basePath, entry.name), olderThan);
74
+ removed += result.removed;
75
+ warnings.push(...result.warnings);
76
+ const remaining = await readdir(join(basePath, entry.name)).catch(() => null);
77
+ if (remaining != null && remaining.length === 0)
78
+ await rm(join(basePath, entry.name), { force: true, recursive: true }).catch(() => undefined);
79
+ }
80
+ return { removed, warnings };
81
+ }
82
+ //# sourceMappingURL=download-maintenance.js.map
@@ -0,0 +1,8 @@
1
+ import { type NormalizedTarget, type ManagedDownloadProgress, type ManagedDownloadResult } from './download-types.js';
2
+ export declare function runManagedDownload(target: NormalizedTarget, options: {
3
+ emit: (progress: ManagedDownloadProgress) => void;
4
+ fetchImpl: typeof globalThis.fetch;
5
+ maxAttempts: number;
6
+ requestHeaders?: Record<string, string> | undefined;
7
+ }): Promise<ManagedDownloadResult>;
8
+ //# sourceMappingURL=download-state.d.ts.map
@@ -0,0 +1,126 @@
1
+ import { mkdir, rename, rm } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES } from './download-types.js';
4
+ import { resetOwnedTarget, readManifest, pathExists, manifestMatchesTarget, hashFile, statFileSize, ensureManagedBase, writeJson, createManifest, errorMessage } from './download-store.js';
5
+ import { pruneManagedDownloads } from './download-maintenance.js';
6
+ import { acquireLock, releaseLock } from './download-lock.js';
7
+ import { downloadWithRetries } from './download-transfer.js';
8
+ async function suspiciousReset({ target }, _options = {}) {
9
+ await resetOwnedTarget({ target });
10
+ return { manifest: null, reset: true };
11
+ }
12
+ async function loadReusableState(target) {
13
+ const manifest = await readManifest(target.manifestPath);
14
+ const finalExists = await pathExists(target.finalPath);
15
+ const partialExists = await pathExists(target.partialPath);
16
+ if (manifest === "invalid") {
17
+ return await suspiciousReset({ target });
18
+ }
19
+ if (manifest == null) {
20
+ return finalExists || partialExists ? await suspiciousReset({ target }) : { manifest: null };
21
+ }
22
+ if (!manifestMatchesTarget(manifest, target)) {
23
+ return await suspiciousReset({ target });
24
+ }
25
+ if (manifest.state === "complete")
26
+ return await reusableCompleteState({ manifest, target });
27
+ if (!partialExists)
28
+ return await suspiciousReset({ target });
29
+ return { manifest };
30
+ }
31
+ /** Reuse a complete download only when its final file exists and still hashes to the requested checksum. */
32
+ async function reusableCompleteState(input) {
33
+ const { manifest, target } = input;
34
+ // A missing final file needs no separate check: hashing it rejects, which
35
+ // maps to `null` and fails the checksum comparison into the same reset.
36
+ const actual = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
37
+ if (actual !== target.checksum.value)
38
+ return await suspiciousReset({ target });
39
+ const bytes = await statFileSize(target.finalPath);
40
+ if (bytes == null)
41
+ return await suspiciousReset({ target });
42
+ return {
43
+ manifest,
44
+ result: {
45
+ bucket: target.bucket,
46
+ bytes,
47
+ checksum: target.checksum,
48
+ fileName: target.fileName,
49
+ path: target.finalPath,
50
+ reusedComplete: true,
51
+ resumed: false,
52
+ urlDigest: target.urlDigest,
53
+ },
54
+ };
55
+ }
56
+ export async function runManagedDownload(target, options) {
57
+ await ensureManagedBase(target.basePath);
58
+ await pruneManagedDownloads({ basePath: target.basePath }).catch(() => undefined);
59
+ const lock = await acquireLock(target);
60
+ try {
61
+ const state = await loadStateAllowingOneReset({ target });
62
+ if (state.result != null)
63
+ return state.result;
64
+ const download = await downloadWithRetries({ target, manifest: state.manifest, options });
65
+ const bytes = await promoteVerifiedPartial({ target });
66
+ await writeJson(target.manifestPath, createManifest({ target, state: "complete", patch: { totalBytes: download.totalBytes } }));
67
+ return {
68
+ bucket: target.bucket,
69
+ bytes,
70
+ checksum: target.checksum,
71
+ fileName: target.fileName,
72
+ path: target.finalPath,
73
+ reusedComplete: false,
74
+ resumed: download.resumed,
75
+ urlDigest: target.urlDigest,
76
+ };
77
+ }
78
+ finally {
79
+ await releaseLock(lock);
80
+ }
81
+ }
82
+ /** Reload once after target cleanup, retaining the lock until the run finishes. */
83
+ async function loadStateAllowingOneReset({ target }, _options = {}) {
84
+ const state = await loadReusableState(target);
85
+ if (state.reset !== true)
86
+ return state;
87
+ // Whole-base cleanup used to remove the lock and require re-acquisition.
88
+ // Keep it throughout target cleanup so another process cannot take it
89
+ // before we write fresh state, or have its own lock deleted by our finally.
90
+ await ensureManagedBase(target.basePath);
91
+ const reloaded = await loadReusableState(target);
92
+ if (reloaded.reset === true) {
93
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "download state kept resetting after target cleanup");
94
+ }
95
+ return reloaded;
96
+ }
97
+ /** Verify the downloaded partial's checksum, promote it to the final path, and return the final size. */
98
+ async function promoteVerifiedPartial({ target }, _options = {}) {
99
+ const actual = await hashFile(target.partialPath, target.checksum.algorithm).catch((error) => {
100
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, `downloaded partial could not be hashed: ${errorMessage(error)}`);
101
+ });
102
+ if (actual !== target.checksum.value) {
103
+ await resetOwnedTarget({ target }).catch(() => undefined);
104
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.CHECKSUM_MISMATCH, "downloaded file checksum did not match requested payload", {
105
+ actual,
106
+ expected: target.checksum.value,
107
+ });
108
+ }
109
+ await mkdir(dirname(target.finalPath), { recursive: true });
110
+ if (await pathExists(target.finalPath)) {
111
+ const existing = await hashFile(target.finalPath, target.checksum.algorithm).catch(() => null);
112
+ if (existing !== target.checksum.value) {
113
+ await resetOwnedTarget({ target }).catch(() => undefined);
114
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "existing complete file did not match requested payload");
115
+ }
116
+ await rm(target.partialPath, { force: true }).catch(() => undefined);
117
+ }
118
+ else {
119
+ await rename(target.partialPath, target.finalPath);
120
+ }
121
+ const bytes = await statFileSize(target.finalPath);
122
+ if (bytes == null)
123
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_CORRUPT, "complete file is missing after promotion");
124
+ return bytes;
125
+ }
126
+ //# sourceMappingURL=download-state.js.map
@@ -0,0 +1,22 @@
1
+ import { type NormalizedTarget, type DownloadManifest } from './download-types.js';
2
+ export declare function errorCode(error: unknown): string | null;
3
+ export declare function errorMessage(error: unknown): string;
4
+ export declare function pathExists(path: string): Promise<boolean>;
5
+ export declare function readJson<T>(path: string): Promise<T | null>;
6
+ export declare function writeJson(path: string, payload: unknown): Promise<void>;
7
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
8
+ /** Clear only this target's data after rechecking store ownership; keep its lock held. */
9
+ export declare function resetOwnedTarget({ target }: {
10
+ target: NormalizedTarget;
11
+ }, _options?: {}): Promise<void>;
12
+ export declare function ensureManagedBase(basePath: string): Promise<void>;
13
+ export declare function readManifest(path: string): Promise<DownloadManifest | "invalid" | null>;
14
+ export declare function manifestMatchesTarget(manifest: DownloadManifest, target: NormalizedTarget): boolean;
15
+ export declare function createManifest({ target, state, patch }: {
16
+ target: NormalizedTarget;
17
+ state: "complete" | "partial";
18
+ patch?: Partial<Pick<DownloadManifest, "totalBytes" | "validators">> | undefined;
19
+ }, _optional?: {}): DownloadManifest;
20
+ export declare function hashFile(path: string, algorithm: "sha256" | "sha512"): Promise<string>;
21
+ export declare function statFileSize(path: string): Promise<number | null>;
22
+ //# sourceMappingURL=download-store.d.ts.map
@@ -0,0 +1,174 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { access, lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { STORE_KIND, STORE_SCHEMA_VERSION, STORE_SENTINEL, ManagedDownloadError, MANAGED_DOWNLOAD_ERROR_CODES, STATE_DIR, PARTIAL_DIR, LOCK_DIR, MANIFEST_KIND, MANIFEST_SCHEMA_VERSION } from './download-types.js';
7
+ export function errorCode(error) {
8
+ if (typeof error !== "object" || error == null || !("code" in error))
9
+ return null;
10
+ const code = error.code;
11
+ return code == null ? null : String(code);
12
+ }
13
+ export function errorMessage(error) {
14
+ return error instanceof Error ? error.message : String(error);
15
+ }
16
+ export async function pathExists(path) {
17
+ try {
18
+ await access(path);
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ export async function readJson(path) {
26
+ try {
27
+ return JSON.parse(await readFile(path, "utf8"));
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ export async function writeJson(path, payload) {
34
+ await mkdir(dirname(path), { recursive: true });
35
+ const tmp = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
36
+ await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
37
+ await rename(tmp, path);
38
+ }
39
+ async function directoryIsEmpty(path) {
40
+ const entries = await readdir(path);
41
+ return entries.length === 0;
42
+ }
43
+ // Every caller feeds this a `JSON.parse` result, and a parsed JSON array can
44
+ // never carry the named string keys (`kind`, `algorithm`, `pid`, ...) each
45
+ // guard goes on to require, so arrays are rejected without a separate
46
+ // `Array.isArray` check.
47
+ export function isPlainObject(value) {
48
+ return typeof value === "object" && value != null;
49
+ }
50
+ function isStoreSentinel(value) {
51
+ if (!isPlainObject(value))
52
+ return false;
53
+ const record = value;
54
+ return record.kind === STORE_KIND && record.schemaVersion === STORE_SCHEMA_VERSION && typeof record.createdAt === "string";
55
+ }
56
+ async function writeSentinel(basePath) {
57
+ await writeJson(join(basePath, STORE_SENTINEL), {
58
+ createdAt: new Date().toISOString(),
59
+ kind: STORE_KIND,
60
+ schemaVersion: STORE_SCHEMA_VERSION,
61
+ });
62
+ }
63
+ /** Clear only this target's data after rechecking store ownership; keep its lock held. */
64
+ export async function resetOwnedTarget({ target }, _options = {}) {
65
+ const { basePath } = target;
66
+ const sentinel = await readJson(join(basePath, STORE_SENTINEL));
67
+ if (!isStoreSentinel(sentinel)) {
68
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not owned: ${basePath}`);
69
+ }
70
+ for (const path of [target.finalPath, target.partialPath, target.manifestPath]) {
71
+ await rm(path, { force: true }).catch(() => undefined);
72
+ }
73
+ }
74
+ async function ensureStoreDirs(basePath) {
75
+ await mkdir(join(basePath, STATE_DIR), { recursive: true });
76
+ await mkdir(join(basePath, PARTIAL_DIR), { recursive: true });
77
+ await mkdir(join(basePath, LOCK_DIR), { recursive: true });
78
+ }
79
+ export async function ensureManagedBase(basePath) {
80
+ await mkdir(basePath, { recursive: true });
81
+ const entry = await lstat(basePath);
82
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
83
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not an owned directory: ${basePath}`);
84
+ }
85
+ const sentinelPath = join(basePath, STORE_SENTINEL);
86
+ const sentinel = await readJson(sentinelPath);
87
+ if (sentinel != null && !isStoreSentinel(sentinel)) {
88
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base has an invalid ownership marker: ${basePath}`);
89
+ }
90
+ if (sentinel == null) {
91
+ if (!(await directoryIsEmpty(basePath))) {
92
+ throw new ManagedDownloadError(MANAGED_DOWNLOAD_ERROR_CODES.STORE_NOT_OWNED, `download base is not empty and has no ownership marker: ${basePath}`);
93
+ }
94
+ await writeSentinel(basePath);
95
+ }
96
+ await ensureStoreDirs(basePath);
97
+ }
98
+ function isChecksum(value) {
99
+ if (!isPlainObject(value))
100
+ return false;
101
+ const checksum = value;
102
+ return ((checksum.algorithm === "sha256" || checksum.algorithm === "sha512") &&
103
+ typeof checksum.value === "string");
104
+ }
105
+ const MANIFEST_STRING_FIELDS = [
106
+ "bucket",
107
+ "fileName",
108
+ "targetKey",
109
+ "identityDigest",
110
+ "urlDigest",
111
+ "createdAt",
112
+ "updatedAt",
113
+ ];
114
+ function isManifest(value) {
115
+ if (!isPlainObject(value))
116
+ return false;
117
+ const record = value;
118
+ const versionMatches = record.kind === MANIFEST_KIND && record.schemaVersion === MANIFEST_SCHEMA_VERSION;
119
+ const knownState = record.state === "complete" || record.state === "partial";
120
+ return (versionMatches &&
121
+ MANIFEST_STRING_FIELDS.every((field) => typeof record[field] === "string") &&
122
+ isChecksum(record.checksum) &&
123
+ knownState);
124
+ }
125
+ export async function readManifest(path) {
126
+ try {
127
+ const parsed = JSON.parse(await readFile(path, "utf8"));
128
+ return isManifest(parsed) ? parsed : "invalid";
129
+ }
130
+ catch (error) {
131
+ if (errorCode(error) === "ENOENT")
132
+ return null;
133
+ return "invalid";
134
+ }
135
+ }
136
+ const MANIFEST_IDENTITY_FIELDS = ["bucket", "fileName", "targetKey", "identityDigest", "urlDigest"];
137
+ export function manifestMatchesTarget(manifest, target) {
138
+ const identityMatches = MANIFEST_IDENTITY_FIELDS.every((field) => manifest[field] === target[field]);
139
+ const checksumMatches = manifest.checksum.algorithm === target.checksum.algorithm &&
140
+ manifest.checksum.value.toLowerCase() === target.checksum.value;
141
+ return identityMatches && checksumMatches;
142
+ }
143
+ export function createManifest({ target, state, patch = {} }, _optional = {}) {
144
+ const now = new Date().toISOString();
145
+ return {
146
+ bucket: target.bucket,
147
+ checksum: target.checksum,
148
+ createdAt: now,
149
+ fileName: target.fileName,
150
+ identityDigest: target.identityDigest,
151
+ kind: MANIFEST_KIND,
152
+ schemaVersion: MANIFEST_SCHEMA_VERSION,
153
+ state,
154
+ targetKey: target.targetKey,
155
+ updatedAt: now,
156
+ urlDigest: target.urlDigest,
157
+ ...patch,
158
+ };
159
+ }
160
+ export async function hashFile(path, algorithm) {
161
+ const hash = createHash(algorithm);
162
+ await pipeline(createReadStream(path), hash);
163
+ return hash.digest("hex");
164
+ }
165
+ export async function statFileSize(path) {
166
+ try {
167
+ const entry = await stat(path);
168
+ return entry.isFile() ? entry.size : null;
169
+ }
170
+ catch {
171
+ return null;
172
+ }
173
+ }
174
+ //# sourceMappingURL=download-store.js.map
@@ -0,0 +1,10 @@
1
+ import { type ManagedDownloadOptions, type NormalizedTarget, type RemoveManagedDownloadOptions } from './download-types.js';
2
+ export declare const activeTargets: Map<string, string>;
3
+ export declare function digest(value: string): string;
4
+ export declare function normalizeBasePath(basePath: string): string;
5
+ export declare function targetFromOptions(options: Pick<ManagedDownloadOptions, "basePath" | "bucket" | "fileName" | "payload">): NormalizedTarget;
6
+ export declare function activeKey(target: NormalizedTarget): string;
7
+ export declare function targetActiveKey(target: NormalizedTarget): string;
8
+ /** Resolve a target's paths for callers (inspect/remove) that have no payload; the placeholder never reaches the network. */
9
+ export declare function targetWithoutPayload(options: RemoveManagedDownloadOptions): NormalizedTarget;
10
+ //# sourceMappingURL=download-target.d.ts.map