@tangle-network/blueprint-ui 0.3.1 → 0.4.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.
@@ -0,0 +1,136 @@
1
+ import { Address, Hex } from 'viem';
2
+
3
+ declare const TANGLE_IFRAME_PROTOCOL_VERSION: "1";
4
+ declare const TANGLE_IFRAME_PROTOCOL_PREFIX = "tangle.app.";
5
+ type HandshakeRequest = {
6
+ kind: 'tangle.app.handshake';
7
+ appId: string;
8
+ version: typeof TANGLE_IFRAME_PROTOCOL_VERSION;
9
+ };
10
+ type ReadAccountRequest = {
11
+ kind: 'tangle.app.readAccount';
12
+ correlationId: string;
13
+ };
14
+ type SwitchChainRequest = {
15
+ kind: 'tangle.app.switchChain';
16
+ correlationId: string;
17
+ chainId: number;
18
+ };
19
+ type SignMessageRequest = {
20
+ kind: 'tangle.app.signMessage';
21
+ correlationId: string;
22
+ chainId: number;
23
+ message: string;
24
+ };
25
+ type SignTransactionRequest = {
26
+ kind: 'tangle.app.signTransaction';
27
+ correlationId: string;
28
+ chainId: number;
29
+ to: Address;
30
+ data: Hex;
31
+ value?: string;
32
+ };
33
+ type HandshakeAck = {
34
+ kind: 'tangle.app.handshakeAck';
35
+ appId: string;
36
+ protocolVersion: typeof TANGLE_IFRAME_PROTOCOL_VERSION;
37
+ };
38
+ type ResultEnvelope<T> = {
39
+ correlationId: string;
40
+ } & ({
41
+ ok: true;
42
+ data: T;
43
+ } | {
44
+ ok: false;
45
+ error: string;
46
+ });
47
+ type ReadAccountResult = {
48
+ kind: 'tangle.app.readAccountResult';
49
+ } & ResultEnvelope<{
50
+ account: Address;
51
+ chainId: number;
52
+ }>;
53
+ type SwitchChainResult = {
54
+ kind: 'tangle.app.switchChainResult';
55
+ } & ResultEnvelope<{
56
+ chainId: number;
57
+ }>;
58
+ type SignMessageResult = {
59
+ kind: 'tangle.app.signMessageResult';
60
+ } & ResultEnvelope<{
61
+ signature: Hex;
62
+ }>;
63
+ type SignTransactionResult = {
64
+ kind: 'tangle.app.signTransactionResult';
65
+ } & ResultEnvelope<{
66
+ txHash: Hex;
67
+ }>;
68
+ type AccountChanged = {
69
+ kind: 'tangle.app.accountChanged';
70
+ account: Address | null;
71
+ };
72
+ type ChainChanged = {
73
+ kind: 'tangle.app.chainChanged';
74
+ chainId: number;
75
+ };
76
+ type ServiceContextOperator = {
77
+ readonly address: Address;
78
+ readonly rpcAddress: string | undefined;
79
+ readonly status: 'active' | 'inactive' | 'unknown';
80
+ };
81
+ type ServiceContextJob = {
82
+ readonly index: number;
83
+ readonly name: string;
84
+ readonly inputSchema?: unknown;
85
+ };
86
+ type ServiceContextBroadcast = {
87
+ kind: 'tangle.app.serviceContext';
88
+ readonly blueprintId: string;
89
+ readonly serviceId: string | null;
90
+ readonly operators: readonly ServiceContextOperator[];
91
+ readonly jobs: readonly ServiceContextJob[];
92
+ readonly mode: string | null;
93
+ };
94
+ type JobInputs = Readonly<Record<string, unknown>>;
95
+ type CallJobRequest = {
96
+ kind: 'tangle.app.callJob';
97
+ correlationId: string;
98
+ /** Job index within the blueprint, e.g. 0 for the primary entry-point. */
99
+ jobIndex: number;
100
+ /** Free-form inputs validated by the parent against the on-chain ABI. */
101
+ inputs: JobInputs;
102
+ /**
103
+ * Whether the publisher wants intermediate progress (streaming chunks)
104
+ * or just the terminal result. Streaming jobs (LLM generation, video
105
+ * encode) opt in; one-shots (embeddings, classifications) don't.
106
+ */
107
+ stream?: boolean;
108
+ };
109
+ type JobResultStatus = 'pending' | 'streaming' | 'success' | 'error';
110
+ type JobResultEvent = {
111
+ kind: 'tangle.app.jobResult';
112
+ correlationId: string;
113
+ status: JobResultStatus;
114
+ /** Present on `streaming` and `success`. Shape is publisher-defined. */
115
+ data?: unknown;
116
+ /** Present on `streaming` only — incremental chunk for live UI. */
117
+ chunk?: unknown;
118
+ /** Present on `error`. Human-readable. */
119
+ error?: string;
120
+ /** Optional progress metadata (e.g. `{ percent: 0.42, eta_ms: 8000 }`). */
121
+ progress?: {
122
+ readonly percent?: number;
123
+ readonly eta_ms?: number;
124
+ };
125
+ };
126
+ type ParentMessage = HandshakeAck | ReadAccountResult | SwitchChainResult | SignMessageResult | SignTransactionResult | AccountChanged | ChainChanged | ServiceContextBroadcast | JobResultEvent;
127
+ type IframeRequest = HandshakeRequest | ReadAccountRequest | SwitchChainRequest | SignMessageRequest | SignTransactionRequest | CallJobRequest;
128
+ declare const NO_WALLET_ADDRESS = "0x0000000000000000000000000000000000000000";
129
+ /**
130
+ * Cryptographically-random ASCII correlation id matching the parent's
131
+ * validator regex (`/^[\w.\-:]+$/`, max length 128). The connector keeps a
132
+ * Map<correlationId, Resolver> so each request resolves independently.
133
+ */
134
+ declare function makeCorrelationId(prefix: string): string;
135
+
136
+ export { type AccountChanged as A, type CallJobRequest as C, type HandshakeAck as H, type IframeRequest as I, type JobInputs as J, NO_WALLET_ADDRESS as N, type ParentMessage as P, type ReadAccountRequest as R, type ServiceContextBroadcast as S, TANGLE_IFRAME_PROTOCOL_PREFIX as T, type ChainChanged as a, type HandshakeRequest as b, type JobResultEvent as c, type JobResultStatus as d, type ReadAccountResult as e, type ServiceContextJob as f, type ServiceContextOperator as g, type SignMessageRequest as h, type SignMessageResult as i, type SignTransactionRequest as j, type SignTransactionResult as k, type SwitchChainRequest as l, type SwitchChainResult as m, TANGLE_IFRAME_PROTOCOL_VERSION as n, makeCorrelationId as o };
package/dist/styles.css CHANGED
@@ -246,6 +246,7 @@
246
246
  .tracking-wider{--un-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider);}
247
247
  .font-medium{--un-font-weight:var(--fontWeight-medium);font-weight:var(--fontWeight-medium);}
248
248
  .font-semibold{--un-font-weight:var(--fontWeight-semibold);font-weight:var(--fontWeight-semibold);}
249
+ .tab{-moz-tab-size:4;-o-tab-size:4;tab-size:4;}
249
250
  .mx-auto{margin-inline:auto;}
250
251
  .my-2{margin-block:calc(var(--spacing) * 2);}
251
252
  .mb-2{margin-bottom:calc(var(--spacing) * 2);}
@@ -403,6 +404,7 @@
403
404
  .inline{display:inline;}
404
405
  .block{display:block;}
405
406
  .hidden{display:none;}
407
+ .collapse{visibility:collapse;}
406
408
  .cursor-pointer{cursor:pointer;}
407
409
  .\[\&_svg\]\:pointer-events-none svg,
408
410
  .pointer-events-none{pointer-events:none;}
@@ -458,6 +460,7 @@
458
460
  .absolute{position:absolute;}
459
461
  .fixed{position:fixed;}
460
462
  .relative{position:relative;}
463
+ .static{position:static;}
461
464
  .z-50{z-index:50;}
462
465
  .overflow-auto{overflow:auto;}
463
466
  .overflow-hidden{overflow:hidden;}
