@ipab/ipfs-store 0.0.0 → 0.1.0-rc.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +244 -1
  3. package/dist/configuration.d.ts +21 -0
  4. package/dist/configuration.d.ts.map +1 -0
  5. package/dist/configuration.js +62 -0
  6. package/dist/configuration.js.map +1 -0
  7. package/dist/dag.d.ts +49 -0
  8. package/dist/dag.d.ts.map +1 -0
  9. package/dist/dag.js +216 -0
  10. package/dist/dag.js.map +1 -0
  11. package/dist/errors.d.ts +6 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +15 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/index.d.ts +57 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +417 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/kubo.d.ts +38 -0
  20. package/dist/kubo.d.ts.map +1 -0
  21. package/dist/kubo.js +189 -0
  22. package/dist/kubo.js.map +1 -0
  23. package/dist/node.d.ts +11 -0
  24. package/dist/node.d.ts.map +1 -0
  25. package/dist/node.js +60 -0
  26. package/dist/node.js.map +1 -0
  27. package/dist/retention.d.ts +44 -0
  28. package/dist/retention.d.ts.map +1 -0
  29. package/dist/retention.js +328 -0
  30. package/dist/retention.js.map +1 -0
  31. package/dist/storage.d.ts +28 -0
  32. package/dist/storage.d.ts.map +1 -0
  33. package/dist/storage.js +161 -0
  34. package/dist/storage.js.map +1 -0
  35. package/dist/store.d.ts +71 -0
  36. package/dist/store.d.ts.map +1 -0
  37. package/dist/store.js +412 -0
  38. package/dist/store.js.map +1 -0
  39. package/package.json +67 -5
  40. package/src/configuration.ts +93 -0
  41. package/src/dag.ts +281 -0
  42. package/src/errors.ts +25 -0
  43. package/src/index.ts +520 -0
  44. package/src/kubo.ts +293 -0
  45. package/src/node.ts +78 -0
  46. package/src/retention.ts +398 -0
  47. package/src/storage.ts +181 -0
  48. package/src/store.ts +577 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 preset-pnpm-monorepo contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,246 @@
1
1
  # @ipab/ipfs-store
2
2
 
