@needmoretruth/nmts-cli 0.45.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 (224) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +61 -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 +8 -0
  9. package/dist/args.js +7 -1
  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/handover.d.ts +13 -0
  15. package/dist/commands/handover.js +328 -0
  16. package/dist/commands/heavy-run.d.ts +59 -0
  17. package/dist/commands/heavy-run.js +247 -0
  18. package/dist/commands/heavy.d.ts +7 -0
  19. package/dist/commands/heavy.js +123 -0
  20. package/dist/commands/ls.d.ts +5 -0
  21. package/dist/commands/ls.js +9 -1
  22. package/dist/commands/public-code.d.ts +6 -0
  23. package/dist/commands/public-code.js +46 -0
  24. package/dist/commands/push-heavy.d.ts +6 -0
  25. package/dist/commands/push-heavy.js +128 -0
  26. package/dist/commands/push-tree.d.ts +24 -0
  27. package/dist/commands/push-tree.js +91 -0
  28. package/dist/commands/push.d.ts +4 -13
  29. package/dist/commands/push.js +7 -77
  30. package/dist/commands/put-heavy.d.ts +9 -0
  31. package/dist/commands/put-heavy.js +120 -0
  32. package/dist/commands/put-payer.d.ts +21 -0
  33. package/dist/commands/put-payer.js +24 -0
  34. package/dist/commands/put.d.ts +2 -2
  35. package/dist/commands/put.js +8 -7
  36. package/dist/commands/receive.js +3 -3
  37. package/dist/commands/s3.js +44 -10
  38. package/dist/crypto-surface.d.ts +8 -0
  39. package/dist/crypto-surface.js +3 -0
  40. package/dist/crypto.d.ts +3 -0
  41. package/dist/crypto.js +3 -0
  42. package/dist/download-part.d.ts +32 -1
  43. package/dist/download-part.js +95 -6
  44. package/dist/download-range.d.ts +19 -0
  45. package/dist/download-range.js +108 -0
  46. package/dist/download-sink.d.ts +15 -0
  47. package/dist/download.d.ts +14 -0
  48. package/dist/download.js +19 -4
  49. package/dist/handover.d.ts +44 -0
  50. package/dist/handover.js +199 -0
  51. package/dist/heavy-api.d.ts +36 -0
  52. package/dist/heavy-api.js +107 -0
  53. package/dist/heavy-copy.d.ts +72 -0
  54. package/dist/heavy-copy.js +108 -0
  55. package/dist/heavy-evm.d.ts +20 -0
  56. package/dist/heavy-evm.js +106 -0
  57. package/dist/heavy-self-pay.d.ts +92 -0
  58. package/dist/heavy-self-pay.js +167 -0
  59. package/dist/heavy-upload.d.ts +87 -0
  60. package/dist/heavy-upload.js +154 -0
  61. package/dist/heavy-wallet-pay.d.ts +39 -0
  62. package/dist/heavy-wallet-pay.js +73 -0
  63. package/dist/help-options.js +4 -2
  64. package/dist/help.js +16 -3
  65. package/dist/list-tier.d.ts +7 -0
  66. package/dist/list-tier.js +47 -0
  67. package/dist/main.js +12 -10
  68. package/dist/manifest-write.d.ts +4 -3
  69. package/dist/platform-sign.d.ts +4 -4
  70. package/dist/platform-sign.js +3 -3
  71. package/dist/portable.d.ts +15 -0
  72. package/dist/portable.js +11 -0
  73. package/dist/product.d.ts +1 -1
  74. package/dist/product.js +1 -1
  75. package/dist/recovery-build.js +16 -0
  76. package/dist/recovery-map-part.d.ts +82 -0
  77. package/dist/recovery-map-part.js +83 -0
  78. package/dist/recovery-map.d.ts +5 -40
  79. package/dist/recovery-map.js +18 -1
  80. package/dist/recovery-source.d.ts +3 -0
  81. package/dist/recovery-source.js +9 -0
  82. package/dist/risk.d.ts +30 -0
  83. package/dist/risk.js +23 -2
  84. package/dist/run-log.d.ts +1 -1
  85. package/dist/run-log.js +7 -1
  86. package/dist/s3/address.d.ts +20 -0
  87. package/dist/s3/address.js +97 -0
  88. package/dist/s3/answer.d.ts +48 -0
  89. package/dist/s3/answer.js +330 -0
  90. package/dist/s3/body-deframe.d.ts +49 -0
  91. package/dist/s3/body-deframe.js +264 -0
  92. package/dist/s3/body-measure.d.ts +13 -0
  93. package/dist/s3/body-measure.js +48 -0
  94. package/dist/s3/body-plan.d.ts +31 -0
  95. package/dist/s3/body-plan.js +159 -0
  96. package/dist/s3/body.d.ts +46 -0
  97. package/dist/s3/body.js +117 -0
  98. package/dist/s3/call.d.ts +36 -0
  99. package/dist/s3/call.js +42 -0
  100. package/dist/s3/checksum.d.ts +26 -0
  101. package/dist/s3/checksum.js +176 -0
  102. package/dist/s3/content-type.d.ts +3 -0
  103. package/dist/s3/content-type.js +49 -0
  104. package/dist/s3/contract.d.ts +91 -14
  105. package/dist/s3/drive-conditions.d.ts +47 -0
  106. package/dist/s3/drive-conditions.js +134 -0
  107. package/dist/s3/drive-key.d.ts +11 -0
  108. package/dist/s3/drive-key.js +58 -0
  109. package/dist/s3/drive-limits.d.ts +33 -0
  110. package/dist/s3/drive-limits.js +53 -0
  111. package/dist/s3/drive-lock.d.ts +11 -0
  112. package/dist/s3/drive-lock.js +47 -0
  113. package/dist/s3/drive-trashed-name.d.ts +13 -0
  114. package/dist/s3/drive-trashed-name.js +59 -0
  115. package/dist/s3/drive-write.d.ts +38 -0
  116. package/dist/s3/drive-write.js +258 -0
  117. package/dist/s3/drive.d.ts +59 -25
  118. package/dist/s3/drive.js +46 -77
  119. package/dist/s3/listing.d.ts +27 -1
  120. package/dist/s3/listing.js +62 -20
  121. package/dist/s3/long-answer.d.ts +12 -0
  122. package/dist/s3/long-answer.js +104 -0
  123. package/dist/s3/multipart-assemble.d.ts +17 -0
  124. package/dist/s3/multipart-assemble.js +68 -0
  125. package/dist/s3/multipart-sweep.d.ts +15 -0
  126. package/dist/s3/multipart-sweep.js +87 -0
  127. package/dist/s3/multipart-view.d.ts +45 -0
  128. package/dist/s3/multipart-view.js +232 -0
  129. package/dist/s3/multipart.d.ts +26 -19
  130. package/dist/s3/multipart.js +193 -78
  131. package/dist/s3/object-read.d.ts +17 -0
  132. package/dist/s3/object-read.js +127 -0
  133. package/dist/s3/object-write.d.ts +35 -0
  134. package/dist/s3/object-write.js +198 -0
  135. package/dist/s3/range.d.ts +14 -0
  136. package/dist/s3/range.js +80 -0
  137. package/dist/s3/response-sink.d.ts +12 -2
  138. package/dist/s3/response-sink.js +71 -7
  139. package/dist/s3/routes.d.ts +0 -1
  140. package/dist/s3/routes.js +242 -217
  141. package/dist/s3/same-file.d.ts +4 -1
  142. package/dist/s3/same-file.js +12 -3
  143. package/dist/s3/server.d.ts +54 -4
  144. package/dist/s3/server.js +174 -14
  145. package/dist/s3/sigv4-canonical.d.ts +91 -0
  146. package/dist/s3/sigv4-canonical.js +148 -0
  147. package/dist/s3/sigv4-presigned.d.ts +13 -0
  148. package/dist/s3/sigv4-presigned.js +82 -0
  149. package/dist/s3/sigv4.d.ts +26 -27
  150. package/dist/s3/sigv4.js +137 -102
  151. package/dist/s3/spool.d.ts +37 -0
  152. package/dist/s3/spool.js +104 -0
  153. package/dist/s3/staging.d.ts +90 -7
  154. package/dist/s3/staging.js +97 -66
  155. package/dist/s3/xml-multipart.d.ts +38 -0
  156. package/dist/s3/xml-multipart.js +47 -0
  157. package/dist/s3/xml-read.d.ts +28 -0
  158. package/dist/s3/xml-read.js +235 -0
  159. package/dist/s3/xml.d.ts +45 -2
  160. package/dist/s3/xml.js +72 -13
  161. package/dist/s3-gateway.d.ts +11 -5
  162. package/dist/s3-gateway.js +5 -2
  163. package/dist/seal.d.ts +1 -1
  164. package/dist/share.d.ts +5 -0
  165. package/dist/share.js +1 -1
  166. package/dist/shared/lib/api/types-heavy.d.ts +167 -0
  167. package/dist/shared/lib/api/types-heavy.js +60 -0
  168. package/dist/shared/lib/drive/rebuild-verify.js +1 -0
  169. package/dist/shared/lib/filecoin/providers.d.ts +25 -0
  170. package/dist/shared/lib/filecoin/providers.js +58 -0
  171. package/dist/shared/lib/heavy/download.d.ts +48 -0
  172. package/dist/shared/lib/heavy/download.js +116 -0
  173. package/dist/shared/lib/heavy/order-plan.d.ts +77 -0
  174. package/dist/shared/lib/heavy/order-plan.js +83 -0
  175. package/dist/shared/lib/heavy/order-runner.d.ts +9 -0
  176. package/dist/shared/lib/heavy/order-runner.js +300 -0
  177. package/dist/shared/lib/heavy/order-types.d.ts +90 -0
  178. package/dist/shared/lib/heavy/order-types.js +6 -0
  179. package/dist/shared/lib/heavy/order-wire.d.ts +55 -0
  180. package/dist/shared/lib/heavy/order-wire.js +113 -0
  181. package/dist/shared/lib/heavy/piece-cid.d.ts +24 -0
  182. package/dist/shared/lib/heavy/piece-cid.js +55 -0
  183. package/dist/shared/lib/heavy/sp-upload.d.ts +37 -0
  184. package/dist/shared/lib/heavy/sp-upload.js +112 -0
  185. package/dist/shared/lib/heavy/synapse-piece.d.ts +1 -0
  186. package/dist/shared/lib/heavy/synapse-piece.js +8 -0
  187. package/dist/shared/lib/share/handover-format.d.ts +129 -0
  188. package/dist/shared/lib/share/handover-format.js +323 -0
  189. package/dist/shared/lib/share/shared-file-info.js +1 -0
  190. package/dist/shared/lib/storage-network.d.ts +4 -4
  191. package/dist/shared/lib/storage-network.js +7 -7
  192. package/dist/shared/lib/storage-tier.d.ts +28 -0
  193. package/dist/shared/lib/storage-tier.js +63 -0
  194. package/dist/shared/lib/wallet/send-rules.js +1 -0
  195. package/dist/upload-file.d.ts +8 -0
  196. package/dist/upload-file.js +57 -25
  197. package/dist/upload-price-node.d.ts +3 -0
  198. package/dist/upload-price-node.js +3 -6
  199. package/dist/upload-price.d.ts +10 -0
  200. package/dist/upload-price.js +13 -1
  201. package/dist/upload-run.d.ts +80 -0
  202. package/dist/upload-run.js +173 -0
  203. package/dist/upload-steps.js +15 -4
  204. package/dist/upload-store.d.ts +15 -6
  205. package/dist/upload-store.js +6 -0
  206. package/dist/upload-wallet-put.d.ts +9 -4
  207. package/dist/upload-wallet-put.js +16 -6
  208. package/dist/upload-wallet.js +4 -0
  209. package/dist/upload-wire.d.ts +25 -0
  210. package/dist/upload-wire.js +20 -1
  211. package/dist/upload.js +28 -13
  212. package/dist/wallet-sign.js +2 -2
  213. package/docs/commands/handover.md +38 -0
  214. package/docs/commands/heavy.md +35 -0
  215. package/docs/commands/public-code.md +7 -0
  216. package/docs/commands/push.md +4 -1
  217. package/docs/commands/put.md +15 -1
  218. package/docs/commands/share.md +3 -1
  219. package/package.json +5 -2
  220. package/server.json +2 -2
  221. package/vendor/nmts-crypto/nmts_crypto_wasm.d.ts +17 -1
  222. package/vendor/nmts-crypto/nmts_crypto_wasm.js +28 -0
  223. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm +0 -0
  224. package/vendor/nmts-crypto/nmts_crypto_wasm_bg.wasm.d.ts +2 -1