@@ -0,0 +1,103 @@
1
+ import { Address, Hex } from 'viem';
2
+ import { g as ServiceContextOperator, f as ServiceContextJob, d as JobResultStatus, J as JobInputs } from './parentBridgeProtocol-CqK9e6Fk.js';
3
+
4
+ type WalletSnapshot = {
5
+ readonly address: Address | null;
6
+ readonly chainId: number | null;
7
+ readonly isConnected: boolean;
8
+ };
9
+ type ServiceSnapshot = {
10
+ readonly blueprintId: string | null;
11
+ readonly serviceId: string | null;
12
+ readonly operators: readonly ServiceContextOperator[];
13
+ readonly jobs: readonly ServiceContextJob[];
14
+ readonly mode: string | null;
15
+ };
16
+ type JobInvocation = {
17
+ readonly correlationId: string;
18
+ readonly status: JobResultStatus;
19
+ readonly data?: unknown;
20
+ readonly chunks: readonly unknown[];
21
+ readonly error?: string;
22
+ readonly progress?: {
23
+ readonly percent?: number;
24
+ readonly eta_ms?: number;
25
+ };
26
+ };
27
+ type ClientEventMap = {
28
+ wallet: WalletSnapshot;
29
+ service: ServiceSnapshot;
30
+ job: JobInvocation;
31
+ };
32
+ type Listener<K extends keyof ClientEventMap> = (value: ClientEventMap[K]) => void;
33
+ type TangleIframeClientOptions = {
34
+ /**
35
+ * Origin of the parent dapp. The client posts every message with this
36
+ * exact `targetOrigin` and rejects inbound messages from any other origin.
37
+ * Pass `'*'` only in dev — production must pin to the real parent
38
+ * (`https://cloud.tangle.tools` etc.).
39
+ */
40
+ parentOrigin: string;
41
+ /**
42
+ * Stable identifier for this iframe app. The parent surfaces it in
43
+ * handshake logs + uses it for permission scoping.
44
+ */
45
+ appId: string;
46
+ /**
47
+ * Per-request timeout. Defaults to 60s — long enough for a user to
48
+ * read + approve a signing prompt in the parent. Long-running jobs
49
+ * stream progress events; the request "completes" only on terminal
50
+ * status, so the timeout protects against parents that drop replies
51
+ * entirely.
52
+ */
53
+ requestTimeoutMs?: number;
54
+ };
55
+ declare class TangleIframeClient {
56
+ private readonly options;
57
+ private wallet;
58
+ private service;
59
+ private handshakeAcked;
60
+ private handshakeWaiters;
61
+ private installed;
62
+ private listeners;
63
+ private pendingJobs;
64
+ constructor(options: TangleIframeClientOptions);
65
+ /** Wire the global message listener + initial handshake. Idempotent. */
66
+ install(): void;
67
+ uninstall(): void;
68
+ getWallet(): WalletSnapshot;
69
+ getService(): ServiceSnapshot;
70
+ subscribe<K extends keyof ClientEventMap>(event: K, listener: Listener<K>): () => void;
71
+ signMessage(message: string): Promise<Hex>;
72
+ sendTransaction(tx: {
73
+ to: Address;
74
+ data: Hex;
75
+ value?: bigint;
76
+ }): Promise<Hex>;
77
+ switchChain(chainId: number): Promise<number>;
78
+ /**
79
+ * Invoke a blueprint job. Returns a Promise that resolves on terminal
80
+ * status (`success` or `error`); subscribe to the `job` event for
81
+ * intermediate streaming chunks.
82
+ *
83
+ * Streaming opt-in: pass `stream: true` if the publisher's job emits
84
+ * chunks (LLM generation, video encoding). One-shot jobs (embeddings,
85
+ * classifications) skip the streaming machinery.
86
+ */
87
+ callJob(args: {
88
+ jobIndex: number;
89
+ inputs: JobInputs;
90
+ stream?: boolean;
91
+ }): Promise<JobInvocation>;
92
+ private postHandshake;
93
+ private postToParent;
94
+ private handleParentMessage;
95
+ private dispatchWallet;
96
+ private handleJobResult;
97
+ private updateWallet;
98
+ private updateService;
99
+ private emit;
100
+ private ensureBootstrapped;
101
+ }
102
+
103
+ export { type ClientEventMap as C, type JobInvocation as J, type ServiceSnapshot as S, TangleIframeClient as T, type WalletSnapshot as W, type TangleIframeClientOptions as a };
@@ -1,30 +1,7 @@
1
+ export { T as TANGLE_CLOUD_ORIGINS_DEFAULT, d as detectTangleCloudParentOrigin } from '../detectParentOrigin-BYruoIdc.js';
1
2
  import * as wagmi from 'wagmi';
2
- import { Address, Hex } from 'viem';
3
-
4
- /**
5
- * Default Tangle Cloud origins. Consumers (agent-sandbox UI,
6
- * trading-arena, future iframe blueprints) pass app-specific additions
7
- * via `extraOrigins` rather than mutating this list.
8
- */
9
- declare const TANGLE_CLOUD_ORIGINS_DEFAULT: readonly ["https://cloud.tangle.tools", "https://develop.cloud.tangle.tools", "http://localhost:4300", "http://localhost:8888"];
10
- /**
11
- * Returns the parent origin to bridge to, or null when no trusted parent is
12
- * detected. Caller should skip installing the bridge connector when this
13
- * returns null.
14
- *
15
- * `extraOrigins` is the application's escape hatch for staging or dev
16
- * deploys not covered by the default list. The library deliberately does
17
- * not read environment variables itself (consumers may bundle for non-Vite
18
- * runtimes); the consuming app threads `import.meta.env.VITE_*` or
19
- * `process.env.*` in itself.
20
- *
21
- * Falls back to a `?parent=<origin>` query parameter when no referrer is
22
- * present (some browsers strip referrer from cross-origin loads). Useful
23
- * for dev embedding flows.
24
- */
25
- declare function detectTangleCloudParentOrigin(options?: {
26
- extraOrigins?: readonly string[];
27
- }): string | null;
3
+ import { Address } from 'viem';
4
+ export { A as AccountChanged, C as CallJobRequest, a as ChainChanged, H as HandshakeAck, b as HandshakeRequest, I as IframeRequest, J as JobInputs, c as JobResultEvent, d as JobResultStatus, N as NO_WALLET_ADDRESS, P as ParentMessage, R as ReadAccountRequest, e as ReadAccountResult, S as ServiceContextBroadcast, f as ServiceContextJob, g as ServiceContextOperator, h as SignMessageRequest, i as SignMessageResult, j as SignTransactionRequest, k as SignTransactionResult, l as SwitchChainRequest, m as SwitchChainResult, T as TANGLE_IFRAME_PROTOCOL_PREFIX, n as TANGLE_IFRAME_PROTOCOL_VERSION, o as makeCorrelationId } from '../parentBridgeProtocol-CqK9e6Fk.js';
28
5
 
29
6
  type EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';
30
7
  type Listener = (...args: unknown[]) => void;
