@needmoretruth/nmts-cli 0.44.0 → 0.46.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 (248) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +73 -0
  3. package/README.ko.md +6 -3
  4. package/README.md +15 -3
  5. package/dist/api-advice.js +17 -2
  6. package/dist/api.d.ts +22 -0
  7. package/dist/api.js +49 -1
  8. package/dist/arg-options.d.ts +14 -0
  9. package/dist/args.js +11 -2
  10. package/dist/artifact-about.d.ts +1 -1
  11. package/dist/collision.d.ts +20 -3
  12. package/dist/collision.js +21 -3
  13. package/dist/commands/erase.js +1 -0
  14. package/dist/commands/get.d.ts +2 -0
  15. package/dist/commands/get.js +13 -1
  16. package/dist/commands/handover.d.ts +13 -0
  17. package/dist/commands/handover.js +328 -0
  18. package/dist/commands/heavy-run.d.ts +59 -0
  19. package/dist/commands/heavy-run.js +247 -0
  20. package/dist/commands/heavy.d.ts +7 -0
  21. package/dist/commands/heavy.js +123 -0
  22. package/dist/commands/ls.d.ts +7 -0
  23. package/dist/commands/ls.js +27 -6
  24. package/dist/commands/public-code.d.ts +6 -0
  25. package/dist/commands/public-code.js +46 -0
  26. package/dist/commands/push-heavy.d.ts +6 -0
  27. package/dist/commands/push-heavy.js +128 -0
  28. package/dist/commands/push-tree.d.ts +24 -0
  29. package/dist/commands/push-tree.js +91 -0
  30. package/dist/commands/push.d.ts +4 -13
  31. package/dist/commands/push.js +7 -77
  32. package/dist/commands/put-heavy.d.ts +9 -0
  33. package/dist/commands/put-heavy.js +120 -0
  34. package/dist/commands/put-payer.d.ts +21 -0
  35. package/dist/commands/put-payer.js +24 -0
  36. package/dist/commands/put-thumbnail.d.ts +4 -0
  37. package/dist/commands/put-thumbnail.js +119 -0
  38. package/dist/commands/put-wallet.d.ts +2 -0
  39. package/dist/commands/put-wallet.js +3 -2
  40. package/dist/commands/put.d.ts +10 -2
  41. package/dist/commands/put.js +13 -7
  42. package/dist/commands/receive.js +3 -3
  43. package/dist/commands/s3.js +44 -10
  44. package/dist/crypto-surface.d.ts +8 -0
  45. package/dist/crypto-surface.js +3 -0
  46. package/dist/crypto.d.ts +3 -0
  47. package/dist/crypto.js +3 -0
  48. package/dist/download-part.d.ts +32 -1
  49. package/dist/download-part.js +95 -6
  50. package/dist/download-range.d.ts +19 -0
  51. package/dist/download-range.js +108 -0
  52. package/dist/download-sink.d.ts +15 -0
  53. package/dist/download.d.ts +14 -0
  54. package/dist/download.js +19 -4
  55. package/dist/drive-edit/trash.js +5 -3
  56. package/dist/drive-edit/tree.d.ts +6 -0
  57. package/dist/drive-edit/tree.js +10 -0
  58. package/dist/drive-erase.js +2 -2
  59. package/dist/drive-paths.d.ts +2 -2
  60. package/dist/drive-paths.js +2 -2
  61. package/dist/handover.d.ts +44 -0
  62. package/dist/handover.js +199 -0
  63. package/dist/heavy-api.d.ts +36 -0
  64. package/dist/heavy-api.js +107 -0
  65. package/dist/heavy-copy.d.ts +72 -0
  66. package/dist/heavy-copy.js +108 -0
  67. package/dist/heavy-evm.d.ts +20 -0
  68. package/dist/heavy-evm.js +106 -0
  69. package/dist/heavy-self-pay.d.ts +92 -0
  70. package/dist/heavy-self-pay.js +167 -0
  71. package/dist/heavy-upload.d.ts +87 -0
  72. package/dist/heavy-upload.js +154 -0
  73. package/dist/heavy-wallet-pay.d.ts +39 -0
  74. package/dist/heavy-wallet-pay.js +73 -0
  75. package/dist/help-options.js +8 -2
  76. package/dist/help.js +16 -3
  77. package/dist/list-tier.d.ts +7 -0
  78. package/dist/list-tier.js +47 -0
  79. package/dist/main.js +14 -9
  80. package/dist/manifest-write.d.ts +4 -3
  81. package/dist/mcp-tools/files.js +21 -2
  82. package/dist/mcp-tools/reads.js +9 -1
  83. package/dist/platform-sign.d.ts +4 -4
  84. package/dist/platform-sign.js +3 -3
  85. package/dist/portable.d.ts +17 -1
  86. package/dist/portable.js +13 -1
  87. package/dist/product.d.ts +1 -1
  88. package/dist/product.js +1 -1
  89. package/dist/recovery-build.js +16 -0
  90. package/dist/recovery-map-part.d.ts +82 -0
  91. package/dist/recovery-map-part.js +83 -0
  92. package/dist/recovery-map.d.ts +5 -40
  93. package/dist/recovery-map.js +18 -1
  94. package/dist/recovery-source.d.ts +3 -0
  95. package/dist/recovery-source.js +9 -0
  96. package/dist/risk.d.ts +30 -0
  97. package/dist/risk.js +23 -2
  98. package/dist/run-log.d.ts +1 -1
  99. package/dist/run-log.js +7 -1
  100. package/dist/s3/address.d.ts +20 -0
  101. package/dist/s3/address.js +97 -0
  102. package/dist/s3/answer.d.ts +48 -0
  103. package/dist/s3/answer.js +330 -0
  104. package/dist/s3/body-deframe.d.ts +49 -0
  105. package/dist/s3/body-deframe.js +264 -0
  106. package/dist/s3/body-measure.d.ts +13 -0
  107. package/dist/s3/body-measure.js +48 -0
  108. package/dist/s3/body-plan.d.ts +31 -0
  109. package/dist/s3/body-plan.js +159 -0
  110. package/dist/s3/body.d.ts +46 -0
  111. package/dist/s3/body.js +117 -0
  112. package/dist/s3/call.d.ts +36 -0
  113. package/dist/s3/call.js +42 -0
  114. package/dist/s3/checksum.d.ts +26 -0
  115. package/dist/s3/checksum.js +176 -0
  116. package/dist/s3/content-type.d.ts +3 -0
  117. package/dist/s3/content-type.js +49 -0
  118. package/dist/s3/contract.d.ts +91 -14
  119. package/dist/s3/drive-conditions.d.ts +47 -0
  120. package/dist/s3/drive-conditions.js +134 -0
  121. package/dist/s3/drive-key.d.ts +11 -0
  122. package/dist/s3/drive-key.js +58 -0
  123. package/dist/s3/drive-limits.d.ts +33 -0
  124. package/dist/s3/drive-limits.js +53 -0
  125. package/dist/s3/drive-lock.d.ts +11 -0
  126. package/dist/s3/drive-lock.js +47 -0
  127. package/dist/s3/drive-trashed-name.d.ts +13 -0
  128. package/dist/s3/drive-trashed-name.js +59 -0
  129. package/dist/s3/drive-write.d.ts +38 -0
  130. package/dist/s3/drive-write.js +258 -0
  131. package/dist/s3/drive.d.ts +59 -25
  132. package/dist/s3/drive.js +46 -77
  133. package/dist/s3/listing.d.ts +27 -1
  134. package/dist/s3/listing.js +62 -20
  135. package/dist/s3/long-answer.d.ts +12 -0
  136. package/dist/s3/long-answer.js +104 -0
  137. package/dist/s3/multipart-assemble.d.ts +17 -0
  138. package/dist/s3/multipart-assemble.js +68 -0
  139. package/dist/s3/multipart-sweep.d.ts +15 -0
  140. package/dist/s3/multipart-sweep.js +87 -0
  141. package/dist/s3/multipart-view.d.ts +45 -0
  142. package/dist/s3/multipart-view.js +232 -0
  143. package/dist/s3/multipart.d.ts +26 -19
  144. package/dist/s3/multipart.js +193 -78
  145. package/dist/s3/object-read.d.ts +17 -0
  146. package/dist/s3/object-read.js +127 -0
  147. package/dist/s3/object-write.d.ts +35 -0
  148. package/dist/s3/object-write.js +198 -0
  149. package/dist/s3/range.d.ts +14 -0
  150. package/dist/s3/range.js +80 -0
  151. package/dist/s3/response-sink.d.ts +12 -2
  152. package/dist/s3/response-sink.js +71 -7
  153. package/dist/s3/routes.d.ts +0 -1
  154. package/dist/s3/routes.js +242 -217
  155. package/dist/s3/same-file.d.ts +4 -1
  156. package/dist/s3/same-file.js +12 -3
  157. package/dist/s3/server.d.ts +54 -4
  158. package/dist/s3/server.js +174 -14
  159. package/dist/s3/sigv4-canonical.d.ts +91 -0
  160. package/dist/s3/sigv4-canonical.js +148 -0
  161. package/dist/s3/sigv4-presigned.d.ts +13 -0
  162. package/dist/s3/sigv4-presigned.js +82 -0
  163. package/dist/s3/sigv4.d.ts +26 -27
  164. package/dist/s3/sigv4.js +137 -102
  165. package/dist/s3/spool.d.ts +37 -0
  166. package/dist/s3/spool.js +104 -0
  167. package/dist/s3/staging.d.ts +90 -7
  168. package/dist/s3/staging.js +97 -66
  169. package/dist/s3/xml-multipart.d.ts +38 -0
  170. package/dist/s3/xml-multipart.js +47 -0
  171. package/dist/s3/xml-read.d.ts +28 -0
  172. package/dist/s3/xml-read.js +235 -0
  173. package/dist/s3/xml.d.ts +45 -2
  174. package/dist/s3/xml.js +72 -13
  175. package/dist/s3-gateway.d.ts +11 -5
  176. package/dist/s3-gateway.js +5 -2
  177. package/dist/seal.d.ts +1 -1
  178. package/dist/share.d.ts +5 -0
  179. package/dist/share.js +1 -1
  180. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  181. package/dist/shared/lib/api/types-heavy.js +60 -0
  182. package/dist/shared/lib/drive/manifest-codec.d.ts +11 -31
  183. package/dist/shared/lib/drive/manifest-codec.js +15 -23
  184. package/dist/shared/lib/drive/manifest-index.d.ts +10 -1
  185. package/dist/shared/lib/drive/manifest-index.js +30 -8
  186. package/dist/shared/lib/drive/manifest-wire-extras.d.ts +50 -0
  187. package/dist/shared/lib/drive/manifest-wire-extras.js +65 -0
  188. package/dist/shared/lib/drive/preview-classify.d.ts +17 -0
  189. package/dist/shared/lib/drive/preview-classify.js +96 -0
  190. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  191. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  192. package/dist/shared/lib/filecoin/providers.js +58 -0
  193. package/dist/shared/lib/heavy/download.d.ts +48 -0
  194. package/dist/shared/lib/heavy/download.js +116 -0
  195. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  196. package/dist/shared/lib/heavy/order-plan.js +83 -0
  197. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  198. package/dist/shared/lib/heavy/order-runner.js +300 -0
  199. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  200. package/dist/shared/lib/heavy/order-types.js +6 -0
  201. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  202. package/dist/shared/lib/heavy/order-wire.js +113 -0
  203. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  204. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  205. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  206. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  207. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  208. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  209. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  210. package/dist/shared/lib/share/handover-format.js +323 -0
  211. package/dist/shared/lib/share/shared-file-info.js +1 -0
  212. package/dist/shared/lib/storage-network.d.ts +4 -4
  213. package/dist/shared/lib/storage-network.js +7 -7
  214. package/dist/shared/lib/storage-tier.d.ts +28 -0
  215. package/dist/shared/lib/storage-tier.js +63 -0
  216. package/dist/shared/lib/wallet/send-rules.js +1 -0
  217. package/dist/upload-file.d.ts +8 -0
  218. package/dist/upload-file.js +57 -25
  219. package/dist/upload-price-node.d.ts +3 -0
  220. package/dist/upload-price-node.js +3 -6
  221. package/dist/upload-price.d.ts +10 -0
  222. package/dist/upload-price.js +13 -1
  223. package/dist/upload-run.d.ts +80 -0
  224. package/dist/upload-run.js +173 -0
  225. package/dist/upload-steps.js +15 -4
  226. package/dist/upload-store.d.ts +15 -6
  227. package/dist/upload-store.js +6 -0
  228. package/dist/upload-wallet-put.d.ts +11 -4
  229. package/dist/upload-wallet-put.js +17 -6
  230. package/dist/upload-wallet.js +4 -0
  231. package/dist/upload-wire.d.ts +25 -0
  232. package/dist/upload-wire.js +20 -1
  233. package/dist/upload.js +28 -13
  234. package/dist/wallet-sign.js +2 -2
  235. package/docs/commands/get.md +3 -0
  236. package/docs/commands/handover.md +38 -0
  237. package/docs/commands/heavy.md +35 -0
  238. package/docs/commands/ls.md +5 -0
  239. package/docs/commands/public-code.md +7 -0
  240. package/docs/commands/push.md +4 -1
  241. package/docs/commands/put.md +23 -1
  242. package/docs/commands/share.md +3 -1
  243. package/package.json +5 -2
  244. package/server.json +2 -2
  245. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  246. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  247. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  248. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -18,6 +18,8 @@ import { tmpdir } from "node:os";