@@ -0,0 +1,90 @@
1
+ import type { HeavyOrderApi, HeavyOrderCreated, HeavyPartCommit, HeavyPrice } from "../api/types-heavy.ts";
2
+ import type { HeavyPayment, HeavyRunFile } from "./order-plan.ts";
3
+ /** A sealed part as the sealer returns it: a Blob (may be disk-backed) or bytes in memory. */
4
+ export type SealedBytes = Blob | Uint8Array<ArrayBuffer>;
5
+ /** What the sealer is asked to seal. */
6
+ export interface HeavySealJob {
7
+ fileKey: string;
8
+ partIndex: number;
9
+ slot: number;
10
+ sealedLen: number;
11
+ }
12
+ /** The moments a caller can show. */
13
+ export type HeavyProgress = {
14
+ phase: "opened";
15
+ orderId: string;
16
+ order: HeavyOrderCreated;
17
+ } | {
18
+ phase: "sealing" | "hashing" | "placing" | "committing" | "stored";
19
+ slot: number;
20
+ fileKey: string;
21
+ partIndex: number;
22
+ } | {
23
+ phase: "uploading";
24
+ slot: number;
25
+ fileKey: string;
26
+ partIndex: number;
27
+ sentBytes: number;
28
+ totalBytes: number;
29
+ } | {
30
+ phase: "paying";
31
+ orderId: string;
32
+ price: HeavyPrice;
33
+ } | {
34
+ phase: "paid";
35
+ orderId: string;
36
+ txDigest: string;
37
+ };
38
+ export interface HeavyRunDeps {
39
+ api: HeavyOrderApi;
40
+ seal: (job: HeavySealJob, signal?: AbortSignal) => Promise<SealedBytes>;
41
+ /** The part's FRC-0069 PieceCID (`bafkzcib…`), e.g. `calculate` from `@filoz/synapse-core/piece`. */
42
+ pieceCid: (bytes: SealedBytes) => Promise<string>;
43
+ /** Upload to the company — `uploadPieceToProvider` in `sp-upload.ts`, with the caller's transport. */
44
+ upload: (input: {
45
+ serviceUrl: string;
46
+ bytes: SealedBytes;
47
+ pieceCid: string;
48
+ signal?: AbortSignal;
49
+ onProgress?: (sentBytes: number, totalBytes: number) => void;
50
+ }) => Promise<void>;
51
+ /** Wait `ms`, rejecting with an AbortError when `signal` aborts. Default: a timer. */
52
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
53
+ /** Milliseconds since some fixed point. Default: `Date.now`. */
54
+ now?: () => number;
55
+ /** A fresh idempotency key (16..64 of `[A-Za-z0-9_-]`). Default: a random UUID. */
56
+ newIdempotencyKey?: () => string;
57
+ }
58
+ export interface HeavyRunOptions {
59
+ files: readonly HeavyRunFile[];
60
+ payment: HeavyPayment;
61
+ /** Pass the key of an earlier run to reach the same order again; otherwise a new one is made. */
62
+ idempotencyKey?: string;
63
+ /** Slots worked on at once. Default 2. */
64
+ concurrency?: number;
65
+ /** First wait between order reads while a slot commits. Default 3 s; it grows by half each time. */
66
+ pollIntervalMs?: number;
67
+ /** Longest wait between order reads. Default 30 s. */
68
+ pollMaxIntervalMs?: number;
69
+ /** How long one slot may take from `uploaded` to `stored`. Default 60 minutes. */
70
+ storeTimeoutMs?: number;
71
+ /** Upload attempts per slot before giving up. Default 3. */
72
+ uploadAttempts?: number;
73
+ signal?: AbortSignal;
74
+ onProgress?: (event: HeavyProgress) => void;
75
+ }
76
+ export interface HeavyRunResult {
77
+ orderId: string;
78
+ idempotencyKey: string;
79
+ /** The Filecoin epoch every copy is kept until. */
80
+ expiryEpoch: number;
81
+ /** Credit orders: what was taken. */
82
+ credits?: number;
83
+ /** Wallet orders: the payment's Sui transaction digest. */
84
+ txDigest?: string;
85
+ /** Per file, in the order given: the parts to put in that file's `POST /v1/items`. */
86
+ files: {
87
+ key: string;
88
+ parts: HeavyPartCommit[];
89
+ }[];
90
+ }
@@ -0,0 +1,6 @@
1
+ // The shapes an NMTS Heavy upload is described in: what the caller hands the orchestrator, what it
2
+ // injects, what it hears along the way and what it gets back (`order-runner.ts` runs it).
3
+ //
4
+ // ⚠ THIS FILE IS PUBLISHED. It is copied byte-for-byte into the `nmts` command-line package.
5
+ // Keep the comments self-contained English, with no pointer only we can follow.
6
+ export {};
@@ -0,0 +1,55 @@
1
+ import { type HeavyCopy, type HeavyRefusal } from "../api/types-heavy.ts";
2
+ /** Why a Heavy upload stopped, as a machine-readable word. */
3
+ export type HeavyFailure =
4
+ /** A sealed part is under 127 bytes. The caller pads the plaintext and tries again. */
5
+ "piece_too_small"
6
+ /** A sealed part is over the per-piece limit. The caller cuts smaller parts. */
7
+ | "piece_too_large"
8
+ /** More parts than one order may hold, none at all, or parts not numbered 0..n-1. */
9
+ | "slot_count"
10
+ /** The sealer produced a different number of bytes than the order was opened for. */
11
+ | "sealed_len_mismatch"
12
+ /** The server refused a call; `refusal` names which refusal when it is one of the contract's. */
13
+ | "refused"
14
+ /** The server's answer did not have the shape the contract gives it. */
15
+ | "bad_answer"
16
+ /** Every upload attempt to the storage company failed. */
17
+ | "upload_failed"
18
+ /** The server reports the slot failed (or was removed) instead of stored. */
19
+ | "slot_failed"
20
+ /** The whole order failed or expired. */
21
+ | "order_failed"
22
+ /** The slot was not stored within the time allowed. */
23
+ | "store_timeout"
24
+ /** The server could not be reached, repeatedly. */
25
+ | "unreachable"
26
+ /** The wallet payment was sent but the server would not accept it. */
27
+ | "payment_refused";
28
+ export declare class HeavyOrderError extends Error {
29
+ readonly reason: HeavyFailure;
30
+ /** The contract refusal behind `refused` or `payment_refused`, when there was one. */
31
+ readonly refusal: HeavyRefusal | null;
32
+ readonly orderId: string | null;
33
+ readonly slot: number | null;
34
+ constructor(reason: HeavyFailure, message: string, details?: {
35
+ refusal?: HeavyRefusal | null;
36
+ orderId?: string | null;
37
+ slot?: number | null;
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ export declare function abortError(): DOMException;
42
+ export declare function isAbort(err: unknown): boolean;
43
+ /** The error's string `code`, if it has one. */
44
+ export declare function codeOf(err: unknown): string | null;
45
+ /**
46
+ * A failure that says nothing about the request itself — the line dropped, the server had a bad
47
+ * moment, or a limiter answered without a named reason — so the same call may simply be made again.
48
+ * A named refusal never is: asking again gets the same answer.
49
+ */
50
+ export declare function isTransient(err: unknown): boolean;
51
+ /** Wait `ms`, rejecting with an AbortError as soon as `signal` aborts. */
52
+ export declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
53
+ export declare function isHttpsUrl(value: unknown): value is string;
54
+ /** A stored slot's copies, checked field by field; `null` when the answer is not usable. */
55
+ export declare function readCopies(raw: unknown): HeavyCopy[] | null;
@@ -0,0 +1,113 @@
1
+ // How an NMTS Heavy upload fails, and how it reads what the server and the network hand back.
2
+ //
3
+ // ⚠ THIS FILE IS PUBLISHED. It is copied byte-for-byte into the `nmts` command-line package.
4
+ // Keep the comments self-contained English, with no pointer only we can follow.
5
+ //
6
+ // The orchestrator (`order-runner.ts`) takes its api from the caller, so it cannot know the caller's
7
+ // error class. It reads errors by SHAPE instead — a string `code` (the server's error code, or a
8
+ // transport word such as NETWORK) and a number `status` — which both the browser's and the command
9
+ // line's api clients carry.
10
+ import { heavyRefusalOf } from "../api/types-heavy.js";
11
+ export class HeavyOrderError extends Error {
12
+ reason;
13
+ /** The contract refusal behind `refused` or `payment_refused`, when there was one. */
14
+ refusal;
15
+ orderId;
16
+ slot;
17
+ constructor(reason, message, details = {}) {
18
+ super(message, details.cause === undefined ? undefined : { cause: details.cause });
19
+ this.name = "HeavyOrderError";
20
+ this.reason = reason;
21
+ this.refusal = details.refusal ?? null;
22
+ this.orderId = details.orderId ?? null;
23
+ this.slot = details.slot ?? null;
24
+ }
25
+ }
26
+ export function abortError() {
27
+ return new DOMException("The operation was aborted.", "AbortError");
28
+ }
29
+ export function isAbort(err) {
30
+ return typeof err === "object" && err !== null && "name" in err && err.name === "AbortError";
31
+ }
32
+ /** The error's string `code`, if it has one. */
33
+ export function codeOf(err) {
34
+ return typeof err === "object" && err !== null && "code" in err && typeof err.code === "string"
35
+ ? err.code
36
+ : null;
37
+ }
38
+ function statusOf(err) {
39
+ return typeof err === "object" && err !== null && "status" in err && typeof err.status === "number"
40
+ ? err.status
41
+ : null;
42
+ }
43
+ /**
44
+ * A failure that says nothing about the request itself — the line dropped, the server had a bad
45
+ * moment, or a limiter answered without a named reason — so the same call may simply be made again.
46
+ * A named refusal never is: asking again gets the same answer.
47
+ */
48
+ export function isTransient(err) {
49
+ if (isAbort(err))
50
+ return false;
51
+ const code = codeOf(err);
52
+ if (code !== null && heavyRefusalOf(code) !== null)
53
+ return false;
54
+ if (code === "NETWORK" || code === "INTERNAL" || code === "BAD_RESPONSE" || code === "RATE_LIMITED") {
55
+ return true;
56
+ }
57
+ const status = statusOf(err);
58
+ if (status !== null)
59
+ return status >= 500;
60
+ // A bare TypeError is what `fetch` throws when the line is down.
61
+ return err instanceof TypeError;
62
+ }
63
+ /** Wait `ms`, rejecting with an AbortError as soon as `signal` aborts. */
64
+ export function defaultSleep(ms, signal) {
65
+ return new Promise((resolve, reject) => {
66
+ if (signal?.aborted) {
67
+ reject(abortError());
68
+ return;
69
+ }
70
+ const onAbort = () => {
71
+ clearTimeout(timer);
72
+ reject(abortError());
73
+ };
74
+ const timer = setTimeout(() => {
75
+ signal?.removeEventListener("abort", onAbort);
76
+ resolve();
77
+ }, ms);
78
+ signal?.addEventListener("abort", onAbort, { once: true });
79
+ });
80
+ }
81
+ export function isHttpsUrl(value) {
82
+ if (typeof value !== "string")
83
+ return false;
84
+ try {
85
+ return new URL(value).protocol === "https:";
86
+ }
87
+ catch {
88
+ // Not a URL at all — the same answer as "not https".
89
+ return false;
90
+ }
91
+ }
92
+ /** A stored slot's copies, checked field by field; `null` when the answer is not usable. */
93
+ export function readCopies(raw) {
94
+ if (!Array.isArray(raw) || raw.length === 0)
95
+ return null;
96
+ const out = [];
97
+ for (const c of raw) {
98
+ if (typeof c !== "object" ||
99
+ c === null ||
100
+ !("provider_id" in c && "data_set_id" in c && "piece_id" in c && "retrieval_url" in c)) {
101
+ return null;
102
+ }
103
+ const { provider_id, data_set_id, piece_id, retrieval_url } = c;
104
+ if (typeof provider_id !== "string" ||
105
+ typeof data_set_id !== "string" ||
106
+ typeof piece_id !== "string" ||
107
+ !isHttpsUrl(retrieval_url)) {
108
+ return null;
109
+ }
110
+ out.push({ provider_id, data_set_id, piece_id, retrieval_url });
111
+ }
112
+ return out;
113
+ }
@@ -0,0 +1,24 @@
1
+ /** What a PieceCID can be computed over: bytes in memory, a Blob (read as a stream), or a stream. */
2
+ export type PieceSource = Uint8Array | Blob | ReadableStream<Uint8Array>;
3
+ /** Bytes a single Filecoin piece may carry at least, and at most (the storage companies' limit). */
4
+ export declare const PIECE_MIN_BYTES = 127;
5
+ export declare const PIECE_MAX_BYTES = 1065353216;
6
+ /** The PieceCID of `source`, in its string form (`bafkzcib…`). */
7
+ export declare function pieceCidOf(source: PieceSource): Promise<string>;
8
+ /**
9
+ * A pass-through stream that computes the PieceCID of whatever flows through it.
10
+ *
11
+ * For a caller that already streams the part somewhere and wants the id from the same read. The
12
+ * `result` settles once the stream is closed.
13
+ */
14
+ export declare function pieceCidTransform(): Promise<{
15
+ transform: TransformStream<Uint8Array, Uint8Array>;
16
+ result: Promise<string>;
17
+ }>;
18
+ /**
19
+ * Whether a string is a well-formed PieceCID, and the raw byte size it names.
20
+ *
21
+ * Used to check what a server hands back before trusting it as the id of our bytes. `null` means
22
+ * the string is not a PieceCID at all.
23
+ */
24
+ export declare function pieceSizeOf(cid: string): Promise<number | null>;
@@ -0,0 +1,55 @@
1
+ // The Filecoin piece id (PieceCID, FRC-0069) of one sealed part.
2
+ //
3
+ // ⚠ THIS FILE IS PUBLISHED. It is copied byte-for-byte into the `nmts` command-line package.
4
+ // Keep the comments self-contained English, with no pointer only we can follow.
5
+ //
6
+ // WHAT IT IS. A PieceCID names bytes by the root of a binary Merkle tree over their FR32-padded form,
7
+ // plus how much padding the tree needed and its height (`bafkzcib…`). The storage company checks the
8
+ // bytes it received against it, and the chain records it. We do not implement the tree: it comes
9
+ // from `@filoz/synapse-core/piece`, the library the Filecoin Onchain Cloud tooling itself uses.
10
+ //
11
+ // ⛔ LOADED ONLY WHEN SOMEBODY STORES ON FILECOIN. The library is imported dynamically on first use,
12
+ // so a program (or a browser page) that never touches NMTS Heavy never loads it.
13
+ //
14
+ // ⚠ THE BYTES ARE READ ONCE MORE. Computing the id is a full pass over the part (seconds for half a
15
+ // gigabyte); uploading is a second pass. The id is needed before the upload starts, because the
16
+ // server places the part only once it knows exactly what the part is.
17
+ /** Bytes a single Filecoin piece may carry at least, and at most (the storage companies' limit). */
18
+ export const PIECE_MIN_BYTES = 127;
19
+ export const PIECE_MAX_BYTES = 1_065_353_216;
20
+ /** The PieceCID of `source`, in its string form (`bafkzcib…`). */
21
+ export async function pieceCidOf(source) {
22
+ const { calculate } = await import("./synapse-piece.js");
23
+ return (await calculate(source)).toString();
24
+ }
25
+ /**
26
+ * A pass-through stream that computes the PieceCID of whatever flows through it.
27
+ *
28
+ * For a caller that already streams the part somewhere and wants the id from the same read. The
29
+ * `result` settles once the stream is closed.
30
+ */
31
+ export async function pieceCidTransform() {
32
+ const { transformStream } = await import("./synapse-piece.js");
33
+ const { transform, result } = transformStream();
34
+ return { transform, result: result.then((cid) => cid.toString()) };
35
+ }
36
+ /**
37
+ * Whether a string is a well-formed PieceCID, and the raw byte size it names.
38
+ *
39
+ * Used to check what a server hands back before trusting it as the id of our bytes. `null` means
40
+ * the string is not a PieceCID at all.
41
+ */
42
+ export async function pieceSizeOf(cid) {
43
+ const { tryFrom } = await import("./synapse-piece.js");
44
+ const piece = tryFrom(cid);
45
+ if (piece === null)
46
+ return null;
47
+ try {
48
+ return piece.size;
49
+ }
50
+ catch {
51
+ // The library refuses a size past the safe-integer range. No part NMTS stores is near it, so
52
+ // such a string is not the id of our bytes, whatever else it may be.
53
+ return null;
54
+ }
55
+ }
@@ -0,0 +1,37 @@
1
+ /** The request function this module needs: `fetch`, or anything shaped like it. */
2
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
3
+ /**
4
+ * How the part's bytes are sent in step 2. The default is `fetch`, which cannot report how much of
5
+ * a request body has gone out; a browser passes one built on XMLHttpRequest, which can.
6
+ */
7
+ export type PutBody = (input: {
8
+ url: string;
9
+ body: Blob | Uint8Array<ArrayBuffer>;
10
+ signal?: AbortSignal;
11
+ onProgress?: (sentBytes: number, totalBytes: number) => void;
12
+ }) => Promise<Response>;
13
+ /** Why an upload did not complete, as a machine-readable word. */
14
+ export type PieceUploadFailure = "not_https" | "size_out_of_range" | "session_refused" | "location_missing" | "upload_refused" | "finalize_refused";
15
+ export declare class PieceUploadError extends Error {
16
+ readonly reason: PieceUploadFailure;
17
+ /** The HTTP status that ended it, when a response was the reason. */
18
+ readonly status: number | null;
19
+ constructor(reason: PieceUploadFailure, message: string, status?: number | null);
20
+ }
21
+ export interface UploadPieceInput {
22
+ /** The company's service origin, as the order's `target` answered it (`https://…`). */
23
+ serviceUrl: string;
24
+ /** The sealed part, exactly the bytes its PieceCID was computed over. */
25
+ bytes: Blob | Uint8Array<ArrayBuffer>;
26
+ /** The part's PieceCID (`bafkzcib…`). The company refuses the upload if the bytes do not match. */
27
+ pieceCid: string;
28
+ signal?: AbortSignal;
29
+ /** Bytes of the part sent so far, and the part's size. */
30
+ onProgress?: (sentBytes: number, totalBytes: number) => void;
31
+ /** Requests for steps 1 and 3 (and step 2 when `put` is absent). Default: the global `fetch`. */
32
+ fetchImpl?: FetchLike;
33
+ /** Step 2's transport. Default: `fetchImpl`, with progress reported only at the end. */
34
+ put?: PutBody;
35
+ }
36
+ /** Upload one part and have the company accept it under `pieceCid`. Resolves once step 3 answers 2xx. */
37
+ export declare function uploadPieceToProvider(input: UploadPieceInput): Promise<void>;
@@ -0,0 +1,112 @@
1
+ // Upload one sealed part to a Filecoin storage company, straight from this device.
2
+ //
3
+ // ⚠ THIS FILE IS PUBLISHED. It is copied byte-for-byte into the `nmts` command-line package.
4
+ // Keep the comments self-contained English, with no pointer only we can follow.
5
+ //
6
+ // THE PROTOCOL — three plain HTTP calls to the company's storage service, no credentials, open CORS:
7
+ // 1. POST <service>/pdp/piece/uploads → 201, `Location: /pdp/piece/uploads/<uuid>`
8
+ // 2. PUT <service>/pdp/piece/uploads/<uuid> (the bytes) → 204
9
+ // 3. POST <service>/pdp/piece/uploads/<uuid> {"pieceCid": "<bafkzcib…>"} → 200
10
+ // This is the same exchange `uploadPieceStreaming` in `@filoz/synapse-core/sp` performs. We write the
11
+ // three calls ourselves because importing that function also loads the library's error decoder,
12
+ // which carries every contract ABI the tooling knows — measured 2026-09-23 with esbuild: about
13
+ // 160 KB minified, of which 98 KB is that ABI table, for three requests that need none of it.
14
+ //
15
+ // ⛔ THE COMPANY IS UNTRUSTED, AND THAT IS FINE. The bytes are sealed (end-to-end encrypted) before
16
+ // they get here, and the company checks them against the PieceCID we name in step 3. Nothing a
17
+ // company does with this exchange can reveal a file or make the wrong bytes open as the right one.
18
+ //
19
+ // ⛔ NO RETRY IN HERE. Each attempt is a fresh upload session; the caller decides whether a failed
20
+ // attempt is worth another (`order-runner.ts` does). A half-finished session is simply abandoned.
21
+ export class PieceUploadError extends Error {
22
+ reason;
23
+ /** The HTTP status that ended it, when a response was the reason. */
24
+ status;
25
+ constructor(reason, message, status = null) {
26
+ super(message);
27
+ this.name = "PieceUploadError";
28
+ this.reason = reason;
29
+ this.status = status;
30
+ }
31
+ }
32
+ /** The bytes one piece may hold, at least and at most — the storage companies' own limits. */
33
+ const MIN_BYTES = 127;
34
+ const MAX_BYTES = 1_065_353_216;
35
+ /** `<service>/<path>`, whether or not the service origin was given with a trailing slash or a path. */
36
+ function endpoint(serviceUrl, path) {
37
+ const base = serviceUrl.endsWith("/") ? serviceUrl : `${serviceUrl}/`;
38
+ return new URL(path, base).toString();
39
+ }
40
+ function sizeOf(bytes) {
41
+ return bytes instanceof Uint8Array ? bytes.byteLength : bytes.size;
42
+ }
43
+ /** Upload one part and have the company accept it under `pieceCid`. Resolves once step 3 answers 2xx. */
44
+ export async function uploadPieceToProvider(input) {
45
+ const { serviceUrl, bytes, pieceCid, signal, onProgress } = input;
46
+ const fetchImpl = input.fetchImpl ?? ((url, init) => fetch(url, init));
47
+ let service;
48
+ try {
49
+ service = new URL(serviceUrl);
50
+ }
51
+ catch {
52
+ // An unparsable address is the same refusal as a non-https one: nothing is sent to it.
53
+ throw new PieceUploadError("not_https", `The storage service address "${serviceUrl}" is not a URL.`);
54
+ }
55
+ if (service.protocol !== "https:") {
56
+ throw new PieceUploadError("not_https", `The storage service must be https, got ${service.protocol}`);
57
+ }
58
+ const total = sizeOf(bytes);
59
+ if (total < MIN_BYTES || total > MAX_BYTES) {
60
+ throw new PieceUploadError("size_out_of_range", `A piece must be ${MIN_BYTES}..${MAX_BYTES} bytes; this part is ${total}.`);
61
+ }
62
+ const withSignal = signal === undefined ? {} : { signal };
63
+ // 1. Open an upload session.
64
+ const created = await fetchImpl(endpoint(serviceUrl, "pdp/piece/uploads"), {
65
+ method: "POST",
66
+ ...withSignal,
67
+ });
68
+ if (created.status !== 201) {
69
+ throw new PieceUploadError("session_refused", `The storage service did not open an upload (HTTP ${created.status}).`, created.status);
70
+ }
71
+ // ⚠ Readable across origins only when the company exposes it (`Access-Control-Expose-Headers`).
72
+ const location = created.headers.get("Location");
73
+ const uuid = location === null ? null : /\/pdp\/piece\/uploads\/([A-Fa-f0-9-]+)/.exec(location)?.[1];
74
+ if (uuid === null || uuid === undefined) {
75
+ throw new PieceUploadError("location_missing", location === null
76
+ ? "The storage service opened an upload but did not say where (no Location header)."
77
+ : `The storage service answered an upload address this client cannot read: ${location}`);
78
+ }
79
+ const sessionUrl = endpoint(serviceUrl, `pdp/piece/uploads/${uuid}`);
80
+ // 2. Send the bytes.
81
+ const put = input.put ??
82
+ (async (req) => {
83
+ const res = await fetchImpl(req.url, {
84
+ method: "PUT",
85
+ headers: { "Content-Type": "application/octet-stream" },
86
+ body: req.body,
87
+ ...(req.signal === undefined ? {} : { signal: req.signal }),
88
+ });
89
+ if (res.ok)
90
+ req.onProgress?.(total, total);
91
+ return res;
92
+ });
93
+ const sent = await put({
94
+ url: sessionUrl,
95
+ body: bytes,
96
+ ...withSignal,
97
+ ...(onProgress === undefined ? {} : { onProgress }),
98
+ });
99
+ if (!sent.ok) {
100
+ throw new PieceUploadError("upload_refused", `The storage service refused the part's bytes (HTTP ${sent.status}).`, sent.status);
101
+ }
102
+ // 3. Name the bytes. The company recomputes the id from what it received and refuses a mismatch.
103
+ const finalized = await fetchImpl(sessionUrl, {
104
+ method: "POST",
105
+ headers: { "Content-Type": "application/json" },
106
+ body: JSON.stringify({ pieceCid }),
107
+ ...withSignal,
108
+ });
109
+ if (!finalized.ok) {
110
+ throw new PieceUploadError("finalize_refused", `The storage service did not accept the part as ${pieceCid} (HTTP ${finalized.status}).`, finalized.status);
111
+ }
112
+ }
@@ -0,0 +1 @@
1
+ export { calculate, transformStream, tryFrom } from "@filoz/synapse-core/piece";
@@ -0,0 +1,8 @@
1
+ // The three piece functions NMTS Heavy uses from `@filoz/synapse-core/piece`, named one by one.
2
+ //
3
+ // WHY A FILE OF ITS OWN. `piece-cid.ts` loads the library lazily, and a lazy `import()` of the
4
+ // library's own entry keeps EVERY export of it alive in the bundle — measured 2026-09-23 with
5
+ // esbuild: about 500 KB minified, because the entry also carries the download and URL helpers and
6
+ // what they import. Lazily importing THIS file instead lets the bundler keep only these three
7
+ // (about 27 KB minified), and the library still loads only when a part is actually hashed.
8
+ export { calculate, transformStream, tryFrom } from "@filoz/synapse-core/piece";
@@ -0,0 +1,129 @@
1
+ /** Wire values of the handover file. Fixed forever once a file carries them. */
2
+ export declare const HANDOVER_FORMAT = "nmts-handover";
3
+ export declare const HANDOVER_VERSION = 1;
4
+ /** Marker inside the sealed parts document. */
5
+ export declare const HANDOVER_PARTS_FORMAT = "nmts-handover-parts/1";
6
+ /** Marker of the name document — the §5.4 share document, which a handover extends by two keys. */
7
+ export declare const SHARE_FILE_FORMAT = "nmts-share-file/1";
8
+ /** Wire values of the public code file. */
9
+ export declare const PUBLIC_CODE_FORMAT = "nmts-public-code";
10
+ export declare const PUBLIC_CODE_VERSION = 1;
11
+ /** File name endings. */
12
+ export declare const HANDOVER_EXTENSION = ".nmtshandover";
13
+ export declare const PUBLIC_CODE_EXTENSION = ".nmtscode";
14
+ /**
15
+ * What a person who opens the file in a text editor reads. Informational; not read back.
16
+ * The two place names are the labels on the screen: the side panel entry and the button.
17
+ */
18
+ export declare const HANDOVER_NOTE: readonly [string, string];
19
+ /** Size caps on the whole text, checked before it is parsed (§5.6, §5.7). */
20
+ export declare const MAX_HANDOVER_FILE_BYTES: number;
21
+ export declare const MAX_PUBLIC_CODE_FILE_BYTES: number;
22
+ /** Field bounds (§5.6). Together they keep a file under MAX_HANDOVER_FILE_BYTES. */
23
+ export declare const MAX_NAME_SEALED_LEN: number;
24
+ export type HandoverNetwork = "mainnet" | "testnet";
25
+ /** One handover file, every binary value still in its base64url text form. */
26
+ export interface HandoverFile {
27
+ network: HandoverNetwork;
28
+ /** The item id, lowercase, exactly as bound into the envelope. */
29
+ item: string;
30
+ /** The sender's published identity (4989 bytes). */
31
+ sender: string;
32
+ /** The share envelope (1240 bytes); its first 16 bytes are the sender's address. */
33
+ envelope: string;
34
+ /** The name document sealed under the file key. */
35
+ name: string;
36
+ /** The whole-file digest sealed under the file key (104 bytes). */
37
+ hash: string;
38
+ /** The parts document sealed under the file key. */
39
+ parts: string;
40
+ }
41
+ /**
42
+ * The name document a handover seals: the §5.4 share document plus the two values that bind the
43
+ * rest of the file to the envelope. `payload_cmt` covers the sealed name, so these two are covered.
44
+ */
45
+ export interface HandoverName {
46
+ name: string;
47
+ /** The file's real length. Required here, unlike a built-in share's document. */
48
+ size: number;
49
+ network: HandoverNetwork;
50
+ /** SHA-256 of the sealed parts value (its bytes, not its text), unpadded base64url. */
51
+ partsSha256: string;
52
+ }
53
+ /** One stored piece of the file, in order. A quilt patch names `patch`; a whole blob names `blob`. */
54
+ export interface HandoverPart {
55
+ blob: string | null;
56
+ patch: string | null;
57
+ /** Bytes the sealed stream occupies. */
58
+ len: number;
59
+ /**
60
+ * The piece's end epoch as the sender's drive recorded it when the file was made — exclusive:
61
+ * the storage has ended once the current epoch reaches it. A hint, not a promise (the sender may
62
+ * extend or delete the storage later); 0 means the drive did not know it.
63
+ */
64
+ exp: number;
65
+ }
66
+ /** The public code file. */
67
+ export interface PublicCodeFile {
68
+ /** The public code in the form a person reads. */
69
+ code: string;
70
+ /** The published identity (4989 bytes), base64url. */
71
+ identity: string;
72
+ }
73
+ /**
74
+ * Why a file was refused:
75
+ * too-large — over the size cap; not parsed at all
76
+ * not-json — it is not a JSON object
77
+ * wrong-format — it is JSON, but not this kind of file
78
+ * unknown-version — this kind of file, with a version number above the one this reader knows
79
+ * other-network — a handover file made on the other network
80
+ * bad-field — the right kind and version, but a field (or `version` itself) is wrong
81
+ */
82
+ export type HandoverFormatProblem = "too-large" | "not-json" | "wrong-format" | "unknown-version" | "other-network" | "bad-field";
83
+ export declare class HandoverFormatError extends Error {
84
+ readonly problem: HandoverFormatProblem;
85
+ /** The field at fault, for `bad-field`. */
86
+ readonly field: string | null;
87
+ constructor(problem: HandoverFormatProblem, field?: string | null);
88
+ }
89
+ /**
90
+ * Bytes behind an unpadded base64url string, or null when it is not one in CANONICAL form: the
91
+ * bits the last character carries beyond the data must be zero, so one byte string has one text.
92
+ */
93
+ export declare function base64UrlByteLength(text: string): number | null;
94
+ /** `nmts-handover-<YYYY-MM-DD>.nmtshandover`, the date in UTC. The file's own name is not in it. */
95
+ export declare function handoverFileName(now: Date): string;
96
+ /** `nmts-public-code-<public code>.nmtscode`. The code is public, and it tells two such files apart. */
97
+ export declare function publicCodeFileName(code: string): string;
98
+ /** The handover file's text. Pretty-printed: somebody may well open it to see what it is. */
99
+ export declare function encodeHandover(file: HandoverFile): string;
100
+ /**
101
+ * Read a handover file's text, in the order §5.6 gives: size, JSON, format, version, network, key
102
+ * set, `note`, fields. `network` is the reader's own. Throws `HandoverFormatError`; never returns a
103
+ * partial file.
104
+ */
105
+ export declare function decodeHandover(text: string, network: HandoverNetwork): HandoverFile;
106
+ /** The name document, exactly as it is sealed. */
107
+ export declare function encodeHandoverName(doc: HandoverName): string;
108
+ /** Whether a name document, once sealed, fits the `name` field. The caller checks before sealing. */
109
+ export declare function handoverNameFits(encoded: string): boolean;
110
+ /** Read an opened name document. Throws `HandoverFormatError` (`bad-field`, `name`). */
111
+ export declare function decodeHandoverName(text: string): HandoverName;
112
+ /** The parts document, exactly as it is sealed. Compact: nobody reads it but the recipient's engine. */
113
+ export declare function encodePartsList(parts: readonly HandoverPart[]): string;
114
+ /** Read an opened parts document. Throws `HandoverFormatError` (`bad-field`, `parts`). */
115
+ export declare function decodePartsList(text: string): HandoverPart[];
116
+ /**
117
+ * The smallest recorded end epoch, or 0 when any piece's is unknown (0). Exclusive, and recorded
118
+ * when the file was made — see `HandoverPart.exp`.
119
+ */
120
+ export declare function earliestExpiry(parts: readonly HandoverPart[]): number;
121
+ /** The public code file's text. */
122
+ export declare function encodePublicCodeFile(file: PublicCodeFile): string;
123
+ /**
124
+ * Read a public code file's text. Throws `HandoverFormatError`.
125
+ *
126
+ * ⚠ This checks the SHAPE only. Whether `identity` really fingerprints to `code` is the engine's
127
+ * question, and a caller must ask it before sealing anything to the identity.
128
+ */
129
+ export declare function decodePublicCodeFile(text: string): PublicCodeFile;