@@ -89,6 +66,12 @@ declare class ParentBridgeProvider {
89
66
  private requestSignTransaction;
90
67
  private requestSwitchChain;
91
68
  private dispatch;
69
+ /**
70
+ * Resolves wallet-shape responses (`{ ok, data | error }`). Job results
71
+ * use a different envelope (`{ status, data?, chunk?, error? }`) and are
72
+ * routed through a separate listener registered by `useCallJob` / the SDK
73
+ * — the provider doesn't double-handle them.
74
+ */
92
75
  private resolvePending;
93
76
  private ensureBootstrapped;
94
77
  private updateAccount;
@@ -103,86 +86,4 @@ declare class ParentBridgeProvider {
103
86
  type ParentBridgeConnectorOptions = ParentBridgeOptions;
104
87
  declare function parentBridgeConnector(options: ParentBridgeConnectorOptions): wagmi.CreateConnectorFn<ParentBridgeProvider, Record<string, unknown>, Record<string, unknown>>;
105
88
 
106
- declare const TANGLE_IFRAME_PROTOCOL_VERSION: "1";
107
- declare const TANGLE_IFRAME_PROTOCOL_PREFIX = "tangle.app.";
108
- type HandshakeRequest = {
109
- kind: 'tangle.app.handshake';
110
- appId: string;
111
- version: typeof TANGLE_IFRAME_PROTOCOL_VERSION;
112
- };
113
- type ReadAccountRequest = {
114
- kind: 'tangle.app.readAccount';
115
- correlationId: string;
116
- };
117
- type SwitchChainRequest = {
118
- kind: 'tangle.app.switchChain';
119
- correlationId: string;
120
- chainId: number;
121
- };
122
- type SignMessageRequest = {
123
- kind: 'tangle.app.signMessage';
124
- correlationId: string;
125
- chainId: number;
126
- message: string;
127
- };
128
- type SignTransactionRequest = {
129
- kind: 'tangle.app.signTransaction';
130
- correlationId: string;
131
- chainId: number;
132
- to: Address;
133
- data: Hex;
134
- value?: string;
135
- };
136
- type HandshakeAck = {
137
- kind: 'tangle.app.handshakeAck';
138
- appId: string;
139
- protocolVersion: typeof TANGLE_IFRAME_PROTOCOL_VERSION;
140
- };
141
- type ResultEnvelope<T> = {
142
- correlationId: string;
143
- } & ({
144
- ok: true;
145
- data: T;
146
- } | {
147
- ok: false;
148
- error: string;
149
- });
150
- type ReadAccountResult = {
151
- kind: 'tangle.app.readAccountResult';
152
- } & ResultEnvelope<{
153
- account: Address;
154
- chainId: number;
155
- }>;
156
- type SwitchChainResult = {
157
- kind: 'tangle.app.switchChainResult';
158
- } & ResultEnvelope<{
159
- chainId: number;
160
- }>;
161
- type SignMessageResult = {
162
- kind: 'tangle.app.signMessageResult';
163
- } & ResultEnvelope<{
164
- signature: Hex;
165
- }>;
166
- type SignTransactionResult = {
167
- kind: 'tangle.app.signTransactionResult';
168
- } & ResultEnvelope<{
169
- txHash: Hex;
170
- }>;
171
- type AccountChanged = {
172
- kind: 'tangle.app.accountChanged';
173
- account: Address | null;
174
- };
175
- type ChainChanged = {
176
- kind: 'tangle.app.chainChanged';
177
- chainId: number;
178
- };
179
- type ParentMessage = HandshakeAck | ReadAccountResult | SwitchChainResult | SignMessageResult | SignTransactionResult | AccountChanged | ChainChanged;
180
- declare const NO_WALLET_ADDRESS = "0x0000000000000000000000000000000000000000";
181
- /**
182
- * Cryptographically-random ASCII correlation id matching the parent's
183
- * validator regex (`/^[\w.\-:]+$/`, max length 128). The connector keeps a
184
- * Map<correlationId, Resolver> so each request resolves independently.
185
- */
186
- declare function makeCorrelationId(prefix: string): string;
187
-
188
- export { type AccountChanged, type ChainChanged, type HandshakeAck, type HandshakeRequest, NO_WALLET_ADDRESS, type ParentBridgeConnectorOptions, type ParentBridgeOptions, ParentBridgeProvider, type ParentMessage, type ReadAccountRequest, type ReadAccountResult, type SignMessageRequest, type SignMessageResult, type SignTransactionRequest, type SignTransactionResult, type SwitchChainRequest, type SwitchChainResult, TANGLE_CLOUD_ORIGINS_DEFAULT, TANGLE_IFRAME_PROTOCOL_PREFIX, TANGLE_IFRAME_PROTOCOL_VERSION, detectTangleCloudParentOrigin, isRunningInIframe, makeCorrelationId, parentBridgeConnector };
89
+ export { type ParentBridgeConnectorOptions, type ParentBridgeOptions, ParentBridgeProvider, isRunningInIframe, parentBridgeConnector };
@@ -1,54 +1,15 @@
1
- // src/wallet/detectParentOrigin.ts
2
- var TANGLE_CLOUD_ORIGINS_DEFAULT = Object.freeze([
3
- "https://cloud.tangle.tools",
4
- "https://develop.cloud.tangle.tools",
5
- // Local dev (Vite default port for tangle-cloud + Netlify dev preview).
6
- "http://localhost:4300",
7
- "http://localhost:8888"
8
- ]);
9
- function originFromReferrer() {
10
- if (typeof document === "undefined") return null;
11
- const ref = document.referrer;
12
- if (!ref) return null;
13
- try {
14
- return new URL(ref).origin;
15
- } catch {
16
- return null;
17
- }
18
- }
19
- function detectTangleCloudParentOrigin(options = {}) {
20
- if (typeof window === "undefined" || window.parent === window) {
21
- return null;
22
- }
23
- const allowlist = /* @__PURE__ */ new Set([
24
- ...TANGLE_CLOUD_ORIGINS_DEFAULT,
25
- ...options.extraOrigins ?? []
26
- ]);
27
- const referrerOrigin = originFromReferrer();
28
- if (referrerOrigin && allowlist.has(referrerOrigin)) {
29
- return referrerOrigin;
30
- }
31
- try {
32
- const url = new URL(window.location.href);
33
- const explicit = url.searchParams.get("parent");
34
- if (explicit && allowlist.has(explicit)) return explicit;
35
- } catch {
36
- }
37
- return null;
38
- }
1
+ import {
2
+ NO_WALLET_ADDRESS,
3
+ TANGLE_CLOUD_ORIGINS_DEFAULT,
4
+ TANGLE_IFRAME_PROTOCOL_PREFIX,
5
+ TANGLE_IFRAME_PROTOCOL_VERSION,
6
+ detectTangleCloudParentOrigin,
7
+ makeCorrelationId
8
+ } from "../chunk-BLXSBQU4.js";
39
9
 
40
10
  // src/wallet/parentBridgeConnector.ts
41
11
  import { createConnector } from "wagmi";
42
12
 
43
- // src/wallet/parentBridgeProtocol.ts
44
- var TANGLE_IFRAME_PROTOCOL_VERSION = "1";
45
- var TANGLE_IFRAME_PROTOCOL_PREFIX = "tangle.app.";
46
- var NO_WALLET_ADDRESS = "0x0000000000000000000000000000000000000000";
47
- function makeCorrelationId(prefix) {
48
- const random = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : Math.random().toString(36).slice(2) + Date.now().toString(36);
49
- return `${prefix}.${random}`;
50
- }
51
-
52
13
  // src/wallet/parentBridgeProvider.ts
53
14
  var DEFAULT_REQUEST_TIMEOUT_MS = 6e4;
54
15
  function isRunningInIframe() {
@@ -260,6 +221,12 @@ var ParentBridgeProvider = class {
260
221
  });
261
222
  });
262
223
  }