3
- Bootstrap placeholder only. Real releases start at 0.1.0+.
3
+ The first npm release is being prepared as `0.1.0-rc.0`. Source and tests were
4
+ migrated from `silvermoon-work/task-engine` at `0f3dd99`, including the Kubo
5
+ indirect-through pin fix. The original MIT license and storage/CID/coordination
6
+ contracts are preserved; existing published packages and repositories are
7
+ unchanged. Tests use the shared workspace Vitest configuration and strict
8
+ type-aware lint. Runtime response boundaries are checked explicitly. In-flight
9
+ cancellation preserves Error reasons; a non-Error reason is reported as an Error
10
+ with that original reason in `cause`, rather than rejecting an untyped value.
11
+
12
+ Run `pnpm check` from the repository root. With Kubo installed, the optional
13
+ real-daemon regression runs against disposable offline repositories:
14
+
15
+ ```powershell
16
+ $env:KUBO_REAL_TEST = '1'
17
+ pnpm --filter @ipab/ipfs-store exec vitest run --root . --config ..\..\vitest.config.ts test\kubo-real.test.ts
18
+ Remove-Item Env:KUBO_REAL_TEST
19
+ ```
20
+
21
+ Build the workspace first. No shared daemon is reconfigured or GC'd by this
22
+ test.
23
+
24
+ Shared verified IPFS/UnixFS acquisition for Builder and Engine, independent of
25
+ task scheduling and Engine databases. Library callers own and inject content
26
+ objects; importing this package does not read configuration or start a client.
27
+
28
+ ```ts
29
+ import { IpfsStore } from "@ipab/ipfs-store";
30
+
31
+ const content = new IpfsStore({
32
+ dataDir: contentDirectory,
33
+ gateway: "https://gateway.example", // omit for strictly local operation
34
+ limits: { bytes: 256 * 1024 * 1024, blocks: 16_384, depth: 64 },
35
+ });
36
+ const output = await buildTaskBundle(input, { ...buildOptions, content });
37
+ const engine = createTaskEngine({
38
+ store: engineDatabase,
39
+ ipfsStore: content,
40
+ authorize,
41
+ });
42
+ // Both borrow the same object. The host closes it after all consumers finish.
43
+ ```
44
+
45
+ `read(cidOrCidPath, { signal? })` returns a discriminated UnixFS node: files
46
+ (`type: "file" | "raw"`) expose `content()` as an async byte stream; directories
47
+ expose `entries()` as an async iterator. It does not materialize the whole file
48
+ or apply Task portable-path rules. The UnixFS node profile is SHA-256 raw/DAG-PB
49
+ regular files and UnixFS directories. Missing local blocks are fetched only
50
+ through an explicit gateway, verified before atomic publication, and reused by
51
+ later readers. Corrupt local content fails rather than silently fetching a
52
+ replacement.
53
+
54
+ `prepare(cid, { signal? })` verifies the complete linked DAG with unique-block,
55
+ byte and depth limits. `block.get` and verified `put` support offline block
56
+ transfer; CAR encoding, task manifests, imports, path policy and DAG grafting
57
+ are not store responsibilities. Low-level verified blocks are SHA-256
58
+ codec-neutral. Full DAG preparation supports raw, DAG-PB and canonical DAG-CBOR
59
+ and follows genuine IPLD links across these codecs, not CID-looking strings or
60
+ objects. Unknown codecs, unsupported hashes, missing/corrupt blocks and exceeded
61
+ budgets fail. Structured blocks also have a 64-level/100,000-node inspection
62
+ limit. Shared subgraphs count once for bytes and blocks, but all paths must
63
+ satisfy the DAG depth limit. `ContentBlocks` in `./dag` is the bounded in-memory
64
+ block primitive for such transfers, not another application-level acquisition
65
+ API. `contentLinks(cid, bytes)` in that subpath is the shared codec-aware link
66
+ extractor used by both preparation paths (callers verify block integrity
67
+ separately). It reuses the identity-safe codec from `ipfs-payload/dag-cbor`,
68
+ which loads no TypeBox/AJV runtime. All pin, retain, finishImport and
69
+ reconciliation preparation uses this same mixed-codec traversal with fresh
70
+ backing reads. CAR framing remains outside Store; tests transfer mixed graphs
71
+ through the existing CAR library and staging/finishImport, including
72
+ parent-before-child delivery and incomplete imports.
73
+
74
+ The additive `readContent(cid)` and `resolveContent(cid, path)` methods
75
+ implement the type-only `ReadonlyIpfsAccess` contract. `readContent` returns the
76
+ shared `IpfsNode` DU (`kind: "file"` with a `ReadableStream`, or
77
+ `kind: "directory"` with an async entry stream). Entries carry target CIDs and
78
+ validated file/directory kinds. File cancellation and directory enumeration
79
+ retain host budgets/signals. `resolveContent` accepts directory-relative
80
+ slash-separated segments and returns the target CID; empty path validates and
81
+ returns the resource itself. Structured archives cannot be read or resolved as a
82
+ third file variant. The existing `read` result shape is unchanged and is now
83
+ named `UnixfsNode`; the exported `IpfsNode` name refers to the shared access
84
+ contract. The temporary writer remains a host contract, not an unprotected alias
85
+ for `put`.
86
+
87
+ `scope(limits?)` borrows the same backing store with an independent, no-larger
88
+ reader budget and cancellation lifetime. Closing a scope does not close its
89
+ parent. Engine uses scopes for its own retention limits; logical
90
+ file/path/execution budgets remain in Builder/Engine, separately from
91
+ unique-block accounting. `IpfsStore.fromClient(port, limits?, dataDir?)`
92
+ explicitly adapts a caller-owned block source (for example an offline CAR); it
93
+ never closes that source. Without a dataDir this adapter is memory-only. The
94
+ borrowed **source** is read-only: adapter `put` still verifies and writes its
95
+ own ContentBlocks/SharedContent, never a source `put`. Closing the adapter never
96
+ closes the source. `writable` does not imply durable coordination: adapters
97
+ expose `supportsRetention: false` and reject retention operations. Engine checks
98
+ that separate capability. Neither construction nor import loads config.
99
+
100
+ ## Optional Kubo backend
101
+
102
+ ```ts
103
+ const content = new IpfsStore({
104
+ backend: "kubo",
105
+ apiUrl: "http://127.0.0.1:5001",
106
+ coordinationDir: "/shared/task-content-retention",
107
+ timeoutMs: 30_000,
108
+ limits: {
109
+ bytes: 256 * 1024 * 1024,
110
+ blocks: 16_384,
111
+ blockBytes: 2 * 1024 * 1024,
112
+ depth: 64,
113
+ },
114
+ });
115
+ ```
116
+
117
+ Kubo is a direct raw-block backend, not a local cache backed by a Gateway. No
118
+ application `blocks` directory or temporary CAR is written. Original bytes and
119
+ SHA-256 raw, DAG-PB and DAG-CBOR block CIDs are preserved; strong closure
120
+ traversal supports all three while file/directory access remains raw/UnixFS
121
+ only. RPC responses, including errors, are bounded while streaming. The same
122
+ read/unique-block/depth limits apply. `limits.bytes` and `retainedBytes` measure
123
+ in-process retention, **not disk quotas**.
124
+
125
+ Explicit trusted remote HTTP(S) RPC endpoints are supported. The host owns
126
+ authentication, transport and access policy; URL user information is sent as
127
+ Basic authorization and is not included in RPC error messages. The library does
128
+ not discover, expose, start, stop, reconfigure or globally GC a daemon. Daemon
129
+ networking is entirely its startup policy. Product code never issues `config`,
130
+ swarm, bootstrap or gateway RPCs. Isolated tests may GC only a dedicated offline
131
+ fixture, never a shared daemon. The default local backend is not a public
132
+ distribution endpoint; optional `gateway` is host-configured. A network-offline
133
+ daemon can serve existing blocks; a missing block or unreachable RPC fails the
134
+ dependent operation. There is no local or Gateway fallback, including Gateway
135
+ hints.
136
+
137
+ `pin(root)` verifies the complete DAG with fresh backing reads and requests a
138
+ recursive retention hint; `unpin(root)` releases an unreferenced known hint.
139
+ Neither `put` nor `prepare` pins. Local pins are durable SQLite metadata, not
140
+ no-ops; releasing one does not delete blocks or add automatic disk GC. Kubo
141
+ hints use `@silvermoon-work/task-engine/<coordinator-id>` names. Kubo's
142
+ `indirect through <CID>` pin status is validated and normalized to `indirect`
143
+ before retention coordination; malformed statuses still fail. Existing
144
+ differently named or unnamed recursive pins are left unchanged; an external
145
+ direct pin that cannot be upgraded without renaming causes an explicit
146
+ unfinished error. Names are **best-effort provenance labels**, not ownership,
147
+ authentication, independent leases or permanent availability. External
148
+ deletion/renaming between checks is not prevented. Reads still verify real
149
+ bytes; missing content is fetched only from the explicitly configured
150
+ backend/source or fails. Closing stores/scopes never unpins.
151
+
152
+ ### Participating Engines and recovery
153
+
154
+ All cooperating Engines must use the **same durable coordination directory** and
155
+ preserve it across restarts. It contains only identity, reference and operation
156
+ metadata, never blocks or CARs. Defaults are `<local-dataDir>/retention` or a
157
+ user-level directory keyed by the exact Kubo API URL. For endpoint aliases,
158
+ remote hosts or distinct configurations, explicitly inject the same directory on
159
+ storage that provides SQLite locking/durability; separate registries are not a
160
+ distributed ownership service. Different registry names are treated as external
161
+ and are never claimed or automatically removed by this registry.
162
+
163
+ Engine automatically registers its persistent Store identity and publishes
164
+ Task/Run bundle roots and optional output CIDs, including historical Runs.
165
+ Protection is arranged before publishing new content references. Durable
166
+ write-ahead intents bridge the RPC/database commit gap; after database commit,
167
+ confirmation publishes the root again before clearing the intent. Recovery uses
168
+ the persisted Store's actual full root set. Hosts sharing one business identity
169
+ supply `retentionOwner` and `retentionRoots` and recover that owner once, while
170
+ its executions are stopped.
171
+
172
+ For custom hosts the primitives are `registerOwner`, `retain`,
173
+ `confirmRetained`, `recoverOwner`, and `reconcile`. `retain` publishes an intent
174
+ and confirms the pin request; call `confirmRetained` only after committing the
175
+ business reference. Use `reconcile(owner, () => readPersistedRoots())` so the
176
+ snapshot is read **inside** the participant mutex, not before waiting for it.
177
+ `recoverOwner` discards abandoned intents/import sessions only when that owner's
178
+ old executions are known to have stopped. Never recover an active shared owner.
179
+ Its optional `isIdle` predicate and root callback are evaluated inside the
180
+ mutex; Engine uses this for collection without racing a newly preparing request.
181
+
182
+ Mark-and-sweep first verifies every participating owner's retained graph and
183
+ pending publication/import references. Only then can it remove this
184
+ coordinator's currently named, unreferenced hints. Other visible names remain.
185
+ Missing/corrupt references, inaccessible coordination, cancellation or RPC
186
+ failure prevent a successful cleanup result. An interrupted or uncertain
187
+ pin/unpin remains journaled for retry; no successful pin/unpin is inferred from
188
+ a timeout. Unpin counts are hints removed, not disk bytes reclaimed.
189
+
190
+ Staging also persists an absent/indirect/already-own before-state before the
191
+ atomic raw put. If naming fails after that put created an unnamed pin, recovery
192
+ retries its name assignment, checks the visible result, then permits ordinary
193
+ named cleanup. Another failure remains an explicit unfinished responsibility,
194
+ not a discarded journal row. A genuinely preexisting external unnamed pin has no
195
+ such claim and is never renamed or removed. This is best-effort recovery of a
196
+ recorded system operation, not protection from outsiders racing the request.
197
+
198
+ For block-by-block imports, `stageBlock(session, cid, bytes)` atomically pins a
199
+ raw alias of each Kubo block before later DAG publication; the alias uses the
200
+ same multihash/bytes and does not create an application block copy. This also
201
+ handles CAR parents arriving before their children.
202
+ `finishImport(session, root, owner?)` verifies and recursively pins the finished
203
+ DAG before releasing the session's staging responsibility. A later coordinated
204
+ sweep removes unreferenced staging hints. Interrupted imports retain durable
205
+ retry/recovery metadata and never claim a complete root.
206
+
207
+ ## Public configuration
208
+
209
+ CLI hosts use `@ipab/ipfs-store/node`. The default file is
210
+ `%LOCALAPPDATA%\TaskContent\config.json` on Windows and
211
+ `~/.config/task-content/config.json` elsewhere; `TASK_CONTENT_CONFIG` selects
212
+ another file. The canonical configuration is a strict union:
213
+
214
+ - `{ "backend": "local", "dataDir": "...", "gateway": "https://..." }`
215
+ - `{ "backend": "kubo", "apiUrl": "http://127.0.0.1:5001" }`
216
+
217
+ Both branches accept `limits` and optional `coordinationDir`; only Kubo accepts
218
+ `timeoutMs`. Local `gateway` can also be an ordered URL list. Unknown fields,
219
+ cross-branch fields, malformed URLs and non-positive/non-integral limits fail.
220
+ Local paths are relative to the config file. Legacy local JSON without
221
+ `backend`, and legacy `{ dataDir, gateway?, limits? }` constructors, still work.
222
+ Default dataDir is `~/.silvermoon.work/content`, independent of Engine
223
+ databases. No gateway is guessed when unset; local misses fail.
224
+
225
+ Builder's `--content-gateway` / `--content-data-dir` and Engine server's
226
+ `--ipfs-gateway` / `--content-data-dir` override the common defaults separately.
227
+ Existing `server.dataDir` remains the Engine database path, not content storage.
228
+ Engine startup rejects using that same directory as content storage. Local CLI
229
+ overrides conflict explicitly with a selected Kubo configuration; they never
230
+ silently change its backend. Selecting a different backend in an existing file
231
+ requires replacing that file's branch, not merging its fields. Migrate old
232
+ private cache settings explicitly; no blocks/databases are moved. Libraries
233
+ accept injected stores and do not read user configuration themselves.
234
+ `createConfiguredContent()` is an explicit host helper returning an `IpfsStore`
235
+ with its resolved `configuration`; it is never invoked by library imports.
236
+
237
+ The backing storage verifies disk reads and writes a uniquely named complete
238
+ file before atomic hard-link publication. Concurrent processes cannot publish
239
+ partial blocks; an interrupted pending file is not a cache hit. Existing
240
+ published bytes are validated, never overwritten with unverified data. Close
241
+ aborts owned work but never removes blocks or closes an injected source. Stores
242
+ own and close only the gateways they create. Disk retention has no automatic GC.
243
+ In-flight acquisition is deduplicated within each instance, not across
244
+ processes. Canceling one reader detaches only that reader; shared acquisition
245
+ belongs to the client's lifetime and remains available to other readers. CID
246
+ storage accounting and logical file/path/execution budgets remain independent.
@@ -0,0 +1,21 @@
1
+ import { type ContentLimits } from "./dag.js";
2
+ interface CommonConfiguration {
3
+ limits?: Partial<ContentLimits>;
4
+ coordinationDir?: string;
5
+ }
6
+ export type StoreConfiguration = (CommonConfiguration & {
7
+ backend: "local";
8
+ dataDir: string;
9
+ gateway?: string | readonly string[];
10
+ }) | (CommonConfiguration & {
11
+ backend: "kubo";
12
+ apiUrl: string;
13
+ timeoutMs?: number;
14
+ });
15
+ export type LegacyStoreOptions = Omit<Extract<StoreConfiguration, {
16
+ backend: "local";
17
+ }>, "backend">;
18
+ export type IpfsStoreOptions = StoreConfiguration | LegacyStoreOptions;
19
+ export declare function validateConfiguration(value: unknown): StoreConfiguration;
20
+ export {};
21
+ //# sourceMappingURL=configuration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.d.ts","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,UAAU,CAAC;AAEpE,UAAU,mBAAmB;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IAChC,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AACD,MAAM,MAAM,kBAAkB,GAC1B,CAAC,mBAAmB,GAAG;IACrB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;CACtC,CAAC,GACF,CAAC,mBAAmB,GAAG;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC,CAAC;AACP,MAAM,MAAM,kBAAkB,GAAG,IAAI,CACnC,OAAO,CAAC,kBAAkB,EAAE;IAAE,OAAO,EAAE,OAAO,CAAA;CAAE,CAAC,EACjD,SAAS,CACV,CAAC;AACF,MAAM,MAAM,gBAAgB,GAAG,kBAAkB,GAAG,kBAAkB,CAAC;AAEvE,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CAqExE"}
@@ -0,0 +1,62 @@
1
+ import { defaultContentLimits } from "./dag.js";
2
+ export function validateConfiguration(value) {
3
+ if (!value || typeof value !== "object" || Array.isArray(value))
4
+ throw new Error("Invalid IPFS store configuration.");
5
+ const record = value;
6
+ const backend = Object.hasOwn(record, "backend") ? record.backend : "local";
7
+ const fields = backend === "local"
8
+ ? ["backend", "dataDir", "gateway", "limits", "coordinationDir"]
9
+ : backend === "kubo"
10
+ ? ["backend", "apiUrl", "timeoutMs", "limits", "coordinationDir"]
11
+ : [];
12
+ if (!fields.length ||
13
+ Object.keys(record).some((key) => !fields.includes(key)))
14
+ throw new Error("Unknown or conflicting IPFS backend configuration field.");
15
+ for (const key of ["dataDir", "coordinationDir"])
16
+ if ((key === "dataDir" && backend === "local") ||
17
+ Object.hasOwn(record, key))
18
+ if (typeof record[key] !== "string" || !record[key].trim())
19
+ throw new Error(`IPFS store ${key} must be a nonempty directory path.`);
20
+ const url = (value) => {
21
+ if (typeof value !== "string" || !value.trim())
22
+ throw new Error("Invalid IPFS URL.");
23
+ let parsed;
24
+ try {
25
+ parsed = new URL(value);
26
+ }
27
+ catch {
28
+ throw new Error("Invalid IPFS URL.");
29
+ }
30
+ if (!["http:", "https:"].includes(parsed.protocol) || parsed.hash)
31
+ throw new Error("IPFS URL must use HTTP(S) without a fragment.");
32
+ };
33
+ if (backend === "kubo")
34
+ url(record.apiUrl);
35
+ if (record.gateway !== undefined) {
36
+ const gateways = Array.isArray(record.gateway)
37
+ ? record.gateway
38
+ : [record.gateway];
39
+ if (!gateways.length)
40
+ throw new Error("Content gateway list must not be empty.");
41
+ for (const gateway of gateways)
42
+ url(gateway);
43
+ }
44
+ if (record.timeoutMs !== undefined)
45
+ if (!Number.isSafeInteger(record.timeoutMs) ||
46
+ Number(record.timeoutMs) <= 0 ||
47
+ Number(record.timeoutMs) > 2_147_483_647)
48
+ throw new Error("IPFS timeoutMs must be an integer between 1 and 2147483647.");
49
+ if (record.limits !== undefined) {
50
+ if (!record.limits ||
51
+ typeof record.limits !== "object" ||
52
+ Array.isArray(record.limits))
53
+ throw new Error("Invalid IPFS content capacity.");
54
+ for (const [key, limit] of Object.entries(record.limits))
55
+ if (!Object.hasOwn(defaultContentLimits, key) ||
56
+ !Number.isSafeInteger(limit) ||
57
+ limit <= 0)
58
+ throw new Error("Invalid IPFS content capacity.");
59
+ }
60
+ return { ...record, backend };
61
+ }
62
+ //# sourceMappingURL=configuration.js.map
@@ -0,0 +1 @@
1
+ {"version":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CAAC;YACvC,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;YAC7B,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,GAAG,aAAa;YAExC,MAAM,IAAI,KAAK,CACb,6DAA6D,CAC9D,CAAC;IACN,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CAAC;QAChC,IACE,CAAC,MAAM,CAAC,MAAM;YACd,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;YACjC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;YAE5B,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACpD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;YACtD,IACE,CAAC,MAAM,CAAC,MAAM,CAAC,oBAAoB,EAAE,GAAG,CAAC;gBACzC,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC;gBAC5B,KAAK,IAAI,CAAC;gBAEV,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IACxD,CAAC;IACD,OAAO,EAAE,GAAG,MAAM,EAAE,OAAO,EAAwB,CAAC;AACtD,CAAC"}
package/dist/dag.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { CID } from "multiformats/cid";
2
+ import type { IpfsClient } from "./index.js";
3
+ export interface ContentLimits {
4
+ bytes: number;
5
+ blocks: number;
6
+ blockBytes: number;
7
+ depth: number;
8
+ }
9
+ export declare const defaultContentLimits: Readonly<ContentLimits>;
10
+ /** Enumerate genuine IPLD links, never CID-looking strings or application object shapes. */
11
+ export declare function contentLinks(cid: CID, bytes: Uint8Array, limits?: {
12
+ depth?: number;
13
+ nodes?: number;
14
+ }): readonly CID[];
15
+ export declare function verifyBlock(cid: CID, bytes: Uint8Array): Promise<void>;
16
+ export declare function acquireBlock(client: IpfsClient, cid: CID, options?: {
17
+ signal?: AbortSignal;
18
+ blockBytes?: number;
19
+ timeoutMs?: number;
20
+ }): Promise<Uint8Array>;
21
+ /** One owner per scope; immutable bytes, unique-CID storage accounting, no implicit source. */
22
+ export declare class ContentBlocks implements IpfsClient {
23
+ private readonly source?;
24
+ readonly blocks: Map<string, Uint8Array<ArrayBufferLike>>;
25
+ private readonly pending;
26
+ private readonly lifetime;
27
+ readonly limits: ContentLimits;
28
+ retainedBytes: number;
29
+ constructor(source?: IpfsClient | undefined, limits?: Partial<ContentLimits>);
30
+ readonly block: {
31
+ get: (value: string, options?: {
32
+ signal?: AbortSignal;
33
+ }) => Promise<Uint8Array>;
34
+ };
35
+ readBlock(value: string, options?: {
36
+ signal?: AbortSignal;
37
+ }, source?: IpfsClient | undefined): Promise<Uint8Array>;
38
+ close(): Promise<void>;
39
+ put(cid: CID, bytes: Uint8Array, options?: {
40
+ signal?: AbortSignal;
41
+ }): Promise<CID>;
42
+ get(cid: CID, options?: {
43
+ signal?: AbortSignal;
44
+ }): AsyncGenerator<Uint8Array<ArrayBufferLike>, void, unknown>;
45
+ prepare(root: CID | string, options?: {
46
+ signal?: AbortSignal;
47
+ }): Promise<void>;
48
+ }
49
+ //# sourceMappingURL=dag.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dag.d.ts","sourceRoot":"","sources":["../src/dag.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAEvC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAG7C,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;CACf;AACD,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,aAAa,CAKvD,CAAC;AAEH,4FAA4F;AAC5F,wBAAgB,YAAY,CAC1B,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,UAAU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EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,GAAG,CAAC;IA0BR,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO;IAGrD,OAAO,CACX,IAAI,EAAE,GAAG,GAAG,MAAM,EAClB,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,GACrC,OAAO,CAAC,IAAI,CAAC;CAsBjB"}
package/dist/dag.js ADDED
@@ -0,0 +1,216 @@
1
+ import * as dagPb from "@ipld/dag-pb";
2
+ import * as dagCbor from "@ipld/dag-cbor";
3
+ import { asNativeCID, encodeDagCbor, } from "@silvermoon-work/ipfs-payload/dag-cbor";
4
+ import { CID } from "multiformats/cid";
5
+ import { sha256 } from "multiformats/hashes/sha2";
6
+ import { abortError, ContentError } from "./errors.js";
7
+ export const defaultContentLimits = Object.freeze({
8
+ bytes: 256 * 1024 * 1024,
9
+ blocks: 16_384,
10
+ blockBytes: 2 * 1024 * 1024,
11
+ depth: 64,
12
+ });
13
+ /** Enumerate genuine IPLD links, never CID-looking strings or application object shapes. */
14
+ export function contentLinks(cid, bytes, limits = {}) {
15
+ for (const limit of Object.values(limits))
16
+ if (!Number.isSafeInteger(limit) || limit < 0)
17
+ throw new ContentError("capacity_exceeded", "Invalid structured content limit.");
18
+ if (cid.code === 0x55)
19
+ return [];
20
+ if (cid.code === dagPb.code)
21
+ return dagPb.decode(bytes).Links.map((link) => link.Hash);
22
+ if (cid.code !== dagCbor.code)
23
+ throw new ContentError("unsupported_content", "Unsupported content DAG codec.");
24
+ const links = [];
25
+ let nodes = 0;
26
+ const value = dagCbor.decode(bytes);
27
+ const visit = (value, depth) => {
28
+ if (++nodes > (limits.nodes ?? 100_000) || depth > (limits.depth ?? 64))
29
+ throw new ContentError("capacity_exceeded", "Structured content capacity exceeded.");
30
+ const link = asNativeCID(value);
31
+ if (link)
32
+ links.push(link);
33
+ else if (Array.isArray(value))
34
+ for (const item of value)
35
+ visit(item, depth + 1);
36
+ else if (value &&
37
+ typeof value === "object" &&
38
+ !(value instanceof Uint8Array))
39
+ for (const item of Object.values(value))
40
+ visit(item, depth + 1);
41
+ };
42
+ visit(value, 0);
43
+ const canonical = encodeDagCbor(value);
44
+ if (canonical.length !== bytes.length ||
45
+ canonical.some((byte, i) => byte !== bytes[i]))
46
+ throw new ContentError("unsupported_content", "Non-canonical DAG-CBOR content.");
47
+ return links;
48
+ }
49
+ export async function verifyBlock(cid, bytes) {
50
+ if (cid.multihash.code !== sha256.code)
51
+ throw new Error("Unsupported content hash.");
52
+ const hash = await sha256.digest(bytes);
53
+ if (!Buffer.from(hash.digest).equals(Buffer.from(cid.multihash.digest)))
54
+ throw new Error(`Content hash verification failed: ${cid.toString()}`);
55
+ }
56
+ export async function acquireBlock(client, cid, options = {}) {
57
+ const timeoutMs = options.timeoutMs ?? 30_000;
58
+ if (!Number.isInteger(timeoutMs) ||
59
+ timeoutMs < 0 ||
60
+ timeoutMs > 4_294_967_295)
61
+ throw new RangeError("Invalid acquisition timeout.");
62
+ const timeout = new AbortController();
63
+ const signal = AbortSignal.any([
64
+ timeout.signal,
65
+ ...(options.signal ? [options.signal] : []),
66
+ ]);
67
+ signal.throwIfAborted();
68
+ // Unlike AbortSignal.timeout(), this deadline must keep an otherwise idle
69
+ // process alive while an injected source has no active I/O handles.
70
+ const timer = setTimeout(() => {
71
+ timeout.abort(new DOMException("Content acquisition timed out.", "TimeoutError"));
72
+ }, timeoutMs);
73
+ let abort = () => { };
74
+ try {
75
+ const bytes = await Promise.race([
76
+ Promise.resolve().then(() => {
77
+ signal.throwIfAborted();
78
+ return client.block.get(cid.toString(), { signal });
79
+ }),
80
+ new Promise((_, reject) => {
81
+ abort = () => {
82
+ reject(abortError(signal));
83
+ };
84
+ signal.addEventListener("abort", abort, { once: true });
85
+ if (signal.aborted)
86
+ abort();
87
+ }),
88
+ ]);
89
+ signal.throwIfAborted();
90
+ if (!(bytes instanceof Uint8Array))
91
+ throw new Error("Content source must return bytes.");
92
+ if (bytes.byteLength > (options.blockBytes ?? 2 * 1024 * 1024))
93
+ throw new ContentError("capacity_exceeded", "Content block capacity exceeded.");
94
+ const snapshot = Uint8Array.from(bytes);
95
+ await verifyBlock(cid, snapshot);
96
+ signal.throwIfAborted();
97
+ return snapshot;
98
+ }
99
+ finally {
100
+ clearTimeout(timer);
101
+ signal.removeEventListener("abort", abort);
102
+ }
103
+ }
104
+ /** One owner per scope; immutable bytes, unique-CID storage accounting, no implicit source. */
105
+ export class ContentBlocks {
106
+ source;
107
+ blocks = new Map();
108
+ pending = new Map();
109
+ lifetime = new AbortController();
110
+ limits;
111
+ retainedBytes = 0;
112
+ constructor(source, limits = {}) {
113
+ this.source = source;
114
+ this.limits = { ...defaultContentLimits, ...limits };
115
+ for (const limit of Object.values(this.limits))
116
+ if (!Number.isSafeInteger(limit) || limit <= 0)
117
+ throw new Error("Invalid content capacity.");
118
+ }
119
+ block = {
120
+ get: async (value, options = {}) => {
121
+ return this.readBlock(value, options);
122
+ },
123
+ };
124
+ async readBlock(value, options = {}, source = this.source) {
125
+ options.signal?.throwIfAborted();
126
+ this.lifetime.signal.throwIfAborted();
127
+ const cid = CID.parse(value), key = cid.toV1().toString();
128
+ let bytes = this.blocks.get(key);
129
+ if (!bytes) {
130
+ let operation = this.pending.get(key);
131
+ if (!operation) {
132
+ operation = (async () => {
133
+ if (!source)
134
+ throw new ContentError("missing_block", `Missing local content block: ${cid.toString()}`);
135
+ const fetched = await acquireBlock(source, cid, {
136
+ signal: this.lifetime.signal,
137
+ blockBytes: this.limits.blockBytes,
138
+ });
139
+ await this.put(cid, fetched, { signal: this.lifetime.signal });
140
+ return this.blocks.get(key);
141
+ })();
142
+ this.pending.set(key, operation);
143
+ void operation.finally(() => this.pending.delete(key)).catch(() => { });
144
+ }
145
+ let abort = () => { };
146
+ try {
147
+ bytes = await Promise.race([
148
+ operation,
149
+ new Promise((_, reject) => {
150
+ abort = () => {
151
+ if (options.signal)
152
+ reject(abortError(options.signal));
153
+ };
154
+ options.signal?.addEventListener("abort", abort, { once: true });
155
+ if (options.signal?.aborted)
156
+ abort();
157
+ }),
158
+ ]);
159
+ }
160
+ finally {
161
+ options.signal?.removeEventListener("abort", abort);
162
+ }
163
+ }
164
+ options.signal?.throwIfAborted();
165
+ return Uint8Array.from(bytes);
166
+ }
167
+ async close() {
168
+ this.lifetime.abort(new Error("Content blocks are closed."));
169
+ await Promise.allSettled([...this.pending.values()]);
170
+ }
171
+ async put(cid, bytes, options = {}) {
172
+ options.signal?.throwIfAborted();
173
+ this.lifetime.signal.throwIfAborted();
174
+ if (bytes.byteLength > this.limits.blockBytes)
175
+ throw new ContentError("capacity_exceeded", "Content block capacity exceeded.");
176
+ const snapshot = Uint8Array.from(bytes);
177
+ await verifyBlock(cid, snapshot);
178
+ options.signal?.throwIfAborted();
179
+ this.lifetime.signal.throwIfAborted();
180
+ const key = cid.toV1().toString();
181
+ if (this.blocks.has(key))
182
+ return cid;
183
+ if (this.blocks.size >= this.limits.blocks ||
184
+ this.retainedBytes + bytes.byteLength > this.limits.bytes)
185
+ throw new ContentError("capacity_exceeded", "Content retention capacity exceeded.");
186
+ this.blocks.set(key, snapshot);
187
+ this.retainedBytes += bytes.byteLength;
188
+ return cid;
189
+ }
190
+ async *get(cid, options = {}) {
191
+ yield await this.block.get(cid.toString(), options);
192
+ }
193
+ async prepare(root, options = {}) {
194
+ const heights = new Map();
195
+ const walk = async (cid, depth) => {
196
+ options.signal?.throwIfAborted();
197
+ if (depth > this.limits.depth)
198
+ throw new Error("Content DAG depth capacity exceeded.");
199
+ const key = cid.toV1().toString();
200
+ const known = heights.get(key);
201
+ if (known !== undefined) {
202
+ if (depth + known > this.limits.depth)
203
+ throw new Error("Content DAG depth capacity exceeded.");
204
+ return known;
205
+ }
206
+ const bytes = await this.block.get(cid.toString(), options);
207
+ let height = 0;
208
+ for (const link of contentLinks(cid, bytes))
209
+ height = Math.max(height, 1 + (await walk(link, depth + 1)));
210
+ heights.set(key, height);
211
+ return height;
212
+ };
213
+ await walk(typeof root === "string" ? CID.parse(root) : root, 0);
214
+ }
215
+ }
216
+ //# sourceMappingURL=dag.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dag.js","sourceRoot":"","sources":["../src/dag.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EACL,WAAW,EACX,aAAa,GACd,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAQvD,MAAM,CAAC,MAAM,oBAAoB,GAA4B,MAAM,CAAC,MAAM,CAAC;IACzE,KAAK,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI;IACxB,MAAM,EAAE,MAAM;IACd,UAAU,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI;IAC3B,KAAK,EAAE,EAAE;CACV,CAAC,CAAC;AAEH,4FAA4F;AAC5F,MAAM,UAAU,YAAY,CAC1B,GAAQ,EACR,KAAiB,EACjB,SAA6C,EAAE;IAE/C,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC;QACvC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;YAC3C,MAAM,IAAI,YAAY,CACpB,mBAAmB,EACnB,mCAAmC,CACpC,CAAC;IACN,IAAI,GAAG,CAAC,IAAI,KAAK,IAAI;QAAE,OAAO,EAAE,CAAC;IACjC,IAAI,GAAG,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI;QACzB,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,CA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