@ipab/ipfs-store 0.0.0 → 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,158 @@
1
1
  # @ipab/ipfs-store
2
2
 
3
- Bootstrap placeholder only. Real releases start at 0.1.0+.
3
+ Verified local IPFS/UnixFS storage with optional read-only upstream HTTP
4
+ gateways. The next npm candidate is `0.1.0-rc.1`; `0.1.0-rc.0` is published.
5
+ Source was migrated from `silvermoon-work/task-engine`; the original MIT license
6
+ and CID/protocol contracts are preserved. Kubo RPC storage is no longer
7
+ supported.
8
+
9
+ Run `pnpm check` from the repository root. Source and tests use strict
10
+ TypeScript, type-aware lint and the shared Vitest configuration.
11
+
12
+ ## Local Store and upstream gateways
13
+
14
+ ```ts
15
+ import { IpfsStore } from "@ipab/ipfs-store";
16
+
17
+ const store = new IpfsStore({
18
+ dataDir: contentDirectory,
19
+ gateway: "http://lan-storage.example:8080", // optional; an HTTP Gateway, not RPC
20
+ limits: { bytes: 256 * 1024 * 1024, blocks: 16_384, depth: 64 },
21
+ });
22
+ ```
23
+
24
+ All writes, persistent pins, usage queries and garbage collection belong to the
25
+ local Store. A gateway only supplies missing blocks, verified before atomic
26
+ local publication. It may be a shared LAN Kubo Gateway or another compatible
27
+ HTTP Gateway. No block is uploaded, no upstream pin is changed and no daemon
28
+ management/GC RPC is issued. No gateway is guessed when unset; local misses
29
+ fail. Successfully pinned complete DAGs remain available without the gateway.
30
+ Unpinned cache can be collected and then needs an available source to reacquire.
31
+
32
+ `read(cidOrCidPath, { signal? })` returns a discriminated `UnixfsNode`: files
33
+ (`type: "file" | "raw"`) expose `content()` as an async byte stream; directories
34
+ expose `entries()` as an async iterator. It does not materialize the whole file
35
+ or apply application portable-path rules. The node profile is SHA-256 raw/DAG-PB
36
+ regular files and UnixFS directories. Corrupt local blocks fail, never silently
37
+ fetching replacements.
38
+
39
+ `prepare(cid, { signal? })` verifies the complete linked DAG with unique-block,
40
+ byte and depth limits. Full DAG preparation supports raw, DAG-PB and canonical
41
+ DAG-CBOR and follows genuine IPLD links, not CID-looking strings or objects.
42
+ Unknown codecs, unsupported hashes, missing/corrupt blocks and exceeded budgets
43
+ fail. Structured blocks also have a 64-level/100,000-node inspection limit.
44
+ Shared subgraphs count once for bytes/blocks, but all paths satisfy the depth
45
+ limit. `block.get` and verified `put` support offline block transfer; low-level
46
+ verified SHA-256 blocks are codec-neutral. CAR framing, manifests, path policy
47
+ and DAG grafting remain outside Store.
48
+
49
+ `ContentBlocks` in `./dag` is the bounded in-memory transfer primitive, not
50
+ another application-level acquisition API. `contentLinks(cid, bytes)` is its
51
+ shared codec-aware extractor; callers verify integrity separately. It reuses the
52
+ identity-safe codec from `ipfs-payload/dag-cbor` without TypeBox/AJV runtime.
53
+ Pin/retain/import/reconciliation always traverse fresh backing reads.
54
+
55
+ `readContent(cid)` and `resolveContent(cid, path)` implement the type-only
56
+ `ReadonlyIpfsAccess` contract. `IpfsNode` is the shared DU: `kind: "file"` with
57
+ a `ReadableStream`, or `kind: "directory"` with an async entry stream. Entries
58
+ carry target CIDs and verified kinds. File cancellation and enumeration retain
59
+ host budgets/signals. Paths are directory-relative slash-separated segments;
60
+ empty path validates and returns the resource. Structured archives are not a
61
+ third file variant. `putContent(byteStream)` creates verified local UnixFS
62
+ content but does not establish persistent retention by itself.
63
+
64
+ `scope(limits?)` borrows backing storage with independent, no-larger reader
65
+ budgets/lifetime; closing it never closes its parent.
66
+ `IpfsStore.fromClient(port, limits?, dataDir?)` adapts a caller-owned block
67
+ source, never writing to or closing that source. Without dataDir it uses
68
+ memory-only `ContentBlocks`. Adapters expose `supportsRetention: false` and
69
+ reject coordinated retention, usage and GC. `withLocalSource(port)` creates a
70
+ coordinated local read-through Store with a borrowed source.
71
+
72
+ ## Pins, ownership and imports
73
+
74
+ `pin(root)` verifies the complete DAG and persists a recursive local pin.
75
+ `unpin(root)` releases an unreferenced known pin without deleting blocks.
76
+ Neither `put`, `prepare` nor closing a Store pins/unpins content. `limits.bytes`
77
+ and `retainedBytes` measure in-process retention, not disk quotas.
78
+
79
+ All cooperating hosts sharing a dataDir must preserve the same durable
80
+ coordinationDir (default `<dataDir>/retention`) on SQLite-compatible storage. It
81
+ contains reference/operation metadata, never blocks or CARs. Distinct
82
+ registries/external writers are not a distributed ownership service.
83
+
84
+ `registerOwner`, `retain`, `confirmRetained`, `recoverOwner` and `reconcile`
85
+ coordinate persistent references. `retain` publishes durable intents before
86
+ acquisition/pinning; call `confirmRetained` after committing business
87
+ references. Use `reconcile(owner, () => readPersistedRoots())` to evaluate the
88
+ snapshot inside the participant mutex. Recovery discards abandoned
89
+ intents/imports only when the owner's old executions are stopped; its optional
90
+ `isIdle` predicate and root callback run inside the mutex. Never recover active
91
+ shared owners. Reconciliation verifies all participating roots before releasing
92
+ unreferenced pins. Failures preserve retry metadata; removed-pin counts are not
93
+ disk bytes.
94
+
95
+ `stageBlock(session, cid, bytes)` records and publishes individual local blocks,
96
+ including CAR parents before children. `finishImport(session, root, owner?)`
97
+ verifies and recursively pins the complete DAG before dropping staging
98
+ responsibility. `discardImport` drops that session's responsibility. Interrupted
99
+ imports retain retry metadata and never claim a complete root.
100
+
101
+ ## Usage and explicit GC
102
+
103
+ `await store.usage({ signal? })` returns `{ cachedBytes, pinnedBytes }`.
104
+ `cachedBytes` sums canonical CID block file lengths, excluding coordination
105
+ metadata, temporary/unknown files and filesystem allocation overhead.
106
+ `pinnedBytes` is every durable recursive pin's verified DAG block union,
107
+ including indirect descendants and shared subgraphs, deduplicated by CIDv1.
108
+
109
+ `await store.gc({ signal? })` returns `{ removedBlocks, reclaimedBytes }`. It
110
+ collects unprotected blocks across the entire local Store without unpinning. The
111
+ participant mutex protects pin/owner changes and staging. Owner roots, pending
112
+ retention roots and active staged blocks survive. Incomplete import parents are
113
+ protected individually. Unknown files and temporary publications are untouched.
114
+
115
+ Every protected DAG is verified with fresh local-only reads before deletion,
116
+ using per-root content limits. Missing/corrupt content and capacity failures
117
+ abort marking before any deletion; queries/GC never fetch missing blocks or
118
+ trust warmed reader caches. Cancellation/storage failures throw; an interrupted
119
+ sweep may already have deleted blocks and can be retried. Unpinned reads/puts do
120
+ not establish a GC hold. Concurrent uncoordinated writes do not provide
121
+ transactionally exact usage snapshots; publications after initial inventory are
122
+ outside the sweep. No automatic GC, quotas, direct-pin mode or MFS.
123
+
124
+ ## Public configuration and migration
125
+
126
+ `@ipab/ipfs-store/node` reads `%LOCALAPPDATA%\TaskContent\config.json` on
127
+ Windows or `~/.config/task-content/config.json` elsewhere. `TASK_CONTENT_CONFIG`
128
+ selects another file:
129
+
130
+ ```json
131
+ {
132
+ "backend": "local",
133
+ "dataDir": "./content",
134
+ "gateway": "http://lan-storage.example:8080"
135
+ }
136
+ ```
137
+
138
+ Optional `limits` and `coordinationDir` are supported; gateway may be an ordered
139
+ URL list. Unknown fields, malformed URLs and invalid limits fail. Paths resolve
140
+ relative to the file. Legacy local configurations without `backend` still work.
141
+ Default dataDir is `~/.silvermoon.work/content`. Overrides cannot hide malformed
142
+ lower layers. `createConfiguredContent()` is an explicit host helper; library
143
+ imports never read configuration or start clients.
144
+
145
+ `backend:kubo`, `apiUrl` and Store `timeoutMs` are rejected. Replace old RPC
146
+ configuration explicitly with a local dataDir and HTTP gateway, not port 5001
147
+ RPC. Old Kubo blocks/pins/owner metadata are not moved, released or treated as
148
+ local retention. Existing CLI pin/history records keep their old configuration
149
+ and unsupported cleanup fails explicitly; independently manage old daemon pins
150
+ and create new local pins before relying on offline availability.
151
+
152
+ Local files are verified on read and published by atomic hard-link after
153
+ writing/syncing a unique complete temporary file. Existing publications are
154
+ validated, not overwritten. Close aborts owned work but never deletes blocks or
155
+ closes borrowed sources. Stores close only gateways they create. Acquisition is
156
+ deduplicated per instance; canceling a reader detaches it without canceling
157
+ another reader's shared acquisition. Non-Error cancellation reasons are reported
158
+ as Errors preserving the original reason in `cause`.
@@ -0,0 +1,17 @@
1
+ import { type ContentLimits } from "./dag.js";
2
+ interface CommonConfiguration {
3
+ limits?: Partial<ContentLimits>;
4
+ coordinationDir?: string;
5
+ }
6
+ export interface StoreConfiguration extends CommonConfiguration {
7
+ backend: "local";
8
+ dataDir: string;
9
+ gateway?: string | readonly string[];
10
+ }
11
+ export type LegacyStoreOptions = Omit<Extract<StoreConfiguration, {
12
+ backend: "local";
13
+ }>, "backend">;
14
+ export type IpfsStoreOptions = StoreConfiguration | LegacyStoreOptions;
15
+ export declare function validateConfiguration(value: unknown): StoreConfiguration;
16
+ export {};
17
+ //# 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,WAAW,kBAAmB,SAAQ,mBAAmB;IAC7D,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;CACtC;AACD,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,CA6DxE"}
@@ -0,0 +1,55 @@
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
+ if (backend === "kubo")
8
+ throw new Error("Kubo Store RPC is no longer supported. Configure a local dataDir and an HTTP gateway; existing Kubo pins are not migrated or released.");
9
+ const fields = backend === "local"
10
+ ? ["backend", "dataDir", "gateway", "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 (record.gateway !== undefined) {
34
+ const gateways = Array.isArray(record.gateway)
35
+ ? record.gateway
36
+ : [record.gateway];
37
+ if (!gateways.length)
38
+ throw new Error("Content gateway list must not be empty.");
39
+ for (const gateway of gateways)
40
+ url(gateway);
41
+ }
42
+ if (record.limits !== undefined) {
43
+ if (!record.limits ||
44
+ typeof record.limits !== "object" ||
45
+ Array.isArray(record.limits))
46
+ throw new Error("Invalid IPFS content capacity.");
47
+ for (const [key, limit] of Object.entries(record.limits))
48
+ if (!Object.hasOwn(defaultContentLimits, key) ||
49
+ !Number.isSafeInteger(limit) ||
50
+ limit <= 0)
51
+ throw new Error("Invalid IPFS content capacity.");
52
+ }
53
+ return { ...record, backend };
54
+ }
55
+ //# sourceMappingURL=configuration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configuration.js","sourceRoot":"","sources":["../src/configuration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAsB,MAAM,UAAU,CAAC;AAiBpE,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAC7D,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;IAC5E,IAAI,OAAO,KAAK,MAAM;QACpB,MAA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AAC,IAAI,MAAM,CAAC,IAAI;YAC/D,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACrE,CAAC,CAAC;IACF,IAAI,MAAM,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QACjC,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC;YAC5C,CAAC,CAAC,MAAM,CAAC,OAAO;YAChB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,CAAC,MAAM;YAClB,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;QAC7D,KAAK,MAAM,OAAO,IAAI,QAAQ;YAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IAC/C,CAAC;IACD,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,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A;SAAE,KAChC,OAAO,CAAC,UAAU,CAAC;MAGtB;IACI,SAAS,CACb,KAAK,EAAE,MAAM,EACb,OAAO,GAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAO,EACtC,MAAM,yBAAc,GACnB,OAAO,CAAC,UAAU,CAAC;IA4ChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAItB,GAAG,CACP,GAAG,EAAE,GAAG,EACR,KAAK,EAAE,UAAU,EACjB,OAAO,GAAE;QAAE,MAAM,CAAC,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,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AAC,CAAC,CAAC;YAC/D,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YACzB,OAAO,MAAM,CAAC;QAChB,CAAC,CAAC;QACF,MAAM,IAAI,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACnE,CAAC;CACF"}
@@ -0,0 +1,6 @@
1
+ export declare class ContentError extends Error {
2
+ readonly code: "capacity_exceeded" | "reclamation_unknown" | "missing_block" | "retention_unfinished" | "read_only" | "unsupported_content";
3
+ constructor(code: "capacity_exceeded" | "reclamation_unknown" | "missing_block" | "retention_unfinished" | "read_only" | "unsupported_content", message: string, options?: ErrorOptions);
4
+ }
5
+ export declare function abortError(signal: AbortSignal): Error;
6
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IAEnC,QAAQ,CAAC,IAAI,EACT,mBAAmB,GACnB,qBAAqB,GACrB,eAAe,GACf,sBAAsB,GACtB,WAAW,GACX,qBAAqB;gBANhB,IAAI,EACT,mBAAmB,GACnB,qBAAqB,GACrB,eAAe,GACf,sBAAsB,GACtB,WAAW,GACX,qBAAqB,EACzB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,YAAY;CAKzB;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,KAAK,CAKrD"}
package/dist/errors.js ADDED
@@ -0,0 +1,15 @@
1
+ export class ContentError extends Error {
2
+ code;
3
+ constructor(code, message, options) {
4
+ super(message, options);
5
+ this.code = code;
6
+ this.name = "ContentError";
7
+ }
8
+ }
9
+ export function abortError(signal) {
10
+ const reason = signal.reason;
11
+ return reason instanceof Error
12
+ ? reason
13
+ : new Error("Content operation aborted.", { cause: reason });
14
+ }
15
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IAE1B;IADX,YACW,IAMgB,EACzB,OAAe,EACf,OAAsB;QAEtB,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAVf,SAAI,GAAJ,IAAI,CAMY;QAKzB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC7B,CAAC;CACF;AAED,MAAM,UAAU,UAAU,CAAC,MAAmB;IAC5C,MAAM,MAAM,GAAY,MAAM,CAAC,MAAM,CAAC;IACtC,OAAO,MAAM,YAAY,KAAK;QAC5B,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,IAAI,KAAK,CAAC,4BAA4B,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,CAAC;AACjE,CAAC"}
@@ -0,0 +1,57 @@
1
+ import { MemoryBlockstore } from "blockstore-core";
2
+ import { type UnixFSEntry } from "ipfs-unixfs-exporter";
3
+ import { CID } from "multiformats/cid";
4
+ export type { IpfsNode, IpfsEntry } from "@silvermoon-work/ipfs-access";
5
+ export { ContentError } from "./errors.js";
6
+ export { IpfsStore, type IpfsStoreOptions, type IpfsReadOptions, type UnixfsNode, type StoreConfiguration, type StoreUsage, type StoreGcResult, } from "./store.js";
7
+ /** Caller-owned read port. Production hosts use createIpfsGatewayClient. */
8
+ export interface IpfsClient {
9
+ block: {
10
+ get(cid: string, options?: {
11
+ signal?: AbortSignal;
12
+ }): Promise<Uint8Array>;
13
+ };
14
+ }
15
+ export interface GatewayClient extends IpfsClient {
16
+ /** Seal reads, abort acquisition, and await owned per-read Helia nodes. */
17
+ close(): Promise<void>;
18
+ }
19
+ export interface GatewayClientOptions {
20
+ allowPath?: boolean;
21
+ /** Total budget for all sources for one missing block. */
22
+ timeoutMs?: number;
23
+ attemptTimeoutMs?: number;
24
+ }
25
+ export interface GatewayAttempt {
26
+ source: string;
27
+ outcome: "timeout" | "read_or_verification_failed";
28
+ }
29
+ export declare class GatewayReadError extends Error {
30
+ readonly attempts: readonly GatewayAttempt[];
31
+ readonly budgetExhausted: boolean;
32
+ constructor(attempts: readonly GatewayAttempt[], budgetExhausted: boolean);
33
+ }
34
+ /** Ordered host-owned sources only; no discovery, public fallback or redirects. */
35
+ export declare function createIpfsGatewayClient(url: string | readonly string[], options?: GatewayClientOptions): GatewayClient;
36
+ /** Existing explicit hint policy is retained, never inferred from request data. */
37
+ export declare function withGatewayHints(primary: IpfsClient, hints: readonly string[], allowGateway?: (url: URL) => boolean): IpfsClient;
38
+ export interface ContentAccessOptions {
39
+ cacheBlocks?: boolean;
40
+ signal: AbortSignal;
41
+ retainedBlocks: Map<string, Uint8Array>;
42
+ retentionBudget: {
43
+ bytes: number;
44
+ limit: number;
45
+ };
46
+ maxBlockBytes: number;
47
+ maxDagBlocks: number;
48
+ depth?: number;
49
+ }
50
+ /** Reader-owned unique-block accounting; no task or logical-path policy. */
51
+ export declare function contentStore(client: IpfsClient, options: ContentAccessOptions): MemoryBlockstore & {
52
+ get: (cid: CID) => AsyncGenerator<Uint8Array<ArrayBuffer>, void, unknown>;
53
+ };
54
+ export declare function openContent(client: IpfsClient, path: string, options: ContentAccessOptions): Promise<UnixFSEntry>;
55
+ /** Verify and retain every linked block, not only file bytes read by the caller. */
56
+ export declare function prepareContent(client: IpfsClient, root: string, options: ContentAccessOptions): Promise<void>;
57
+ //# sourceMappingURL=index.d.ts.map