224
+ /**
225
+ * Resolves wallet-shape responses (`{ ok, data | error }`). Job results
226
+ * use a different envelope (`{ status, data?, chunk?, error? }`) and are
227
+ * routed through a separate listener registered by `useCallJob` / the SDK
228
+ * — the provider doesn't double-handle them.
229
+ */
263
230
  resolvePending(message) {
264
231
  const entry = this.pending.get(message.correlationId);
265
232
  if (!entry) return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/wallet/detectParentOrigin.ts","../../src/wallet/parentBridgeConnector.ts","../../src/wallet/parentBridgeProtocol.ts","../../src/wallet/parentBridgeProvider.ts"],"sourcesContent":["// Determine which origin to trust as the parent dapp.\n//\n// `document.referrer` is the *initial* embedder — it's set when the iframe is\n// first loaded and survives reloads (though it can be cleared by `referrerpolicy`\n// or by the embedder). The Tangle Cloud iframe wrapper deliberately omits\n// `referrerpolicy=\"no-referrer\"` so we get the embedder's origin here.\n//\n// We compare it against an allowlist of known Tangle Cloud origins. If it\n// matches, that's the parent. Otherwise the iframe is being loaded directly\n// (standalone domain visit, dev server, untrusted embedder) and the bridge\n// stays disabled — the app falls back to its normal injected/WC wallet path.\n\n/**\n * Default Tangle Cloud origins. Consumers (agent-sandbox UI,\n * trading-arena, future iframe blueprints) pass app-specific additions\n * via `extraOrigins` rather than mutating this list.\n */\nexport const TANGLE_CLOUD_ORIGINS_DEFAULT = Object.freeze([\n 'https://cloud.tangle.tools',\n 'https://develop.cloud.tangle.tools',\n // Local dev (Vite default port for tangle-cloud + Netlify dev preview).\n 'http://localhost:4300',\n 'http://localhost:8888',\n] as const);\n\nfunction originFromReferrer(): string | null {\n if (typeof document === 'undefined') return null;\n const ref = document.referrer;\n if (!ref) return null;\n try {\n return new URL(ref).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the parent origin to bridge to, or null when no trusted parent is\n * detected. Caller should skip installing the bridge connector when this\n * returns null.\n *\n * `extraOrigins` is the application's escape hatch for staging or dev\n * deploys not covered by the default list. The library deliberately does\n * not read environment variables itself (consumers may bundle for non-Vite\n * runtimes); the consuming app threads `import.meta.env.VITE_*` or\n * `process.env.*` in itself.\n *\n * Falls back to a `?parent=<origin>` query parameter when no referrer is\n * present (some browsers strip referrer from cross-origin loads). Useful\n * for dev embedding flows.\n */\nexport function detectTangleCloudParentOrigin(\n options: { extraOrigins?: readonly string[] } = {},\n): string | null {\n if (typeof window === 'undefined' || window.parent === window) {\n return null;\n }\n const allowlist = new Set<string>([\n ...TANGLE_CLOUD_ORIGINS_DEFAULT,\n ...(options.extraOrigins ?? []),\n ]);\n const referrerOrigin = originFromReferrer();\n if (referrerOrigin && allowlist.has(referrerOrigin)) {\n return referrerOrigin;\n }\n try {\n const url = new URL(window.location.href);\n const explicit = url.searchParams.get('parent');\n if (explicit && allowlist.has(explicit)) return explicit;\n } catch {\n // ignore\n }\n return null;\n}\n","// Wagmi connector that proxies wallet operations to the Tangle Cloud parent\n// dapp via the iframe postMessage bridge. Becomes the autoConnect target\n// when this app is loaded inside an iframe sandbox without a window.ethereum\n// — i.e. always, when embedded by cloud.tangle.tools.\n//\n// Architecture: the connector owns one `ParentBridgeProvider` (singleton),\n// forwards every wagmi method to it, and reflects the provider's EIP-1193\n// events back to wagmi's emitter so the rest of the dapp (ConnectKit's\n// account chip, hooks like useAccount/useChainId) reacts to parent-state\n// changes without polling.\n\nimport type { Address, Chain } from 'viem';\nimport { createConnector } from 'wagmi';\n\nimport { ParentBridgeProvider, type ParentBridgeOptions } from './parentBridgeProvider';\n\nexport type ParentBridgeConnectorOptions = ParentBridgeOptions;\n\nexport function parentBridgeConnector(options: ParentBridgeConnectorOptions) {\n let provider: ParentBridgeProvider | undefined;\n let installed = false;\n\n return createConnector<ParentBridgeProvider>((config) => {\n const ensureProvider = (): ParentBridgeProvider => {\n if (!provider) provider = new ParentBridgeProvider(options);\n if (!installed) {\n provider.install();\n installed = true;\n // Wire the provider's EIP-1193 events to wagmi's emitter so\n // ConnectKit and useAccount/useChainId reflect parent-state changes\n // without polling.\n provider.on('accountsChanged', (accounts) => {\n config.emitter.emit('change', {\n accounts: Array.isArray(accounts)\n ? (accounts as readonly Address[])\n : ([] as readonly Address[]),\n });\n });\n provider.on('chainChanged', (chainIdHex) => {\n const chainId =\n typeof chainIdHex === 'string'\n ? Number.parseInt(chainIdHex, 16)\n : Number(chainIdHex);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n });\n provider.on('disconnect', () => {\n config.emitter.emit('disconnect');\n });\n }\n return provider;\n };\n\n return {\n id: 'tangleParentBridge',\n name: 'Tangle Cloud',\n type: 'parentBridge',\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async connect(): Promise<any> {\n // wagmi v3's connect() return type is a conditional based on\n // `withCapabilities`. We always return plain addresses; cast through\n // `any` rather than re-implementing the type predicate.\n const p = ensureProvider();\n const accountsResult = (await p.request({\n method: 'eth_requestAccounts',\n })) as readonly Address[];\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return {\n accounts: accountsResult,\n chainId: Number.isFinite(chainId) ? chainId : 0,\n };\n },\n\n async disconnect() {\n // Disconnect from the iframe's perspective is a local-only state\n // reset — we can't ask the parent dapp to disconnect its wallet on\n // our behalf, and a real disconnect should be initiated from the\n // parent's UI. Tear down listeners + the message bridge so a future\n // reconnect re-handshakes cleanly.\n if (provider) provider.uninstall();\n installed = false;\n provider = undefined;\n },\n\n async getAccounts() {\n const p = ensureProvider();\n const cached = p.getCachedAccount();\n if (cached) return [cached];\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts;\n },\n\n async getChainId() {\n const p = ensureProvider();\n const cached = p.getCachedChainId();\n if (cached !== null) return cached;\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return Number.isFinite(chainId) ? chainId : 0;\n },\n\n async getProvider() {\n return ensureProvider();\n },\n\n async isAuthorized() {\n // Always authorized when in iframe mode — the parent dapp has\n // already gated access by being the embedder. Returning `true`\n // makes wagmi auto-reconnect on every page load, which is the\n // right UX (iframe → parent wallet is always-on).\n try {\n const p = ensureProvider();\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts.length > 0;\n } catch {\n return false;\n }\n },\n\n async switchChain({ chainId }): Promise<Chain> {\n const p = ensureProvider();\n await p.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: `0x${chainId.toString(16)}` }],\n });\n const chain = config.chains.find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(`Chain ${chainId} not configured for this app`);\n }\n return chain;\n },\n\n onAccountsChanged(accounts) {\n config.emitter.emit('change', {\n accounts: accounts as readonly Address[],\n });\n },\n onChainChanged(chainIdHex) {\n const chainId = Number.parseInt(chainIdHex, 16);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n },\n onDisconnect() {\n config.emitter.emit('disconnect');\n },\n };\n });\n}\n","// Tangle Cloud iframe ↔ parent dapp protocol — must mirror the parent's\n// spec at `apps/tangle-cloud/src/blueprintApps/iframe/protocol.ts`. Bump the\n// version constant in lockstep when either side adds a request kind.\n\nimport type { Address, Hex } from 'viem';\n\nexport const TANGLE_IFRAME_PROTOCOL_VERSION = '1' as const;\nexport const TANGLE_IFRAME_PROTOCOL_PREFIX = 'tangle.app.';\n\n// ─── Iframe → Parent requests ────────────────────────────────────────────────\n\nexport type HandshakeRequest = {\n kind: 'tangle.app.handshake';\n appId: string;\n version: typeof TANGLE_IFRAME_PROTOCOL_VERSION;\n};\n\nexport type ReadAccountRequest = {\n kind: 'tangle.app.readAccount';\n correlationId: string;\n};\n\nexport type SwitchChainRequest = {\n kind: 'tangle.app.switchChain';\n correlationId: string;\n chainId: number;\n};\n\nexport type SignMessageRequest = {\n kind: 'tangle.app.signMessage';\n correlationId: string;\n chainId: number;\n message: string;\n};\n\nexport type SignTransactionRequest = {\n kind: 'tangle.app.signTransaction';\n correlationId: string;\n chainId: number;\n to: Address;\n data: Hex;\n value?: string;\n};\n\n// ─── Parent → Iframe messages ────────────────────────────────────────────────\n\nexport type HandshakeAck = {\n kind: 'tangle.app.handshakeAck';\n appId: string;\n protocolVersion: typeof TANGLE_IFRAME_PROTOCOL_VERSION;\n};\n\nexport type ResultEnvelope<T> = { correlationId: string } & (\n | { ok: true; data: T }\n | { ok: false; error: string }\n);\n\nexport type ReadAccountResult = {\n kind: 'tangle.app.readAccountResult';\n} & ResultEnvelope<{ account: Address; chainId: number }>;\n\nexport type SwitchChainResult = {\n kind: 'tangle.app.switchChainResult';\n} & ResultEnvelope<{ chainId: number }>;\n\nexport type SignMessageResult = {\n kind: 'tangle.app.signMessageResult';\n} & ResultEnvelope<{ signature: Hex }>;\n\nexport type SignTransactionResult = {\n kind: 'tangle.app.signTransactionResult';\n} & ResultEnvelope<{ txHash: Hex }>;\n\nexport type AccountChanged = {\n kind: 'tangle.app.accountChanged';\n account: Address | null;\n};\n\nexport type ChainChanged = {\n kind: 'tangle.app.chainChanged';\n chainId: number;\n};\n\nexport type ParentMessage =\n | HandshakeAck\n | ReadAccountResult\n | SwitchChainResult\n | SignMessageResult\n | SignTransactionResult\n | AccountChanged\n | ChainChanged;\n\n// The zero address used by the parent when no wallet is connected. The parent\n// always responds to readAccount with an address; this sentinel means \"no\n// wallet\" without making the response type a union of result shapes.\nexport const NO_WALLET_ADDRESS = '0x0000000000000000000000000000000000000000';\n\n/**\n * Cryptographically-random ASCII correlation id matching the parent's\n * validator regex (`/^[\\w.\\-:]+$/`, max length 128). The connector keeps a\n * Map<correlationId, Resolver> so each request resolves independently.\n */\nexport function makeCorrelationId(prefix: string): string {\n const random =\n typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2) + Date.now().toString(36);\n return `${prefix}.${random}`;\n}\n","// EIP-1193 provider implementation that proxies wallet calls to the parent\n// dapp via window.postMessage. The iframe doesn't talk to a wallet directly\n// — it inherits the parent's connected account + chain, and forwards signing\n// requests through the existing tangle.app.* protocol.\n//\n// This is the lowest layer of the parent-bridge stack. Wagmi sees this as a\n// regular Ethereum provider and routes `eth_accounts`, `eth_chainId`,\n// `personal_sign`, `eth_sendTransaction`, `wallet_switchEthereumChain`, etc.\n// through it.\n\nimport type { Address, Hex } from 'viem';\n\nimport {\n makeCorrelationId,\n NO_WALLET_ADDRESS,\n TANGLE_IFRAME_PROTOCOL_VERSION,\n type ParentMessage,\n} from './parentBridgeProtocol';\n\ntype EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';\ntype Listener = (...args: unknown[]) => void;\n\ntype PendingRequest<T> = {\n resolve: (value: T) => void;\n reject: (reason: Error) => void;\n expectedKind: ParentMessage['kind'];\n};\n\nexport type ParentBridgeOptions = {\n /**\n * Origin of the parent dapp that hosts this iframe. The provider posts to\n * `window.parent` with this exact origin and rejects inbound messages from\n * any other origin. Pass `'*'` only in development; production must pin to\n * the real parent (`https://cloud.tangle.tools` or its develop equivalent).\n */\n parentOrigin: string;\n /**\n * Stable identifier for this iframe app. The parent includes this in the\n * handshake ack so dev tooling can correlate logs across the two windows.\n */\n appId: string;\n /**\n * Optional ms timeout for each bridged request. Defaults to 60 seconds —\n * long enough for a user to read + approve a signing prompt in the parent.\n */\n requestTimeoutMs?: number;\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\n\n/**\n * Detect iframe execution context. When this returns `false` the bridge\n * connector should not be installed and the host app should fall back to its\n * normal wallet config (ConnectKit + injected/walletConnect).\n *\n * `window.parent !== window` is the most reliable signal that works across\n * sandbox-iframe contexts where direct property access to parent throws.\n */\nexport function isRunningInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.parent !== undefined && window.parent !== window;\n } catch {\n // Cross-origin read of `window.parent` shouldn't throw, but be defensive.\n return true;\n }\n}\n\n/**\n * EIP-1193 provider backed by the Tangle Cloud iframe protocol. One instance\n * lives per iframe app; the wagmi connector owns the singleton.\n */\nexport class ParentBridgeProvider {\n private listeners = new Map<EventName, Set<Listener>>();\n private pending = new Map<string, PendingRequest<unknown>>();\n private cachedAccount: Address | null = null;\n private cachedChainId: number | null = null;\n private handshakeAcked = false;\n private handshakeWaiters: Array<() => void> = [];\n private installed = false;\n\n constructor(private readonly options: ParentBridgeOptions) {}\n\n /**\n * Wire up the global message listener and send the initial handshake.\n * Idempotent — safe to call repeatedly during reconnect attempts.\n */\n install(): void {\n if (this.installed || typeof window === 'undefined') return;\n this.installed = true;\n window.addEventListener('message', this.handleParentMessage);\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }\n\n uninstall(): void {\n if (!this.installed || typeof window === 'undefined') return;\n this.installed = false;\n window.removeEventListener('message', this.handleParentMessage);\n // Reject every pending request so callers don't hang forever.\n for (const [, pending] of this.pending) {\n pending.reject(new Error('Parent bridge uninstalled'));\n }\n this.pending.clear();\n }\n\n // ── EIP-1193 surface ────────────────────────────────────────────────────\n\n async request(req: { method: string; params?: unknown[] }): Promise<unknown> {\n const method = req.method;\n const params = (req.params ?? []) as unknown[];\n switch (method) {\n case 'eth_chainId': {\n await this.ensureBootstrapped();\n return this.cachedChainId !== null ? `0x${this.cachedChainId.toString(16)}` : '0x0';\n }\n case 'eth_accounts':\n case 'eth_requestAccounts': {\n await this.ensureBootstrapped();\n return this.cachedAccount !== null ? [this.cachedAccount] : [];\n }\n case 'personal_sign': {\n const [message, _signer] = params as [string, Address];\n return this.requestSignMessage(message);\n }\n case 'eth_signTypedData_v4': {\n // The current protocol doesn't carry typed-data — surface a clear\n // error rather than silently producing a personal_sign. Publishers\n // that need typed-data signing should upgrade the protocol.\n throw bridgeError(\n 4200,\n 'eth_signTypedData_v4 is not supported by the parent-bridge protocol yet.',\n );\n }\n case 'eth_sendTransaction': {\n const [tx] = params as [\n { to?: Address; data?: Hex; value?: Hex | string; chainId?: Hex | number },\n ];\n if (!tx?.to || !tx.data) {\n throw bridgeError(-32602, 'eth_sendTransaction requires `to` and `data`.');\n }\n return this.requestSignTransaction(tx);\n }\n case 'wallet_switchEthereumChain': {\n const [{ chainId }] = params as [{ chainId: Hex }];\n const numeric = Number.parseInt(chainId, 16);\n if (!Number.isFinite(numeric) || numeric <= 0) {\n throw bridgeError(-32602, `Invalid chainId: ${chainId}`);\n }\n await this.requestSwitchChain(numeric);\n return null;\n }\n case 'wallet_addEthereumChain': {\n // The parent owns the chain registry; iframes can't add chains the\n // dapp doesn't already know about.\n throw bridgeError(\n 4200,\n 'wallet_addEthereumChain is not supported through the parent bridge.',\n );\n }\n default:\n throw bridgeError(4200, `Method ${method} not supported by parent bridge.`);\n }\n }\n\n on(event: EventName, listener: Listener): void {\n const set = this.listeners.get(event) ?? new Set();\n set.add(listener);\n this.listeners.set(event, set);\n }\n\n removeListener(event: EventName, listener: Listener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n // ── Internal: dispatch + book-keeping ───────────────────────────────────\n\n private postToParent(message: object): void {\n if (typeof window === 'undefined') return;\n try {\n window.parent.postMessage(message, this.options.parentOrigin);\n } catch {\n // Cross-origin / sandboxed; parent.postMessage shouldn't actually throw\n // but be defensive against future browser changes.\n }\n }\n\n private handleParentMessage = (event: MessageEvent): void => {\n // Origin gate first; never parse untrusted payloads.\n if (event.origin !== this.options.parentOrigin) return;\n const data = event.data;\n if (typeof data !== 'object' || data === null) return;\n const message = data as ParentMessage;\n switch (message.kind) {\n case 'tangle.app.handshakeAck':\n this.handshakeAcked = true;\n for (const resolve of this.handshakeWaiters) resolve();\n this.handshakeWaiters = [];\n // After ack, ask for the current account so cached state reflects\n // reality before any consumer queries. Fire-and-forget — explicit\n // calls (`eth_accounts`, etc.) await their own request.\n this.sendReadAccount().catch(() => {\n // The first read commonly races with bridge teardown in tests\n // and isn't user-facing; swallow rather than producing unhandled\n // rejections. Subsequent `eth_accounts` calls retry on demand.\n });\n return;\n case 'tangle.app.readAccountResult':\n this.resolvePending(message);\n if (message.ok) {\n this.updateAccount(\n message.data.account === NO_WALLET_ADDRESS\n ? null\n : message.data.account,\n );\n this.updateChainId(message.data.chainId);\n }\n return;\n case 'tangle.app.switchChainResult':\n this.resolvePending(message);\n if (message.ok) this.updateChainId(message.data.chainId);\n return;\n case 'tangle.app.signMessageResult':\n case 'tangle.app.signTransactionResult':\n this.resolvePending(message);\n return;\n case 'tangle.app.accountChanged':\n this.updateAccount(message.account);\n return;\n case 'tangle.app.chainChanged':\n this.updateChainId(message.chainId);\n return;\n }\n };\n\n private sendReadAccount(): Promise<{ account: Address; chainId: number }> {\n return this.dispatch({\n kind: 'tangle.app.readAccount',\n expectedKind: 'tangle.app.readAccountResult',\n }) as Promise<{ account: Address; chainId: number }>;\n }\n\n private requestSignMessage(message: string): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n return this.dispatch({\n kind: 'tangle.app.signMessage',\n expectedKind: 'tangle.app.signMessageResult',\n payload: { chainId, message },\n }).then((data) => (data as { signature: Hex }).signature);\n }\n\n private requestSignTransaction(tx: {\n to?: Address;\n data?: Hex;\n value?: Hex | string;\n }): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n const value =\n typeof tx.value === 'string' && tx.value.startsWith('0x')\n ? BigInt(tx.value).toString(10)\n : typeof tx.value === 'string'\n ? tx.value\n : undefined;\n return this.dispatch({\n kind: 'tangle.app.signTransaction',\n expectedKind: 'tangle.app.signTransactionResult',\n payload: {\n chainId,\n to: tx.to as Address,\n data: tx.data as Hex,\n ...(value !== undefined ? { value } : {}),\n },\n }).then((data) => (data as { txHash: Hex }).txHash);\n }\n\n private requestSwitchChain(chainId: number): Promise<number> {\n return this.dispatch({\n kind: 'tangle.app.switchChain',\n expectedKind: 'tangle.app.switchChainResult',\n payload: { chainId },\n }).then((data) => (data as { chainId: number }).chainId);\n }\n\n private async dispatch(req: {\n kind: 'tangle.app.readAccount' | 'tangle.app.switchChain' | 'tangle.app.signMessage' | 'tangle.app.signTransaction';\n expectedKind: ParentMessage['kind'];\n payload?: Record<string, unknown>;\n }): Promise<unknown> {\n await this.ensureBootstrapped();\n const correlationId = makeCorrelationId(req.kind);\n const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n return new Promise<unknown>((resolve, reject) => {\n const timer = window.setTimeout(() => {\n this.pending.delete(correlationId);\n reject(bridgeError(4900, `Parent did not respond to ${req.kind} within ${timeout}ms`));\n }, timeout);\n this.pending.set(correlationId, {\n resolve: (v) => {\n window.clearTimeout(timer);\n resolve(v);\n },\n reject: (e) => {\n window.clearTimeout(timer);\n reject(e);\n },\n expectedKind: req.expectedKind,\n });\n this.postToParent({\n kind: req.kind,\n correlationId,\n ...(req.payload ?? {}),\n });\n });\n }\n\n private resolvePending(message: Extract<ParentMessage, { correlationId: string }>): void {\n const entry = this.pending.get(message.correlationId);\n if (!entry) return;\n this.pending.delete(message.correlationId);\n if (entry.expectedKind !== message.kind) {\n entry.reject(\n bridgeError(\n -32000,\n `Parent replied with ${message.kind} but ${entry.expectedKind} was expected`,\n ),\n );\n return;\n }\n if (message.ok) {\n entry.resolve(message.data);\n } else {\n entry.reject(bridgeError(4001, message.error));\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.handshakeAcked) return;\n this.install();\n await new Promise<void>((resolve) => {\n this.handshakeWaiters.push(resolve);\n // Re-send handshake every 500ms while we wait — covers a parent that\n // mounted after the iframe and missed the initial post.\n const retry = window.setInterval(() => {\n if (this.handshakeAcked) {\n window.clearInterval(retry);\n return;\n }\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }, 500);\n // Safety stop — handshake won't be re-attempted indefinitely.\n window.setTimeout(() => window.clearInterval(retry), 10_000);\n });\n }\n\n private updateAccount(next: Address | null): void {\n if (this.cachedAccount === next) return;\n const prev = this.cachedAccount;\n this.cachedAccount = next;\n if (next === null && prev !== null) {\n this.emit('disconnect');\n this.emit('accountsChanged', []);\n } else if (next !== null) {\n this.emit('accountsChanged', [next]);\n if (prev === null) {\n this.emit('connect', { chainId: this.cachedChainId ?? 0 });\n }\n }\n }\n\n private updateChainId(next: number): void {\n if (this.cachedChainId === next) return;\n this.cachedChainId = next;\n this.emit('chainChanged', `0x${next.toString(16)}`);\n }\n\n private emit(event: EventName, ...args: unknown[]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n listener(...args);\n } catch {\n // Listener bugs shouldn't break the bridge.\n }\n }\n }\n\n // ── Test seams ──────────────────────────────────────────────────────────\n\n /** Visible for tests + the connector's `getAccounts()` shortcut. */\n getCachedAccount(): Address | null {\n return this.cachedAccount;\n }\n /** Visible for tests + the connector's `getChainId()` shortcut. */\n getCachedChainId(): number | null {\n return this.cachedChainId;\n }\n}\n\nfunction bridgeError(code: number, message: string): Error {\n const err = new Error(message) as Error & { code?: number };\n err.code = code;\n return err;\n}\n"],"mappings":";AAiBO,IAAM,+BAA+B,OAAO,OAAO;AAAA,EACxD;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF,CAAU;AAEV,SAAS,qBAAoC;AAC3C,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,QAAM,MAAM,SAAS;AACrB,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAiBO,SAAS,8BACd,UAAgD,CAAC,GAClC;AACf,MAAI,OAAO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B,QAAQ;AACN,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,MAEA,MAAM,YAAY,EAAE,QAAQ,GAAmB;AAC7C,cAAM,IAAI,eAAe;AACzB,cAAM,EAAE,QAAQ;AAAA,UACd,QAAQ;AAAA,UACR,QAAQ,CAAC,EAAE,SAAS,KAAK,QAAQ,SAAS,EAAE,CAAC,GAAG,CAAC;AAAA,QACnD,CAAC;AACD,cAAM,QAAQ,OAAO,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AACxD,YAAI,CAAC,OAAO;AACV,gBAAM,IAAI,MAAM,SAAS,OAAO,8BAA8B;AAAA,QAChE;AACA,eAAO;AAAA,MACT;AAAA,MAEA,kBAAkB,UAAU;AAC1B,eAAO,QAAQ,KAAK,UAAU;AAAA,UAC5B;AAAA,QACF,CAAC;AAAA,MACH;AAAA,MACA,eAAe,YAAY;AACzB,cAAM,UAAU,OAAO,SAAS,YAAY,EAAE;AAC9C,YAAI,OAAO,SAAS,OAAO,GAAG;AAC5B,iBAAO,QAAQ,KAAK,UAAU,EAAE,QAAQ,CAAC;AAAA,QAC3C;AAAA,MACF;AAAA,MACA,eAAe;AACb,eAAO,QAAQ,KAAK,YAAY;AAAA,MAClC;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/wallet/parentBridgeConnector.ts","../../src/wallet/parentBridgeProvider.ts"],"sourcesContent":["// Wagmi connector that proxies wallet operations to the Tangle Cloud parent\n// dapp via the iframe postMessage bridge. Becomes the autoConnect target\n// when this app is loaded inside an iframe sandbox without a window.ethereum\n// — i.e. always, when embedded by cloud.tangle.tools.\n//\n// Architecture: the connector owns one `ParentBridgeProvider` (singleton),\n// forwards every wagmi method to it, and reflects the provider's EIP-1193\n// events back to wagmi's emitter so the rest of the dapp (ConnectKit's\n// account chip, hooks like useAccount/useChainId) reacts to parent-state\n// changes without polling.\n\nimport type { Address, Chain } from 'viem';\nimport { createConnector } from 'wagmi';\n\nimport { ParentBridgeProvider, type ParentBridgeOptions } from './parentBridgeProvider';\n\nexport type ParentBridgeConnectorOptions = ParentBridgeOptions;\n\nexport function parentBridgeConnector(options: ParentBridgeConnectorOptions) {\n let provider: ParentBridgeProvider | undefined;\n let installed = false;\n\n return createConnector<ParentBridgeProvider>((config) => {\n const ensureProvider = (): ParentBridgeProvider => {\n if (!provider) provider = new ParentBridgeProvider(options);\n if (!installed) {\n provider.install();\n installed = true;\n // Wire the provider's EIP-1193 events to wagmi's emitter so\n // ConnectKit and useAccount/useChainId reflect parent-state changes\n // without polling.\n provider.on('accountsChanged', (accounts) => {\n config.emitter.emit('change', {\n accounts: Array.isArray(accounts)\n ? (accounts as readonly Address[])\n : ([] as readonly Address[]),\n });\n });\n provider.on('chainChanged', (chainIdHex) => {\n const chainId =\n typeof chainIdHex === 'string'\n ? Number.parseInt(chainIdHex, 16)\n : Number(chainIdHex);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n });\n provider.on('disconnect', () => {\n config.emitter.emit('disconnect');\n });\n }\n return provider;\n };\n\n return {\n id: 'tangleParentBridge',\n name: 'Tangle Cloud',\n type: 'parentBridge',\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async connect(): Promise<any> {\n // wagmi v3's connect() return type is a conditional based on\n // `withCapabilities`. We always return plain addresses; cast through\n // `any` rather than re-implementing the type predicate.\n const p = ensureProvider();\n const accountsResult = (await p.request({\n method: 'eth_requestAccounts',\n })) as readonly Address[];\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return {\n accounts: accountsResult,\n chainId: Number.isFinite(chainId) ? chainId : 0,\n };\n },\n\n async disconnect() {\n // Disconnect from the iframe's perspective is a local-only state\n // reset — we can't ask the parent dapp to disconnect its wallet on\n // our behalf, and a real disconnect should be initiated from the\n // parent's UI. Tear down listeners + the message bridge so a future\n // reconnect re-handshakes cleanly.\n if (provider) provider.uninstall();\n installed = false;\n provider = undefined;\n },\n\n async getAccounts() {\n const p = ensureProvider();\n const cached = p.getCachedAccount();\n if (cached) return [cached];\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts;\n },\n\n async getChainId() {\n const p = ensureProvider();\n const cached = p.getCachedChainId();\n if (cached !== null) return cached;\n const chainIdHex = (await p.request({ method: 'eth_chainId' })) as string;\n const chainId = Number.parseInt(chainIdHex, 16);\n return Number.isFinite(chainId) ? chainId : 0;\n },\n\n async getProvider() {\n return ensureProvider();\n },\n\n async isAuthorized() {\n // Always authorized when in iframe mode — the parent dapp has\n // already gated access by being the embedder. Returning `true`\n // makes wagmi auto-reconnect on every page load, which is the\n // right UX (iframe → parent wallet is always-on).\n try {\n const p = ensureProvider();\n const accounts = (await p.request({\n method: 'eth_accounts',\n })) as readonly Address[];\n return accounts.length > 0;\n } catch {\n return false;\n }\n },\n\n async switchChain({ chainId }): Promise<Chain> {\n const p = ensureProvider();\n await p.request({\n method: 'wallet_switchEthereumChain',\n params: [{ chainId: `0x${chainId.toString(16)}` }],\n });\n const chain = config.chains.find((c) => c.id === chainId);\n if (!chain) {\n throw new Error(`Chain ${chainId} not configured for this app`);\n }\n return chain;\n },\n\n onAccountsChanged(accounts) {\n config.emitter.emit('change', {\n accounts: accounts as readonly Address[],\n });\n },\n onChainChanged(chainIdHex) {\n const chainId = Number.parseInt(chainIdHex, 16);\n if (Number.isFinite(chainId)) {\n config.emitter.emit('change', { chainId });\n }\n },\n onDisconnect() {\n config.emitter.emit('disconnect');\n },\n };\n });\n}\n","// EIP-1193 provider implementation that proxies wallet calls to the parent\n// dapp via window.postMessage. The iframe doesn't talk to a wallet directly\n// — it inherits the parent's connected account + chain, and forwards signing\n// requests through the existing tangle.app.* protocol.\n//\n// This is the lowest layer of the parent-bridge stack. Wagmi sees this as a\n// regular Ethereum provider and routes `eth_accounts`, `eth_chainId`,\n// `personal_sign`, `eth_sendTransaction`, `wallet_switchEthereumChain`, etc.\n// through it.\n\nimport type { Address, Hex } from 'viem';\n\nimport {\n makeCorrelationId,\n NO_WALLET_ADDRESS,\n TANGLE_IFRAME_PROTOCOL_VERSION,\n type ParentMessage,\n type ReadAccountResult,\n type SignMessageResult,\n type SignTransactionResult,\n type SwitchChainResult,\n} from './parentBridgeProtocol';\n\ntype EventName = 'accountsChanged' | 'chainChanged' | 'connect' | 'disconnect' | 'message';\ntype Listener = (...args: unknown[]) => void;\n\ntype PendingRequest<T> = {\n resolve: (value: T) => void;\n reject: (reason: Error) => void;\n expectedKind: ParentMessage['kind'];\n};\n\nexport type ParentBridgeOptions = {\n /**\n * Origin of the parent dapp that hosts this iframe. The provider posts to\n * `window.parent` with this exact origin and rejects inbound messages from\n * any other origin. Pass `'*'` only in development; production must pin to\n * the real parent (`https://cloud.tangle.tools` or its develop equivalent).\n */\n parentOrigin: string;\n /**\n * Stable identifier for this iframe app. The parent includes this in the\n * handshake ack so dev tooling can correlate logs across the two windows.\n */\n appId: string;\n /**\n * Optional ms timeout for each bridged request. Defaults to 60 seconds —\n * long enough for a user to read + approve a signing prompt in the parent.\n */\n requestTimeoutMs?: number;\n};\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 60_000;\n\n/**\n * Detect iframe execution context. When this returns `false` the bridge\n * connector should not be installed and the host app should fall back to its\n * normal wallet config (ConnectKit + injected/walletConnect).\n *\n * `window.parent !== window` is the most reliable signal that works across\n * sandbox-iframe contexts where direct property access to parent throws.\n */\nexport function isRunningInIframe(): boolean {\n if (typeof window === 'undefined') return false;\n try {\n return window.parent !== undefined && window.parent !== window;\n } catch {\n // Cross-origin read of `window.parent` shouldn't throw, but be defensive.\n return true;\n }\n}\n\n/**\n * EIP-1193 provider backed by the Tangle Cloud iframe protocol. One instance\n * lives per iframe app; the wagmi connector owns the singleton.\n */\nexport class ParentBridgeProvider {\n private listeners = new Map<EventName, Set<Listener>>();\n private pending = new Map<string, PendingRequest<unknown>>();\n private cachedAccount: Address | null = null;\n private cachedChainId: number | null = null;\n private handshakeAcked = false;\n private handshakeWaiters: Array<() => void> = [];\n private installed = false;\n\n constructor(private readonly options: ParentBridgeOptions) {}\n\n /**\n * Wire up the global message listener and send the initial handshake.\n * Idempotent — safe to call repeatedly during reconnect attempts.\n */\n install(): void {\n if (this.installed || typeof window === 'undefined') return;\n this.installed = true;\n window.addEventListener('message', this.handleParentMessage);\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }\n\n uninstall(): void {\n if (!this.installed || typeof window === 'undefined') return;\n this.installed = false;\n window.removeEventListener('message', this.handleParentMessage);\n // Reject every pending request so callers don't hang forever.\n for (const [, pending] of this.pending) {\n pending.reject(new Error('Parent bridge uninstalled'));\n }\n this.pending.clear();\n }\n\n // ── EIP-1193 surface ────────────────────────────────────────────────────\n\n async request(req: { method: string; params?: unknown[] }): Promise<unknown> {\n const method = req.method;\n const params = (req.params ?? []) as unknown[];\n switch (method) {\n case 'eth_chainId': {\n await this.ensureBootstrapped();\n return this.cachedChainId !== null ? `0x${this.cachedChainId.toString(16)}` : '0x0';\n }\n case 'eth_accounts':\n case 'eth_requestAccounts': {\n await this.ensureBootstrapped();\n return this.cachedAccount !== null ? [this.cachedAccount] : [];\n }\n case 'personal_sign': {\n const [message, _signer] = params as [string, Address];\n return this.requestSignMessage(message);\n }\n case 'eth_signTypedData_v4': {\n // The current protocol doesn't carry typed-data — surface a clear\n // error rather than silently producing a personal_sign. Publishers\n // that need typed-data signing should upgrade the protocol.\n throw bridgeError(\n 4200,\n 'eth_signTypedData_v4 is not supported by the parent-bridge protocol yet.',\n );\n }\n case 'eth_sendTransaction': {\n const [tx] = params as [\n { to?: Address; data?: Hex; value?: Hex | string; chainId?: Hex | number },\n ];\n if (!tx?.to || !tx.data) {\n throw bridgeError(-32602, 'eth_sendTransaction requires `to` and `data`.');\n }\n return this.requestSignTransaction(tx);\n }\n case 'wallet_switchEthereumChain': {\n const [{ chainId }] = params as [{ chainId: Hex }];\n const numeric = Number.parseInt(chainId, 16);\n if (!Number.isFinite(numeric) || numeric <= 0) {\n throw bridgeError(-32602, `Invalid chainId: ${chainId}`);\n }\n await this.requestSwitchChain(numeric);\n return null;\n }\n case 'wallet_addEthereumChain': {\n // The parent owns the chain registry; iframes can't add chains the\n // dapp doesn't already know about.\n throw bridgeError(\n 4200,\n 'wallet_addEthereumChain is not supported through the parent bridge.',\n );\n }\n default:\n throw bridgeError(4200, `Method ${method} not supported by parent bridge.`);\n }\n }\n\n on(event: EventName, listener: Listener): void {\n const set = this.listeners.get(event) ?? new Set();\n set.add(listener);\n this.listeners.set(event, set);\n }\n\n removeListener(event: EventName, listener: Listener): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n // ── Internal: dispatch + book-keeping ───────────────────────────────────\n\n private postToParent(message: object): void {\n if (typeof window === 'undefined') return;\n try {\n window.parent.postMessage(message, this.options.parentOrigin);\n } catch {\n // Cross-origin / sandboxed; parent.postMessage shouldn't actually throw\n // but be defensive against future browser changes.\n }\n }\n\n private handleParentMessage = (event: MessageEvent): void => {\n // Origin gate first; never parse untrusted payloads.\n if (event.origin !== this.options.parentOrigin) return;\n const data = event.data;\n if (typeof data !== 'object' || data === null) return;\n const message = data as ParentMessage;\n switch (message.kind) {\n case 'tangle.app.handshakeAck':\n this.handshakeAcked = true;\n for (const resolve of this.handshakeWaiters) resolve();\n this.handshakeWaiters = [];\n // After ack, ask for the current account so cached state reflects\n // reality before any consumer queries. Fire-and-forget — explicit\n // calls (`eth_accounts`, etc.) await their own request.\n this.sendReadAccount().catch(() => {\n // The first read commonly races with bridge teardown in tests\n // and isn't user-facing; swallow rather than producing unhandled\n // rejections. Subsequent `eth_accounts` calls retry on demand.\n });\n return;\n case 'tangle.app.readAccountResult':\n this.resolvePending(message);\n if (message.ok) {\n this.updateAccount(\n message.data.account === NO_WALLET_ADDRESS\n ? null\n : message.data.account,\n );\n this.updateChainId(message.data.chainId);\n }\n return;\n case 'tangle.app.switchChainResult':\n this.resolvePending(message);\n if (message.ok) this.updateChainId(message.data.chainId);\n return;\n case 'tangle.app.signMessageResult':\n case 'tangle.app.signTransactionResult':\n this.resolvePending(message);\n return;\n case 'tangle.app.accountChanged':\n this.updateAccount(message.account);\n return;\n case 'tangle.app.chainChanged':\n this.updateChainId(message.chainId);\n return;\n }\n };\n\n private sendReadAccount(): Promise<{ account: Address; chainId: number }> {\n return this.dispatch({\n kind: 'tangle.app.readAccount',\n expectedKind: 'tangle.app.readAccountResult',\n }) as Promise<{ account: Address; chainId: number }>;\n }\n\n private requestSignMessage(message: string): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n return this.dispatch({\n kind: 'tangle.app.signMessage',\n expectedKind: 'tangle.app.signMessageResult',\n payload: { chainId, message },\n }).then((data) => (data as { signature: Hex }).signature);\n }\n\n private requestSignTransaction(tx: {\n to?: Address;\n data?: Hex;\n value?: Hex | string;\n }): Promise<Hex> {\n const chainId = this.cachedChainId ?? 1;\n const value =\n typeof tx.value === 'string' && tx.value.startsWith('0x')\n ? BigInt(tx.value).toString(10)\n : typeof tx.value === 'string'\n ? tx.value\n : undefined;\n return this.dispatch({\n kind: 'tangle.app.signTransaction',\n expectedKind: 'tangle.app.signTransactionResult',\n payload: {\n chainId,\n to: tx.to as Address,\n data: tx.data as Hex,\n ...(value !== undefined ? { value } : {}),\n },\n }).then((data) => (data as { txHash: Hex }).txHash);\n }\n\n private requestSwitchChain(chainId: number): Promise<number> {\n return this.dispatch({\n kind: 'tangle.app.switchChain',\n expectedKind: 'tangle.app.switchChainResult',\n payload: { chainId },\n }).then((data) => (data as { chainId: number }).chainId);\n }\n\n private async dispatch(req: {\n kind: 'tangle.app.readAccount' | 'tangle.app.switchChain' | 'tangle.app.signMessage' | 'tangle.app.signTransaction';\n expectedKind: ParentMessage['kind'];\n payload?: Record<string, unknown>;\n }): Promise<unknown> {\n await this.ensureBootstrapped();\n const correlationId = makeCorrelationId(req.kind);\n const timeout = this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n return new Promise<unknown>((resolve, reject) => {\n const timer = window.setTimeout(() => {\n this.pending.delete(correlationId);\n reject(bridgeError(4900, `Parent did not respond to ${req.kind} within ${timeout}ms`));\n }, timeout);\n this.pending.set(correlationId, {\n resolve: (v) => {\n window.clearTimeout(timer);\n resolve(v);\n },\n reject: (e) => {\n window.clearTimeout(timer);\n reject(e);\n },\n expectedKind: req.expectedKind,\n });\n this.postToParent({\n kind: req.kind,\n correlationId,\n ...(req.payload ?? {}),\n });\n });\n }\n\n /**\n * Resolves wallet-shape responses (`{ ok, data | error }`). Job results\n * use a different envelope (`{ status, data?, chunk?, error? }`) and are\n * routed through a separate listener registered by `useCallJob` / the SDK\n * — the provider doesn't double-handle them.\n */\n private resolvePending(\n message:\n | ReadAccountResult\n | SwitchChainResult\n | SignMessageResult\n | SignTransactionResult,\n ): void {\n const entry = this.pending.get(message.correlationId);\n if (!entry) return;\n this.pending.delete(message.correlationId);\n if (entry.expectedKind !== message.kind) {\n entry.reject(\n bridgeError(\n -32000,\n `Parent replied with ${message.kind} but ${entry.expectedKind} was expected`,\n ),\n );\n return;\n }\n if (message.ok) {\n entry.resolve(message.data);\n } else {\n entry.reject(bridgeError(4001, message.error));\n }\n }\n\n private async ensureBootstrapped(): Promise<void> {\n if (this.handshakeAcked) return;\n this.install();\n await new Promise<void>((resolve) => {\n this.handshakeWaiters.push(resolve);\n // Re-send handshake every 500ms while we wait — covers a parent that\n // mounted after the iframe and missed the initial post.\n const retry = window.setInterval(() => {\n if (this.handshakeAcked) {\n window.clearInterval(retry);\n return;\n }\n this.postToParent({\n kind: 'tangle.app.handshake',\n appId: this.options.appId,\n version: TANGLE_IFRAME_PROTOCOL_VERSION,\n });\n }, 500);\n // Safety stop — handshake won't be re-attempted indefinitely.\n window.setTimeout(() => window.clearInterval(retry), 10_000);\n });\n }\n\n private updateAccount(next: Address | null): void {\n if (this.cachedAccount === next) return;\n const prev = this.cachedAccount;\n this.cachedAccount = next;\n if (next === null && prev !== null) {\n this.emit('disconnect');\n this.emit('accountsChanged', []);\n } else if (next !== null) {\n this.emit('accountsChanged', [next]);\n if (prev === null) {\n this.emit('connect', { chainId: this.cachedChainId ?? 0 });\n }\n }\n }\n\n private updateChainId(next: number): void {\n if (this.cachedChainId === next) return;\n this.cachedChainId = next;\n this.emit('chainChanged', `0x${next.toString(16)}`);\n }\n\n private emit(event: EventName, ...args: unknown[]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n listener(...args);\n } catch {\n // Listener bugs shouldn't break the bridge.\n }\n }\n }\n\n // ── Test seams ──────────────────────────────────────────────────────────\n\n /** Visible for tests + the connector's `getAccounts()` shortcut. */\n getCachedAccount(): Address | null {\n return this.cachedAccount;\n }\n /** Visible for tests + the connector's `getChainId()` shortcut. */\n getCachedChainId(): number | null {\n return this.cachedChainId;\n }\n}\n\nfunction bridgeError(code: number, message: string): Error {\n const err = new Error(message) as Error & { code?: number };\n err.code = code;\n return err;\n}\n"],"mappings":";;;;;;;;;;AAYA,SAAS,uBAAuB;;;ACwChC,IAAM,6BAA6B;AAU5B,SAAS,oBAA6B;AAC3C,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AACF,WAAO,OAAO,WAAW,UAAa,OAAO,WAAW;AAAA,EAC1D,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;AAMO,IAAM,uBAAN,MAA2B;AAAA,EAShC,YAA6B,SAA8B;AAA9B;AAAA,EAA+B;AAAA,EAA/B;AAAA,EARrB,YAAY,oBAAI,IAA8B;AAAA,EAC9C,UAAU,oBAAI,IAAqC;AAAA,EACnD,gBAAgC;AAAA,EAChC,gBAA+B;AAAA,EAC/B,iBAAiB;AAAA,EACjB,mBAAsC,CAAC;AAAA,EACvC,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA,EAQpB,UAAgB;AACd,QAAI,KAAK,aAAa,OAAO,WAAW,YAAa;AACrD,SAAK,YAAY;AACjB,WAAO,iBAAi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