@unicitylabs/sphere-sdk 0.2.3 → 0.3.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.
- package/README.md +61 -20
- package/dist/core/index.cjs +5764 -3576
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +648 -256
- package/dist/core/index.d.ts +648 -256
- package/dist/core/index.js +5767 -3576
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +2118 -185
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +2118 -185
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/browser/ipfs.cjs +1823 -513
- package/dist/impl/browser/ipfs.cjs.map +1 -1
- package/dist/impl/browser/ipfs.js +1823 -513
- package/dist/impl/browser/ipfs.js.map +1 -1
- package/dist/impl/nodejs/index.cjs +2110 -183
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +86 -23
- package/dist/impl/nodejs/index.d.ts +86 -23
- package/dist/impl/nodejs/index.js +2110 -183
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +5782 -3603
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +719 -105
- package/dist/index.d.ts +719 -105
- package/dist/index.js +5780 -3603
- package/dist/index.js.map +1 -1
- package/package.json +28 -6
|
@@ -30,67 +30,73 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// impl/browser/ipfs.ts
|
|
31
31
|
var ipfs_exports = {};
|
|
32
32
|
__export(ipfs_exports, {
|
|
33
|
+
BrowserIpfsStatePersistence: () => BrowserIpfsStatePersistence,
|
|
33
34
|
IpfsStorageProvider: () => IpfsStorageProvider,
|
|
35
|
+
createBrowserIpfsStorageProvider: () => createBrowserIpfsStorageProvider,
|
|
34
36
|
createIpfsStorageProvider: () => createIpfsStorageProvider
|
|
35
37
|
});
|
|
36
38
|
module.exports = __toCommonJS(ipfs_exports);
|
|
37
39
|
|
|
38
|
-
//
|
|
39
|
-
var
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
/** Wallet existence flag */
|
|
55
|
-
WALLET_EXISTS: "wallet_exists",
|
|
56
|
-
/** Current active address index */
|
|
57
|
-
CURRENT_ADDRESS_INDEX: "current_address_index",
|
|
58
|
-
/** Nametag cache per address (separate from tracked addresses registry) */
|
|
59
|
-
ADDRESS_NAMETAGS: "address_nametags",
|
|
60
|
-
/** Active addresses registry (JSON: TrackedAddressesStorage) */
|
|
61
|
-
TRACKED_ADDRESSES: "tracked_addresses",
|
|
62
|
-
/** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
|
|
63
|
-
LAST_WALLET_EVENT_TS: "last_wallet_event_ts"
|
|
64
|
-
};
|
|
65
|
-
var STORAGE_KEYS_ADDRESS = {
|
|
66
|
-
/** Pending transfers for this address */
|
|
67
|
-
PENDING_TRANSFERS: "pending_transfers",
|
|
68
|
-
/** Transfer outbox for this address */
|
|
69
|
-
OUTBOX: "outbox",
|
|
70
|
-
/** Conversations for this address */
|
|
71
|
-
CONVERSATIONS: "conversations",
|
|
72
|
-
/** Messages for this address */
|
|
73
|
-
MESSAGES: "messages",
|
|
74
|
-
/** Transaction history for this address */
|
|
75
|
-
TRANSACTION_HISTORY: "transaction_history"
|
|
40
|
+
// impl/shared/ipfs/ipfs-error-types.ts
|
|
41
|
+
var IpfsError = class extends Error {
|
|
42
|
+
category;
|
|
43
|
+
gateway;
|
|
44
|
+
cause;
|
|
45
|
+
constructor(message, category, gateway, cause) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "IpfsError";
|
|
48
|
+
this.category = category;
|
|
49
|
+
this.gateway = gateway;
|
|
50
|
+
this.cause = cause;
|
|
51
|
+
}
|
|
52
|
+
/** Whether this error should trigger the circuit breaker */
|
|
53
|
+
get shouldTriggerCircuitBreaker() {
|
|
54
|
+
return this.category !== "NOT_FOUND" && this.category !== "SEQUENCE_DOWNGRADE";
|
|
55
|
+
}
|
|
76
56
|
};
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
57
|
+
function classifyFetchError(error) {
|
|
58
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
59
|
+
return "TIMEOUT";
|
|
60
|
+
}
|
|
61
|
+
if (error instanceof TypeError) {
|
|
62
|
+
return "NETWORK_ERROR";
|
|
63
|
+
}
|
|
64
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
65
|
+
return "TIMEOUT";
|
|
66
|
+
}
|
|
67
|
+
return "NETWORK_ERROR";
|
|
68
|
+
}
|
|
69
|
+
function classifyHttpStatus(status, responseBody) {
|
|
70
|
+
if (status === 404) {
|
|
71
|
+
return "NOT_FOUND";
|
|
72
|
+
}
|
|
73
|
+
if (status === 500 && responseBody) {
|
|
74
|
+
if (/routing:\s*not\s*found/i.test(responseBody)) {
|
|
75
|
+
return "NOT_FOUND";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (status >= 500) {
|
|
79
|
+
return "GATEWAY_ERROR";
|
|
80
|
+
}
|
|
81
|
+
if (status >= 400) {
|
|
82
|
+
return "GATEWAY_ERROR";
|
|
83
|
+
}
|
|
84
|
+
return "GATEWAY_ERROR";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// impl/shared/ipfs/ipfs-state-persistence.ts
|
|
88
|
+
var InMemoryIpfsStatePersistence = class {
|
|
89
|
+
states = /* @__PURE__ */ new Map();
|
|
90
|
+
async load(ipnsName) {
|
|
91
|
+
return this.states.get(ipnsName) ?? null;
|
|
92
|
+
}
|
|
93
|
+
async save(ipnsName, state) {
|
|
94
|
+
this.states.set(ipnsName, { ...state });
|
|
95
|
+
}
|
|
96
|
+
async clear(ipnsName) {
|
|
97
|
+
this.states.delete(ipnsName);
|
|
98
|
+
}
|
|
80
99
|
};
|
|
81
|
-
var DEFAULT_IPFS_GATEWAYS = [
|
|
82
|
-
"https://ipfs.unicity.network",
|
|
83
|
-
"https://dweb.link",
|
|
84
|
-
"https://ipfs.io"
|
|
85
|
-
];
|
|
86
|
-
var DEFAULT_IPFS_BOOTSTRAP_PEERS = [
|
|
87
|
-
"/dns4/unicity-ipfs2.dyndns.org/tcp/4001/p2p/12D3KooWLNi5NDPPHbrfJakAQqwBqymYTTwMQXQKEWuCrJNDdmfh",
|
|
88
|
-
"/dns4/unicity-ipfs3.dyndns.org/tcp/4001/p2p/12D3KooWQ4aujVE4ShLjdusNZBdffq3TbzrwT2DuWZY9H1Gxhwn6",
|
|
89
|
-
"/dns4/unicity-ipfs4.dyndns.org/tcp/4001/p2p/12D3KooWJ1ByPfUzUrpYvgxKU8NZrR8i6PU1tUgMEbQX9Hh2DEn1",
|
|
90
|
-
"/dns4/unicity-ipfs5.dyndns.org/tcp/4001/p2p/12D3KooWB1MdZZGHN5B8TvWXntbycfe7Cjcz7n6eZ9eykZadvmDv"
|
|
91
|
-
];
|
|
92
|
-
var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
93
|
-
var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
|
|
94
100
|
|
|
95
101
|
// node_modules/@noble/hashes/utils.js
|
|
96
102
|
function isBytes(a) {
|
|
@@ -528,581 +534,1885 @@ var sha256 = /* @__PURE__ */ createHasher(
|
|
|
528
534
|
/* @__PURE__ */ oidNist(1)
|
|
529
535
|
);
|
|
530
536
|
|
|
531
|
-
//
|
|
532
|
-
var
|
|
533
|
-
var
|
|
534
|
-
var
|
|
537
|
+
// core/crypto.ts
|
|
538
|
+
var bip39 = __toESM(require("bip39"), 1);
|
|
539
|
+
var import_crypto_js = __toESM(require("crypto-js"), 1);
|
|
540
|
+
var import_elliptic = __toESM(require("elliptic"), 1);
|
|
541
|
+
var ec = new import_elliptic.default.ec("secp256k1");
|
|
542
|
+
var CURVE_ORDER = BigInt(
|
|
543
|
+
"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
|
|
544
|
+
);
|
|
545
|
+
function hexToBytes(hex) {
|
|
546
|
+
const matches = hex.match(/../g);
|
|
547
|
+
if (!matches) {
|
|
548
|
+
return new Uint8Array(0);
|
|
549
|
+
}
|
|
550
|
+
return Uint8Array.from(matches.map((x) => parseInt(x, 16)));
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// impl/shared/ipfs/ipns-key-derivation.ts
|
|
554
|
+
var IPNS_HKDF_INFO = "ipfs-storage-ed25519-v1";
|
|
535
555
|
var libp2pCryptoModule = null;
|
|
536
556
|
var libp2pPeerIdModule = null;
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
[
|
|
541
|
-
heliaModule,
|
|
542
|
-
heliaJsonModule,
|
|
543
|
-
libp2pBootstrapModule,
|
|
544
|
-
libp2pCryptoModule,
|
|
545
|
-
libp2pPeerIdModule,
|
|
546
|
-
multiformatsCidModule
|
|
547
|
-
] = await Promise.all([
|
|
548
|
-
import("helia"),
|
|
549
|
-
import("@helia/json"),
|
|
550
|
-
import("@libp2p/bootstrap"),
|
|
557
|
+
async function loadLibp2pModules() {
|
|
558
|
+
if (!libp2pCryptoModule) {
|
|
559
|
+
[libp2pCryptoModule, libp2pPeerIdModule] = await Promise.all([
|
|
551
560
|
import("@libp2p/crypto/keys"),
|
|
552
|
-
import("@libp2p/peer-id")
|
|
553
|
-
import("multiformats/cid")
|
|
561
|
+
import("@libp2p/peer-id")
|
|
554
562
|
]);
|
|
555
563
|
}
|
|
556
564
|
return {
|
|
557
|
-
createHelia: heliaModule.createHelia,
|
|
558
|
-
json: heliaJsonModule.json,
|
|
559
|
-
bootstrap: libp2pBootstrapModule.bootstrap,
|
|
560
565
|
generateKeyPairFromSeed: libp2pCryptoModule.generateKeyPairFromSeed,
|
|
561
|
-
peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
|
|
562
|
-
CID: multiformatsCidModule.CID
|
|
566
|
+
peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
|
|
563
567
|
};
|
|
564
568
|
}
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
bootstrapPeers: config?.bootstrapPeers ?? [...DEFAULT_IPFS_BOOTSTRAP_PEERS],
|
|
592
|
-
enableIpns: config?.enableIpns ?? true,
|
|
593
|
-
ipnsTimeout: config?.ipnsTimeout ?? 3e4,
|
|
594
|
-
fetchTimeout: config?.fetchTimeout ?? 15e3,
|
|
595
|
-
debug: config?.debug ?? false
|
|
569
|
+
function deriveEd25519KeyMaterial(privateKeyHex, info = IPNS_HKDF_INFO) {
|
|
570
|
+
const walletSecret = hexToBytes(privateKeyHex);
|
|
571
|
+
const infoBytes = new TextEncoder().encode(info);
|
|
572
|
+
return hkdf(sha256, walletSecret, void 0, infoBytes, 32);
|
|
573
|
+
}
|
|
574
|
+
async function deriveIpnsIdentity(privateKeyHex) {
|
|
575
|
+
const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadLibp2pModules();
|
|
576
|
+
const derivedKey = deriveEd25519KeyMaterial(privateKeyHex);
|
|
577
|
+
const keyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
|
|
578
|
+
const peerId = peerIdFromPrivateKey(keyPair);
|
|
579
|
+
return {
|
|
580
|
+
keyPair,
|
|
581
|
+
ipnsName: peerId.toString()
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// impl/shared/ipfs/ipns-record-manager.ts
|
|
586
|
+
var DEFAULT_LIFETIME_MS = 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
587
|
+
var ipnsModule = null;
|
|
588
|
+
async function loadIpnsModule() {
|
|
589
|
+
if (!ipnsModule) {
|
|
590
|
+
const mod = await import("ipns");
|
|
591
|
+
ipnsModule = {
|
|
592
|
+
createIPNSRecord: mod.createIPNSRecord,
|
|
593
|
+
marshalIPNSRecord: mod.marshalIPNSRecord,
|
|
594
|
+
unmarshalIPNSRecord: mod.unmarshalIPNSRecord
|
|
596
595
|
};
|
|
597
596
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
597
|
+
return ipnsModule;
|
|
598
|
+
}
|
|
599
|
+
async function createSignedRecord(keyPair, cid, sequenceNumber, lifetimeMs = DEFAULT_LIFETIME_MS) {
|
|
600
|
+
const { createIPNSRecord, marshalIPNSRecord } = await loadIpnsModule();
|
|
601
|
+
const record = await createIPNSRecord(
|
|
602
|
+
keyPair,
|
|
603
|
+
`/ipfs/${cid}`,
|
|
604
|
+
sequenceNumber,
|
|
605
|
+
lifetimeMs
|
|
606
|
+
);
|
|
607
|
+
return marshalIPNSRecord(record);
|
|
608
|
+
}
|
|
609
|
+
async function parseRoutingApiResponse(responseText) {
|
|
610
|
+
const { unmarshalIPNSRecord } = await loadIpnsModule();
|
|
611
|
+
const lines = responseText.trim().split("\n");
|
|
612
|
+
for (const line of lines) {
|
|
613
|
+
if (!line.trim()) continue;
|
|
604
614
|
try {
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
615
|
+
const obj = JSON.parse(line);
|
|
616
|
+
if (obj.Extra) {
|
|
617
|
+
const recordData = base64ToUint8Array(obj.Extra);
|
|
618
|
+
const record = unmarshalIPNSRecord(recordData);
|
|
619
|
+
const valueBytes = typeof record.value === "string" ? new TextEncoder().encode(record.value) : record.value;
|
|
620
|
+
const valueStr = new TextDecoder().decode(valueBytes);
|
|
621
|
+
const cidMatch = valueStr.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
622
|
+
if (cidMatch) {
|
|
623
|
+
return {
|
|
624
|
+
cid: cidMatch[1],
|
|
625
|
+
sequence: record.sequence,
|
|
626
|
+
recordData
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
} catch {
|
|
631
|
+
continue;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
function base64ToUint8Array(base64) {
|
|
637
|
+
const binary = atob(base64);
|
|
638
|
+
const bytes = new Uint8Array(binary.length);
|
|
639
|
+
for (let i = 0; i < binary.length; i++) {
|
|
640
|
+
bytes[i] = binary.charCodeAt(i);
|
|
641
|
+
}
|
|
642
|
+
return bytes;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// impl/shared/ipfs/ipfs-cache.ts
|
|
646
|
+
var DEFAULT_IPNS_TTL_MS = 6e4;
|
|
647
|
+
var DEFAULT_FAILURE_COOLDOWN_MS = 6e4;
|
|
648
|
+
var DEFAULT_FAILURE_THRESHOLD = 3;
|
|
649
|
+
var DEFAULT_KNOWN_FRESH_WINDOW_MS = 3e4;
|
|
650
|
+
var IpfsCache = class {
|
|
651
|
+
ipnsRecords = /* @__PURE__ */ new Map();
|
|
652
|
+
content = /* @__PURE__ */ new Map();
|
|
653
|
+
gatewayFailures = /* @__PURE__ */ new Map();
|
|
654
|
+
knownFreshTimestamps = /* @__PURE__ */ new Map();
|
|
655
|
+
ipnsTtlMs;
|
|
656
|
+
failureCooldownMs;
|
|
657
|
+
failureThreshold;
|
|
658
|
+
knownFreshWindowMs;
|
|
659
|
+
constructor(config) {
|
|
660
|
+
this.ipnsTtlMs = config?.ipnsTtlMs ?? DEFAULT_IPNS_TTL_MS;
|
|
661
|
+
this.failureCooldownMs = config?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
|
|
662
|
+
this.failureThreshold = config?.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
|
|
663
|
+
this.knownFreshWindowMs = config?.knownFreshWindowMs ?? DEFAULT_KNOWN_FRESH_WINDOW_MS;
|
|
664
|
+
}
|
|
665
|
+
// ---------------------------------------------------------------------------
|
|
666
|
+
// IPNS Record Cache (60s TTL)
|
|
667
|
+
// ---------------------------------------------------------------------------
|
|
668
|
+
getIpnsRecord(ipnsName) {
|
|
669
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
670
|
+
if (!entry) return null;
|
|
671
|
+
if (Date.now() - entry.timestamp > this.ipnsTtlMs) {
|
|
672
|
+
this.ipnsRecords.delete(ipnsName);
|
|
673
|
+
return null;
|
|
612
674
|
}
|
|
675
|
+
return entry.data;
|
|
613
676
|
}
|
|
614
677
|
/**
|
|
615
|
-
*
|
|
678
|
+
* Get cached IPNS record ignoring TTL (for known-fresh optimization).
|
|
616
679
|
*/
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
this.log("Initializing Helia with bootstrap peers...");
|
|
621
|
-
const { createHelia, json, bootstrap } = await loadHeliaModules();
|
|
622
|
-
this.helia = await createHelia({
|
|
623
|
-
libp2p: {
|
|
624
|
-
peerDiscovery: [
|
|
625
|
-
bootstrap({ list: this.config.bootstrapPeers })
|
|
626
|
-
],
|
|
627
|
-
connectionManager: {
|
|
628
|
-
maxConnections: 10
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
});
|
|
632
|
-
this.heliaJson = json(this.helia);
|
|
633
|
-
const peerId = this.helia.libp2p.peerId.toString();
|
|
634
|
-
this.log("Helia initialized, browser peer ID:", peerId.slice(0, 20) + "...");
|
|
635
|
-
setTimeout(() => {
|
|
636
|
-
const connections = this.helia?.libp2p.getConnections() || [];
|
|
637
|
-
this.log(`Active Helia connections: ${connections.length}`);
|
|
638
|
-
}, 3e3);
|
|
639
|
-
} catch (error) {
|
|
640
|
-
this.log("Helia initialization failed (will use HTTP only):", error);
|
|
641
|
-
}
|
|
680
|
+
getIpnsRecordIgnoreTtl(ipnsName) {
|
|
681
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
682
|
+
return entry?.data ?? null;
|
|
642
683
|
}
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
this.log("Error stopping Helia:", error);
|
|
649
|
-
}
|
|
650
|
-
this.helia = null;
|
|
651
|
-
this.heliaJson = null;
|
|
652
|
-
}
|
|
653
|
-
this.status = "disconnected";
|
|
654
|
-
this.localCache = null;
|
|
655
|
-
this.ipnsKeyPair = null;
|
|
656
|
-
this.log("Disconnected from IPFS");
|
|
684
|
+
setIpnsRecord(ipnsName, result) {
|
|
685
|
+
this.ipnsRecords.set(ipnsName, {
|
|
686
|
+
data: result,
|
|
687
|
+
timestamp: Date.now()
|
|
688
|
+
});
|
|
657
689
|
}
|
|
658
|
-
|
|
659
|
-
|
|
690
|
+
invalidateIpns(ipnsName) {
|
|
691
|
+
this.ipnsRecords.delete(ipnsName);
|
|
660
692
|
}
|
|
661
|
-
|
|
662
|
-
|
|
693
|
+
// ---------------------------------------------------------------------------
|
|
694
|
+
// Content Cache (infinite TTL - content is immutable by CID)
|
|
695
|
+
// ---------------------------------------------------------------------------
|
|
696
|
+
getContent(cid) {
|
|
697
|
+
const entry = this.content.get(cid);
|
|
698
|
+
return entry?.data ?? null;
|
|
663
699
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
try {
|
|
670
|
-
const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadHeliaModules();
|
|
671
|
-
const walletSecret = this.hexToBytes(identity.privateKey);
|
|
672
|
-
const derivedKey = hkdf(sha256, walletSecret, void 0, HKDF_INFO, 32);
|
|
673
|
-
this.ipnsKeyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
|
|
674
|
-
const peerId = peerIdFromPrivateKey(this.ipnsKeyPair);
|
|
675
|
-
this.ipnsName = peerId.toString();
|
|
676
|
-
this.log("Identity set, IPNS name:", this.ipnsName);
|
|
677
|
-
} catch {
|
|
678
|
-
this.ipnsName = identity.ipnsName ?? this.deriveIpnsNameSimple(identity.privateKey);
|
|
679
|
-
this.log("Identity set with fallback IPNS name:", this.ipnsName);
|
|
680
|
-
}
|
|
700
|
+
setContent(cid, data) {
|
|
701
|
+
this.content.set(cid, {
|
|
702
|
+
data,
|
|
703
|
+
timestamp: Date.now()
|
|
704
|
+
});
|
|
681
705
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
706
|
+
// ---------------------------------------------------------------------------
|
|
707
|
+
// Gateway Failure Tracking (Circuit Breaker)
|
|
708
|
+
// ---------------------------------------------------------------------------
|
|
709
|
+
/**
|
|
710
|
+
* Record a gateway failure. After threshold consecutive failures,
|
|
711
|
+
* the gateway enters cooldown and is considered unhealthy.
|
|
712
|
+
*/
|
|
713
|
+
recordGatewayFailure(gateway) {
|
|
714
|
+
const existing = this.gatewayFailures.get(gateway);
|
|
715
|
+
this.gatewayFailures.set(gateway, {
|
|
716
|
+
count: (existing?.count ?? 0) + 1,
|
|
717
|
+
lastFailure: Date.now()
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
/** Reset failure count for a gateway (on successful request) */
|
|
721
|
+
recordGatewaySuccess(gateway) {
|
|
722
|
+
this.gatewayFailures.delete(gateway);
|
|
723
|
+
}
|
|
724
|
+
/**
|
|
725
|
+
* Check if a gateway is currently in circuit breaker cooldown.
|
|
726
|
+
* A gateway is considered unhealthy if it has had >= threshold
|
|
727
|
+
* consecutive failures and the cooldown period hasn't elapsed.
|
|
728
|
+
*/
|
|
729
|
+
isGatewayInCooldown(gateway) {
|
|
730
|
+
const failure = this.gatewayFailures.get(gateway);
|
|
731
|
+
if (!failure) return false;
|
|
732
|
+
if (failure.count < this.failureThreshold) return false;
|
|
733
|
+
const elapsed = Date.now() - failure.lastFailure;
|
|
734
|
+
if (elapsed >= this.failureCooldownMs) {
|
|
735
|
+
this.gatewayFailures.delete(gateway);
|
|
736
|
+
return false;
|
|
685
737
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
738
|
+
return true;
|
|
739
|
+
}
|
|
740
|
+
// ---------------------------------------------------------------------------
|
|
741
|
+
// Known-Fresh Flag (FAST mode optimization)
|
|
742
|
+
// ---------------------------------------------------------------------------
|
|
743
|
+
/**
|
|
744
|
+
* Mark IPNS cache as "known-fresh" (after local publish or push notification).
|
|
745
|
+
* Within the fresh window, we can skip network resolution.
|
|
746
|
+
*/
|
|
747
|
+
markIpnsFresh(ipnsName) {
|
|
748
|
+
this.knownFreshTimestamps.set(ipnsName, Date.now());
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Check if the cache is known-fresh (within the fresh window).
|
|
752
|
+
*/
|
|
753
|
+
isIpnsKnownFresh(ipnsName) {
|
|
754
|
+
const timestamp = this.knownFreshTimestamps.get(ipnsName);
|
|
755
|
+
if (!timestamp) return false;
|
|
756
|
+
if (Date.now() - timestamp > this.knownFreshWindowMs) {
|
|
757
|
+
this.knownFreshTimestamps.delete(ipnsName);
|
|
690
758
|
return false;
|
|
691
759
|
}
|
|
760
|
+
return true;
|
|
692
761
|
}
|
|
693
|
-
|
|
694
|
-
|
|
762
|
+
// ---------------------------------------------------------------------------
|
|
763
|
+
// Cache Management
|
|
764
|
+
// ---------------------------------------------------------------------------
|
|
765
|
+
clear() {
|
|
766
|
+
this.ipnsRecords.clear();
|
|
767
|
+
this.content.clear();
|
|
768
|
+
this.gatewayFailures.clear();
|
|
769
|
+
this.knownFreshTimestamps.clear();
|
|
695
770
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
// impl/shared/ipfs/ipfs-http-client.ts
|
|
774
|
+
var DEFAULT_CONNECTIVITY_TIMEOUT_MS = 5e3;
|
|
775
|
+
var DEFAULT_FETCH_TIMEOUT_MS = 15e3;
|
|
776
|
+
var DEFAULT_RESOLVE_TIMEOUT_MS = 1e4;
|
|
777
|
+
var DEFAULT_PUBLISH_TIMEOUT_MS = 3e4;
|
|
778
|
+
var DEFAULT_GATEWAY_PATH_TIMEOUT_MS = 3e3;
|
|
779
|
+
var DEFAULT_ROUTING_API_TIMEOUT_MS = 2e3;
|
|
780
|
+
var IpfsHttpClient = class {
|
|
781
|
+
gateways;
|
|
782
|
+
fetchTimeoutMs;
|
|
783
|
+
resolveTimeoutMs;
|
|
784
|
+
publishTimeoutMs;
|
|
785
|
+
connectivityTimeoutMs;
|
|
786
|
+
debug;
|
|
787
|
+
cache;
|
|
788
|
+
constructor(config, cache) {
|
|
789
|
+
this.gateways = config.gateways;
|
|
790
|
+
this.fetchTimeoutMs = config.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
791
|
+
this.resolveTimeoutMs = config.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
|
|
792
|
+
this.publishTimeoutMs = config.publishTimeoutMs ?? DEFAULT_PUBLISH_TIMEOUT_MS;
|
|
793
|
+
this.connectivityTimeoutMs = config.connectivityTimeoutMs ?? DEFAULT_CONNECTIVITY_TIMEOUT_MS;
|
|
794
|
+
this.debug = config.debug ?? false;
|
|
795
|
+
this.cache = cache;
|
|
796
|
+
}
|
|
797
|
+
// ---------------------------------------------------------------------------
|
|
798
|
+
// Public Accessors
|
|
799
|
+
// ---------------------------------------------------------------------------
|
|
800
|
+
/**
|
|
801
|
+
* Get configured gateway URLs.
|
|
802
|
+
*/
|
|
803
|
+
getGateways() {
|
|
804
|
+
return [...this.gateways];
|
|
805
|
+
}
|
|
806
|
+
// ---------------------------------------------------------------------------
|
|
807
|
+
// Gateway Health
|
|
808
|
+
// ---------------------------------------------------------------------------
|
|
809
|
+
/**
|
|
810
|
+
* Test connectivity to a single gateway.
|
|
811
|
+
*/
|
|
812
|
+
async testConnectivity(gateway) {
|
|
813
|
+
const start = Date.now();
|
|
699
814
|
try {
|
|
700
|
-
const
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
}
|
|
707
|
-
};
|
|
708
|
-
const cid = await this.publishToGateways(dataToSave);
|
|
709
|
-
if (this.config.enableIpns && this.ipnsName) {
|
|
710
|
-
await this.publishIpns(cid);
|
|
815
|
+
const response = await this.fetchWithTimeout(
|
|
816
|
+
`${gateway}/api/v0/version`,
|
|
817
|
+
this.connectivityTimeoutMs,
|
|
818
|
+
{ method: "POST" }
|
|
819
|
+
);
|
|
820
|
+
if (!response.ok) {
|
|
821
|
+
return { gateway, healthy: false, error: `HTTP ${response.status}` };
|
|
711
822
|
}
|
|
712
|
-
this.localCache = dataToSave;
|
|
713
|
-
this.cacheTimestamp = Date.now();
|
|
714
|
-
this.lastCid = cid;
|
|
715
|
-
this.emitEvent({ type: "storage:saved", timestamp: Date.now(), data: { cid } });
|
|
716
823
|
return {
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
824
|
+
gateway,
|
|
825
|
+
healthy: true,
|
|
826
|
+
responseTimeMs: Date.now() - start
|
|
720
827
|
};
|
|
721
828
|
} catch (error) {
|
|
722
|
-
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
723
|
-
this.emitEvent({ type: "storage:error", timestamp: Date.now(), error: errorMsg });
|
|
724
829
|
return {
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
830
|
+
gateway,
|
|
831
|
+
healthy: false,
|
|
832
|
+
error: error instanceof Error ? error.message : String(error)
|
|
728
833
|
};
|
|
729
834
|
}
|
|
730
835
|
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
836
|
+
/**
|
|
837
|
+
* Find healthy gateways from the configured list.
|
|
838
|
+
*/
|
|
839
|
+
async findHealthyGateways() {
|
|
840
|
+
const results = await Promise.allSettled(
|
|
841
|
+
this.gateways.map((gw) => this.testConnectivity(gw))
|
|
842
|
+
);
|
|
843
|
+
return results.filter((r) => r.status === "fulfilled" && r.value.healthy).map((r) => r.value.gateway);
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Get gateways that are not in circuit breaker cooldown.
|
|
847
|
+
*/
|
|
848
|
+
getAvailableGateways() {
|
|
849
|
+
return this.gateways.filter((gw) => !this.cache.isGatewayInCooldown(gw));
|
|
850
|
+
}
|
|
851
|
+
// ---------------------------------------------------------------------------
|
|
852
|
+
// Content Upload
|
|
853
|
+
// ---------------------------------------------------------------------------
|
|
854
|
+
/**
|
|
855
|
+
* Upload JSON content to IPFS.
|
|
856
|
+
* Tries all gateways in parallel, returns first success.
|
|
857
|
+
*/
|
|
858
|
+
async upload(data, gateways) {
|
|
859
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
860
|
+
if (targets.length === 0) {
|
|
861
|
+
throw new IpfsError("No gateways available for upload", "NETWORK_ERROR");
|
|
862
|
+
}
|
|
863
|
+
const jsonBytes = new TextEncoder().encode(JSON.stringify(data));
|
|
864
|
+
const promises = targets.map(async (gateway) => {
|
|
865
|
+
try {
|
|
866
|
+
const formData = new FormData();
|
|
867
|
+
formData.append("file", new Blob([jsonBytes], { type: "application/json" }), "data.json");
|
|
868
|
+
const response = await this.fetchWithTimeout(
|
|
869
|
+
`${gateway}/api/v0/add?pin=true&cid-version=1`,
|
|
870
|
+
this.publishTimeoutMs,
|
|
871
|
+
{ method: "POST", body: formData }
|
|
872
|
+
);
|
|
873
|
+
if (!response.ok) {
|
|
874
|
+
throw new IpfsError(
|
|
875
|
+
`Upload failed: HTTP ${response.status}`,
|
|
876
|
+
classifyHttpStatus(response.status),
|
|
877
|
+
gateway
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
const result = await response.json();
|
|
881
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
882
|
+
this.log(`Uploaded to ${gateway}: CID=${result.Hash}`);
|
|
883
|
+
return { cid: result.Hash, gateway };
|
|
884
|
+
} catch (error) {
|
|
885
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
886
|
+
this.cache.recordGatewayFailure(gateway);
|
|
887
|
+
}
|
|
888
|
+
throw error;
|
|
744
889
|
}
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
890
|
+
});
|
|
891
|
+
try {
|
|
892
|
+
const result = await Promise.any(promises);
|
|
893
|
+
return { cid: result.cid };
|
|
894
|
+
} catch (error) {
|
|
895
|
+
if (error instanceof AggregateError) {
|
|
896
|
+
throw new IpfsError(
|
|
897
|
+
`Upload failed on all gateways: ${error.errors.map((e) => e.message).join("; ")}`,
|
|
898
|
+
"NETWORK_ERROR"
|
|
899
|
+
);
|
|
748
900
|
}
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
901
|
+
throw error;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
// ---------------------------------------------------------------------------
|
|
905
|
+
// Content Fetch
|
|
906
|
+
// ---------------------------------------------------------------------------
|
|
907
|
+
/**
|
|
908
|
+
* Fetch content by CID from IPFS gateways.
|
|
909
|
+
* Checks content cache first. Races all gateways for fastest response.
|
|
910
|
+
*/
|
|
911
|
+
async fetchContent(cid, gateways) {
|
|
912
|
+
const cached = this.cache.getContent(cid);
|
|
913
|
+
if (cached) {
|
|
914
|
+
this.log(`Content cache hit for CID=${cid}`);
|
|
915
|
+
return cached;
|
|
916
|
+
}
|
|
917
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
918
|
+
if (targets.length === 0) {
|
|
919
|
+
throw new IpfsError("No gateways available for fetch", "NETWORK_ERROR");
|
|
920
|
+
}
|
|
921
|
+
const promises = targets.map(async (gateway) => {
|
|
922
|
+
try {
|
|
923
|
+
const response = await this.fetchWithTimeout(
|
|
924
|
+
`${gateway}/ipfs/${cid}`,
|
|
925
|
+
this.fetchTimeoutMs,
|
|
926
|
+
{ headers: { Accept: "application/octet-stream" } }
|
|
927
|
+
);
|
|
928
|
+
if (!response.ok) {
|
|
929
|
+
const body = await response.text().catch(() => "");
|
|
930
|
+
throw new IpfsError(
|
|
931
|
+
`Fetch failed: HTTP ${response.status}`,
|
|
932
|
+
classifyHttpStatus(response.status, body),
|
|
933
|
+
gateway
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const data = await response.json();
|
|
937
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
938
|
+
this.cache.setContent(cid, data);
|
|
939
|
+
this.log(`Fetched from ${gateway}: CID=${cid}`);
|
|
940
|
+
return data;
|
|
941
|
+
} catch (error) {
|
|
942
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
943
|
+
this.cache.recordGatewayFailure(gateway);
|
|
944
|
+
}
|
|
945
|
+
throw error;
|
|
756
946
|
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
this.lastCid = cid;
|
|
761
|
-
this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
|
|
762
|
-
return {
|
|
763
|
-
success: true,
|
|
764
|
-
data,
|
|
765
|
-
source: "remote",
|
|
766
|
-
timestamp: Date.now()
|
|
767
|
-
};
|
|
947
|
+
});
|
|
948
|
+
try {
|
|
949
|
+
return await Promise.any(promises);
|
|
768
950
|
} catch (error) {
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
data: this.localCache,
|
|
775
|
-
source: "cache",
|
|
776
|
-
timestamp: Date.now()
|
|
777
|
-
};
|
|
951
|
+
if (error instanceof AggregateError) {
|
|
952
|
+
throw new IpfsError(
|
|
953
|
+
`Fetch failed on all gateways for CID=${cid}`,
|
|
954
|
+
"NETWORK_ERROR"
|
|
955
|
+
);
|
|
778
956
|
}
|
|
779
|
-
|
|
780
|
-
success: false,
|
|
781
|
-
error: errorMsg,
|
|
782
|
-
source: "remote",
|
|
783
|
-
timestamp: Date.now()
|
|
784
|
-
};
|
|
957
|
+
throw error;
|
|
785
958
|
}
|
|
786
959
|
}
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
960
|
+
// ---------------------------------------------------------------------------
|
|
961
|
+
// IPNS Resolution
|
|
962
|
+
// ---------------------------------------------------------------------------
|
|
963
|
+
/**
|
|
964
|
+
* Resolve IPNS via Routing API (returns record with sequence number).
|
|
965
|
+
* POST /api/v0/routing/get?arg=/ipns/{name}
|
|
966
|
+
*/
|
|
967
|
+
async resolveIpnsViaRoutingApi(gateway, ipnsName, timeoutMs = DEFAULT_ROUTING_API_TIMEOUT_MS) {
|
|
790
968
|
try {
|
|
791
|
-
const
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
conflicts: 0
|
|
802
|
-
};
|
|
969
|
+
const response = await this.fetchWithTimeout(
|
|
970
|
+
`${gateway}/api/v0/routing/get?arg=/ipns/${ipnsName}`,
|
|
971
|
+
timeoutMs,
|
|
972
|
+
{ method: "POST" }
|
|
973
|
+
);
|
|
974
|
+
if (!response.ok) {
|
|
975
|
+
const body = await response.text().catch(() => "");
|
|
976
|
+
const category = classifyHttpStatus(response.status, body);
|
|
977
|
+
if (category === "NOT_FOUND") return null;
|
|
978
|
+
throw new IpfsError(`Routing API: HTTP ${response.status}`, category, gateway);
|
|
803
979
|
}
|
|
804
|
-
const
|
|
805
|
-
await
|
|
806
|
-
|
|
980
|
+
const text = await response.text();
|
|
981
|
+
const parsed = await parseRoutingApiResponse(text);
|
|
982
|
+
if (!parsed) return null;
|
|
983
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
807
984
|
return {
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
conflicts: mergeResult.conflicts
|
|
985
|
+
cid: parsed.cid,
|
|
986
|
+
sequence: parsed.sequence,
|
|
987
|
+
gateway,
|
|
988
|
+
recordData: parsed.recordData
|
|
813
989
|
};
|
|
814
990
|
} catch (error) {
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
conflicts: 0,
|
|
822
|
-
error: errorMsg
|
|
823
|
-
};
|
|
991
|
+
if (error instanceof IpfsError) throw error;
|
|
992
|
+
const category = classifyFetchError(error);
|
|
993
|
+
if (category !== "NOT_FOUND") {
|
|
994
|
+
this.cache.recordGatewayFailure(gateway);
|
|
995
|
+
}
|
|
996
|
+
return null;
|
|
824
997
|
}
|
|
825
998
|
}
|
|
826
|
-
|
|
827
|
-
|
|
999
|
+
/**
|
|
1000
|
+
* Resolve IPNS via gateway path (simpler, no sequence number).
|
|
1001
|
+
* GET /ipns/{name}?format=dag-json
|
|
1002
|
+
*/
|
|
1003
|
+
async resolveIpnsViaGatewayPath(gateway, ipnsName, timeoutMs = DEFAULT_GATEWAY_PATH_TIMEOUT_MS) {
|
|
828
1004
|
try {
|
|
829
|
-
const
|
|
830
|
-
|
|
1005
|
+
const response = await this.fetchWithTimeout(
|
|
1006
|
+
`${gateway}/ipns/${ipnsName}`,
|
|
1007
|
+
timeoutMs,
|
|
1008
|
+
{ headers: { Accept: "application/json" } }
|
|
1009
|
+
);
|
|
1010
|
+
if (!response.ok) return null;
|
|
1011
|
+
const content = await response.json();
|
|
1012
|
+
const cidHeader = response.headers.get("X-Ipfs-Path");
|
|
1013
|
+
if (cidHeader) {
|
|
1014
|
+
const match = cidHeader.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
1015
|
+
if (match) {
|
|
1016
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
1017
|
+
return { cid: match[1], content };
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
return { cid: "", content };
|
|
831
1021
|
} catch {
|
|
832
|
-
return
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
async clear() {
|
|
836
|
-
const emptyData = {
|
|
837
|
-
_meta: {
|
|
838
|
-
version: 0,
|
|
839
|
-
address: this.identity?.l1Address ?? "",
|
|
840
|
-
formatVersion: "2.0",
|
|
841
|
-
updatedAt: Date.now()
|
|
842
|
-
},
|
|
843
|
-
_tombstones: []
|
|
844
|
-
};
|
|
845
|
-
const result = await this.save(emptyData);
|
|
846
|
-
return result.success;
|
|
847
|
-
}
|
|
848
|
-
onEvent(callback) {
|
|
849
|
-
this.eventCallbacks.add(callback);
|
|
850
|
-
return () => this.eventCallbacks.delete(callback);
|
|
851
|
-
}
|
|
852
|
-
// ===========================================================================
|
|
853
|
-
// Private: IPFS Operations
|
|
854
|
-
// ===========================================================================
|
|
855
|
-
async testGatewayConnectivity() {
|
|
856
|
-
const gateway = this.config.gateways[0];
|
|
857
|
-
const controller = new AbortController();
|
|
858
|
-
const timeout = setTimeout(() => controller.abort(), 5e3);
|
|
859
|
-
try {
|
|
860
|
-
const response = await fetch(`${gateway}/api/v0/version`, {
|
|
861
|
-
method: "POST",
|
|
862
|
-
signal: controller.signal
|
|
863
|
-
});
|
|
864
|
-
if (!response.ok) throw new Error("Gateway not responding");
|
|
865
|
-
} finally {
|
|
866
|
-
clearTimeout(timeout);
|
|
1022
|
+
return null;
|
|
867
1023
|
}
|
|
868
1024
|
}
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
1025
|
+
/**
|
|
1026
|
+
* Progressive IPNS resolution across all gateways.
|
|
1027
|
+
* Queries all gateways in parallel, returns highest sequence number.
|
|
1028
|
+
*/
|
|
1029
|
+
async resolveIpns(ipnsName, gateways) {
|
|
1030
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
1031
|
+
if (targets.length === 0) {
|
|
1032
|
+
return { best: null, allResults: [], respondedCount: 0, totalGateways: 0 };
|
|
875
1033
|
}
|
|
876
|
-
|
|
877
|
-
|
|
1034
|
+
const results = [];
|
|
1035
|
+
let respondedCount = 0;
|
|
1036
|
+
const promises = targets.map(async (gateway) => {
|
|
1037
|
+
const result = await this.resolveIpnsViaRoutingApi(
|
|
1038
|
+
gateway,
|
|
1039
|
+
ipnsName,
|
|
1040
|
+
this.resolveTimeoutMs
|
|
1041
|
+
);
|
|
1042
|
+
if (result) results.push(result);
|
|
1043
|
+
respondedCount++;
|
|
1044
|
+
return result;
|
|
1045
|
+
});
|
|
1046
|
+
await Promise.race([
|
|
1047
|
+
Promise.allSettled(promises),
|
|
1048
|
+
new Promise((resolve) => setTimeout(resolve, this.resolveTimeoutMs + 1e3))
|
|
1049
|
+
]);
|
|
1050
|
+
let best = null;
|
|
1051
|
+
for (const result of results) {
|
|
1052
|
+
if (!best || result.sequence > best.sequence) {
|
|
1053
|
+
best = result;
|
|
1054
|
+
}
|
|
878
1055
|
}
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
this.log("Published to IPFS, CID:", cid);
|
|
882
|
-
return cid;
|
|
883
|
-
} catch {
|
|
884
|
-
throw new Error("All publish attempts failed");
|
|
1056
|
+
if (best) {
|
|
1057
|
+
this.cache.setIpnsRecord(ipnsName, best);
|
|
885
1058
|
}
|
|
1059
|
+
return {
|
|
1060
|
+
best,
|
|
1061
|
+
allResults: results,
|
|
1062
|
+
respondedCount,
|
|
1063
|
+
totalGateways: targets.length
|
|
1064
|
+
};
|
|
886
1065
|
}
|
|
1066
|
+
// ---------------------------------------------------------------------------
|
|
1067
|
+
// IPNS Publishing
|
|
1068
|
+
// ---------------------------------------------------------------------------
|
|
887
1069
|
/**
|
|
888
|
-
* Publish
|
|
1070
|
+
* Publish IPNS record to a single gateway via routing API.
|
|
889
1071
|
*/
|
|
890
|
-
async
|
|
891
|
-
if (!this.heliaJson) {
|
|
892
|
-
throw new Error("Helia not initialized");
|
|
893
|
-
}
|
|
894
|
-
const cid = await this.heliaJson.add(data);
|
|
895
|
-
this.log("Published via Helia, CID:", cid.toString());
|
|
896
|
-
return cid.toString();
|
|
897
|
-
}
|
|
898
|
-
async publishToGateway(gateway, blob) {
|
|
899
|
-
const formData = new FormData();
|
|
900
|
-
formData.append("file", blob);
|
|
901
|
-
const controller = new AbortController();
|
|
902
|
-
const timeout = setTimeout(() => controller.abort(), this.config.fetchTimeout);
|
|
1072
|
+
async publishIpnsViaRoutingApi(gateway, ipnsName, marshalledRecord, timeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS) {
|
|
903
1073
|
try {
|
|
904
|
-
const
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
1074
|
+
const formData = new FormData();
|
|
1075
|
+
formData.append(
|
|
1076
|
+
"file",
|
|
1077
|
+
new Blob([new Uint8Array(marshalledRecord)]),
|
|
1078
|
+
"record"
|
|
1079
|
+
);
|
|
1080
|
+
const response = await this.fetchWithTimeout(
|
|
1081
|
+
`${gateway}/api/v0/routing/put?arg=/ipns/${ipnsName}&allow-offline=true`,
|
|
1082
|
+
timeoutMs,
|
|
1083
|
+
{ method: "POST", body: formData }
|
|
1084
|
+
);
|
|
909
1085
|
if (!response.ok) {
|
|
910
|
-
|
|
1086
|
+
const errorText = await response.text().catch(() => "");
|
|
1087
|
+
throw new IpfsError(
|
|
1088
|
+
`IPNS publish: HTTP ${response.status}: ${errorText.slice(0, 100)}`,
|
|
1089
|
+
classifyHttpStatus(response.status, errorText),
|
|
1090
|
+
gateway
|
|
1091
|
+
);
|
|
911
1092
|
}
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
1093
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
1094
|
+
this.log(`IPNS published to ${gateway}: ${ipnsName}`);
|
|
1095
|
+
return true;
|
|
1096
|
+
} catch (error) {
|
|
1097
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
1098
|
+
this.cache.recordGatewayFailure(gateway);
|
|
1099
|
+
}
|
|
1100
|
+
this.log(`IPNS publish to ${gateway} failed: ${error}`);
|
|
1101
|
+
return false;
|
|
1102
|
+
}
|
|
917
1103
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
1104
|
+
/**
|
|
1105
|
+
* Publish IPNS record to all gateways in parallel.
|
|
1106
|
+
*/
|
|
1107
|
+
async publishIpns(ipnsName, marshalledRecord, gateways) {
|
|
1108
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
1109
|
+
if (targets.length === 0) {
|
|
1110
|
+
return { success: false, error: "No gateways available" };
|
|
1111
|
+
}
|
|
1112
|
+
const results = await Promise.allSettled(
|
|
1113
|
+
targets.map((gw) => this.publishIpnsViaRoutingApi(gw, ipnsName, marshalledRecord, this.publishTimeoutMs))
|
|
922
1114
|
);
|
|
923
|
-
|
|
924
|
-
|
|
1115
|
+
const successfulGateways = [];
|
|
1116
|
+
results.forEach((result, index) => {
|
|
1117
|
+
if (result.status === "fulfilled" && result.value) {
|
|
1118
|
+
successfulGateways.push(targets[index]);
|
|
1119
|
+
}
|
|
1120
|
+
});
|
|
1121
|
+
return {
|
|
1122
|
+
success: successfulGateways.length > 0,
|
|
1123
|
+
ipnsName,
|
|
1124
|
+
successfulGateways,
|
|
1125
|
+
error: successfulGateways.length === 0 ? "All gateways failed" : void 0
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
// ---------------------------------------------------------------------------
|
|
1129
|
+
// IPNS Verification
|
|
1130
|
+
// ---------------------------------------------------------------------------
|
|
1131
|
+
/**
|
|
1132
|
+
* Verify IPNS record persistence after publishing.
|
|
1133
|
+
* Retries resolution to confirm the record was accepted.
|
|
1134
|
+
*/
|
|
1135
|
+
async verifyIpnsRecord(ipnsName, expectedSeq, expectedCid, retries = 3, delayMs = 1e3) {
|
|
1136
|
+
for (let i = 0; i < retries; i++) {
|
|
1137
|
+
if (i > 0) {
|
|
1138
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1139
|
+
}
|
|
1140
|
+
const { best } = await this.resolveIpns(ipnsName);
|
|
1141
|
+
if (best && best.sequence >= expectedSeq && best.cid === expectedCid) {
|
|
1142
|
+
return true;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
return false;
|
|
925
1146
|
}
|
|
926
|
-
|
|
1147
|
+
// ---------------------------------------------------------------------------
|
|
1148
|
+
// Helpers
|
|
1149
|
+
// ---------------------------------------------------------------------------
|
|
1150
|
+
async fetchWithTimeout(url, timeoutMs, options) {
|
|
927
1151
|
const controller = new AbortController();
|
|
928
|
-
const
|
|
1152
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
929
1153
|
try {
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
1154
|
+
return await fetch(url, {
|
|
1155
|
+
...options,
|
|
1156
|
+
signal: controller.signal
|
|
1157
|
+
});
|
|
1158
|
+
} finally {
|
|
1159
|
+
clearTimeout(timer);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
log(message) {
|
|
1163
|
+
if (this.debug) {
|
|
1164
|
+
console.log(`[IPFS-HTTP] ${message}`);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
};
|
|
1168
|
+
|
|
1169
|
+
// impl/shared/ipfs/txf-merge.ts
|
|
1170
|
+
function mergeTxfData(local, remote) {
|
|
1171
|
+
let added = 0;
|
|
1172
|
+
let removed = 0;
|
|
1173
|
+
let conflicts = 0;
|
|
1174
|
+
const localVersion = local._meta?.version ?? 0;
|
|
1175
|
+
const remoteVersion = remote._meta?.version ?? 0;
|
|
1176
|
+
const baseMeta = localVersion >= remoteVersion ? local._meta : remote._meta;
|
|
1177
|
+
const mergedMeta = {
|
|
1178
|
+
...baseMeta,
|
|
1179
|
+
version: Math.max(localVersion, remoteVersion) + 1,
|
|
1180
|
+
updatedAt: Date.now()
|
|
1181
|
+
};
|
|
1182
|
+
const mergedTombstones = mergeTombstones(
|
|
1183
|
+
local._tombstones ?? [],
|
|
1184
|
+
remote._tombstones ?? []
|
|
1185
|
+
);
|
|
1186
|
+
const tombstoneKeys = new Set(
|
|
1187
|
+
mergedTombstones.map((t) => `${t.tokenId}:${t.stateHash}`)
|
|
1188
|
+
);
|
|
1189
|
+
const localTokenKeys = getTokenKeys(local);
|
|
1190
|
+
const remoteTokenKeys = getTokenKeys(remote);
|
|
1191
|
+
const allTokenKeys = /* @__PURE__ */ new Set([...localTokenKeys, ...remoteTokenKeys]);
|
|
1192
|
+
const mergedTokens = {};
|
|
1193
|
+
for (const key of allTokenKeys) {
|
|
1194
|
+
const tokenId = key.startsWith("_") ? key.slice(1) : key;
|
|
1195
|
+
const localToken = local[key];
|
|
1196
|
+
const remoteToken = remote[key];
|
|
1197
|
+
if (isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys)) {
|
|
1198
|
+
if (localTokenKeys.has(key)) removed++;
|
|
1199
|
+
continue;
|
|
1200
|
+
}
|
|
1201
|
+
if (localToken && !remoteToken) {
|
|
1202
|
+
mergedTokens[key] = localToken;
|
|
1203
|
+
} else if (!localToken && remoteToken) {
|
|
1204
|
+
mergedTokens[key] = remoteToken;
|
|
1205
|
+
added++;
|
|
1206
|
+
} else if (localToken && remoteToken) {
|
|
1207
|
+
mergedTokens[key] = localToken;
|
|
1208
|
+
conflicts++;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const mergedOutbox = mergeArrayById(
|
|
1212
|
+
local._outbox ?? [],
|
|
1213
|
+
remote._outbox ?? [],
|
|
1214
|
+
"id"
|
|
1215
|
+
);
|
|
1216
|
+
const mergedSent = mergeArrayById(
|
|
1217
|
+
local._sent ?? [],
|
|
1218
|
+
remote._sent ?? [],
|
|
1219
|
+
"tokenId"
|
|
1220
|
+
);
|
|
1221
|
+
const mergedInvalid = mergeArrayById(
|
|
1222
|
+
local._invalid ?? [],
|
|
1223
|
+
remote._invalid ?? [],
|
|
1224
|
+
"tokenId"
|
|
1225
|
+
);
|
|
1226
|
+
const localNametags = local._nametags ?? [];
|
|
1227
|
+
const remoteNametags = remote._nametags ?? [];
|
|
1228
|
+
const mergedNametags = mergeNametagsByName(localNametags, remoteNametags);
|
|
1229
|
+
const merged = {
|
|
1230
|
+
_meta: mergedMeta,
|
|
1231
|
+
_tombstones: mergedTombstones.length > 0 ? mergedTombstones : void 0,
|
|
1232
|
+
_nametags: mergedNametags.length > 0 ? mergedNametags : void 0,
|
|
1233
|
+
_outbox: mergedOutbox.length > 0 ? mergedOutbox : void 0,
|
|
1234
|
+
_sent: mergedSent.length > 0 ? mergedSent : void 0,
|
|
1235
|
+
_invalid: mergedInvalid.length > 0 ? mergedInvalid : void 0,
|
|
1236
|
+
...mergedTokens
|
|
1237
|
+
};
|
|
1238
|
+
return { merged, added, removed, conflicts };
|
|
1239
|
+
}
|
|
1240
|
+
function mergeTombstones(local, remote) {
|
|
1241
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1242
|
+
for (const tombstone of [...local, ...remote]) {
|
|
1243
|
+
const key = `${tombstone.tokenId}:${tombstone.stateHash}`;
|
|
1244
|
+
const existing = merged.get(key);
|
|
1245
|
+
if (!existing || tombstone.timestamp > existing.timestamp) {
|
|
1246
|
+
merged.set(key, tombstone);
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
return Array.from(merged.values());
|
|
1250
|
+
}
|
|
1251
|
+
function getTokenKeys(data) {
|
|
1252
|
+
const reservedKeys = /* @__PURE__ */ new Set([
|
|
1253
|
+
"_meta",
|
|
1254
|
+
"_tombstones",
|
|
1255
|
+
"_outbox",
|
|
1256
|
+
"_sent",
|
|
1257
|
+
"_invalid",
|
|
1258
|
+
"_nametag",
|
|
1259
|
+
"_nametags",
|
|
1260
|
+
"_mintOutbox",
|
|
1261
|
+
"_invalidatedNametags",
|
|
1262
|
+
"_integrity"
|
|
1263
|
+
]);
|
|
1264
|
+
const keys = /* @__PURE__ */ new Set();
|
|
1265
|
+
for (const key of Object.keys(data)) {
|
|
1266
|
+
if (reservedKeys.has(key)) continue;
|
|
1267
|
+
if (key.startsWith("archived-") || key.startsWith("_forked_")) continue;
|
|
1268
|
+
keys.add(key);
|
|
1269
|
+
}
|
|
1270
|
+
return keys;
|
|
1271
|
+
}
|
|
1272
|
+
function isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys) {
|
|
1273
|
+
for (const key of tombstoneKeys) {
|
|
1274
|
+
if (key.startsWith(`${tokenId}:`)) {
|
|
1275
|
+
return true;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
void localToken;
|
|
1279
|
+
void remoteToken;
|
|
1280
|
+
return false;
|
|
1281
|
+
}
|
|
1282
|
+
function mergeNametagsByName(local, remote) {
|
|
1283
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1284
|
+
for (const item of local) {
|
|
1285
|
+
if (item.name) seen.set(item.name, item);
|
|
1286
|
+
}
|
|
1287
|
+
for (const item of remote) {
|
|
1288
|
+
if (item.name && !seen.has(item.name)) {
|
|
1289
|
+
seen.set(item.name, item);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
return Array.from(seen.values());
|
|
1293
|
+
}
|
|
1294
|
+
function mergeArrayById(local, remote, idField) {
|
|
1295
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1296
|
+
for (const item of local) {
|
|
1297
|
+
const id = item[idField];
|
|
1298
|
+
if (id !== void 0) {
|
|
1299
|
+
seen.set(id, item);
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
for (const item of remote) {
|
|
1303
|
+
const id = item[idField];
|
|
1304
|
+
if (id !== void 0 && !seen.has(id)) {
|
|
1305
|
+
seen.set(id, item);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return Array.from(seen.values());
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// transport/websocket.ts
|
|
1312
|
+
var WebSocketReadyState = {
|
|
1313
|
+
CONNECTING: 0,
|
|
1314
|
+
OPEN: 1,
|
|
1315
|
+
CLOSING: 2,
|
|
1316
|
+
CLOSED: 3
|
|
1317
|
+
};
|
|
1318
|
+
|
|
1319
|
+
// impl/shared/ipfs/ipns-subscription-client.ts
|
|
1320
|
+
var IpnsSubscriptionClient = class {
|
|
1321
|
+
ws = null;
|
|
1322
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
1323
|
+
reconnectTimeout = null;
|
|
1324
|
+
pingInterval = null;
|
|
1325
|
+
fallbackPollInterval = null;
|
|
1326
|
+
wsUrl;
|
|
1327
|
+
createWebSocket;
|
|
1328
|
+
pingIntervalMs;
|
|
1329
|
+
initialReconnectDelayMs;
|
|
1330
|
+
maxReconnectDelayMs;
|
|
1331
|
+
debugEnabled;
|
|
1332
|
+
reconnectAttempts = 0;
|
|
1333
|
+
isConnecting = false;
|
|
1334
|
+
connectionOpenedAt = 0;
|
|
1335
|
+
destroyed = false;
|
|
1336
|
+
/** Minimum stable connection time before resetting backoff (30 seconds) */
|
|
1337
|
+
minStableConnectionMs = 3e4;
|
|
1338
|
+
fallbackPollFn = null;
|
|
1339
|
+
fallbackPollIntervalMs = 0;
|
|
1340
|
+
constructor(config) {
|
|
1341
|
+
this.wsUrl = config.wsUrl;
|
|
1342
|
+
this.createWebSocket = config.createWebSocket;
|
|
1343
|
+
this.pingIntervalMs = config.pingIntervalMs ?? 3e4;
|
|
1344
|
+
this.initialReconnectDelayMs = config.reconnectDelayMs ?? 5e3;
|
|
1345
|
+
this.maxReconnectDelayMs = config.maxReconnectDelayMs ?? 6e4;
|
|
1346
|
+
this.debugEnabled = config.debug ?? false;
|
|
1347
|
+
}
|
|
1348
|
+
// ---------------------------------------------------------------------------
|
|
1349
|
+
// Public API
|
|
1350
|
+
// ---------------------------------------------------------------------------
|
|
1351
|
+
/**
|
|
1352
|
+
* Subscribe to IPNS updates for a specific name.
|
|
1353
|
+
* Automatically connects the WebSocket if not already connected.
|
|
1354
|
+
* If WebSocket is connecting, the name will be subscribed once connected.
|
|
1355
|
+
*/
|
|
1356
|
+
subscribe(ipnsName, callback) {
|
|
1357
|
+
if (!ipnsName || typeof ipnsName !== "string") {
|
|
1358
|
+
this.log("Invalid IPNS name for subscription");
|
|
1359
|
+
return () => {
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
const isNewSubscription = !this.subscriptions.has(ipnsName);
|
|
1363
|
+
if (isNewSubscription) {
|
|
1364
|
+
this.subscriptions.set(ipnsName, /* @__PURE__ */ new Set());
|
|
1365
|
+
}
|
|
1366
|
+
this.subscriptions.get(ipnsName).add(callback);
|
|
1367
|
+
if (isNewSubscription && this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1368
|
+
this.sendSubscribe([ipnsName]);
|
|
1369
|
+
}
|
|
1370
|
+
if (!this.ws || this.ws.readyState !== WebSocketReadyState.OPEN) {
|
|
1371
|
+
this.connect();
|
|
1372
|
+
}
|
|
1373
|
+
return () => {
|
|
1374
|
+
const callbacks = this.subscriptions.get(ipnsName);
|
|
1375
|
+
if (callbacks) {
|
|
1376
|
+
callbacks.delete(callback);
|
|
1377
|
+
if (callbacks.size === 0) {
|
|
1378
|
+
this.subscriptions.delete(ipnsName);
|
|
1379
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1380
|
+
this.sendUnsubscribe([ipnsName]);
|
|
1381
|
+
}
|
|
1382
|
+
if (this.subscriptions.size === 0) {
|
|
1383
|
+
this.disconnect();
|
|
1384
|
+
}
|
|
935
1385
|
}
|
|
936
|
-
);
|
|
937
|
-
if (!response.ok) {
|
|
938
|
-
throw new Error(`IPNS publish failed: ${response.status}`);
|
|
939
1386
|
}
|
|
940
|
-
}
|
|
941
|
-
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Register a convenience update callback for all subscriptions.
|
|
1391
|
+
* Returns an unsubscribe function.
|
|
1392
|
+
*/
|
|
1393
|
+
onUpdate(callback) {
|
|
1394
|
+
if (!this.subscriptions.has("*")) {
|
|
1395
|
+
this.subscriptions.set("*", /* @__PURE__ */ new Set());
|
|
942
1396
|
}
|
|
1397
|
+
this.subscriptions.get("*").add(callback);
|
|
1398
|
+
return () => {
|
|
1399
|
+
const callbacks = this.subscriptions.get("*");
|
|
1400
|
+
if (callbacks) {
|
|
1401
|
+
callbacks.delete(callback);
|
|
1402
|
+
if (callbacks.size === 0) {
|
|
1403
|
+
this.subscriptions.delete("*");
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
};
|
|
943
1407
|
}
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
1408
|
+
/**
|
|
1409
|
+
* Set a fallback poll function to use when WebSocket is disconnected.
|
|
1410
|
+
* The poll function will be called at the specified interval while WS is down.
|
|
1411
|
+
*/
|
|
1412
|
+
setFallbackPoll(fn, intervalMs) {
|
|
1413
|
+
this.fallbackPollFn = fn;
|
|
1414
|
+
this.fallbackPollIntervalMs = intervalMs;
|
|
1415
|
+
if (!this.isConnected()) {
|
|
1416
|
+
this.startFallbackPolling();
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
/**
|
|
1420
|
+
* Connect to the WebSocket server.
|
|
1421
|
+
*/
|
|
1422
|
+
connect() {
|
|
1423
|
+
if (this.destroyed) return;
|
|
1424
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN || this.isConnecting) {
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
this.isConnecting = true;
|
|
1428
|
+
try {
|
|
1429
|
+
this.log(`Connecting to ${this.wsUrl}...`);
|
|
1430
|
+
this.ws = this.createWebSocket(this.wsUrl);
|
|
1431
|
+
this.ws.onopen = () => {
|
|
1432
|
+
this.log("WebSocket connected");
|
|
1433
|
+
this.isConnecting = false;
|
|
1434
|
+
this.connectionOpenedAt = Date.now();
|
|
1435
|
+
const names = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
1436
|
+
if (names.length > 0) {
|
|
1437
|
+
this.sendSubscribe(names);
|
|
1438
|
+
}
|
|
1439
|
+
this.startPingInterval();
|
|
1440
|
+
this.stopFallbackPolling();
|
|
1441
|
+
};
|
|
1442
|
+
this.ws.onmessage = (event) => {
|
|
1443
|
+
this.handleMessage(event.data);
|
|
1444
|
+
};
|
|
1445
|
+
this.ws.onclose = () => {
|
|
1446
|
+
const connectionDuration = this.connectionOpenedAt > 0 ? Date.now() - this.connectionOpenedAt : 0;
|
|
1447
|
+
const wasStable = connectionDuration >= this.minStableConnectionMs;
|
|
1448
|
+
this.log(`WebSocket closed (duration: ${Math.round(connectionDuration / 1e3)}s)`);
|
|
1449
|
+
this.isConnecting = false;
|
|
1450
|
+
this.connectionOpenedAt = 0;
|
|
1451
|
+
this.stopPingInterval();
|
|
1452
|
+
if (wasStable) {
|
|
1453
|
+
this.reconnectAttempts = 0;
|
|
1454
|
+
}
|
|
1455
|
+
this.startFallbackPolling();
|
|
1456
|
+
this.scheduleReconnect();
|
|
1457
|
+
};
|
|
1458
|
+
this.ws.onerror = () => {
|
|
1459
|
+
this.log("WebSocket error");
|
|
1460
|
+
this.isConnecting = false;
|
|
1461
|
+
};
|
|
1462
|
+
} catch (e) {
|
|
1463
|
+
this.log(`Failed to connect: ${e}`);
|
|
1464
|
+
this.isConnecting = false;
|
|
1465
|
+
this.startFallbackPolling();
|
|
1466
|
+
this.scheduleReconnect();
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Disconnect from the WebSocket server and clean up.
|
|
1471
|
+
*/
|
|
1472
|
+
disconnect() {
|
|
1473
|
+
this.destroyed = true;
|
|
1474
|
+
if (this.reconnectTimeout) {
|
|
1475
|
+
clearTimeout(this.reconnectTimeout);
|
|
1476
|
+
this.reconnectTimeout = null;
|
|
1477
|
+
}
|
|
1478
|
+
this.stopPingInterval();
|
|
1479
|
+
this.stopFallbackPolling();
|
|
1480
|
+
if (this.ws) {
|
|
1481
|
+
this.ws.onopen = null;
|
|
1482
|
+
this.ws.onclose = null;
|
|
1483
|
+
this.ws.onerror = null;
|
|
1484
|
+
this.ws.onmessage = null;
|
|
1485
|
+
this.ws.close();
|
|
1486
|
+
this.ws = null;
|
|
1487
|
+
}
|
|
1488
|
+
this.isConnecting = false;
|
|
1489
|
+
this.reconnectAttempts = 0;
|
|
1490
|
+
}
|
|
1491
|
+
/**
|
|
1492
|
+
* Check if connected to the WebSocket server.
|
|
1493
|
+
*/
|
|
1494
|
+
isConnected() {
|
|
1495
|
+
return this.ws?.readyState === WebSocketReadyState.OPEN;
|
|
1496
|
+
}
|
|
1497
|
+
// ---------------------------------------------------------------------------
|
|
1498
|
+
// Internal: Message Handling
|
|
1499
|
+
// ---------------------------------------------------------------------------
|
|
1500
|
+
handleMessage(data) {
|
|
1501
|
+
try {
|
|
1502
|
+
const message = JSON.parse(data);
|
|
1503
|
+
switch (message.type) {
|
|
1504
|
+
case "update":
|
|
1505
|
+
if (message.name && message.sequence !== void 0) {
|
|
1506
|
+
this.notifySubscribers({
|
|
1507
|
+
type: "update",
|
|
1508
|
+
name: message.name,
|
|
1509
|
+
sequence: message.sequence,
|
|
1510
|
+
cid: message.cid ?? "",
|
|
1511
|
+
timestamp: message.timestamp || (/* @__PURE__ */ new Date()).toISOString()
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
break;
|
|
1515
|
+
case "subscribed":
|
|
1516
|
+
this.log(`Subscribed to ${message.names?.length || 0} names`);
|
|
1517
|
+
break;
|
|
1518
|
+
case "unsubscribed":
|
|
1519
|
+
this.log(`Unsubscribed from ${message.names?.length || 0} names`);
|
|
1520
|
+
break;
|
|
1521
|
+
case "pong":
|
|
1522
|
+
break;
|
|
1523
|
+
case "error":
|
|
1524
|
+
this.log(`Server error: ${message.message}`);
|
|
1525
|
+
break;
|
|
1526
|
+
default:
|
|
1527
|
+
break;
|
|
950
1528
|
}
|
|
1529
|
+
} catch {
|
|
1530
|
+
this.log("Failed to parse message");
|
|
951
1531
|
}
|
|
952
|
-
return null;
|
|
953
1532
|
}
|
|
954
|
-
|
|
955
|
-
const
|
|
956
|
-
|
|
1533
|
+
notifySubscribers(update) {
|
|
1534
|
+
const callbacks = this.subscriptions.get(update.name);
|
|
1535
|
+
if (callbacks) {
|
|
1536
|
+
this.log(`Update: ${update.name.slice(0, 16)}... seq=${update.sequence}`);
|
|
1537
|
+
for (const callback of callbacks) {
|
|
1538
|
+
try {
|
|
1539
|
+
callback(update);
|
|
1540
|
+
} catch {
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
const globalCallbacks = this.subscriptions.get("*");
|
|
1545
|
+
if (globalCallbacks) {
|
|
1546
|
+
for (const callback of globalCallbacks) {
|
|
1547
|
+
try {
|
|
1548
|
+
callback(update);
|
|
1549
|
+
} catch {
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
// ---------------------------------------------------------------------------
|
|
1555
|
+
// Internal: WebSocket Send
|
|
1556
|
+
// ---------------------------------------------------------------------------
|
|
1557
|
+
sendSubscribe(names) {
|
|
1558
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1559
|
+
this.ws.send(JSON.stringify({ action: "subscribe", names }));
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
sendUnsubscribe(names) {
|
|
1563
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1564
|
+
this.ws.send(JSON.stringify({ action: "unsubscribe", names }));
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
// ---------------------------------------------------------------------------
|
|
1568
|
+
// Internal: Reconnection
|
|
1569
|
+
// ---------------------------------------------------------------------------
|
|
1570
|
+
/**
|
|
1571
|
+
* Schedule reconnection with exponential backoff.
|
|
1572
|
+
* Sequence: 5s, 10s, 20s, 40s, 60s (capped)
|
|
1573
|
+
*/
|
|
1574
|
+
scheduleReconnect() {
|
|
1575
|
+
if (this.destroyed || this.reconnectTimeout) return;
|
|
1576
|
+
const realSubscriptions = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
1577
|
+
if (realSubscriptions.length === 0) return;
|
|
1578
|
+
this.reconnectAttempts++;
|
|
1579
|
+
const delay = Math.min(
|
|
1580
|
+
this.initialReconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
|
|
1581
|
+
this.maxReconnectDelayMs
|
|
1582
|
+
);
|
|
1583
|
+
this.log(`Reconnecting in ${(delay / 1e3).toFixed(1)}s (attempt ${this.reconnectAttempts})...`);
|
|
1584
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
1585
|
+
this.reconnectTimeout = null;
|
|
1586
|
+
this.connect();
|
|
1587
|
+
}, delay);
|
|
1588
|
+
}
|
|
1589
|
+
// ---------------------------------------------------------------------------
|
|
1590
|
+
// Internal: Keepalive
|
|
1591
|
+
// ---------------------------------------------------------------------------
|
|
1592
|
+
startPingInterval() {
|
|
1593
|
+
this.stopPingInterval();
|
|
1594
|
+
this.pingInterval = setInterval(() => {
|
|
1595
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
1596
|
+
this.ws.send(JSON.stringify({ action: "ping" }));
|
|
1597
|
+
}
|
|
1598
|
+
}, this.pingIntervalMs);
|
|
1599
|
+
}
|
|
1600
|
+
stopPingInterval() {
|
|
1601
|
+
if (this.pingInterval) {
|
|
1602
|
+
clearInterval(this.pingInterval);
|
|
1603
|
+
this.pingInterval = null;
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
// ---------------------------------------------------------------------------
|
|
1607
|
+
// Internal: Fallback Polling
|
|
1608
|
+
// ---------------------------------------------------------------------------
|
|
1609
|
+
startFallbackPolling() {
|
|
1610
|
+
if (this.fallbackPollInterval || !this.fallbackPollFn || this.destroyed) return;
|
|
1611
|
+
this.log(`Starting fallback polling (${this.fallbackPollIntervalMs / 1e3}s interval)`);
|
|
1612
|
+
this.fallbackPollFn().catch(() => {
|
|
1613
|
+
});
|
|
1614
|
+
this.fallbackPollInterval = setInterval(() => {
|
|
1615
|
+
this.fallbackPollFn?.().catch(() => {
|
|
1616
|
+
});
|
|
1617
|
+
}, this.fallbackPollIntervalMs);
|
|
1618
|
+
}
|
|
1619
|
+
stopFallbackPolling() {
|
|
1620
|
+
if (this.fallbackPollInterval) {
|
|
1621
|
+
clearInterval(this.fallbackPollInterval);
|
|
1622
|
+
this.fallbackPollInterval = null;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
// ---------------------------------------------------------------------------
|
|
1626
|
+
// Internal: Logging
|
|
1627
|
+
// ---------------------------------------------------------------------------
|
|
1628
|
+
log(message) {
|
|
1629
|
+
if (this.debugEnabled) {
|
|
1630
|
+
console.log(`[IPNS-WS] ${message}`);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
};
|
|
1634
|
+
|
|
1635
|
+
// impl/shared/ipfs/write-behind-buffer.ts
|
|
1636
|
+
var AsyncSerialQueue = class {
|
|
1637
|
+
tail = Promise.resolve();
|
|
1638
|
+
/** Enqueue an async operation. Returns when it completes. */
|
|
1639
|
+
enqueue(fn) {
|
|
1640
|
+
let resolve;
|
|
1641
|
+
let reject;
|
|
1642
|
+
const promise = new Promise((res, rej) => {
|
|
1643
|
+
resolve = res;
|
|
1644
|
+
reject = rej;
|
|
1645
|
+
});
|
|
1646
|
+
this.tail = this.tail.then(
|
|
1647
|
+
() => fn().then(resolve, reject),
|
|
1648
|
+
() => fn().then(resolve, reject)
|
|
1649
|
+
);
|
|
1650
|
+
return promise;
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
var WriteBuffer = class {
|
|
1654
|
+
/** Full TXF data from save() calls — latest wins */
|
|
1655
|
+
txfData = null;
|
|
1656
|
+
get isEmpty() {
|
|
1657
|
+
return this.txfData === null;
|
|
1658
|
+
}
|
|
1659
|
+
clear() {
|
|
1660
|
+
this.txfData = null;
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Merge another buffer's contents into this one (for rollback).
|
|
1664
|
+
* Existing (newer) mutations in `this` take precedence over `other`.
|
|
1665
|
+
*/
|
|
1666
|
+
mergeFrom(other) {
|
|
1667
|
+
if (other.txfData && !this.txfData) {
|
|
1668
|
+
this.txfData = other.txfData;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
};
|
|
1672
|
+
|
|
1673
|
+
// constants.ts
|
|
1674
|
+
var STORAGE_KEYS_GLOBAL = {
|
|
1675
|
+
/** Encrypted BIP39 mnemonic */
|
|
1676
|
+
MNEMONIC: "mnemonic",
|
|
1677
|
+
/** Encrypted master private key */
|
|
1678
|
+
MASTER_KEY: "master_key",
|
|
1679
|
+
/** BIP32 chain code */
|
|
1680
|
+
CHAIN_CODE: "chain_code",
|
|
1681
|
+
/** HD derivation path (full path like m/44'/0'/0'/0/0) */
|
|
1682
|
+
DERIVATION_PATH: "derivation_path",
|
|
1683
|
+
/** Base derivation path (like m/44'/0'/0' without chain/index) */
|
|
1684
|
+
BASE_PATH: "base_path",
|
|
1685
|
+
/** Derivation mode: bip32, wif_hmac, legacy_hmac */
|
|
1686
|
+
DERIVATION_MODE: "derivation_mode",
|
|
1687
|
+
/** Wallet source: mnemonic, file, unknown */
|
|
1688
|
+
WALLET_SOURCE: "wallet_source",
|
|
1689
|
+
/** Wallet existence flag */
|
|
1690
|
+
WALLET_EXISTS: "wallet_exists",
|
|
1691
|
+
/** Current active address index */
|
|
1692
|
+
CURRENT_ADDRESS_INDEX: "current_address_index",
|
|
1693
|
+
/** Nametag cache per address (separate from tracked addresses registry) */
|
|
1694
|
+
ADDRESS_NAMETAGS: "address_nametags",
|
|
1695
|
+
/** Active addresses registry (JSON: TrackedAddressesStorage) */
|
|
1696
|
+
TRACKED_ADDRESSES: "tracked_addresses",
|
|
1697
|
+
/** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
|
|
1698
|
+
LAST_WALLET_EVENT_TS: "last_wallet_event_ts",
|
|
1699
|
+
/** Group chat: joined groups */
|
|
1700
|
+
GROUP_CHAT_GROUPS: "group_chat_groups",
|
|
1701
|
+
/** Group chat: messages */
|
|
1702
|
+
GROUP_CHAT_MESSAGES: "group_chat_messages",
|
|
1703
|
+
/** Group chat: members */
|
|
1704
|
+
GROUP_CHAT_MEMBERS: "group_chat_members",
|
|
1705
|
+
/** Group chat: processed event IDs for deduplication */
|
|
1706
|
+
GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
|
|
1707
|
+
/** Group chat: last used relay URL (stale data detection) */
|
|
1708
|
+
GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
|
|
1709
|
+
};
|
|
1710
|
+
var STORAGE_KEYS_ADDRESS = {
|
|
1711
|
+
/** Pending transfers for this address */
|
|
1712
|
+
PENDING_TRANSFERS: "pending_transfers",
|
|
1713
|
+
/** Transfer outbox for this address */
|
|
1714
|
+
OUTBOX: "outbox",
|
|
1715
|
+
/** Conversations for this address */
|
|
1716
|
+
CONVERSATIONS: "conversations",
|
|
1717
|
+
/** Messages for this address */
|
|
1718
|
+
MESSAGES: "messages",
|
|
1719
|
+
/** Transaction history for this address */
|
|
1720
|
+
TRANSACTION_HISTORY: "transaction_history",
|
|
1721
|
+
/** Pending V5 finalization tokens (unconfirmed instant split tokens) */
|
|
1722
|
+
PENDING_V5_TOKENS: "pending_v5_tokens"
|
|
1723
|
+
};
|
|
1724
|
+
var STORAGE_KEYS = {
|
|
1725
|
+
...STORAGE_KEYS_GLOBAL,
|
|
1726
|
+
...STORAGE_KEYS_ADDRESS
|
|
1727
|
+
};
|
|
1728
|
+
var UNICITY_IPFS_NODES = [
|
|
1729
|
+
{
|
|
1730
|
+
host: "unicity-ipfs1.dyndns.org",
|
|
1731
|
+
peerId: "12D3KooWDKJqEMAhH4nsSSiKtK1VLcas5coUqSPZAfbWbZpxtL4u",
|
|
1732
|
+
httpPort: 9080,
|
|
1733
|
+
httpsPort: 443
|
|
1734
|
+
}
|
|
1735
|
+
];
|
|
1736
|
+
function getIpfsGatewayUrls(isSecure) {
|
|
1737
|
+
return UNICITY_IPFS_NODES.map(
|
|
1738
|
+
(node) => isSecure !== false ? `https://${node.host}` : `http://${node.host}:${node.httpPort}`
|
|
1739
|
+
);
|
|
1740
|
+
}
|
|
1741
|
+
var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
1742
|
+
var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
|
|
1743
|
+
|
|
1744
|
+
// impl/shared/ipfs/ipfs-storage-provider.ts
|
|
1745
|
+
var IpfsStorageProvider = class {
|
|
1746
|
+
id = "ipfs";
|
|
1747
|
+
name = "IPFS Storage";
|
|
1748
|
+
type = "p2p";
|
|
1749
|
+
status = "disconnected";
|
|
1750
|
+
identity = null;
|
|
1751
|
+
ipnsKeyPair = null;
|
|
1752
|
+
ipnsName = null;
|
|
1753
|
+
ipnsSequenceNumber = 0n;
|
|
1754
|
+
lastCid = null;
|
|
1755
|
+
lastKnownRemoteSequence = 0n;
|
|
1756
|
+
dataVersion = 0;
|
|
1757
|
+
/**
|
|
1758
|
+
* The CID currently stored on the sidecar for this IPNS name.
|
|
1759
|
+
* Used as `_meta.lastCid` in the next save to satisfy chain validation.
|
|
1760
|
+
* - null for bootstrap (first-ever save)
|
|
1761
|
+
* - set after every successful save() or load()
|
|
1762
|
+
*/
|
|
1763
|
+
remoteCid = null;
|
|
1764
|
+
cache;
|
|
1765
|
+
httpClient;
|
|
1766
|
+
statePersistence;
|
|
1767
|
+
eventCallbacks = /* @__PURE__ */ new Set();
|
|
1768
|
+
debug;
|
|
1769
|
+
ipnsLifetimeMs;
|
|
1770
|
+
/** WebSocket factory for push subscriptions */
|
|
1771
|
+
createWebSocket;
|
|
1772
|
+
/** Override WS URL */
|
|
1773
|
+
wsUrl;
|
|
1774
|
+
/** Fallback poll interval (default: 90000) */
|
|
1775
|
+
fallbackPollIntervalMs;
|
|
1776
|
+
/** IPNS subscription client for push notifications */
|
|
1777
|
+
subscriptionClient = null;
|
|
1778
|
+
/** Unsubscribe function from subscription client */
|
|
1779
|
+
subscriptionUnsubscribe = null;
|
|
1780
|
+
/** Write-behind buffer: serializes flush / sync / shutdown */
|
|
1781
|
+
flushQueue = new AsyncSerialQueue();
|
|
1782
|
+
/** Pending mutations not yet flushed to IPFS */
|
|
1783
|
+
pendingBuffer = new WriteBuffer();
|
|
1784
|
+
/** Debounce timer for background flush */
|
|
1785
|
+
flushTimer = null;
|
|
1786
|
+
/** Debounce interval in ms */
|
|
1787
|
+
flushDebounceMs;
|
|
1788
|
+
/** Set to true during shutdown to prevent new flushes */
|
|
1789
|
+
isShuttingDown = false;
|
|
1790
|
+
constructor(config, statePersistence) {
|
|
1791
|
+
const gateways = config?.gateways ?? getIpfsGatewayUrls();
|
|
1792
|
+
this.debug = config?.debug ?? false;
|
|
1793
|
+
this.ipnsLifetimeMs = config?.ipnsLifetimeMs ?? 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
1794
|
+
this.flushDebounceMs = config?.flushDebounceMs ?? 2e3;
|
|
1795
|
+
this.cache = new IpfsCache({
|
|
1796
|
+
ipnsTtlMs: config?.ipnsCacheTtlMs,
|
|
1797
|
+
failureCooldownMs: config?.circuitBreakerCooldownMs,
|
|
1798
|
+
failureThreshold: config?.circuitBreakerThreshold,
|
|
1799
|
+
knownFreshWindowMs: config?.knownFreshWindowMs
|
|
1800
|
+
});
|
|
1801
|
+
this.httpClient = new IpfsHttpClient({
|
|
1802
|
+
gateways,
|
|
1803
|
+
fetchTimeoutMs: config?.fetchTimeoutMs,
|
|
1804
|
+
resolveTimeoutMs: config?.resolveTimeoutMs,
|
|
1805
|
+
publishTimeoutMs: config?.publishTimeoutMs,
|
|
1806
|
+
connectivityTimeoutMs: config?.connectivityTimeoutMs,
|
|
1807
|
+
debug: this.debug
|
|
1808
|
+
}, this.cache);
|
|
1809
|
+
this.statePersistence = statePersistence ?? new InMemoryIpfsStatePersistence();
|
|
1810
|
+
this.createWebSocket = config?.createWebSocket;
|
|
1811
|
+
this.wsUrl = config?.wsUrl;
|
|
1812
|
+
this.fallbackPollIntervalMs = config?.fallbackPollIntervalMs ?? 9e4;
|
|
1813
|
+
}
|
|
1814
|
+
// ---------------------------------------------------------------------------
|
|
1815
|
+
// BaseProvider interface
|
|
1816
|
+
// ---------------------------------------------------------------------------
|
|
1817
|
+
async connect() {
|
|
1818
|
+
await this.initialize();
|
|
1819
|
+
}
|
|
1820
|
+
async disconnect() {
|
|
1821
|
+
await this.shutdown();
|
|
1822
|
+
}
|
|
1823
|
+
isConnected() {
|
|
1824
|
+
return this.status === "connected";
|
|
1825
|
+
}
|
|
1826
|
+
getStatus() {
|
|
1827
|
+
return this.status;
|
|
1828
|
+
}
|
|
1829
|
+
// ---------------------------------------------------------------------------
|
|
1830
|
+
// Identity & Initialization
|
|
1831
|
+
// ---------------------------------------------------------------------------
|
|
1832
|
+
setIdentity(identity) {
|
|
1833
|
+
this.identity = identity;
|
|
1834
|
+
}
|
|
1835
|
+
async initialize() {
|
|
1836
|
+
if (!this.identity) {
|
|
1837
|
+
this.log("Cannot initialize: no identity set");
|
|
1838
|
+
return false;
|
|
1839
|
+
}
|
|
1840
|
+
this.status = "connecting";
|
|
1841
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
957
1842
|
try {
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
|
|
1843
|
+
const { keyPair, ipnsName } = await deriveIpnsIdentity(this.identity.privateKey);
|
|
1844
|
+
this.ipnsKeyPair = keyPair;
|
|
1845
|
+
this.ipnsName = ipnsName;
|
|
1846
|
+
this.log(`IPNS name derived: ${ipnsName}`);
|
|
1847
|
+
const persisted = await this.statePersistence.load(ipnsName);
|
|
1848
|
+
if (persisted) {
|
|
1849
|
+
this.ipnsSequenceNumber = BigInt(persisted.sequenceNumber);
|
|
1850
|
+
this.lastCid = persisted.lastCid;
|
|
1851
|
+
this.remoteCid = persisted.lastCid;
|
|
1852
|
+
this.dataVersion = persisted.version;
|
|
1853
|
+
this.log(`Loaded persisted state: seq=${this.ipnsSequenceNumber}, cid=${this.lastCid}`);
|
|
1854
|
+
}
|
|
1855
|
+
if (this.createWebSocket) {
|
|
1856
|
+
try {
|
|
1857
|
+
const wsUrlFinal = this.wsUrl ?? this.deriveWsUrl();
|
|
1858
|
+
if (wsUrlFinal) {
|
|
1859
|
+
this.subscriptionClient = new IpnsSubscriptionClient({
|
|
1860
|
+
wsUrl: wsUrlFinal,
|
|
1861
|
+
createWebSocket: this.createWebSocket,
|
|
1862
|
+
debug: this.debug
|
|
1863
|
+
});
|
|
1864
|
+
this.subscriptionUnsubscribe = this.subscriptionClient.subscribe(
|
|
1865
|
+
ipnsName,
|
|
1866
|
+
(update) => {
|
|
1867
|
+
this.log(`Push update: seq=${update.sequence}, cid=${update.cid}`);
|
|
1868
|
+
this.emitEvent({
|
|
1869
|
+
type: "storage:remote-updated",
|
|
1870
|
+
timestamp: Date.now(),
|
|
1871
|
+
data: { name: update.name, sequence: update.sequence, cid: update.cid }
|
|
1872
|
+
});
|
|
1873
|
+
}
|
|
1874
|
+
);
|
|
1875
|
+
this.subscriptionClient.setFallbackPoll(
|
|
1876
|
+
() => this.pollForRemoteChanges(),
|
|
1877
|
+
this.fallbackPollIntervalMs
|
|
1878
|
+
);
|
|
1879
|
+
this.subscriptionClient.connect();
|
|
1880
|
+
}
|
|
1881
|
+
} catch (wsError) {
|
|
1882
|
+
this.log(`Failed to set up IPNS subscription: ${wsError}`);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
this.httpClient.findHealthyGateways().then((healthy) => {
|
|
1886
|
+
if (healthy.length > 0) {
|
|
1887
|
+
this.log(`${healthy.length} healthy gateway(s) found`);
|
|
1888
|
+
} else {
|
|
1889
|
+
this.log("Warning: no healthy gateways found");
|
|
1890
|
+
}
|
|
1891
|
+
}).catch(() => {
|
|
961
1892
|
});
|
|
962
|
-
|
|
963
|
-
|
|
1893
|
+
this.isShuttingDown = false;
|
|
1894
|
+
this.status = "connected";
|
|
1895
|
+
this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
|
|
1896
|
+
return true;
|
|
1897
|
+
} catch (error) {
|
|
1898
|
+
this.status = "error";
|
|
1899
|
+
this.emitEvent({
|
|
1900
|
+
type: "storage:error",
|
|
1901
|
+
timestamp: Date.now(),
|
|
1902
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1903
|
+
});
|
|
1904
|
+
return false;
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
async shutdown() {
|
|
1908
|
+
this.isShuttingDown = true;
|
|
1909
|
+
if (this.flushTimer) {
|
|
1910
|
+
clearTimeout(this.flushTimer);
|
|
1911
|
+
this.flushTimer = null;
|
|
1912
|
+
}
|
|
1913
|
+
await this.flushQueue.enqueue(async () => {
|
|
1914
|
+
if (!this.pendingBuffer.isEmpty) {
|
|
1915
|
+
try {
|
|
1916
|
+
await this.executeFlush();
|
|
1917
|
+
} catch {
|
|
1918
|
+
this.log("Final flush on shutdown failed (data may be lost)");
|
|
1919
|
+
}
|
|
964
1920
|
}
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
1921
|
+
});
|
|
1922
|
+
if (this.subscriptionUnsubscribe) {
|
|
1923
|
+
this.subscriptionUnsubscribe();
|
|
1924
|
+
this.subscriptionUnsubscribe = null;
|
|
1925
|
+
}
|
|
1926
|
+
if (this.subscriptionClient) {
|
|
1927
|
+
this.subscriptionClient.disconnect();
|
|
1928
|
+
this.subscriptionClient = null;
|
|
969
1929
|
}
|
|
1930
|
+
this.cache.clear();
|
|
1931
|
+
this.status = "disconnected";
|
|
970
1932
|
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
1933
|
+
// ---------------------------------------------------------------------------
|
|
1934
|
+
// Save (non-blocking — buffers data for async flush)
|
|
1935
|
+
// ---------------------------------------------------------------------------
|
|
1936
|
+
async save(data) {
|
|
1937
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
1938
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
975
1939
|
}
|
|
976
|
-
|
|
977
|
-
|
|
1940
|
+
this.pendingBuffer.txfData = data;
|
|
1941
|
+
this.scheduleFlush();
|
|
1942
|
+
return { success: true, timestamp: Date.now() };
|
|
1943
|
+
}
|
|
1944
|
+
// ---------------------------------------------------------------------------
|
|
1945
|
+
// Internal: Blocking save (used by sync and executeFlush)
|
|
1946
|
+
// ---------------------------------------------------------------------------
|
|
1947
|
+
/**
|
|
1948
|
+
* Perform the actual upload + IPNS publish synchronously.
|
|
1949
|
+
* Called by executeFlush() and sync() — never by public save().
|
|
1950
|
+
*/
|
|
1951
|
+
async _doSave(data) {
|
|
1952
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
1953
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
1954
|
+
}
|
|
1955
|
+
this.emitEvent({ type: "storage:saving", timestamp: Date.now() });
|
|
1956
|
+
try {
|
|
1957
|
+
this.dataVersion++;
|
|
1958
|
+
const metaUpdate = {
|
|
1959
|
+
...data._meta,
|
|
1960
|
+
version: this.dataVersion,
|
|
1961
|
+
ipnsName: this.ipnsName,
|
|
1962
|
+
updatedAt: Date.now()
|
|
1963
|
+
};
|
|
1964
|
+
if (this.remoteCid) {
|
|
1965
|
+
metaUpdate.lastCid = this.remoteCid;
|
|
1966
|
+
}
|
|
1967
|
+
const updatedData = { ...data, _meta: metaUpdate };
|
|
1968
|
+
const { cid } = await this.httpClient.upload(updatedData);
|
|
1969
|
+
this.log(`Content uploaded: CID=${cid}`);
|
|
1970
|
+
const baseSeq = this.ipnsSequenceNumber > this.lastKnownRemoteSequence ? this.ipnsSequenceNumber : this.lastKnownRemoteSequence;
|
|
1971
|
+
const newSeq = baseSeq + 1n;
|
|
1972
|
+
const marshalledRecord = await createSignedRecord(
|
|
1973
|
+
this.ipnsKeyPair,
|
|
1974
|
+
cid,
|
|
1975
|
+
newSeq,
|
|
1976
|
+
this.ipnsLifetimeMs
|
|
1977
|
+
);
|
|
1978
|
+
const publishResult = await this.httpClient.publishIpns(
|
|
1979
|
+
this.ipnsName,
|
|
1980
|
+
marshalledRecord
|
|
1981
|
+
);
|
|
1982
|
+
if (!publishResult.success) {
|
|
1983
|
+
this.dataVersion--;
|
|
1984
|
+
this.log(`IPNS publish failed: ${publishResult.error}`);
|
|
1985
|
+
return {
|
|
1986
|
+
success: false,
|
|
1987
|
+
error: publishResult.error ?? "IPNS publish failed",
|
|
1988
|
+
timestamp: Date.now()
|
|
1989
|
+
};
|
|
1990
|
+
}
|
|
1991
|
+
this.ipnsSequenceNumber = newSeq;
|
|
1992
|
+
this.lastCid = cid;
|
|
1993
|
+
this.remoteCid = cid;
|
|
1994
|
+
this.cache.setIpnsRecord(this.ipnsName, {
|
|
1995
|
+
cid,
|
|
1996
|
+
sequence: newSeq,
|
|
1997
|
+
gateway: "local"
|
|
1998
|
+
});
|
|
1999
|
+
this.cache.setContent(cid, updatedData);
|
|
2000
|
+
this.cache.markIpnsFresh(this.ipnsName);
|
|
2001
|
+
await this.statePersistence.save(this.ipnsName, {
|
|
2002
|
+
sequenceNumber: newSeq.toString(),
|
|
2003
|
+
lastCid: cid,
|
|
2004
|
+
version: this.dataVersion
|
|
2005
|
+
});
|
|
2006
|
+
this.emitEvent({
|
|
2007
|
+
type: "storage:saved",
|
|
2008
|
+
timestamp: Date.now(),
|
|
2009
|
+
data: { cid, sequence: newSeq.toString() }
|
|
2010
|
+
});
|
|
2011
|
+
this.log(`Saved: CID=${cid}, seq=${newSeq}`);
|
|
2012
|
+
return { success: true, cid, timestamp: Date.now() };
|
|
2013
|
+
} catch (error) {
|
|
2014
|
+
this.dataVersion--;
|
|
2015
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2016
|
+
this.emitEvent({
|
|
2017
|
+
type: "storage:error",
|
|
2018
|
+
timestamp: Date.now(),
|
|
2019
|
+
error: errorMessage
|
|
2020
|
+
});
|
|
2021
|
+
return { success: false, error: errorMessage, timestamp: Date.now() };
|
|
978
2022
|
}
|
|
979
|
-
return Promise.any(promises);
|
|
980
2023
|
}
|
|
2024
|
+
// ---------------------------------------------------------------------------
|
|
2025
|
+
// Write-behind buffer: scheduling and flushing
|
|
2026
|
+
// ---------------------------------------------------------------------------
|
|
981
2027
|
/**
|
|
982
|
-
*
|
|
2028
|
+
* Schedule a debounced background flush.
|
|
2029
|
+
* Resets the timer on each call so rapid mutations coalesce.
|
|
983
2030
|
*/
|
|
984
|
-
|
|
985
|
-
if (
|
|
986
|
-
|
|
2031
|
+
scheduleFlush() {
|
|
2032
|
+
if (this.isShuttingDown) return;
|
|
2033
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
2034
|
+
this.flushTimer = setTimeout(() => {
|
|
2035
|
+
this.flushTimer = null;
|
|
2036
|
+
this.flushQueue.enqueue(() => this.executeFlush()).catch((err) => {
|
|
2037
|
+
this.log(`Background flush failed: ${err}`);
|
|
2038
|
+
});
|
|
2039
|
+
}, this.flushDebounceMs);
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* Execute a flush of the pending buffer to IPFS.
|
|
2043
|
+
* Runs inside AsyncSerialQueue for concurrency safety.
|
|
2044
|
+
*/
|
|
2045
|
+
async executeFlush() {
|
|
2046
|
+
if (this.pendingBuffer.isEmpty) return;
|
|
2047
|
+
const active = this.pendingBuffer;
|
|
2048
|
+
this.pendingBuffer = new WriteBuffer();
|
|
2049
|
+
try {
|
|
2050
|
+
const baseData = active.txfData ?? {
|
|
2051
|
+
_meta: { version: 0, address: this.identity?.directAddress ?? "", formatVersion: "2.0", updatedAt: 0 }
|
|
2052
|
+
};
|
|
2053
|
+
const result = await this._doSave(baseData);
|
|
2054
|
+
if (!result.success) {
|
|
2055
|
+
throw new Error(result.error ?? "Save failed");
|
|
2056
|
+
}
|
|
2057
|
+
this.log(`Flushed successfully: CID=${result.cid}`);
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
this.pendingBuffer.mergeFrom(active);
|
|
2060
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2061
|
+
this.log(`Flush failed (will retry): ${msg}`);
|
|
2062
|
+
this.scheduleFlush();
|
|
2063
|
+
throw error;
|
|
987
2064
|
}
|
|
988
|
-
const { CID } = await loadHeliaModules();
|
|
989
|
-
const cid = CID.parse(cidString);
|
|
990
|
-
const data = await this.heliaJson.get(cid);
|
|
991
|
-
this.log("Fetched via Helia, CID:", cidString);
|
|
992
|
-
return data;
|
|
993
2065
|
}
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
2066
|
+
// ---------------------------------------------------------------------------
|
|
2067
|
+
// Load
|
|
2068
|
+
// ---------------------------------------------------------------------------
|
|
2069
|
+
async load(identifier) {
|
|
2070
|
+
if (!this.ipnsName && !identifier) {
|
|
2071
|
+
return { success: false, error: "Not initialized", source: "local", timestamp: Date.now() };
|
|
2072
|
+
}
|
|
2073
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
997
2074
|
try {
|
|
998
|
-
|
|
999
|
-
|
|
2075
|
+
if (identifier) {
|
|
2076
|
+
const data2 = await this.httpClient.fetchContent(identifier);
|
|
2077
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
2078
|
+
}
|
|
2079
|
+
const ipnsName = this.ipnsName;
|
|
2080
|
+
if (this.cache.isIpnsKnownFresh(ipnsName)) {
|
|
2081
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(ipnsName);
|
|
2082
|
+
if (cached) {
|
|
2083
|
+
const content = this.cache.getContent(cached.cid);
|
|
2084
|
+
if (content) {
|
|
2085
|
+
this.log("Using known-fresh cached data");
|
|
2086
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
const cachedRecord = this.cache.getIpnsRecord(ipnsName);
|
|
2091
|
+
if (cachedRecord) {
|
|
2092
|
+
const content = this.cache.getContent(cachedRecord.cid);
|
|
2093
|
+
if (content) {
|
|
2094
|
+
this.log("IPNS cache hit");
|
|
2095
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2096
|
+
}
|
|
2097
|
+
try {
|
|
2098
|
+
const data2 = await this.httpClient.fetchContent(cachedRecord.cid);
|
|
2099
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
2100
|
+
} catch {
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
const { best } = await this.httpClient.resolveIpns(ipnsName);
|
|
2104
|
+
if (!best) {
|
|
2105
|
+
this.log("IPNS record not found (new wallet?)");
|
|
2106
|
+
return { success: false, error: "IPNS record not found", source: "remote", timestamp: Date.now() };
|
|
2107
|
+
}
|
|
2108
|
+
if (best.sequence > this.lastKnownRemoteSequence) {
|
|
2109
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
2110
|
+
}
|
|
2111
|
+
this.remoteCid = best.cid;
|
|
2112
|
+
const data = await this.httpClient.fetchContent(best.cid);
|
|
2113
|
+
const remoteVersion = data?._meta?.version;
|
|
2114
|
+
if (typeof remoteVersion === "number" && remoteVersion > this.dataVersion) {
|
|
2115
|
+
this.dataVersion = remoteVersion;
|
|
2116
|
+
}
|
|
2117
|
+
this.emitEvent({
|
|
2118
|
+
type: "storage:loaded",
|
|
2119
|
+
timestamp: Date.now(),
|
|
2120
|
+
data: { cid: best.cid, sequence: best.sequence.toString() }
|
|
1000
2121
|
});
|
|
1001
|
-
|
|
1002
|
-
|
|
2122
|
+
return { success: true, data, source: "remote", timestamp: Date.now() };
|
|
2123
|
+
} catch (error) {
|
|
2124
|
+
if (this.ipnsName) {
|
|
2125
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(this.ipnsName);
|
|
2126
|
+
if (cached) {
|
|
2127
|
+
const content = this.cache.getContent(cached.cid);
|
|
2128
|
+
if (content) {
|
|
2129
|
+
this.log("Network error, returning stale cache");
|
|
2130
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
1003
2133
|
}
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
const existing = tombstones.get(t.tokenId);
|
|
1022
|
-
if (!existing || t.timestamp > existing.timestamp) {
|
|
1023
|
-
tombstones.set(t.tokenId, t);
|
|
2134
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2135
|
+
this.emitEvent({
|
|
2136
|
+
type: "storage:error",
|
|
2137
|
+
timestamp: Date.now(),
|
|
2138
|
+
error: errorMessage
|
|
2139
|
+
});
|
|
2140
|
+
return { success: false, error: errorMessage, source: "remote", timestamp: Date.now() };
|
|
2141
|
+
}
|
|
2142
|
+
}
|
|
2143
|
+
// ---------------------------------------------------------------------------
|
|
2144
|
+
// Sync (enters serial queue to avoid concurrent IPNS conflicts)
|
|
2145
|
+
// ---------------------------------------------------------------------------
|
|
2146
|
+
async sync(localData) {
|
|
2147
|
+
return this.flushQueue.enqueue(async () => {
|
|
2148
|
+
if (this.flushTimer) {
|
|
2149
|
+
clearTimeout(this.flushTimer);
|
|
2150
|
+
this.flushTimer = null;
|
|
1024
2151
|
}
|
|
2152
|
+
this.emitEvent({ type: "sync:started", timestamp: Date.now() });
|
|
2153
|
+
try {
|
|
2154
|
+
this.pendingBuffer.clear();
|
|
2155
|
+
const remoteResult = await this.load();
|
|
2156
|
+
if (!remoteResult.success || !remoteResult.data) {
|
|
2157
|
+
this.log("No remote data found, uploading local data");
|
|
2158
|
+
const saveResult2 = await this._doSave(localData);
|
|
2159
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
2160
|
+
return {
|
|
2161
|
+
success: saveResult2.success,
|
|
2162
|
+
merged: localData,
|
|
2163
|
+
added: 0,
|
|
2164
|
+
removed: 0,
|
|
2165
|
+
conflicts: 0,
|
|
2166
|
+
error: saveResult2.error
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
const remoteData = remoteResult.data;
|
|
2170
|
+
const localVersion = localData._meta?.version ?? 0;
|
|
2171
|
+
const remoteVersion = remoteData._meta?.version ?? 0;
|
|
2172
|
+
if (localVersion === remoteVersion && this.lastCid) {
|
|
2173
|
+
this.log("Data is in sync (same version)");
|
|
2174
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
2175
|
+
return {
|
|
2176
|
+
success: true,
|
|
2177
|
+
merged: localData,
|
|
2178
|
+
added: 0,
|
|
2179
|
+
removed: 0,
|
|
2180
|
+
conflicts: 0
|
|
2181
|
+
};
|
|
2182
|
+
}
|
|
2183
|
+
this.log(`Merging: local v${localVersion} <-> remote v${remoteVersion}`);
|
|
2184
|
+
const { merged, added, removed, conflicts } = mergeTxfData(localData, remoteData);
|
|
2185
|
+
if (conflicts > 0) {
|
|
2186
|
+
this.emitEvent({
|
|
2187
|
+
type: "sync:conflict",
|
|
2188
|
+
timestamp: Date.now(),
|
|
2189
|
+
data: { conflicts }
|
|
2190
|
+
});
|
|
2191
|
+
}
|
|
2192
|
+
const saveResult = await this._doSave(merged);
|
|
2193
|
+
this.emitEvent({
|
|
2194
|
+
type: "sync:completed",
|
|
2195
|
+
timestamp: Date.now(),
|
|
2196
|
+
data: { added, removed, conflicts }
|
|
2197
|
+
});
|
|
2198
|
+
return {
|
|
2199
|
+
success: saveResult.success,
|
|
2200
|
+
merged,
|
|
2201
|
+
added,
|
|
2202
|
+
removed,
|
|
2203
|
+
conflicts,
|
|
2204
|
+
error: saveResult.error
|
|
2205
|
+
};
|
|
2206
|
+
} catch (error) {
|
|
2207
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2208
|
+
this.emitEvent({
|
|
2209
|
+
type: "sync:error",
|
|
2210
|
+
timestamp: Date.now(),
|
|
2211
|
+
error: errorMessage
|
|
2212
|
+
});
|
|
2213
|
+
return {
|
|
2214
|
+
success: false,
|
|
2215
|
+
added: 0,
|
|
2216
|
+
removed: 0,
|
|
2217
|
+
conflicts: 0,
|
|
2218
|
+
error: errorMessage
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
// ---------------------------------------------------------------------------
|
|
2224
|
+
// Private Helpers
|
|
2225
|
+
// ---------------------------------------------------------------------------
|
|
2226
|
+
// ---------------------------------------------------------------------------
|
|
2227
|
+
// Optional Methods
|
|
2228
|
+
// ---------------------------------------------------------------------------
|
|
2229
|
+
async exists() {
|
|
2230
|
+
if (!this.ipnsName) return false;
|
|
2231
|
+
const cached = this.cache.getIpnsRecord(this.ipnsName);
|
|
2232
|
+
if (cached) return true;
|
|
2233
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
2234
|
+
return best !== null;
|
|
2235
|
+
}
|
|
2236
|
+
async clear() {
|
|
2237
|
+
if (!this.ipnsKeyPair || !this.ipnsName) return false;
|
|
2238
|
+
this.pendingBuffer.clear();
|
|
2239
|
+
if (this.flushTimer) {
|
|
2240
|
+
clearTimeout(this.flushTimer);
|
|
2241
|
+
this.flushTimer = null;
|
|
1025
2242
|
}
|
|
1026
|
-
const
|
|
2243
|
+
const emptyData = {
|
|
1027
2244
|
_meta: {
|
|
1028
|
-
|
|
1029
|
-
|
|
2245
|
+
version: 0,
|
|
2246
|
+
address: this.identity?.directAddress ?? "",
|
|
2247
|
+
ipnsName: this.ipnsName,
|
|
2248
|
+
formatVersion: "2.0",
|
|
1030
2249
|
updatedAt: Date.now()
|
|
1031
|
-
},
|
|
1032
|
-
_tombstones: Array.from(tombstones.values())
|
|
1033
|
-
};
|
|
1034
|
-
let added = 0;
|
|
1035
|
-
let conflicts = 0;
|
|
1036
|
-
const processedKeys = /* @__PURE__ */ new Set();
|
|
1037
|
-
for (const key of Object.keys(local)) {
|
|
1038
|
-
if (!key.startsWith("_") || key === "_meta" || key === "_tombstones") continue;
|
|
1039
|
-
processedKeys.add(key);
|
|
1040
|
-
const tokenId = key.slice(1);
|
|
1041
|
-
if (tombstones.has(tokenId)) continue;
|
|
1042
|
-
const localToken = local[key];
|
|
1043
|
-
const remoteToken = remote[key];
|
|
1044
|
-
if (remoteToken) {
|
|
1045
|
-
conflicts++;
|
|
1046
|
-
merged[key] = localToken;
|
|
1047
|
-
} else {
|
|
1048
|
-
merged[key] = localToken;
|
|
1049
2250
|
}
|
|
2251
|
+
};
|
|
2252
|
+
const result = await this._doSave(emptyData);
|
|
2253
|
+
if (result.success) {
|
|
2254
|
+
this.cache.clear();
|
|
2255
|
+
await this.statePersistence.clear(this.ipnsName);
|
|
1050
2256
|
}
|
|
1051
|
-
|
|
1052
|
-
if (!key.startsWith("_") || key === "_meta" || key === "_tombstones") continue;
|
|
1053
|
-
if (processedKeys.has(key)) continue;
|
|
1054
|
-
const tokenId = key.slice(1);
|
|
1055
|
-
if (tombstones.has(tokenId)) continue;
|
|
1056
|
-
merged[key] = remote[key];
|
|
1057
|
-
added++;
|
|
1058
|
-
}
|
|
1059
|
-
return { merged, added, removed: 0, conflicts };
|
|
2257
|
+
return result.success;
|
|
1060
2258
|
}
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
2259
|
+
onEvent(callback) {
|
|
2260
|
+
this.eventCallbacks.add(callback);
|
|
2261
|
+
return () => {
|
|
2262
|
+
this.eventCallbacks.delete(callback);
|
|
2263
|
+
};
|
|
2264
|
+
}
|
|
2265
|
+
// ---------------------------------------------------------------------------
|
|
2266
|
+
// Public Accessors
|
|
2267
|
+
// ---------------------------------------------------------------------------
|
|
2268
|
+
getIpnsName() {
|
|
2269
|
+
return this.ipnsName;
|
|
2270
|
+
}
|
|
2271
|
+
getLastCid() {
|
|
2272
|
+
return this.lastCid;
|
|
2273
|
+
}
|
|
2274
|
+
getSequenceNumber() {
|
|
2275
|
+
return this.ipnsSequenceNumber;
|
|
2276
|
+
}
|
|
2277
|
+
getDataVersion() {
|
|
2278
|
+
return this.dataVersion;
|
|
2279
|
+
}
|
|
2280
|
+
getRemoteCid() {
|
|
2281
|
+
return this.remoteCid;
|
|
2282
|
+
}
|
|
2283
|
+
// ---------------------------------------------------------------------------
|
|
2284
|
+
// Testing helper: wait for pending flush to complete
|
|
2285
|
+
// ---------------------------------------------------------------------------
|
|
2286
|
+
/**
|
|
2287
|
+
* Wait for the pending flush timer to fire and the flush operation to
|
|
2288
|
+
* complete. Useful in tests to await background writes.
|
|
2289
|
+
* Returns immediately if no flush is pending.
|
|
2290
|
+
*/
|
|
2291
|
+
async waitForFlush() {
|
|
2292
|
+
if (this.flushTimer) {
|
|
2293
|
+
clearTimeout(this.flushTimer);
|
|
2294
|
+
this.flushTimer = null;
|
|
2295
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
2296
|
+
});
|
|
2297
|
+
} else if (!this.pendingBuffer.isEmpty) {
|
|
2298
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
2299
|
+
});
|
|
2300
|
+
} else {
|
|
2301
|
+
await this.flushQueue.enqueue(async () => {
|
|
2302
|
+
});
|
|
1070
2303
|
}
|
|
1071
2304
|
}
|
|
2305
|
+
// ---------------------------------------------------------------------------
|
|
2306
|
+
// Internal: Push Subscription Helpers
|
|
2307
|
+
// ---------------------------------------------------------------------------
|
|
1072
2308
|
/**
|
|
1073
|
-
*
|
|
2309
|
+
* Derive WebSocket URL from the first configured gateway.
|
|
2310
|
+
* Converts https://host → wss://host/ws/ipns
|
|
1074
2311
|
*/
|
|
1075
|
-
|
|
1076
|
-
|
|
2312
|
+
deriveWsUrl() {
|
|
2313
|
+
const gateways = this.httpClient.getGateways();
|
|
2314
|
+
if (gateways.length === 0) return null;
|
|
2315
|
+
const gateway = gateways[0];
|
|
2316
|
+
const wsProtocol = gateway.startsWith("https://") ? "wss://" : "ws://";
|
|
2317
|
+
const host = gateway.replace(/^https?:\/\//, "");
|
|
2318
|
+
return `${wsProtocol}${host}/ws/ipns`;
|
|
1077
2319
|
}
|
|
1078
2320
|
/**
|
|
1079
|
-
*
|
|
2321
|
+
* Poll for remote IPNS changes (fallback when WS is unavailable).
|
|
2322
|
+
* Compares remote sequence number with last known and emits event if changed.
|
|
1080
2323
|
*/
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
2324
|
+
async pollForRemoteChanges() {
|
|
2325
|
+
if (!this.ipnsName) return;
|
|
2326
|
+
try {
|
|
2327
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
2328
|
+
if (best && best.sequence > this.lastKnownRemoteSequence) {
|
|
2329
|
+
this.log(`Poll detected remote change: seq=${best.sequence} (was ${this.lastKnownRemoteSequence})`);
|
|
2330
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
2331
|
+
this.emitEvent({
|
|
2332
|
+
type: "storage:remote-updated",
|
|
2333
|
+
timestamp: Date.now(),
|
|
2334
|
+
data: { name: this.ipnsName, sequence: Number(best.sequence), cid: best.cid }
|
|
2335
|
+
});
|
|
2336
|
+
}
|
|
2337
|
+
} catch {
|
|
1085
2338
|
}
|
|
1086
|
-
return bytes;
|
|
1087
2339
|
}
|
|
2340
|
+
// ---------------------------------------------------------------------------
|
|
2341
|
+
// Internal
|
|
2342
|
+
// ---------------------------------------------------------------------------
|
|
1088
2343
|
emitEvent(event) {
|
|
1089
2344
|
for (const callback of this.eventCallbacks) {
|
|
1090
2345
|
try {
|
|
1091
2346
|
callback(event);
|
|
1092
|
-
} catch
|
|
1093
|
-
console.error("[IpfsStorageProvider] Event callback error:", error);
|
|
2347
|
+
} catch {
|
|
1094
2348
|
}
|
|
1095
2349
|
}
|
|
1096
2350
|
}
|
|
1097
|
-
log(
|
|
1098
|
-
if (this.
|
|
1099
|
-
console.log(
|
|
2351
|
+
log(message) {
|
|
2352
|
+
if (this.debug) {
|
|
2353
|
+
console.log(`[IPFS-Storage] ${message}`);
|
|
1100
2354
|
}
|
|
1101
2355
|
}
|
|
1102
2356
|
};
|
|
1103
|
-
|
|
1104
|
-
|
|
2357
|
+
|
|
2358
|
+
// impl/browser/ipfs/browser-ipfs-state-persistence.ts
|
|
2359
|
+
var KEY_PREFIX = "sphere_ipfs_";
|
|
2360
|
+
function seqKey(ipnsName) {
|
|
2361
|
+
return `${KEY_PREFIX}seq_${ipnsName}`;
|
|
2362
|
+
}
|
|
2363
|
+
function cidKey(ipnsName) {
|
|
2364
|
+
return `${KEY_PREFIX}cid_${ipnsName}`;
|
|
2365
|
+
}
|
|
2366
|
+
function verKey(ipnsName) {
|
|
2367
|
+
return `${KEY_PREFIX}ver_${ipnsName}`;
|
|
2368
|
+
}
|
|
2369
|
+
var BrowserIpfsStatePersistence = class {
|
|
2370
|
+
async load(ipnsName) {
|
|
2371
|
+
try {
|
|
2372
|
+
const seq = localStorage.getItem(seqKey(ipnsName));
|
|
2373
|
+
if (!seq) return null;
|
|
2374
|
+
return {
|
|
2375
|
+
sequenceNumber: seq,
|
|
2376
|
+
lastCid: localStorage.getItem(cidKey(ipnsName)),
|
|
2377
|
+
version: parseInt(localStorage.getItem(verKey(ipnsName)) ?? "0", 10)
|
|
2378
|
+
};
|
|
2379
|
+
} catch {
|
|
2380
|
+
return null;
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
async save(ipnsName, state) {
|
|
2384
|
+
try {
|
|
2385
|
+
localStorage.setItem(seqKey(ipnsName), state.sequenceNumber);
|
|
2386
|
+
if (state.lastCid) {
|
|
2387
|
+
localStorage.setItem(cidKey(ipnsName), state.lastCid);
|
|
2388
|
+
} else {
|
|
2389
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
2390
|
+
}
|
|
2391
|
+
localStorage.setItem(verKey(ipnsName), String(state.version));
|
|
2392
|
+
} catch {
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
async clear(ipnsName) {
|
|
2396
|
+
try {
|
|
2397
|
+
localStorage.removeItem(seqKey(ipnsName));
|
|
2398
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
2399
|
+
localStorage.removeItem(verKey(ipnsName));
|
|
2400
|
+
} catch {
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
};
|
|
2404
|
+
|
|
2405
|
+
// impl/browser/ipfs/index.ts
|
|
2406
|
+
function createBrowserWebSocket(url) {
|
|
2407
|
+
return new WebSocket(url);
|
|
2408
|
+
}
|
|
2409
|
+
function createBrowserIpfsStorageProvider(config) {
|
|
2410
|
+
return new IpfsStorageProvider(
|
|
2411
|
+
{ ...config, createWebSocket: config?.createWebSocket ?? createBrowserWebSocket },
|
|
2412
|
+
new BrowserIpfsStatePersistence()
|
|
2413
|
+
);
|
|
1105
2414
|
}
|
|
2415
|
+
var createIpfsStorageProvider = createBrowserIpfsStorageProvider;
|
|
1106
2416
|
/*! Bundled license information:
|
|
1107
2417
|
|
|
1108
2418
|
@noble/hashes/utils.js:
|