18
18
  import { join } from "node:path";
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { createDriveSource, fetchObject, LIST_CACHE_MS } from "../s3/drive.js";
21
+ import { freeTrashedName } from "../s3/drive-trashed-name.js";
22
+ import { createStagingStore, SWEEP_EVERY_MS } from "../s3/staging.js";
21
23
  import { NmtsError } from "../errors.js";
22
24
  import { ensureFolderPath } from "../drive-edit.js";
23
25
  import { put } from "./put.js";
@@ -30,6 +32,17 @@ import { BUCKET } from "../s3/listing.js";
30
32
  import { BIND_ADDRESS, createGateway, newCredential } from "../s3/server.js";
31
33
  /** MinIO's port, which is what most S3 tools already have in their examples. */
32
34
  export const DEFAULT_PORT = 9000;
35
+ /** The `id` in the one line `put --json` prints, or undefined when there is none to read. */
36
+ function idIn(line) {
37
+ try {
38
+ const parsed = JSON.parse(line);
39
+ const id = typeof parsed === "object" && parsed !== null ? Reflect.get(parsed, "id") : undefined;
40
+ return typeof id === "string" ? id : undefined;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
33
46
  function portOf(raw) {
34
47
  if (raw === undefined)
35
48
  return DEFAULT_PORT;
@@ -54,6 +67,8 @@ export async function s3(options = {}) {
54
67
  * takes and afterwards.
55
68
  */
56
69
  const stagingRoot = join(tmpdir(), `nmts-s3-${randomUUID()}`);
70
+ // The uploads in pieces, swept on a timer that does not keep the process alive.
71
+ const staging = createStagingStore(stagingRoot, { sweepEveryMs: SWEEP_EVERY_MS });
57
72
  // ⛔ THE QUESTION WAS ANSWERED BEFORE THIS STARTED. A gateway cannot ask: its caller is a program
58
73
  // and its stdin is not a terminal. `s3` is a medium act (`risk.ts`) — uploads through it spend
59
74
  // credits — so the tier gate asked at the start, or the mode waved it through, and every write
@@ -62,14 +77,19 @@ export async function s3(options = {}) {
62
77
  /**
63
78
  * This account, as the shared drive module takes it.
64
79
  *
65
- * ⛔ THE SIX FUNCTIONS ARE THE ONLY THING THIS COMMAND CONTRIBUTES. What an upload DOES — the
80
+ * ⛔ THESE FUNCTIONS ARE THE ONLY THING THIS COMMAND CONTRIBUTES. What an upload DOES — the
66
81
  * same-file verdict, the folders above the key, forgetting the cached list — lives in
67
82
  * `s3/drive.ts`, so that the gateway a business runs from the SDK and the one a person runs
68
83
  * here cannot come to disagree about it.
69
84
  */
70
85
  const source = createDriveSource({
71
86
  stagingRoot,
87
+ staging,
88
+ bucket: BUCKET,
72
89
  writable,
90
+ // ⛔ A FILE ALREADY IN THE DRIVE IS NOT REPLACED FROM HERE. Different bytes at a taken key are
91
+ // refused, and the person deletes the old file first; what is said at start-up below.
92
+ overwrite: "refuse",
73
93
  onAlreadyStored: (key) => say(`same ${key} — already stored, nothing sent`),
74
94
  account: {
75
95
  readList: async () => {
@@ -81,22 +101,32 @@ export async function s3(options = {}) {
81
101
  makeFolder: async (folder) => {
82
102
  await ensureFolderPath(session, folder);
83
103
  },
84
- store: async (path, name, folder) => {
104
+ // ⚠ The collision rule is named rather than left to this machine's setting: the drive module
105
+ // decides replace-or-not, and a person's `on-collision` must not quietly change that answer.
106
+ // ⚠ Asked for `--json` so the id of the stored file comes back, and the tag answered is its.
107
+ store: async (path, name, folder, how) => {
108
+ let said = "";
85
109
  await put(path, {
86
110
  server: options.server,
87
111
  network: options.network,
88
112
  ...(folder === undefined ? {} : { to: folder }),
89
113
  name,
90
- write: () => undefined,
114
+ onCollision: how.replace ? "overwrite" : "rename",
115
+ json: true,
116
+ write: (line) => {
117
+ said = line;
118
+ },
91
119
  });
120
+ return { id: idIn(said) };
92
121
  },
93
122
  trash: async (path) => {
94
- await rm([path], {
95
- server: options.server,
96
- network: options.network,
97
- write: () => undefined,
98
- });
123
+ await rm([path], { server: options.server, network: options.network, write: () => undefined });
124
+ },
125
+ // One run of `rm` is one write to the file list, however many paths it names.
126
+ trashMany: async (paths) => {
127
+ await rm(paths, { server: options.server, network: options.network, write: () => undefined });
99
128
  },
129
+ freeTrashedName: (folder, name) => freeTrashedName(session, folder, name),
100
130
  fetch: (object, sink) => fetchObject({ server: session.server, bearer: session.apiKey, code: session.code, chain }, object, sink),
101
131
  },
102
132
  });
@@ -152,11 +182,15 @@ export async function s3(options = {}) {
152
182
  }
153
183
  await new Promise((resolve) => {
154
184
  const stop = () => {
155
- // Nothing half-uploaded outlives the command that was staging it.
156
- void removeFile(stagingRoot, { recursive: true, force: true });
157
185
  server.close(() => resolve());
158
186
  // A client holding a connection open must not keep the process alive after Ctrl-C.
159
187
  server.closeAllConnections();
188
+ // Nothing half-uploaded outlives the command that was staging it — but a finish still
189
+ // storing is waited for, rather than having its file removed underneath it.
190
+ void staging
191
+ .close()
192
+ .then(() => removeFile(stagingRoot, { recursive: true, force: true }))
193
+ .catch(() => undefined);
160
194
  };
161
195
  process.once("SIGINT", stop);
162
196
  process.once("SIGTERM", stop);
@@ -223,6 +223,14 @@ export interface CryptoGlue {
223
223
  * would look like the account's money had vanished.
224
224
  */
225
225
  wallet_seed_for(walletRoot: Uint8Array, index: number): Uint8Array;
226
+ /**
227
+ * The secp256k1 private key (32 bytes) of EVM wallet `index`, from the same wallet root
228
+ * (NCF-3 §1.9) — the key that pays Filecoin itself for NMTS Heavy on the self-paid path.
229
+ *
230
+ * ⛔ KEY MATERIAL, LIKE `wallet_seed_for`. The address is computed from it on this side
231
+ * (`heavy-evm.ts`); the key is wiped by whoever asked for it.
232
+ */
233
+ evm_key_for(walletRoot: Uint8Array, index: number): Uint8Array;
226
234
  }
227
235
  export declare function isCryptoGlue(value: unknown): value is CryptoGlue;
228
236
  /** Which of the required functions this object does not have. Empty means it is the engine. */
@@ -43,6 +43,9 @@ const REQUIRED = [
43
43
  // "this function is missing" said at load time is a different day's problem from
44
44
  // `undefined is not a function` in the middle of deriving somebody's second account.
45
45
  "derive_ai_account_code",
46
+ // The EVM wallets (NCF-3 §1.9), required for the same reason: `put --tier heavy --pay evm` and
47
+ // `heavy wallet` cannot run on a build without it.
48
+ "evm_key_for",
46
49
  ];
47
50
  export function isCryptoGlue(value) {
48
51
  return missingExports(value).length === 0;
package/dist/crypto.d.ts CHANGED
@@ -29,6 +29,9 @@ export declare const AAD: {
29
29
  readonly shareName: "nmts/v3/share-name";
30
30
  /** Seals the shared file's plaintext digest for the recipient, under the same file key. */
31
31
  readonly shareContentHash: "nmts/v3/share-content-hash";
32
+ /** Seals a handover file's list of stored pieces under the file's own key (NCF-3 §5.6), so a file
33
+ * that is intercepted does not even say where the ciphertext is. */
34
+ readonly handoverParts: "nmts/v3/handover-parts";
32
35
  /** Seals the RECOVERY LIST — where every file's bytes are (NRM §1). ⛔ The old spelling of the
33
36
  * artefact's name is frozen INTO the separator: every list ever sealed is bound to these bytes. */
34
37
  readonly recoveryMap: "nmts/v3/recovery-map";
package/dist/crypto.js CHANGED
@@ -47,6 +47,9 @@ export const AAD = {
47
47
  shareName: "nmts/v3/share-name",
48
48
  /** Seals the shared file's plaintext digest for the recipient, under the same file key. */
49
49
  shareContentHash: "nmts/v3/share-content-hash",
50
+ /** Seals a handover file's list of stored pieces under the file's own key (NCF-3 §5.6), so a file
51
+ * that is intercepted does not even say where the ciphertext is. */
52
+ handoverParts: "nmts/v3/handover-parts",
50
53
  /** Seals the RECOVERY LIST — where every file's bytes are (NRM §1). ⛔ The old spelling of the
51
54
  * artefact's name is frozen INTO the separator: every list ever sealed is bound to these bytes. */
52
55
  recoveryMap: "nmts/v3/recovery-map",
@@ -1,11 +1,14 @@
1
1
  import type { CryptoGlue } from "./crypto.ts";
2
2
  import { type ReadOptions } from "./walrus.ts";
3
+ import type { HeavyCopy } from "./shared/lib/api/types-heavy.ts";
3
4
  export interface PartView {
4
5
  part_index: number;
5
6
  storage_kind: number;
6
7
  network?: number;
7
8
  blob_id: string;
8
9
  patch_id?: string;
10
+ /** Network 1 (NMTS Heavy): the storage companies keeping a whole copy each, in the order to ask. */
11
+ copies?: HeavyCopy[];
9
12
  }
10
13
  export interface PartsResponse {
11
14
  size: number;
@@ -33,8 +36,36 @@ export declare function fetchPart(part: PartView, chain: string, read: ReadOptio
33
36
  *
34
37
  * ⛔ `finish()` IS WHAT CATCHES A PART CUT SHORT. Every chunk that arrived authenticates; only the
35
38
  * end-of-stream check knows the rest is missing. Skipping it would accept a truncated part.
39
+ * ⚠ The one caller that skips it is a RANGE that asked for the part's first chunks only
40
+ * (`prefix`): it wants no byte past them, and every byte it keeps is authenticated.
36
41
  *
37
42
  * ⛔ THE ENGINE-SIDE SESSION IS FREED ON EVERY PATH OUT, including a failure: it holds the file
38
43
  * key until it is, and a download that failed is exactly when nobody comes back to tidy up.
39
44
  */
40
- export declare function openPart(crypt: CryptoGlue, dek: Uint8Array, part: PartView, sealed: Uint8Array, isLast: boolean, remaining: number, emit: (body: Uint8Array) => Promise<void>): Promise<number>;
45
+ export declare function openPart(crypt: CryptoGlue, dek: Uint8Array, part: PartView, sealed: Uint8Array, position: {
46
+ index: number;
47
+ total: number;
48
+ }, remaining: number, emit: (body: Uint8Array) => Promise<void>, prefix?: boolean): Promise<number>;
49
+ /** What a part's sealed header says about it, once it is known to be this file's. */
50
+ export interface PartHeader {
51
+ /** Plaintext bytes the stream declares — the whole part, padding included. */
52
+ declared: number;
53
+ /** Plaintext bytes per chunk. */
54
+ chunkSize: number;
55
+ }
56
+ /**
57
+ * Read a part's 72-byte header, and refuse it unless it is THIS file's part at THIS position.
58
+ *
59
+ * ⛔ THE ENGINE CHECKS THE KEY COMMITMENT FIRST. It covers every field read below, so a length or a
60
+ * position that passes here was sealed under this file's key — a range that leaves the parts
61
+ * before it out works out where it starts from these numbers, and a lie in them would put
62
+ * authentic bytes at the wrong place in the answer.
63
+ *
64
+ * ⛔ THE POSITION IS THE ONE THE CALLER IS READING INTO, never the part's own claim: every part of a
65
+ * file is sealed under one key, so a part served in another's place passes the commitment and is
66
+ * caught only by comparing where it says it is with where it is being used.
67
+ */
68
+ export declare function checkedHeader(crypt: CryptoGlue, dek: Uint8Array, part: PartView, header: Uint8Array, position: {
69
+ index: number;
70
+ total: number;
71
+ }): PartHeader;
@@ -3,6 +3,9 @@ import { NCF3_SHAPE } from "./seal.js";
3
3
  import { isRecord } from "./guards.js";
4
4
  import { readBlob, readQuiltPatch } from "./walrus.js";
5
5
  import { NETWORK_WHEN_UNRECORDED, networkName } from "./shared/lib/storage-network.js";
6
+ import { reachFetch } from "./reach.js";
7
+ import { FILECOIN_CHAIN_FOR_NETWORK } from "./shared/lib/filecoin/providers.js";
8
+ import { readCopies } from "./shared/lib/heavy/order-wire.js";
6
9
  /** `storage_kind` in the server's part rows. */
7
10
  const DEDICATED_BLOB = 0;
8
11
  const QUILT_PATCH = 1;
@@ -34,6 +37,11 @@ export function asParts(value) {
34
37
  view.network = p["network"];
35
38
  if (typeof p["patch_id"] === "string")
36
39
  view.patch_id = p["patch_id"];
40
+ // ⚠ Checked field by field (`readCopies`); a list that does not read is left out, and the read
41
+ // below then says it has no copy to ask rather than asking a half-read address.
42
+ const copies = p["copies"] === undefined ? null : readCopies(p["copies"]);
43
+ if (copies !== null)
44
+ view.copies = copies;
37
45
  out.push(view);
38
46
  }
39
47
  return { size, parts: out };
@@ -47,6 +55,8 @@ export function asParts(value) {
47
55
  */
48
56
  export async function fetchPart(part, chain, read) {
49
57
  const where = networkName(part.network ?? NETWORK_WHEN_UNRECORDED);
58
+ if (where === "filecoin" && (chain === "testnet" || chain === "mainnet"))
59
+ return readHeavyPart(part, chain, read);
50
60
  if (where !== "walrus") {
51
61
  throw new NmtsError(`Part ${part.part_index} is stored on ${where ?? `an unknown network (${part.network})`}, which this version cannot read.`, { nextStep: "Nothing was written. Open the file in a browser, which may know that network." });
52
62
  }
@@ -57,6 +67,33 @@ export async function fetchPart(part, chain, read) {
57
67
  ? readQuiltPatch(chain, part.patch_id, read ?? {})
58
68
  : readBlob(chain, part.blob_id, read ?? {});
59
69
  }
70
+ /**
71
+ * One NMTS Heavy part, from the first of its copies that serves it (`shared/lib/heavy/download.ts`,
72
+ * the browser's own reader).
73
+ *
74
+ * ⛔ ANY https COMPANY, NOT ONLY THE LISTED ONES. The list exists because a browser page may only
75
+ * talk to hosts its security policy names; this program has no such policy, and somebody who paid
76
+ * from their own EVM wallet may have picked a company the list does not name. The bytes are
77
+ * judged by the decryption, as every part's are, so the company is not trusted either way.
78
+ */
79
+ async function readHeavyPart(part, chain, read) {
80
+ const { fetchHeavyPart } = await import("./shared/lib/heavy/download.js");
81
+ const range = read?.range;
82
+ const response = await fetchHeavyPart({
83
+ pieceCid: part.blob_id,
84
+ copies: part.copies ?? [],
85
+ chain: FILECOIN_CHAIN_FOR_NETWORK[chain],
86
+ allowUnlisted: true,
87
+ fetchImpl: reachFetch,
88
+ ...(range === undefined ? {} : { range }),
89
+ ...(read?.signal === undefined ? {} : { signal: read.signal }),
90
+ });
91
+ const body = new Uint8Array(await response.arrayBuffer());
92
+ if (range === undefined)
93
+ return body;
94
+ // A 206 holds exactly the asked-for bytes; a company that ignored `Range` sent the part from zero.
95
+ return body.length === range.end - range.start ? body : body.subarray(range.start, range.end);
96
+ }
60
97
  /**
61
98
  * Open ONE part and pass its contribution on, a chunk at a time. Returns how much of the file it
62
99
  * contributed.
@@ -70,17 +107,27 @@ export async function fetchPart(part, chain, read) {
70
107
  *
71
108
  * ⛔ `finish()` IS WHAT CATCHES A PART CUT SHORT. Every chunk that arrived authenticates; only the
72
109
  * end-of-stream check knows the rest is missing. Skipping it would accept a truncated part.
110
+ * ⚠ The one caller that skips it is a RANGE that asked for the part's first chunks only
111
+ * (`prefix`): it wants no byte past them, and every byte it keeps is authenticated.
73
112
  *
74
113
  * ⛔ THE ENGINE-SIDE SESSION IS FREED ON EVERY PATH OUT, including a failure: it holds the file
75
114
  * key until it is, and a download that failed is exactly when nobody comes back to tidy up.
76
115
  */
77
- export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit) {
78
- const refuse = () => new NmtsError(`Part ${part.part_index} did not decrypt.`, {
79
- nextStep: "The bytes that arrived are not the bytes this account sealed. Nothing was written. " +
80
- "Try again — a different aggregator may hold the right ones.",
81
- });
116
+ export async function openPart(crypt, dek, part, sealed, position, remaining, emit, prefix = false) {
117
+ const isLast = position.index === position.total - 1;
118
+ const refuse = refusal(part);
82
119
  if (sealed.length < NCF3_SHAPE.headerLen)
83
120
  throw refuse();
121
+ // ⛔ POSITIONAL, AS NCF-3 §4.1 REQUIRES. The header names its own place (`part_index` of
122
+ // `part_total`, bytes 8..16) and every chunk authenticates that header — so a stream fetched in
123
+ // a place it does not claim still decrypts, and only this comparison notices. A reordered or
124
+ // substituted list of pieces would otherwise be stitched together in the wrong order.
125
+ const header = new DataView(sealed.buffer, sealed.byteOffset, NCF3_SHAPE.headerLen);
126
+ const claimedIndex = header.getUint32(8, true);
127
+ const claimedTotal = header.getUint32(12, true);
128
+ if (claimedIndex !== position.index || claimedTotal !== position.total) {
129
+ throw new NmtsError(`Part ${part.part_index} says it is part ${claimedIndex + 1} of ${claimedTotal}, but it was listed as part ${position.index + 1} of ${position.total}.`, { nextStep: "Nothing was written. The list of stored pieces does not match what was sealed." });
130
+ }
84
131
  // ⚠ Constructed on the header alone, which is parsed and checked inside the engine, so a blob
85
132
  // that is not an NCF-3 stream at all fails here rather than as a strange length later.
86
133
  let opener;
@@ -131,7 +178,8 @@ export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit
131
178
  left -= take;
132
179
  }
133
180
  try {
134
- opener.finish();
181
+ if (!prefix)
182
+ opener.finish();
135
183
  }
136
184
  catch {
137
185
  throw refuse();
@@ -142,3 +190,44 @@ export async function openPart(crypt, dek, part, sealed, isLast, remaining, emit
142
190
  }
143
191
  return taken;
144
192
  }
193
+ function refusal(part) {
194
+ return () => new NmtsError(`Part ${part.part_index} did not decrypt.`, {
195
+ nextStep: "The bytes that arrived are not the bytes that were sealed. Nothing was written. " +
196
+ "Try again — a different aggregator may hold the right ones.",
197
+ });
198
+ }
199
+ /**
200
+ * Read a part's 72-byte header, and refuse it unless it is THIS file's part at THIS position.
201
+ *
202
+ * ⛔ THE ENGINE CHECKS THE KEY COMMITMENT FIRST. It covers every field read below, so a length or a
203
+ * position that passes here was sealed under this file's key — a range that leaves the parts
204
+ * before it out works out where it starts from these numbers, and a lie in them would put
205
+ * authentic bytes at the wrong place in the answer.
206
+ *
207
+ * ⛔ THE POSITION IS THE ONE THE CALLER IS READING INTO, never the part's own claim: every part of a
208
+ * file is sealed under one key, so a part served in another's place passes the commitment and is
209
+ * caught only by comparing where it says it is with where it is being used.
210
+ */
211
+ export function checkedHeader(crypt, dek, part, header, position) {
212
+ const refuse = refusal(part);
213
+ if (header.length < NCF3_SHAPE.headerLen)
214
+ throw refuse();
215
+ const bytes = header.subarray(0, NCF3_SHAPE.headerLen);
216
+ try {
217
+ new crypt.StreamDecryptor(dek, bytes).free();
218
+ }
219
+ catch {
220
+ throw refuse();
221
+ }
222
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
223
+ const log2 = view.getUint8(5);
224
+ const declared = view.getBigUint64(16, true);
225
+ if (view.getUint32(8, true) !== position.index || view.getUint32(12, true) !== position.total) {
226
+ throw new NmtsError(`Part ${part.part_index} was served in the wrong place in the file.`, {
227
+ nextStep: "The stored parts do not agree with the file this list describes. Nothing was written.",
228
+ });
229
+ }
230
+ if (declared > BigInt(Number.MAX_SAFE_INTEGER) || log2 > 40)
231
+ throw refuse();
232
+ return { declared: Number(declared), chunkSize: 2 ** log2 };
233
+ }
@@ -0,0 +1,19 @@
1
+ import type { CryptoGlue } from "./crypto.ts";
2
+ import { type PartView } from "./download-part.ts";
3
+ import type { FetchedFile } from "./download.ts";
4
+ import type { PlaintextSink } from "./download-sink.ts";
5
+ import type { ReadOptions } from "./walrus.ts";
6
+ /** The bytes a sink keeps, when it keeps only some of the file and can be told what was left out. */
7
+ export declare function windowOf(sink: PlaintextSink): {
8
+ start: number;
9
+ end: number;
10
+ } | null;
11
+ /**
12
+ * Deliver `window` of the file to `sink`, reading only the parts it falls in.
13
+ *
14
+ * ⛔ THE SINK IS COMMITTED IN ONE PLACE AND ABANDONED ON EVERY OTHER WAY OUT, as in `download.ts`.
15
+ */
16
+ export declare function collectWindow(crypt: CryptoGlue, ordered: readonly PartView[], dek: Uint8Array, expected: Uint8Array | null, size: number, chain: string, read: ReadOptions | undefined, sink: PlaintextSink, window: {
17
+ start: number;
18
+ end: number;
19
+ }): Promise<FetchedFile>;
@@ -0,0 +1,108 @@
1
+ // Reading part of a file: from the stored part a range starts in, not from the file's first byte.
2
+ //
3
+ // ⛔ WHY THIS EXISTS. An S3 client fetches a large object as many ranges at once — eight MiB each,
4
+ // ten at a time — and a reader that decrypted every range from the file's first byte made a 1 GB
5
+ // file cost about 64 GB of reads, with the late ranges timing out. Every part of a file is its own
6
+ // sealed stream, so the parts wholly before a range can be left out: their headers (72 bytes
7
+ // each) say how long they are, and the range begins in the part where those lengths run out.
8
+ // Inside that part the read starts at the part's first chunk and stops at the chunk the range
9
+ // ends in, because the sequential opener is the one this tool's engine surface offers.
10
+ //
11
+ // ⛔ WHAT A RANGE IS CHECKED AGAINST. Every chunk it keeps is authenticated under the file's key.
12
+ // Every part it touches — the ones it leaves out included — has its header's key commitment
13
+ // checked and its sealed position compared with the position it is used in, so authentic bytes
14
+ // cannot be answered from the wrong place. The whole-file digest needs every byte from the first,
15
+ // so it is checked only when nothing was left out and the range runs to the file's end; that is
16
+ // the one range the whole-file path checked before, and it still is.
17
+ //
18
+ // ⚠ ONLY FOR A SINK THAT NAMES A WINDOW AND CAN BE TOLD WHAT WAS LEFT OUT (`PlaintextSink.window`
19
+ // with `skip`). Every other sink goes through `download.ts` exactly as before.
20
+ import { sha256 } from "@noble/hashes/sha2.js";
21
+ import { checkedHeader, fetchPart, openPart } from "./download-part.js";
22
+ import { NmtsError } from "./errors.js";
23
+ import { NCF3_SHAPE } from "./seal.js";
24
+ /** The bytes a sink keeps, when it keeps only some of the file and can be told what was left out. */
25
+ export function windowOf(sink) {
26
+ const window = sink.window ?? null;
27
+ return window !== null && sink.skip !== undefined ? window : null;
28
+ }
29
+ /**
30
+ * Where a read of one part may stop: just past the chunk holding its last wanted byte, or null for
31
+ * the whole part.
32
+ */
33
+ function prefixEnd(header, lastWanted) {
34
+ const step = header.chunkSize + NCF3_SHAPE.tagLen;
35
+ const chunks = header.declared === 0 ? 1 : Math.ceil(header.declared / header.chunkSize);
36
+ const lastChunk = Math.floor(lastWanted / header.chunkSize);
37
+ return lastChunk >= chunks - 1 ? null : NCF3_SHAPE.headerLen + (lastChunk + 1) * step;
38
+ }
39
+ function disagree(what) {
40
+ return new NmtsError(what, {
41
+ nextStep: "The file list and the stored parts do not agree. Nothing more was written.",
42
+ });
43
+ }
44
+ /**
45
+ * Deliver `window` of the file to `sink`, reading only the parts it falls in.
46
+ *
47
+ * ⛔ THE SINK IS COMMITTED IN ONE PLACE AND ABANDONED ON EVERY OTHER WAY OUT, as in `download.ts`.
48
+ */
49
+ export async function collectWindow(crypt, ordered, dek, expected, size, chain, read, sink, window) {
50
+ const hasher = sha256.create();
51
+ // ⚠ True until a part is left out: the digest is of every byte, and then it can no longer be had.
52
+ let whole = true;
53
+ let at = 0;
54
+ const total = ordered.length;
55
+ try {
56
+ sink.expect(size);
57
+ for (let index = 0; index < total && at <= window.end; index += 1) {
58
+ const part = ordered[index];
59
+ if (part === undefined)
60
+ continue;
61
+ const isLast = index === total - 1;
62
+ const headerBytes = await fetchPart(part, chain, { ...(read ?? {}), range: { start: 0, end: NCF3_SHAPE.headerLen } });
63
+ const header = checkedHeader(crypt, dek, part, headerBytes, { index, total });
64
+ // Every part but the last contributes all it declares; the last is what the file has left.
65
+ const contributes = isLast ? size - at : header.declared;
66
+ if (contributes < 0 || contributes > header.declared) {
67
+ throw disagree(`Part ${part.part_index} holds ${header.declared} bytes and would have to give ${contributes}.`);
68
+ }
69
+ if (!isLast && at + contributes <= window.start) {
70
+ sink.skip?.(contributes);
71
+ whole = false;
72
+ at += contributes;
73
+ continue;
74
+ }
75
+ const lastWanted = Math.min(window.end, at + contributes - 1) - at;
76
+ const end = contributes === 0 ? null : prefixEnd(header, lastWanted);
77
+ const sealed = await fetchPart(part, chain, end === null ? read : { ...(read ?? {}), range: { start: 0, end } });
78
+ at += await openPart(crypt, dek, part, sealed, { index, total }, size - at, async (body) => {
79
+ if (whole)
80
+ hasher.update(body);
81
+ await sink.write(body);
82
+ }, end !== null);
83
+ if (end !== null)
84
+ break;
85
+ }
86
+ if (at <= window.end)
87
+ throw disagree(`The stored parts end at byte ${at}, before the range does.`);
88
+ const checked = whole && at === size && expected !== null;
89
+ if (checked) {
90
+ const got = hasher.digest();
91
+ if (expected.length !== got.length || !expected.every((b, i) => b === got[i])) {
92
+ throw new NmtsError("The file came back whole but does not match the hash this account recorded for it.", {
93
+ nextStep: "The bytes themselves are not the ones that were uploaded.",
94
+ });
95
+ }
96
+ }
97
+ const delivered = await sink.commit();
98
+ return { byteCount: size, partCount: total, contentHashChecked: checked, delivered };
99
+ }
100
+ catch (failure) {
101
+ await sink.abandon();
102
+ throw failure;
103
+ }
104
+ finally {
105
+ dek.fill(0);
106
+ expected?.fill(0);
107
+ }
108
+ }
@@ -25,4 +25,19 @@ export interface PlaintextSink {
25
25
  commit(): Promise<boolean>;
26
26
  /** Something did not check out: leave nothing behind. Never throws. */
27
27
  abandon(): Promise<void>;
28
+ /**
29
+ * A destination that keeps only SOME of the file — an HTTP range — says which bytes, inclusive.
30
+ * Absent (or null) is the whole file, which is every sink but one.
31
+ *
32
+ * ⚠ WITH `skip`, AND ONLY WITH IT, a reader may leave out whole stored parts that end before
33
+ * `start`, and stop reading once `end` is written: a late range then costs the parts it falls
34
+ * in rather than every part before it. A sink that names a window must still cut what it is
35
+ * given, because a reader is free to hand it everything.
36
+ */
37
+ readonly window?: {
38
+ readonly start: number;
39
+ readonly end: number;
40
+ } | null | undefined;
41
+ /** Told, before the next write, that the reader left out this many bytes of the file. */
42
+ skip?(bytes: number): void;
28
43
  }
@@ -1,3 +1,4 @@
1
+ import { type PartView } from "./download-part.ts";
1
2
  import type { PlaintextSink } from "./download-sink.ts";
2
3
  import type { ReadOptions } from "./walrus.ts";
3
4
  export interface FetchedFile {
@@ -76,4 +77,17 @@ export declare function fetchWithKey(input: {
76
77
  /** Where the plaintext goes as it is decrypted. Committed only after the whole file checks out. */
77
78
  sink: PlaintextSink;
78
79
  }): Promise<FetchedFile>;
80
+ /**
81
+ * Fetch, decrypt and verify a file whose key is open AND whose pieces are already known — a
82
+ * handover file carries them sealed, so the NMTS server is asked nothing at all.
83
+ */
84
+ export declare function fetchKnownParts(input: {
85
+ parts: readonly PartView[];
86
+ size: number;
87
+ dek: Uint8Array;
88
+ expected: Uint8Array;
89
+ chain: string;
90
+ read?: ReadOptions;
91
+ sink: PlaintextSink;
92
+ }): Promise<FetchedFile>;
79
93
  export declare function fetchFile(input: FetchInput): Promise<FetchedFile>;
package/dist/download.js CHANGED
@@ -31,6 +31,7 @@ import { fromBase64Url, utf8 } from "./bytes.js";
31
31
  import { request } from "./api.js";
32
32
  import { AAD, DERIVED, loadCrypto } from "./crypto.js";
33
33
  import { asParts, fetchPart, openPart } from "./download-part.js";
34
+ import { collectWindow, windowOf } from "./download-range.js";
34
35
  import { NmtsError } from "./errors.js";
35
36
  /**
36
37
  * Fetch, decrypt and verify one file.
@@ -60,8 +61,22 @@ export async function fetchWithKey(input) {
60
61
  const crypt = await loadCrypto();
61
62
  const dek = input.dek;
62
63
  const expected = input.expected;
64
+ // ⚠ A sink that keeps only a window of the file is read from the part the window starts in
65
+ // (`download-range.ts`); every other sink takes the whole-file path below, unchanged.
66
+ const window = windowOf(input.sink);
67
+ if (window !== null) {
68
+ return collectWindow(crypt, ordered, dek, expected, input.size, input.chain, input.read, input.sink, window);
69
+ }
63
70
  return collect(crypt, ordered, dek, expected, input.size, input.chain, input.read, input.sink);
64
71
  }
72
+ /**
73
+ * Fetch, decrypt and verify a file whose key is open AND whose pieces are already known — a
74
+ * handover file carries them sealed, so the NMTS server is asked nothing at all.
75
+ */
76
+ export async function fetchKnownParts(input) {
77
+ const crypt = await loadCrypto();
78
+ return collect(crypt, input.parts, input.dek, input.expected, input.size, input.chain, input.read, input.sink);
79
+ }
65
80
  export async function fetchFile(input) {
66
81
  const crypt = await loadCrypto();
67
82
  const [from, to] = DERIVED.dataKey;
@@ -127,14 +142,14 @@ async function collect(crypt, ordered, dek, expected, size, chain, read, sink) {
127
142
  if (part === undefined)
128
143
  continue;
129
144
  const sealed = await fetchPart(part, chain, read);
130
- remaining -= await openPart(crypt, dek, part, sealed, i === ordered.length - 1, remaining, async (body) => {
145
+ remaining -= await openPart(crypt, dek, part, sealed, { index: i, total: ordered.length }, remaining, async (body) => {
131
146
  hasher.update(body);
132
147
  await sink.write(body);
133
148
  });
134
149
  }
135
150
  if (remaining !== 0) {
136
- throw new NmtsError(`The stored parts are ${remaining} bytes short of the file this list describes.`, {
137
- nextStep: "Nothing was written. Open the account in a browser and compare before uploading anything again.",
151
+ throw new NmtsError(`The stored parts are ${remaining} bytes short of the file's recorded length.`, {
152
+ nextStep: "Nothing was written. The stored bytes and the recorded length describe different files.",
138
153
  });
139
154
  }
140
155
  if (expected !== null) {
@@ -142,7 +157,7 @@ async function collect(crypt, ordered, dek, expected, size, chain, read, sink) {
142
157
  const same = expected.length === got.length && expected.every((b, i) => b === got[i]);
143
158
  expected.fill(0);
144
159
  if (!same) {
145
- throw new NmtsError("The file came back whole but does not match the hash this account recorded for it.", {
160
+ throw new NmtsError("The file came back whole but does not match the hash recorded for it.", {
146
161
  nextStep: "Nothing was written. Every part decrypted, so this is not a wrong key — the bytes " +
147
162
  "themselves are not the ones that were uploaded.",
148
163
  });
@@ -6,7 +6,7 @@ import { readFileList } from "../manifest.js";
6
6
  import { applyManyToList, batchTargets } from "../manifest-write.js";
7
7
  import { applyIntent } from "../shared/lib/drive/manifest-ops.js";
8
8
  import { DriveEditError, resolving } from "./errors.js";
9
- import { filesUnder, hasNamedAncestor, uniqueById } from "./tree.js";
9
+ import { filesUnder, hasNamedAncestor, uniqueById, withPreviews } from "./tree.js";
10
10
  /**
11
11
  * Move things to the trash, or bring them back.
12
12
  *
@@ -88,9 +88,11 @@ export async function trashPaths(input, verb, paths, options = {}) {
88
88
  // storage, and leave the list saying "trashed" while the server says "live" — after which
89
89
  // `rm` refuses to put it back and there is no way out.
90
90
  const at = Date.now();
91
- const ids = targets.map((t) => t.entry.id);
91
+ // A video's hidden preview picture goes into and out of the trash with it (gallery spec §4).
92
+ const under = withPreviews(entries, targets.flatMap((t) => filesUnder(entries, t.entry.id)));
93
+ const chosen = targets.map((t) => t.entry.id);
94
+ const ids = [...chosen, ...under.filter((f) => f.thumbOf !== undefined && !chosen.includes(f.id)).map((f) => f.id)];
92
95
  const preview = buildIndex(applyIntent(entries, intentFor(verb, ids, at)));
93
- const under = uniqueById(targets.flatMap((t) => filesUnder(entries, t.entry.id)));
94
96
  // ⚠ Judged on the PREVIEW's own row, not on the one in hand: `applyIntent` returns new objects,
95
97
  // so asking the preview about the old object reads the old `deletedAt` and answers "still
96
98
  // trashed" for the very thing being restored.
@@ -3,6 +3,12 @@ import type { ManifestEntry } from "../shared/lib/drive/manifest-codec.ts";
3
3
  export declare function isUnder(entries: readonly ManifestEntry[], id: string | null, rootId: string): boolean;
4
4
  /** Is any ancestor of this entry in the set? Used to drop a target a named folder already covers. */
5
5
  export declare function hasNamedAncestor(entries: readonly ManifestEntry[], entry: ManifestEntry, named: ReadonlySet<string>): boolean;
6
+ /**
7
+ * `files` and the preview pictures of the videos among them. A video's
8
+ * picture is a file of its own, hidden from every listing while the video is there, so it goes
9
+ * wherever the video goes — left behind, it would be charged for and then show up on its own.
10
+ */
11
+ export declare function withPreviews(entries: readonly ManifestEntry[], files: readonly ManifestEntry[]): ManifestEntry[];
6
12
  /** One entry per id, keeping the first. Two named folders can hold the same file only once. */
7
13
  export declare function uniqueById(files: readonly ManifestEntry[]): ManifestEntry[];
8
14
  /**