@stridge/pay-kit 0.0.0-stage → 0.1.0-alpha.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/LICENSE +21 -0
- package/README.md +339 -2
- package/dist/account.d.ts +4 -0
- package/dist/account.js +1 -0
- package/dist/channel/createAppChannel.js +1 -0
- package/dist/channel/createDialogAriaHiddenIntent.js +1 -0
- package/dist/channel/createDialogHost.js +1 -0
- package/dist/channel/createScrollLock.js +2 -0
- package/dist/channel/iframeTransport.js +1 -0
- package/dist/channel/popupTransport.js +1 -0
- package/dist/channel/presentation.js +1 -0
- package/dist/channel/types.d.ts +225 -0
- package/dist/core/buildElementUrl.js +1 -0
- package/dist/core/createElementClient.js +1 -0
- package/dist/core/createElementHandle.js +1 -0
- package/dist/core/createElementLedger.js +1 -0
- package/dist/core/createElementLifetimeBridge.js +1 -0
- package/dist/core/elementClientTypes.d.ts +20 -0
- package/dist/core/elementGeometry.js +1 -0
- package/dist/core/elementLoadState.d.ts +1 -0
- package/dist/core/elementLoadState.js +1 -0
- package/dist/core/elementSizing.js +1 -0
- package/dist/core/elementStartGate.js +1 -0
- package/dist/core/types.d.ts +1 -0
- package/dist/errors/PayError.d.ts +37 -0
- package/dist/errors/PayError.js +1 -0
- package/dist/hooks/keypairState.js +1 -0
- package/dist/hooks/types.d.ts +104 -0
- package/dist/hooks/usePayAccount.d.ts +16 -0
- package/dist/hooks/usePayAccount.js +1 -0
- package/dist/hooks/usePaySnapshot.d.ts +13 -0
- package/dist/hooks/usePaySnapshot.js +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +1 -0
- package/dist/provider/PayProvider.d.ts +47 -0
- package/dist/provider/PayProvider.js +1 -0
- package/dist/provider/context.js +1 -0
- package/dist/provider/createProviderLifetime.js +1 -0
- package/dist/provider/elementContext.js +1 -0
- package/dist/provider/hubAddress.js +1 -0
- package/dist/provider/types.d.ts +73 -0
- package/dist/react/ElementDefault.d.ts +23 -0
- package/dist/react/ElementDefault.js +1 -0
- package/dist/react/ElementHost.js +1 -0
- package/dist/react/ElementLanes.js +1 -0
- package/dist/react/PayElement.d.ts +13 -0
- package/dist/react/PayElement.js +1 -0
- package/dist/react/compileElementOptions.js +1 -0
- package/dist/react/compilePayRequest.js +1 -0
- package/dist/react/elementDefaultStyles.d.ts +15 -0
- package/dist/react/elementDefaultStyles.js +69 -0
- package/dist/react/elementSwap.js +1 -0
- package/dist/react/payEvents.d.ts +139 -0
- package/dist/react/payEvents.js +1 -0
- package/dist/react/presentElement.js +1 -0
- package/dist/react/stridgeLockup.js +1 -0
- package/dist/react/types.d.ts +118 -0
- package/dist/react/useElementHandle.js +1 -0
- package/dist/shared/presentation/hubWindow.js +1 -0
- package/dist/shared/presentation/subscribeToNothing.js +1 -0
- package/package.json +124 -3
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { HubAppearance, HubDiagnosticsDetailsPayload, HubDiagnosticsObservation, HubErrorCode, HubRequestType, HubStateSnapshot, HubTransport, PayMenuRect } from "@stridge/pay-sdk";
|
|
2
|
+
//#region src/channel/types.d.ts
|
|
3
|
+
/** The screen a Fund request starts on: `"home"` or `"fund"`. */
|
|
4
|
+
type PayFundStartScreen = import("@stridge/pay-sdk").FundStartScreen;
|
|
5
|
+
/**
|
|
6
|
+
* Where the handshake with the hub stands.
|
|
7
|
+
*
|
|
8
|
+
* - `idle` — not mounted.
|
|
9
|
+
* - `connecting` — the iframe is loading, or `init` was sent and not answered yet.
|
|
10
|
+
* - `ready` — the hub answered `init`; requests are sent.
|
|
11
|
+
* - `failed` — the handshake timed out or the hub refused `init`; the app face reports `unavailable`, and
|
|
12
|
+
* `connectionError` says why.
|
|
13
|
+
*/
|
|
14
|
+
type PayConnectionState = "idle" | "connecting" | "ready" | "failed";
|
|
15
|
+
/**
|
|
16
|
+
* Why the handshake failed, for diagnostics.
|
|
17
|
+
*
|
|
18
|
+
* - `timeout` — the hub did not answer `init` within `handshakeTimeoutMs`: the hub is down or slow, or its page could
|
|
19
|
+
* not load in the frame (its `frame-ancestors` does not list this origin, for example).
|
|
20
|
+
* - any `HubErrorCode` — the hub refused `init` with that code. `app-suspended` means the app id is not registered for
|
|
21
|
+
* this page's origin.
|
|
22
|
+
*/
|
|
23
|
+
type PayConnectionError = "timeout" | HubErrorCode;
|
|
24
|
+
/**
|
|
25
|
+
* The app side's state, as an external store for the headless hooks.
|
|
26
|
+
*/
|
|
27
|
+
interface PaySnapshot {
|
|
28
|
+
/** Optional live frame observation. Handwritten snapshots may omit it. */
|
|
29
|
+
diagnostics?: PayDiagnostics;
|
|
30
|
+
/**
|
|
31
|
+
* The iframe's handshake.
|
|
32
|
+
*/
|
|
33
|
+
connection: PayConnectionState;
|
|
34
|
+
/**
|
|
35
|
+
* Why the handshake failed while `connection` is `failed`, `null` otherwise. For diagnostics; the app face shows
|
|
36
|
+
* `unavailable` either way.
|
|
37
|
+
*/
|
|
38
|
+
connectionError: PayConnectionError | null;
|
|
39
|
+
/**
|
|
40
|
+
* The hub's last `state` message, from the iframe or the Stridge window, whichever sent the latest one; `null` before
|
|
41
|
+
* the first one (and after an unmount or a hub reload in the iframe).
|
|
42
|
+
*/
|
|
43
|
+
hub: HubStateSnapshot | null;
|
|
44
|
+
/**
|
|
45
|
+
* Whether the hub frame reports that the hub is busy: the `pending` of its last `activity` notice. `null` means
|
|
46
|
+
* unknown: before the first notice of the current handshake, and again whenever the frame's connection starts over
|
|
47
|
+
* (a mount, a hub reload, a failed handshake, an unmount). Only the iframe, once its handshake is `ready`, sets it;
|
|
48
|
+
* the Stridge window sends no notice. Closing the overlay or settling a request does not clear it: the hub can stay
|
|
49
|
+
* busy after both, for one while a wallet it was creating finishes in the background. App-side state, not a field
|
|
50
|
+
* of any message.
|
|
51
|
+
*/
|
|
52
|
+
hubActivity: boolean | null;
|
|
53
|
+
/**
|
|
54
|
+
* Whether the overlay shows: the hub asked for it (`overlay-open` without a later `overlay-close`) and the browser
|
|
55
|
+
* did not close its dialog meanwhile. Only the iframe opens it; the Stridge window is its own surface.
|
|
56
|
+
*/
|
|
57
|
+
overlayOpen: boolean;
|
|
58
|
+
/**
|
|
59
|
+
* The request in flight, or `null`.
|
|
60
|
+
*/
|
|
61
|
+
pending: Exclude<HubRequestType, "init" | "pay"> | null;
|
|
62
|
+
/**
|
|
63
|
+
* The current authenticated frame transport report, or `null` before a report and after connection loss. Requests
|
|
64
|
+
* use popup while this is unknown.
|
|
65
|
+
*/
|
|
66
|
+
currentTransport: HubTransport | null;
|
|
67
|
+
}
|
|
68
|
+
/** Consumer opt-in and peer capability are independent of ceremony availability. */
|
|
69
|
+
type PayDiagnostics = {
|
|
70
|
+
state: "off" | "waiting" | "disabled" | "unsupported";
|
|
71
|
+
} | ({
|
|
72
|
+
state: "ready";
|
|
73
|
+
sequence: number;
|
|
74
|
+
observedAt: number;
|
|
75
|
+
details?: PayDiagnosticsDetails;
|
|
76
|
+
} & HubDiagnosticsObservation);
|
|
77
|
+
/** Details negotiation belongs to the current base subscription and carries no persisted observation. */
|
|
78
|
+
type PayDiagnosticsDetails = {
|
|
79
|
+
state: "waiting" | "unsupported" | "unavailable";
|
|
80
|
+
} | HubDiagnosticsDetailsPayload;
|
|
81
|
+
/** An opaque hub-issued pair from current available details. It grants no authority by itself. */
|
|
82
|
+
interface PayDiagnosticsDisconnectTarget {
|
|
83
|
+
readonly subscriptionId: string;
|
|
84
|
+
readonly targetId: string;
|
|
85
|
+
}
|
|
86
|
+
interface PayDisconnectOptions {
|
|
87
|
+
/**
|
|
88
|
+
* The diagnostics subscription a disconnect ends: only the provider's own diagnostics pass it.
|
|
89
|
+
*
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
diagnosticsTarget: PayDiagnosticsDisconnectTarget;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Options for {@link AppChannel.fund}.
|
|
96
|
+
*/
|
|
97
|
+
interface PayFundOptions {
|
|
98
|
+
/**
|
|
99
|
+
* The screen Fund starts on: `fund` (the default) or `home`, the account home.
|
|
100
|
+
*/
|
|
101
|
+
start?: PayFundStartScreen;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The app side of the app↔hub channel. It creates and owns the hub iframe and the `<dialog>` that holds it, completes
|
|
105
|
+
* the handshake, sends requests and correlates their answers, and keeps the latest hub state as an external store.
|
|
106
|
+
* When the hub's transport is `popup`, each request opens the Sua window (the hub page on its own origin) from the
|
|
107
|
+
* click instead, and talks to it.
|
|
108
|
+
*
|
|
109
|
+
* Message acceptance (every rule must hold, else the message is ignored): `event.source` is the iframe's
|
|
110
|
+
* `contentWindow` or the open Sua window, `event.origin ===` the hub origin (from `hubUrl`), and the data is well
|
|
111
|
+
* formed: `decodeHubFrameAppMessage(event.data)` from the iframe, which also carries the hub's `activity` notice, and
|
|
112
|
+
* `decodeHubMessage(event.data)` from the Sua window. Every message is posted with `postMessage(message, hubOrigin)` to
|
|
113
|
+
* that same window, never `"*"`.
|
|
114
|
+
*/
|
|
115
|
+
interface AppChannel {
|
|
116
|
+
/**
|
|
117
|
+
* `new URL(hubUrl).origin`.
|
|
118
|
+
*/
|
|
119
|
+
readonly hubOrigin: string;
|
|
120
|
+
/**
|
|
121
|
+
* The iframe while mounted, `null` otherwise.
|
|
122
|
+
*/
|
|
123
|
+
readonly iframe: HTMLIFrameElement | null;
|
|
124
|
+
/**
|
|
125
|
+
* Returns the current snapshot; the same object until it changes.
|
|
126
|
+
*/
|
|
127
|
+
getSnapshot(): PaySnapshot;
|
|
128
|
+
/**
|
|
129
|
+
* Registers a listener called after every snapshot change. Returns the unsubscribe function.
|
|
130
|
+
*/
|
|
131
|
+
subscribe(listener: () => void): () => void;
|
|
132
|
+
/**
|
|
133
|
+
* Creates the iframe (hidden) inside a closed `<dialog>`, appends the dialog to `container`, attaches the `message`
|
|
134
|
+
* listener, and starts the handshake timer. Returns the iframe. Mounting while mounted returns the current iframe.
|
|
135
|
+
* Throws after `dispose()`.
|
|
136
|
+
*/
|
|
137
|
+
mount(container: HTMLElement): HTMLIFrameElement;
|
|
138
|
+
/**
|
|
139
|
+
* Removes the dialog with the iframe (closing it and releasing focus, `aria-hidden` and the scroll lock it held) and
|
|
140
|
+
* the listener, closes only never-dispatched Sua windows, clears timers, rejects the local request in flight with
|
|
141
|
+
* `cancelled`, and resets the snapshot to `idle` with no hub state, no overlay and no transport report. Local
|
|
142
|
+
* cancellation does not prove posted registration settlement or safe final teardown. A later `mount()` starts
|
|
143
|
+
* over with a new iframe.
|
|
144
|
+
*/
|
|
145
|
+
unmount(): void;
|
|
146
|
+
/**
|
|
147
|
+
* Replaces the appearance: posts `appearance` to the iframe when its handshake is `ready` and to the Sua window
|
|
148
|
+
* when its handshake is done, and uses it for the next `init`, the next iframe URL and the next Sua window URL.
|
|
149
|
+
*
|
|
150
|
+
* @throws {TypeError} when `theme` is neither `"dark"` nor `"light"`.
|
|
151
|
+
*/
|
|
152
|
+
setAppearance(appearance: HubAppearance): void;
|
|
153
|
+
/**
|
|
154
|
+
* Asks the hub to sign the user in. Resolves with the signed-in EVM address, which can come with a wallet that is
|
|
155
|
+
* still `pending` (after "Continue as", for one); signing waits until the wallet is active.
|
|
156
|
+
*
|
|
157
|
+
* When the transport is `popup`, the Sua window opens synchronously in this call, so call it straight from the
|
|
158
|
+
* user's click, before any `await`: a browser blocks a window opened later.
|
|
159
|
+
*
|
|
160
|
+
* @throws {PayError} (as a rejection) with the hub's error code, `busy` when another request is in flight,
|
|
161
|
+
* `unavailable` when the handshake failed, the hub reloaded or the Sua window lost its link to this page (a
|
|
162
|
+
* `Cross-Origin-Opener-Policy: same-origin` header cuts it), `cancelled` on unmount or when the user closed the
|
|
163
|
+
* Sua window, `popup-blocked` when the browser refused to open it.
|
|
164
|
+
*/
|
|
165
|
+
signIn(): Promise<{
|
|
166
|
+
evmAddress: string;
|
|
167
|
+
}>;
|
|
168
|
+
/**
|
|
169
|
+
* Asks the hub to sign `message` (text, shown to the user on the hub's confirm screen). Resolves with the EVM
|
|
170
|
+
* signature (`0x`, 132 characters). With no session, the hub first signs the user in, or offers "Continue as" when
|
|
171
|
+
* the session's user has not authorized this app; it authorizes this app and then shows the confirm, all in one
|
|
172
|
+
* dialog. A confirm cancelled after that sign-in leaves the app signed in. Opens the Sua window like
|
|
173
|
+
* {@link AppChannel.signIn}.
|
|
174
|
+
*
|
|
175
|
+
* @throws {TypeError} (as a rejection, before anything is posted or opened) when `message` is not a non-empty
|
|
176
|
+
* string of at most `MAX_SIGN_MESSAGE_BYTES` UTF-8 bytes.
|
|
177
|
+
* @throws {PayError} (as a rejection) as {@link AppChannel.signIn}.
|
|
178
|
+
*/
|
|
179
|
+
sign(message: string): Promise<string>;
|
|
180
|
+
/**
|
|
181
|
+
* Asks the hub to sign out of Sua in this browser. The hub ends the session, which signs out every app that shares
|
|
182
|
+
* it, and forgets every app's authorization; {@link AppChannel.disconnect} covers this app only. Resolves with
|
|
183
|
+
* nothing signed out when this app is not authorized; rejects with `signed-out` when the browser now holds another
|
|
184
|
+
* account's session, which stays signed in. Opens the Sua window like {@link AppChannel.signIn}: only a page on the
|
|
185
|
+
* hub's own origin can end that session.
|
|
186
|
+
*
|
|
187
|
+
* @throws {PayError} (as a rejection) as {@link AppChannel.signIn}.
|
|
188
|
+
*/
|
|
189
|
+
signOut(): Promise<void>;
|
|
190
|
+
/**
|
|
191
|
+
* Asks the hub to revoke this app's authorization: the app then sees `signed-out`, while the session and every
|
|
192
|
+
* other app stay signed in. Resolves also when there was nothing to revoke; the next `signIn()` asks the user to
|
|
193
|
+
* continue with no code. Opens the Sua window like {@link AppChannel.signIn}.
|
|
194
|
+
* With `diagnosticsTarget`, requires current eligible frame details and never opens a popup or queues before init.
|
|
195
|
+
*
|
|
196
|
+
* @throws {PayError} (as a rejection) as {@link AppChannel.signIn}.
|
|
197
|
+
*/
|
|
198
|
+
disconnect(options?: PayDisconnectOptions): Promise<void>;
|
|
199
|
+
/**
|
|
200
|
+
* Asks the hub to open Fund in its Stridge Wallet dialog, on the screen `options.start` names (`fund` by default).
|
|
201
|
+
* Every amount, address and linked wallet stays in the hub; the answer carries none. Resolves once the user closes
|
|
202
|
+
* Fund, which is how it ends, whatever the user did inside it (closing the Sua window that shows it counts too).
|
|
203
|
+
* The hub opens it only for a signed-in app the session's user authorized, and signs no one in and renews nothing
|
|
204
|
+
* for it. Opens the Sua window like {@link AppChannel.signIn}.
|
|
205
|
+
*
|
|
206
|
+
* A hub that predates Fund drops the request and answers nothing. The channel bounds that wait: when the hub
|
|
207
|
+
* neither answers nor receipts the exact request id within `FUND_RECEIPT_TIMEOUT_MS` of the post, the request
|
|
208
|
+
* rejects with `unavailable` and cancels that id. The limit starts once the request is posted, so the Sua window's
|
|
209
|
+
* handshake does not count. A receipted Fund stays pending until the user closes it. After timeout, this channel
|
|
210
|
+
* refuses new requests until the hub answers the cancellation or the frame reconnects, so a late overlay stays hidden.
|
|
211
|
+
*
|
|
212
|
+
* @throws {TypeError} (as a rejection) when `options` is not an object or `start` is not `fund` or `home`.
|
|
213
|
+
* @throws {PayError} (as a rejection) as {@link AppChannel.signIn}, plus `signed-out`, `session-locked`,
|
|
214
|
+
* `app-suspended`, `wallet-closed`, `network`, `rate-limited`, `wallet-not-ready` or `internal` when the
|
|
215
|
+
* session cannot open Fund, and `unavailable` when the hub never opened Fund (see above).
|
|
216
|
+
*/
|
|
217
|
+
fund(options?: PayFundOptions): Promise<void>;
|
|
218
|
+
/**
|
|
219
|
+
* Calls {@link AppChannel.unmount} and makes the channel unusable: later requests reject with `cancelled`, and `mount()` throws.
|
|
220
|
+
* Idempotent.
|
|
221
|
+
*/
|
|
222
|
+
dispose(): void;
|
|
223
|
+
}
|
|
224
|
+
//#endregion
|
|
225
|
+
export { AppChannel, PayConnectionError, PayConnectionState, PayDiagnostics, PayDiagnosticsDetails, PayDiagnosticsDisconnectTarget, PayDisconnectOptions, PayFundOptions, PayFundStartScreen, PaySnapshot };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{buildHubFrameUrl as e}from"../shared/presentation/hubWindow.js";import{APP_ID_PATTERN as t,HUB_URL_PARAMS as n,PAY_ELEMENT_PATH as r,isHubFrameName as i}from"@stridge/pay-sdk";const a=[n.surface,n.origin];function o(e){if(typeof e!=`string`)throw TypeError(`buildElementUrl: hubUrl must be a string`);let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw TypeError(`buildElementUrl: hubUrl must be an http: or https: URL`);if(t.username!==``||t.password!==``)throw TypeError(`buildElementUrl: hubUrl must carry no credentials`);return t}function s(s){let{hubUrl:c,appId:l,appearance:u,hubFrame:d}=s;if(typeof l!=`string`||!t.test(l))throw TypeError(`buildElementUrl: appId must match APP_ID_PATTERN`);if(!i(d))throw TypeError(`buildElementUrl: hubFrame must be a hub frame name`);let f=new URL(e(o(c).href,u,l));for(let e of a)f.searchParams.delete(e);return f.searchParams.set(n.hubFrame,d),f.pathname=r,f.hash=``,f.href}export{s as buildElementUrl};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PayError as e}from"../errors/PayError.js";import{createElementHandle as t}from"./createElementHandle.js";import{isAppearance as n}from"@stridge/pay-sdk";function r(r){let{hubUrl:i,appId:a,hubFrame:o,onConnected:s,showMenu:c,startGate:l}=r,u=Object.freeze({...r.appearance}),d=!1,f=new Set;return{createHandle(n){if(d)throw Error(`The PayElement client was destroyed`);let r,p=t({...n,hubUrl:i,appId:a,hubFrame:o,appearance:u,startGate:l,onConnected:s,...c===void 0?{}:{showMenu(t,n,r){return d?Promise.reject(new e(`cancelled`,`The PayElement client ended`)):c(t,n,r)}}},()=>{r!==void 0&&f.delete(r)});if(r=p,d)throw p.destroy(),Error(`The PayElement client was destroyed during frame creation`);return f.add(p),p.setAppearance(u),p},setAppearance(e){if(d)return;let t=Object.freeze({...e});if(!n(t))throw TypeError(`Invalid PayElement appearance`);if(u.theme===t.theme)return;u=t;let r=[...f];for(let e of r){if(d||u!==t)break;e.setAppearance(t)}},destroy(){if(d)return;d=!0;let e=[...f];f.clear();for(let t of e)t.destroy()}}}export{r as createElementClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PayError as e}from"../errors/PayError.js";import{ELEMENT_DEFAULT_TOKENS as t}from"../react/elementDefaultStyles.js";import{buildElementUrl as n}from"./buildElementUrl.js";import{createElementLedger as r}from"./createElementLedger.js";import{createElementLifetimeBridge as i}from"./createElementLifetimeBridge.js";import{createAppElementGeometry as a}from"./elementGeometry.js";import{INITIAL_ELEMENT_LOAD as o,reduceElementLoad as s}from"./elementLoadState.js";import{createElementSizing as c}from"./elementSizing.js";import{PAY_ELEMENT_LIFETIME_MESSAGE_TYPES as ee,PAY_ELEMENT_MESSAGE_TYPES as l,PAY_ELEMENT_NOTIFICATION_MESSAGE_TYPES as u,PAY_MESSAGE_TYPES as d,answersPayAmount as te,createPayEnvelope as f,decodeElementMessage as ne,isAppElementMessage as re,isAppearance as ie,isElementDepositRequestPayload as ae,isElementMessage as oe,isElementPayRequestPayload as se,payJobOf as ce,samePayTerms as le}from"@stridge/pay-sdk";const p=1e4,m=[250,1e3,3e3],h=1e3,ue=m[m.length-1]+h,de=6e4,g=`data-stridge-pay-element-load`;function fe(e){let t=m.length,n=0;return e>t?n=m[t-1]+(e-t)*2e3:e>0&&(n=m[e-1]),n<de?n:null}function _(e){let{onSigned:t,onFailed:n,onCheckStatus:r,onCheckoutResult:i,onPaid:a,onHeld:o,onUnconfirmed:s}=e;return Object.freeze({onSigned:t,onFailed:n,onCheckStatus:r,onCheckoutResult:i,onPaid:a,onHeld:o,onUnconfirmed:s})}function v(e){try{e?.()}catch{}}function pe(e){if(e===`0`)return 0;if(!/^(?:\d+(?:\.\d*)?|\.\d+)px$/.test(e))return null;let t=Number.parseFloat(e);return Number.isFinite(t)&&t>=0?t:null}function y(e,t){let n=e;for(;n!==null;){let e=t.getComputedStyle(n);for(let t of[e.perspective,e.rotate,e.scale,e.translate,e.getPropertyValue(`offset-path`)])if(t&&t!==`none`)return!1;let r=e.getPropertyValue(`zoom`);if(r&&r!==`normal`&&r!==`1`)return!1;let i=e.transform;if(i&&i!==`none`){let e=/^matrix\(([^)]+)\)$/.exec(i);if(e===null)return!1;let t=e[1].split(`,`).map(Number);if(t.length!==6||!t.every(Number.isFinite)||t[0]<=0||t[3]<=0||t[1]!==0||t[2]!==0)return!1}let a=n.parentElement;if(a!==null)n=a;else{let e=n.getRootNode();n=e.nodeType===11&&`host`in e?e.host:null}}return!0}function me(e,t,n){try{if(!y(e,n))return null;let r=n.getComputedStyle(e),i=[pe(r.width),pe(r.height),...[r.borderLeftWidth,r.borderRightWidth,r.borderTopWidth,r.borderBottomWidth,r.paddingLeft,r.paddingRight,r.paddingTop,r.paddingBottom].map(e=>pe(e||`0px`))];if(i.some(e=>e===null))return null;let[a,o,s,c,ee,u,d,te,ne,re]=i,ie=s+d,ae=ee+ne,se=ie+c+te,ce=ae+u+re,le=r.boxSizing===`border-box`;if(r.boxSizing&&r.boxSizing!==`border-box`&&r.boxSizing!==`content-box`)return null;let p=a-(le?se:0),m=o-(le?ce:0),h=p+se,ue=m+ce,{left:de,top:g,width:fe,height:_}=e.getBoundingClientRect();if(![p,m,h,ue,fe,_].every(e=>Number.isFinite(e)&&e>0)||!Number.isFinite(de)||!Number.isFinite(g))return null;let v=fe/h,me=_/ue,he=Object.freeze({x:de+(ie+t.x)*v,y:g+(ae+t.y)*me,width:t.width*v,height:t.height*me});return oe(f(`menu`,l.menuAnchor,{rect:he}))?he:null}catch{return null}}function he(oe,pe){let{container:y,hubUrl:he,appId:ve,hubFrame:ye,onConnected:be,showMenu:xe,startGate:Se}=oe,b=Object.freeze({...oe.appearance});if(!re(f(`init`,l.init,{appId:ve,hubFrame:ye,appearance:b})))throw TypeError(`Invalid PayElement initialization`);let Ce=n({hubUrl:he,appId:ve,hubFrame:ye,appearance:b}),we=new URL(Ce).origin,x=y.ownerDocument.defaultView;if(x===null)throw TypeError(`A PayElement needs a host in a window`);let S=y.ownerDocument.createElement(`iframe`),C=r({}),w=i(C);S.style.setProperty(`color-scheme`,`light`,`important`);let T=c(S),E=!1,D=Se.isOpen(),Te=!1,Ee=!1,De=!D,O=!1,k=null,A=0,j=null,M=null,Oe=!1,N={},P=null,F=new Map,ke=null,Ae=null,je=0,Me=new Set,Ne=new Set,Pe=new Set,I=null,Fe=!1,L=0,Ie=null,R=null,z=null,B=0,V=o,Le=new Set,H=null,U=null,W=null,G=null,Re=Promise.resolve(),ze=null;function K(e){if(E)return;let t=s(V,e);if(t===V)return;V=t,y.setAttribute(g,t.status);let n=[...Le];for(let e of n)v(e)}function q(){H!==null&&clearTimeout(H),U!==null&&clearTimeout(U),H=null,U=null}function Be(){q(),!E&&(H=setTimeout(()=>{H=null,K({type:`frameExpired`})},15e3))}function Ve(){q(),!E&&(U=setTimeout(()=>{U=null,K({type:`viewExpired`})},2e4))}function He(){W!==null&&clearTimeout(W),W=null}function Ue(e,t,n){He(),W=setTimeout(()=>{W=null,!(ke!==e||!J(t,n)||!Y(n))&&(G===n&&(G=null),q(),K({type:`payRequestUnanswered`}))},p)}function We(e=G){G!==null&&G===e&&(G=null,Be(),K({type:`peerLost`}))}function Ge(){let e=z;return z=null,B+=1,()=>e?.abort()}function Ke(){return S.isConnected&&S.ownerDocument===y.ownerDocument&&y.contains(S)}function qe(e,t,n,r){if(xe===void 0||!J(n,r)||!Y(r)||!Ke())return;let i=B,a=me(S,e,x);if(a===null||B!==i||!J(n,r)||!Y(r)||!Ke())return;let o=z,s=new AbortController;z=s,B+=1,o?.abort();let c=()=>z===s&&J(n,r)&&Y(r)&&Ke();if(!c()){z===s&&(z=null),s.abort();return}let ee=()=>{z===s&&(z=null,B+=1)},u=e=>{c()&&(ee(),X(f(t,l.menuEnded,{restoreFocus:e}),n,r))};try{xe(a,s.signal,{element:S,onEnd:u}).catch(()=>u(!1)),!c()&&z===s&&(z=null,s.abort())}catch{ee(),s.abort()}}function Je(){Ie!==null&&clearTimeout(Ie),R!==null&&clearTimeout(R),Ie=null,R=null,I=null,Fe=!1,L=0,Pe.clear()}function J(e,t){return!E&&A===e&&j===t}function Y(e){let t=C.getSnapshot();return Oe&&t.epoch===e&&t.accepted&&!t.destroyed}function X(e,t,n){if(!J(t,n))return!1;let r=S.contentWindow;return r===null?!1:(r.postMessage(e,we),!0)}function Ye(t){for(let n of t)v(()=>n.context?.onFailed?.({request:`sign`,attemptId:n.attemptId,message:n.message,error:new e(`unavailable`,`The PayElement was replaced or removed before the outcome arrived`)}))}function Xe(t){let{attemptId:n,message:r,outcome:i,context:a}=t;i.type===`signed`?v(()=>a?.onSigned?.({attemptId:n,message:r,signature:i.signature})):v(()=>a?.onFailed?.({request:`sign`,attemptId:n,message:r,error:new e(i.code,i.description,i.retryAfterSeconds)}))}function Ze(e,t,n){if(!$.heightHolds()){ze={event:e,expected:t,peer:n};return}ze=null,!(G!==n||!Y(n)||!J(t,n))&&(q(),K(e))}function Qe(){let e=ze;e!==null&&Ze(e.event,e.expected,e.peer)}function Z(){ze=null,$.reset(),A+=1;let e=Ge();return Je(),He(),j=null,M=null,Oe=!1,je=0,Ne.clear(),T.reset(),{expected:A,drainMenu:e}}function $e(e){w.resetPeer(e).then(e=>{(e.status===`reset`||e.status===`already-reset`)&&Ye(e.lost)})}function et(e,t){if(!J(e,t))return;let{drainMenu:n}=Z();n(),We(t),$e(t)}function Q(e,t){if(!J(e,t)||I===null)return!1;let n=C.getSnapshot();return n.epoch!==t||n.accepted||n.destroyed?(Je(),!1):!Fe||Date.now()<I+p?!0:(et(e,t),!1)}function tt(e,t,n){if(Q(t,n)){if(e){et(t,n);return}Fe=!0,Q(t,n)}}function nt(){return I!==null&&fe(L)!==null&&Date.now()<I+de}function rt(e,t){if(R!==null&&clearTimeout(R),R=null,!Q(e,t))return;let n=fe(L);if(n===null)return;let r=Math.max(0,I+n-Date.now());R=setTimeout(()=>{R=null,it(e,t)},r)}function it(e,t){let n=M;if(!(n===null||!Q(e,t)||!nt())){if(L+=1,O&&L===m.length+1&&ot(h),De&&!Se.rootCurrent()){J(e,t)&&rt(e,t);return}try{let r=X(n,e,t);if(!J(e,t))return;Oe=r,r?rt(e,t):et(e,t)}catch{et(e,t)}}}function at(){O=!1,k!==null&&clearTimeout(k),k=null}function ot(e){k!==null&&clearTimeout(k),k=setTimeout(st,e)}function st(){if(k=null,!(E||!O)){if(R!==null&&L<=m.length){ot(h);return}O=!1,Z().drainMenu(),S.src=Ce}}function ct(){if(E)return;if(at(),!D){Te=!0;return}let{expected:e,drainMenu:t}=Z();if(t(),We(),E||A!==e)return;let n=x.crypto.randomUUID();E||A!==e||(I=Date.now(),Ie=setTimeout(()=>{if(E||A!==e)return;let t=j;t===null?Z().drainMenu():Q(e,t)},p),w.beginHandshake(n).then(t=>{t.status===`started`&&(Ye(t.lost),!(E||A!==e||C.getSnapshot().epoch!==t.epoch)&&(j=t.epoch,M=Object.freeze(f(n,l.init,Object.freeze({appId:ve,hubFrame:ye,appearance:b}))),it(e,t.epoch)))}))}function lt(e){let t=j;t===null||!Q(A,t)||!nt()||Pe.has(e)||(Pe.add(e),it(A,t))}function ut(e,t){if(P===null||!J(e,t)||!Y(t)||!dt(e,t))return;let n=x.crypto.randomUUID();ke=n,X(`amount`in P?f(n,d.payRequest,P):f(n,d.depositRequest,P),e,t)&&Ue(n,e,t)}function dt(e,t){let n=x.location.href,r=f(x.crypto.randomUUID(),l.pageUrl,{url:n});return re(r)?!X(r,e,t)||!J(e,t)?!1:(Ae=n,!0):!0}function ft(){let e=j;P===null||e===null||!Y(e)||x.location.href===Ae||dt(A,e)}function pt(e,t){!J(e,t)||!Y(t)||w.postConfig(t,x.crypto.randomUUID(),n=>X(n,e,t))}async function mt(t,n,r){if(!J(n,r)||!Oe||I!==null&&(Q(n,r),!J(n,r)))return;if(t.type===d.payRequestAck){Y(r)&&t.id===ke&&t.payload.revision===P?.revision&&(ke=null,He());return}if(t.type===d.held||t.type===d.unconfirmed){if(!Y(r))return;let e=F.get(t.payload.paymentId);if(e===void 0||e.paid)return;let n=Object.freeze({...t.payload}),i=t.type===d.held?e.callbacks.onHeld:e.callbacks.onUnconfirmed;v(()=>i?.(n));return}if(t.type===d.checkoutResult){if(!Y(r))return;let e=t.payload,n=F.get(e.paymentId),i=JSON.stringify([e.paymentId,e.id,e.state]);if(n===void 0||Me.has(i))return;Me.add(i);let a=Object.freeze({...e,destinationTxs:Object.freeze([...e.destinationTxs])});v(()=>n.callbacks.onCheckoutResult?.(a));return}if(t.type===d.paid){if(!Y(r))return;let e=F.get(t.payload.paymentId);if(e===void 0||e.paid||ce(e.request)!==t.payload.job||e.request.currency!==t.payload.currency||!te(e.request,t.payload.amount))return;e.paid=!0;let n=Object.freeze({...t.payload});v(()=>e.callbacks.onPaid?.(n));return}if(t.type===u.viewShown||t.type===u.loadFailed){await Re,Ze(t.type===u.viewShown?{type:`viewShown`}:{type:`loadFailed`,reason:t.payload.reason},n,r);return}if(t.type===l.refused||t.type===l.accepted&&t.id!==M?.id){tt(t.type===l.refused&&t.id===M?.id,n,r);return}if(t.type===l.geometryCapabilities||t.type===l.geometryTarget){let e=(async()=>{(await w.dispatchAuthenticated(r,t,e=>X(e,n,r))).status===`correlated`&&J(n,r)&&Y(r)&&M!==null&&$.receive(t,M.id)})();Re=e.catch(()=>void 0),await e;return}if(t.type===l.resize){if(!Y(r)||$.steering())return;T.resize(t.payload),Qe();return}if(t.type===l.menuAnchor){qe(t.payload.rect,t.id,n,r);return}if(t.type===l.failed&&t.payload.request!==`sign`){if(!Y(r)||Ne.has(t.id))return;Ne.add(t.id);let{request:n,code:i,message:a,retryAfterSeconds:o}=t.payload,s=N.onFailed;v(()=>s?.({request:n,error:new e(i,a,o)}));return}let i=await w.dispatchAuthenticated(r,t,e=>{if(e.type===ee.reloadGrant&&e.payload.granted&&J(n,r)){vt=!0;try{$.reset()}finally{vt=!1}}return X(e,n,r)});if(i.status===`check-status`&&J(n,r)&&w.isCheckStatusCurrent(r,i.message)){let e=i.message,t=N.onCheckStatus;if(t!==void 0){try{await t({attemptId:e.payload.attemptId})}catch{}await w.settleCheckStatus(r,e,e=>X(e,n,r))}}if(i.status===`delivered`&&Xe(i.delivery),i.status===`responded`){if(J(n,r)&&C.getSnapshot().epoch!==r){let e=Ge();Je(),He(),T.reset(),Ne.clear(),je=0,e(),We(r)}Ye(i.lost)}if(!(!J(n,r)||!Y(r))){if(i.status===`accepted`){if(Je(),G=r,Ve(),K({type:`accepted`}),!J(n,r)||!Y(r)||(pt(n,r),ut(n,r),!J(n,r)||!Y(r)))return;M?.payload.appearance!==b&>(n,r)}else if(i.status===`correlated`&&i.message.type===u.connected){let e=i.message.payload;if(e.sequence<=je)return;je=e.sequence,v(()=>be?.({evmAddress:e.evmAddress}))}}}function ht(e){if(E||e.origin!==we)return;let t=S.contentWindow;if(t===null||e.source!==t)return;let n=A,r=ne(e.data);if(r===void 0||E||A!==n)return;if(at(),r.type===l.ready){D||(Ee=!0),lt(r.id);return}let i=j;i!==null&&Promise.resolve().then(()=>mt(r,n,i))}function gt(e,t){let n=f(x.crypto.randomUUID(),`appearance`,{appearance:b});try{X(n,e,t)}catch{}}function _t(){let e=A,t=j;w.setCheckStatusCapability(N.onCheckStatus!==void 0,n=>t!==null&&X(n,e,t))}let vt=!1,$=a(S,e=>{let t=j;if(t===null||!Y(t)&&!vt)return!1;try{return X(e,A,t)}catch{return!1}},e=>{T.resize(e),Qe()}),yt={configurePay(e,t){if(E)return{status:`ignored`,reason:`destroyed`};if(!Se.isOpen())return{status:`ignored`,reason:`not-started`};if(!(`amount`in e?se({...e,revision:1}):ae({...e,revision:1})))return{status:`ignored`,reason:`invalid-config`};let n=F.get(e.paymentId);if(n!==void 0&&!le(n.request,e))return{status:`ignored`,reason:`payment-conflict`};let r=(P?.revision??0)+1;return Number.isSafeInteger(r)?(P=Object.freeze({...e,revision:r}),N=_(t),n===void 0&&F.set(e.paymentId,{request:P,callbacks:N,paid:!1}),j!==null&&ut(A,j),{status:`updated`,revision:r}):{status:`ignored`,reason:`exhausted`}},configure(e,t){if(E)return{status:`ignored`,reason:`destroyed`};if(!Se.isOpen())return{status:`ignored`,reason:`not-started`};let n=_(t);if(E)return{status:`ignored`,reason:`destroyed`};let r=N.onCheckStatus!==n.onCheckStatus;N=n,r&&_t();let i=C.update(e,n);return i.status===`updated`&&j!==null&&pt(A,j),i},setCallbacks(e){if(E)return;let t=_(e);if(!E){let e=N.onCheckStatus!==t.onCheckStatus;N=t,e&&_t()}},setAppearance(e){if(E)return;let t=Object.freeze({...e});if(!ie(t))throw TypeError(`Invalid PayElement appearance`);t.theme!==b.theme&&(b=t,j!==null&&Y(j)&>(A,j))},getLoadState:()=>V,subscribeLoadState(e){if(E)return()=>void 0;let t=()=>e();return Le.add(t),()=>{Le.delete(t)}},retry(){if(E||s(V,{type:`retried`})===V)return;at();let e=j,{expected:t,drainMenu:n}=Z();G=null,n(),e!==null&&$e(e),!(E||A!==t)&&(Be(),S.src=Ce,K({type:`retried`}))},start(){E||D||!Se.isOpen()||(D=!0,Be(),Te&&(Te=!1,ct(),!(Ee||E)&&(O=!0,ot(ue))))},focus(){if(E)return;S.focus({preventScroll:!0});let e=j;if(!(e===null||!Y(e)))try{X(f(x.crypto.randomUUID(),l.focus,{}),A,e)}catch{}},destroy(){if(E)return;at(),$.dispose(),E=!0,q(),Le.clear(),G=null;let{drainMenu:e}=Z();x.removeEventListener(`message`,ht);for(let e of ge)x.removeEventListener(e,ft);_e(x)?.removeEventListener(`currententrychange`,ft),S.removeEventListener(`load`,ct),T.destroy(),S.remove(),y.removeAttribute(g),N={},Pe.clear(),e(),w.destroy().then(e=>Ye(e.lost)),pe?.()}};S.title=`Stridge Wallet ${x.crypto.randomUUID()}`,S.loading=`eager`,S.allow=`clipboard-write`,S.style.display=`block`,S.style.inlineSize=`100%`,S.style.border=`0`,S.style.borderRadius=t.inkRadius.value,x.addEventListener(`message`,ht);for(let e of ge)x.addEventListener(e,ft);_e(x)?.addEventListener(`currententrychange`,ft),S.addEventListener(`load`,ct),y.setAttribute(g,V.status),D&&Be();try{S.src=Ce,E||y.append(S)}catch(e){throw yt.destroy(),e}return yt}const ge=[`popstate`,`hashchange`,`blur`];function _e(e){let t=e.navigation;return typeof t?.addEventListener==`function`&&typeof t.removeEventListener==`function`?t:null}export{he as createElementHandle};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PAY_ELEMENT_MESSAGE_TYPES as e,PAY_PROTOCOL as t,SUA_PROTOCOL_VERSION as n,isAppElementMessage as r}from"@stridge/pay-sdk";function i(e){return Object.freeze({status:`ignored`,reason:e})}function a(r,i){return{protocol:t,version:n,id:r,type:e.config,payload:i}}function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=e,n={};for(let e of Object.keys(t)){let r=t[e];r!==void 0&&(n[e]=r)}return n}function s(e,t){let n=e,r={};for(let e of Object.keys(n))e===`labels`||e===`action`?r[e]=o(n[e]):r[e]=n[e];return r.revision=t,r}function c(e){return Object.freeze(e.labels),e.action!==null&&Object.freeze(e.action),Object.freeze(e)}function l(e){return e.action===null?null:e.action}function u(t){if(t.type===e.signed){let{attemptId:e,message:n,signature:r}=t.payload;return{attemptId:e,signedMessage:n,outcome:Object.freeze({type:`signed`,signature:r})}}let n=t.payload;if(n.request!==`sign`)return null;let{attemptId:r,code:i,message:a,retryAfterSeconds:o}=n;return{attemptId:r,signedMessage:null,outcome:Object.freeze(o===void 0?{type:`failed`,code:i,description:a}:{type:`failed`,code:i,description:a,retryAfterSeconds:o})}}function d(){return Object.freeze(Object.create(null))}function f(e){if(e===void 0)return 0;if(!Number.isSafeInteger(e)||e<0)throw RangeError(`lastRevision must be a safe integer from 0 to Number.MAX_SAFE_INTEGER`);return e}function p(e){let t=f(e.lastRevision),n=null,o=new Map,p=new Set,m=new Map,h=null,g=null,_=new WeakSet,v=!1;function y(e){return g!==null&&g.epoch===e&&g.accepted}function b(){if(g===null)return Object.freeze([]);_.add(g.epoch),g=null,m.clear(),h=null;let e=[];for(let t of o.values())(t.status===`exposed`||t.status===`consumed`)&&(e.push(Object.freeze({attemptId:t.attemptId,message:t.message,context:t.context,consumption:t.status===`consumed`?`recorded`:`uncertain`})),t.status=`retired`);return Object.freeze(e)}function x(e){return e.status===`configured`?`not-exposed`:e.status===`retired`?`retired`:e.status===`settled`?`settled`:null}function S(e,t,n){let r=o.get(e);if(r!==void 0)return r;let i={attemptId:e,message:t,context:n,status:`configured`};return o.set(e,i),i}return{update(e,u){if(v)return i(`destroyed`);if(t>=2**53-1)return i(`exhausted`);if(typeof e!=`object`||!e)return i(`invalid-config`);let d=t+1,f=s(e,d);if(!r(a(`element-ledger-check`,f)))return i(`invalid-config`);let p=c(f),m=l(p),h=m===null?void 0:o.get(m.attemptId);if(m!==null&&h!==void 0&&h.message!==m.message)return i(`attempt-conflict`);t=d,n=p;let g=m===null?null:S(m.attemptId,m.message,u);return Object.freeze({status:`updated`,revision:d,config:p,attemptStatus:g?.status??null})},beginHandshake(){if(v)return i(`destroyed`);let e=b(),t=d();return g={epoch:t,accepted:!1},Object.freeze({status:`started`,epoch:t,lost:e})},acceptHandshake(e){return v?i(`destroyed`):g===null||g.epoch!==e?i(`stale-epoch`):g.accepted?i(`already-accepted`):(g.accepted=!0,Object.freeze({status:`accepted`,latestRevision:n?.revision??null}))},prepareConfig(e,t){if(v)return i(`destroyed`);if(!y(t))return i(`stale-epoch`);if(n===null)return i(`no-config`);let o=a(e,n);return r(o)?p.has(e)?i(`envelope-id-reused`):(p.add(e),m.set(e,{envelopeId:e,config:n,posted:!1}),Object.freeze({status:`prepared`,message:Object.freeze(o)})):i(`invalid-envelope-id`)},configPosted(e,t,n){if(v)return i(`destroyed`);if(!y(t))return i(`stale-epoch`);let r=m.get(e);if(r===void 0)return i(`unknown-envelope`);if(r.posted)return i(`already-reported`);if(!n)return m.delete(e),Object.freeze({status:`recorded`,posted:!1,exposedAttemptId:null});r.posted=!0;let a=l(r.config),s=a===null?void 0:o.get(a.attemptId);return s===void 0||s.status!==`configured`?Object.freeze({status:`recorded`,posted:!0,exposedAttemptId:null}):(s.status=`exposed`,Object.freeze({status:`recorded`,posted:!0,exposedAttemptId:s.attemptId}))},acceptAck(e,t,n){if(v)return i(`destroyed`);if(!y(n))return i(`stale-epoch`);let r=m.get(e);return r===void 0?i(`unknown-envelope`):r.posted?r.config.revision===t?(m.delete(e),h=Math.max(h??0,t),Object.freeze({status:`acknowledged`,revision:t,acknowledgedRevision:h})):i(`revision-mismatch`):i(`not-posted`)},recordConsumed(e,t){if(v)return i(`destroyed`);if(!y(t))return i(`stale-epoch`);let{attemptId:n,message:r}=e,a=o.get(n);if(a===void 0)return i(`unknown-attempt`);let s=x(a);return s===null?a.message===r?a.status===`consumed`?i(`already-consumed`):(a.status=`consumed`,Object.freeze({status:`recorded`})):i(`message-mismatch`):i(s)},settle(e,t){if(v)return i(`destroyed`);if(!y(t))return i(`stale-epoch`);let n=u(e);if(n===null)return i(`not-sign`);let r=o.get(n.attemptId);if(r===void 0)return i(`unknown-attempt`);let a=x(r);if(a!==null)return i(a);if(n.signedMessage!==null&&n.signedMessage!==r.message)return i(`message-mismatch`);r.status=`settled`;let s=Object.freeze({attemptId:r.attemptId,message:r.message,context:r.context,outcome:n.outcome});return Object.freeze({status:`delivered`,delivery:s})},resetPeer(e){return v?i(`destroyed`):g!==null&&g.epoch===e?Object.freeze({status:`reset`,lost:b()}):_.has(e)?Object.freeze({status:`already-reset`,lost:Object.freeze([])}):i(`unknown-epoch`)},getSnapshot(){return Object.freeze({destroyed:v,lastRevision:t,exhausted:t>=2**53-1,latest:n,epoch:g?.epoch??null,accepted:g?.accepted??!1,acknowledgedRevision:h,ready:g!==null&&g.accepted&&n!==null&&h===n.revision,outstanding:Object.freeze([...m.values()].map(e=>Object.freeze({envelopeId:e.envelopeId,revision:e.config.revision,posted:e.posted}))),attempts:Object.freeze([...o.values()].map(e=>Object.freeze({attemptId:e.attemptId,message:e.message,status:e.status})))})},getRetiredAttempts(){let e=[];for(let t of o.values())t.status!==`configured`&&t.status!==`exposed`&&e.push(Object.freeze({attemptId:t.attemptId,message:t.message}));return Object.freeze(e)},destroy(){if(v)return Object.freeze({status:`already-destroyed`,lost:Object.freeze([])});let e=b();v=!0,m.clear();for(let e of o.values())e.context=void 0;return Object.freeze({status:`destroyed`,lost:e})}}}export{p as createElementLedger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MAX_MESSAGE_ID_LENGTH as e,PAY_ELEMENT_LIFETIME_MESSAGE_TYPES as t,PAY_ELEMENT_MESSAGE_TYPES as n,PAY_ELEMENT_NOTIFICATION_MESSAGE_TYPES as r,createPayEnvelope as i}from"@stridge/pay-sdk";function a(e){return Object.freeze({status:`ignored`,reason:e})}function o(e,t){try{return{postSucceeded:e(t)===!0,postError:null}}catch(e){return{postSucceeded:!1,postError:e}}}function s(s){let c=null,l=null,u=!1,d=!1,f=null,p=new Set,m=new Map,h=!1,g=null,_=new Set,v=[],y=!1;function b(e){return new Promise((t,n)=>{if(v.push(()=>{try{t(e())}catch(e){n(e)}}),!y){y=!0;try{for(;v.length>0;)v.shift()()}finally{y=!1}}})}function x(e){let t=s.getSnapshot();return c?.epoch===e&&t.epoch===e&&t.accepted&&!t.destroyed}function S(e,t,n){return!x(e)||c===null||c.initId!==t||c.documentId!==null&&c.documentId!==n?!1:(c.documentId=n,!0)}function C(e){let t=c;if(!d||t===null||t.documentId===null||!x(t.epoch)||f?.peer===t&&f.supported===u)return;let r=u;o(e,i(t.initId,n.checkStatusCapability,{documentId:t.documentId,initId:t.initId,supported:r})).postSucceeded&&c===t&&u===r&&(f={peer:t,supported:r})}function w(e,t){let{documentId:n,initId:r,configId:i,revision:a,attemptId:o}=t.payload,d=l,f=s.getSnapshot(),p=f.attempts.find(e=>e.attemptId===o);return u&&x(e)&&c?.documentId===n&&c.initId===r&&d!==null&&d.epoch===e&&d.configId===i&&d.initId===r&&d.postSucceeded&&d.acknowledged&&d.fullConfig===f.latest&&d.fullConfig.revision===a&&d.fullConfig.action?.attemptId===o&&p!==void 0&&p.message===d.fullConfig.action.message&&(p.status===`consumed`||p.status===`settled`||p.status===`retired`)}function T(e,t,n=[]){return Object.freeze(e.payload),Object.freeze(e),Object.freeze({status:`responded`,response:e,lost:n,...o(t,e)})}function E(e,n,r){let{initId:o,documentId:c,configId:u,revision:d,attemptId:f}=n.payload;if(!S(e,o,c))return a(`stale-document`);let p=l,m=s.getSnapshot();if(p===null||p.epoch!==e||p.initId!==o||p.configId!==u||!p.postSucceeded||!p.acknowledged||p.fullConfig.revision!==d||m.latest!==p.fullConfig)return a(`not-current-config`);let h=p.fullConfig;if(h.action===null||h.action.attemptId!==f)return a(`not-current-action`);let g=m.attempts.find(e=>e.attemptId===f);return g===void 0||g.message!==h.action.message||g.status===`configured`?a(`conflicting-attempt`):T(i(n.id,t.actionEligibility,{...n.payload,eligible:g.status===`exposed`}),r)}function D(e,n,r){let o=g,u=s.getSnapshot();if(!u.destroyed&&u.epoch===null&&o?.epoch===e&&o.request.id===n.id&&o.request.payload.documentId===n.payload.documentId&&o.request.payload.initId===n.payload.initId&&o.request.payload.reason===n.payload.reason)return T(o.response,r);let{initId:d,documentId:p}=n.payload;if(!S(e,d,p))return a(`stale-document`);let _=i(n.id,t.reloadGrant,{initId:d,documentId:p,granted:!h});if(h)return T(_,r);h=!0,g={epoch:e,request:n,response:_},c=null,l=null,m.clear(),f=null;let v=s.resetPeer(e);return v.status===`reset`?T(_,r,v.lost):(g=null,a(`reset-unavailable`))}function O(e,i,o){if(i.type===t.reloadRequest)return D(e,i,o);if(c?.epoch!==e||s.getSnapshot().epoch!==e)return a(`stale-epoch`);if(i.type===n.accepted)return c.initId===i.id?s.acceptHandshake(e):a(`wrong-init`);if(!x(e))return a(`not-accepted`);switch(i.type){case n.configAck:{let t=s.acceptAck(i.id,i.payload.revision,e);return t.status===`acknowledged`&&l?.epoch===e&&l.configId===i.id&&l.fullConfig.revision===i.payload.revision&&l.postSucceeded&&(l.acknowledged=!0),t}case t.actionCheck:return E(e,i,o);case r.checkStatusRequest:return!w(e,i)||p.has(i.id)?a(`invalid-check-status`):(p.add(i.id),m.set(i,l),Object.freeze({status:`check-status`,message:i}));case n.signed:case n.failed:return s.settle(i,e);case n.geometryCapabilities:case n.geometryTarget:case r.connected:return S(e,i.payload.initId,i.payload.documentId)?Object.freeze({status:`correlated`,message:i}):a(`stale-document`);default:return a(`not-bridge-message`)}}return{setCheckStatusCapability(e,t){return b(()=>{d=!0,u=e,e||m.clear(),f=null,C(t)})},isCheckStatusCurrent(e,t){return m.get(t)===l&&w(e,t)},settleCheckStatus(e,t,r){return b(()=>{let s=m.get(t)===l&&w(e,t);return m.delete(t),s?o(r,i(t.id,n.checkStatusSettled,t.payload)):a(`stale-check-status`)})},beginHandshake(t){return b(()=>{if(typeof t!=`string`||t.length===0||t.length>e)return a(`invalid-init-id`);if(_.has(t))return a(`init-id-reused`);let n=s.beginHandshake();return n.status===`started`?(_.add(t),m.clear(),f=null,c={epoch:n.epoch,initId:t,documentId:null},l=null,g=null,n):n})},postConfig(e,t,n){return b(()=>{if(!x(e)||c===null)return a(`not-accepted`);let r=s.prepareConfig(t,e);if(r.status!==`prepared`)return r;let i={epoch:e,initId:c.initId,configId:t,fullConfig:r.message.payload,postSucceeded:!1,acknowledged:!1};m.clear(),l=i;let u=o(n,r.message),d=s.configPosted(t,e,u.postSucceeded);return i.postSucceeded=d.status===`recorded`&&d.posted,Object.freeze({status:`posted`,message:r.message,...u})})},dispatchAuthenticated(e,t,n){return b(()=>{let r=O(e,t,n);return x(e)&&C(n),r})},resetPeer(e){return b(()=>{let t=s.resetPeer(e);return c?.epoch===e&&(m.clear(),f=null,c=null,l=null),t})},destroy(){return b(()=>{let e=s.destroy();return c=null,l=null,g=null,_.clear(),m.clear(),p.clear(),e})}}}export{s as createElementLifetimeBridge};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import "../errors/PayError.js";
|
|
2
|
+
import "../channel/types.js";
|
|
3
|
+
import "./elementLoadState.js";
|
|
4
|
+
import "./types.js";
|
|
5
|
+
import { CeremonyRequestType, ElementDepositRequestPayload, ElementPayRequestPayload, HubAppearance } from "@stridge/pay-sdk";
|
|
6
|
+
//#region src/core/elementClientTypes.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* An address observed through an authenticated element connected notice or a successful app-owned sign-in.
|
|
9
|
+
* The provider notifies once per distinct address across both sources, using one set for its lifetime, including
|
|
10
|
+
* an element that starts connected. Multiple elements, StrictMode replay and reconnection of the same address
|
|
11
|
+
* do not repeat the notification. This is not proof of a live signing session.
|
|
12
|
+
*/
|
|
13
|
+
interface PayConnectedEvent {
|
|
14
|
+
/**
|
|
15
|
+
* The connected wallet's EVM address, as the hub reports it.
|
|
16
|
+
*/
|
|
17
|
+
readonly evmAddress: string;
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
export { PayConnectedEvent };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PAY_ELEMENT_MESSAGE_TYPES as e,createPayEnvelope as t}from"@stridge/pay-sdk";function n(n,r,i){let a=n.ownerDocument.defaultView,o=null,s=null,c=0,l=0,u=null,d=null,f=!1,p=!1,m=new Set,h=()=>n.getBoundingClientRect().width;function g(e){let t=u;u=null,d!==null&&a.cancelAnimationFrame(d),d=null,t!==null&&_(t,e)}function _(n,i){m.has(n.id)||(m.add(n.id),r(t(n.id,i?e.geometryCancelled:e.geometryComplete,{documentId:n.payload.documentId,initId:n.payload.initId})))}function v(){if(g(!0),o===null)return;c=h(),s=a.crypto.randomUUID(),l=0;let n=s;!r(t(n,e.geometryCapabilities,{...o,supported:!0}))&&s===n&&(s=null)}function y(){o!==null&&h()!==c&&(p=!0,v())}let b=typeof ResizeObserver>`u`?null:new ResizeObserver(y);return b?.observe(n),a.addEventListener(`resize`,y),{receive(t,r){if(t.type===e.geometryCapabilities){if(t.payload.initId!==r||o!==null&&o.documentId!==t.payload.documentId)return;if(!t.payload.supported){this.reset();return}o={documentId:t.payload.documentId,initId:r},v()}else if(t.type===e.geometryTarget){let e=t.payload;if(o===null||e.initId!==r||e.initId!==o.initId||e.documentId!==o.documentId||m.has(t.id)||(y(),u?.id===t.id))return;if(s===null||!t.id.startsWith(`${s}:`)||e.durationMs!==0||!n.isConnected){_(t,!0);return}let c=Number(t.id.slice(s.length+1));if(!Number.isSafeInteger(c)||c<=l){_(t,!0);return}g(!0),u=t,l=c,f=!0,p=!1,i({blockSize:e.blockSize,durationMs:0}),d=a.requestAnimationFrame(()=>{d=null,u===t&&(y(),u===t&&g(!n.isConnected))})}},enabled:()=>s!==null,steering:()=>f,heightHolds(){return y(),!p},reset(){g(!0),o=null,s=null,f=!1,p=!1,m.clear()},dispose(){this.reset(),b?.disconnect(),a.removeEventListener(`resize`,y)}}}export{n as createAppElementGeometry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { PayElementLoadFailureReason } from "@stridge/pay-sdk";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PAY_ELEMENT_LOAD_FAILURE_REASONS as e}from"@stridge/pay-sdk";const t=Object.freeze({status:`loading`,retrying:!1}),n=Object.freeze({status:`loading`,retrying:!0}),r=Object.freeze({status:`shown`}),i=Object.freeze({status:`failed`,by:`frame`}),a=Object.freeze({[e.hubFrame]:Object.freeze({status:`failed`,by:`hub`,reason:e.hubFrame}),[e.internal]:Object.freeze({status:`failed`,by:`hub`,reason:e.internal})});function o(e,o){switch(o.type){case`retried`:return e.status===`failed`?n:e;case`accepted`:return e.status===`failed`&&e.by===`frame`?t:e;case`viewShown`:return r;case`loadFailed`:return a[o.reason];case`frameExpired`:return e.status===`loading`?i:e;case`viewExpired`:return e.status===`loading`?r:e;case`peerLost`:return e.status===`loading`||e.status===`failed`&&e.by===`frame`?e:t;case`payRequestUnanswered`:return e.status===`failed`?e:i}}export{t as INITIAL_ELEMENT_LOAD,o as reduceElementLoad};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{MAX_ELEMENT_BLOCK_SIZE as e,MAX_ELEMENT_RESIZE_DURATION_MS as t}from"@stridge/pay-sdk";function n(){return 62}function r(r){let i=n(),a=!1,o=!1;function s(){a||(o=!1,r.inert=!0,r.style.pointerEvents=`none`,r.style.visibility=`hidden`,r.style.transition=`none`,r.style.blockSize=`${i}px`)}return s(),{reset:s,resize({blockSize:n,durationMs:i}){a||!Number.isFinite(n)||n<0||n>e||!Number.isSafeInteger(i)||i<0||i>t||(r.style.transition=i>0?`block-size ${i}ms`:`none`,r.style.blockSize=`${n}px`,n>0&&(o||i===0)&&(o=!0,r.style.visibility=``,r.style.pointerEvents=``,r.inert=!1))},destroy(){a=!0,r.inert=!0,r.style.pointerEvents=`none`,r.style.transition=`none`}}}export{r as createElementSizing,n as initialElementBlockSize};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=!1;return{gate:Object.freeze({isOpen:()=>t,rootCurrent:()=>t&&e()}),open(){t=!0}}}export{e as createElementStartGate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { AppElementConfigMessage, ElementConfigPayload, ElementFailureCode } from "@stridge/pay-sdk";
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { HubErrorCode } from "@stridge/pay-sdk";
|
|
2
|
+
//#region src/errors/PayError.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Why a request from the app face failed: the hub's own error codes, plus two the app face raises itself.
|
|
5
|
+
*
|
|
6
|
+
* - `unavailable` — the hub never completed the handshake, or reloaded while the request was in flight, or a `fund`
|
|
7
|
+
* request got neither an answer nor the hub's dialog within its limit (a hub that predates Fund drops it).
|
|
8
|
+
* - `popup-blocked` — the browser refused to open the Stridge window (`window.open` returned `null` or threw), usually
|
|
9
|
+
* because the request did not start in the user's click. No hub sends it.
|
|
10
|
+
*/
|
|
11
|
+
type PayErrorCode = HubErrorCode | "unavailable" | "popup-blocked";
|
|
12
|
+
/**
|
|
13
|
+
* A request from the app face (`signIn`, `sign`, `signOut`, `disconnect`, `fund`) did not succeed.
|
|
14
|
+
* Branch on `code`.
|
|
15
|
+
*/
|
|
16
|
+
declare class PayError extends Error {
|
|
17
|
+
/**
|
|
18
|
+
* Why it failed.
|
|
19
|
+
*/
|
|
20
|
+
readonly code: PayErrorCode;
|
|
21
|
+
/**
|
|
22
|
+
* Whole seconds to wait, with `rate-limited`, when the hub said.
|
|
23
|
+
*/
|
|
24
|
+
readonly retryAfterSeconds: number | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Builds the error: `name` is `"PayError"`, `message` is `message` when not empty, else `Request failed:
|
|
27
|
+
* <code>`, and the prototype is fixed with `Object.setPrototypeOf` for transpiled targets.
|
|
28
|
+
*/
|
|
29
|
+
constructor(code: PayErrorCode, message?: string, retryAfterSeconds?: number);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Reports whether `value` is a {@link PayError}: `instanceof`, or an `Error` whose `name` is `"PayError"`
|
|
33
|
+
* and whose `code` is a string (a copy from a second bundle). With `code` given, the error's `code` must also equal it.
|
|
34
|
+
*/
|
|
35
|
+
declare function isPayError(value: unknown, code?: PayErrorCode): value is PayError;
|
|
36
|
+
//#endregion
|
|
37
|
+
export { PayError, PayErrorCode, isPayError };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{code;retryAfterSeconds;constructor(e,t,n){super(t!==void 0&&t.length>0?t:`Request failed: ${e}`),Object.setPrototypeOf(this,new.target.prototype),this.name=`PayError`,this.code=e,this.retryAfterSeconds=n}};function t(t,n){return t instanceof e||t instanceof Error&&t.name===`PayError`&&typeof t.code==`string`?n===void 0||t.code===n:!1}export{e as PayError,t as isPayError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{useEffect as e,useState as t}from"react";function n({status:e,evmAddress:t,keypairExpiresAt:n},r){if(e!==`signed-in`||t===void 0)return`none`;if(n===void 0)return`expired`;let i=Date.parse(n);return Number.isNaN(i)||i<=r?`expired`:`live`}function r(r){let[i,a]=t(0),o=n(r,Date.now()),{keypairExpiresAt:s}=r;return e(()=>{if(o!==`live`||s===void 0)return;let e=Math.min(Math.max(Date.parse(s)-Date.now(),0),2147483647),t=setTimeout(()=>a(e=>e+1),e);return()=>clearTimeout(t)},[o,s,i]),o}export{n as keypairStateAt,r as useKeypairState};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { PayDisconnectOptions, PayFundOptions } from "../channel/types.js";
|
|
2
|
+
import { HubStatus, HubTransport } from "@stridge/pay-sdk";
|
|
3
|
+
//#region src/hooks/types.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The provider channel's observed hub status. `checking` also covers the time before its first state message,
|
|
6
|
+
* and `unavailable` also covers a failed connection.
|
|
7
|
+
*/
|
|
8
|
+
type PayAccountStatus = HubStatus;
|
|
9
|
+
/**
|
|
10
|
+
* Where the hub shows its ceremonies:
|
|
11
|
+
*
|
|
12
|
+
* - `overlay`: in the hub's iframe, shown as a full-viewport layer over the app's page.
|
|
13
|
+
* - `popup`: in the Stridge window, a window on the hub's origin that each request opens from the user's click. The hub
|
|
14
|
+
* picks it when its frame cannot reach the hub's own storage (Safari, Firefox, blocked third-party cookies), or
|
|
15
|
+
* when it is set to always use it.
|
|
16
|
+
*/
|
|
17
|
+
type PayTransport = HubTransport;
|
|
18
|
+
/**
|
|
19
|
+
* Whether the hub holds a keypair that can sign now, as the app face can tell from the hub's state:
|
|
20
|
+
*
|
|
21
|
+
* - `live`: signed in with an address, and the keypair's expiry is still ahead on this device's clock.
|
|
22
|
+
* - `expired`: signed in with an address, and the keypair has lapsed. The hub sends no expiry for a lapsed keypair,
|
|
23
|
+
* and a live one flips to `expired` when its expiry passes. The next `sign()` asks for a code and renews it first.
|
|
24
|
+
* - `none`: not signed in with an address (signed out, checking, or a wallet still being created).
|
|
25
|
+
*/
|
|
26
|
+
type PayKeypairState = "live" | "expired" | "none";
|
|
27
|
+
/**
|
|
28
|
+
* The headless state and commands `usePayAccount` returns.
|
|
29
|
+
*/
|
|
30
|
+
interface PayAccount {
|
|
31
|
+
/**
|
|
32
|
+
* The provider's own hub frame and app-owned Stridge windows supply this observation. Without an observed state it
|
|
33
|
+
* stays `checking`; a failed connection is `unavailable`. Element-connected notices notify `onConnected` without
|
|
34
|
+
* mirroring status or account into headless state. A click may call a command while status is still `checking`.
|
|
35
|
+
*/
|
|
36
|
+
status: PayAccountStatus;
|
|
37
|
+
/**
|
|
38
|
+
* Where the next request shows its ceremony; see {@link PayTransport}. Uses the current authenticated frame
|
|
39
|
+
* report, with popup before that report and after its connection restarts. Saved display hints do not select it.
|
|
40
|
+
*/
|
|
41
|
+
transport: PayTransport;
|
|
42
|
+
/**
|
|
43
|
+
* The wallet's EVM address, while signed in and once the wallet has one, which a `pending` wallet already has.
|
|
44
|
+
* Signing waits until the wallet is active: until then `sign()` fails because the wallet cannot sign yet.
|
|
45
|
+
*/
|
|
46
|
+
evmAddress?: string;
|
|
47
|
+
/**
|
|
48
|
+
* When the provider channel observed that the hub's live keypair stops signing (RFC 3339).
|
|
49
|
+
*/
|
|
50
|
+
keypairExpiresAt?: string;
|
|
51
|
+
/**
|
|
52
|
+
* Whether the hub's keypair can sign now; see {@link PayKeypairState}. A display hint on the device's clock: the
|
|
53
|
+
* hub decides at the next `sign()`.
|
|
54
|
+
*/
|
|
55
|
+
keypair: PayKeypairState;
|
|
56
|
+
/**
|
|
57
|
+
* Whether a ceremony is in progress: the hub frame reports it is busy, a request is in flight, or the hub's overlay
|
|
58
|
+
* is open. The hub can stay busy after its dialog closes, for one while a wallet it was creating finishes in the
|
|
59
|
+
* background; before the frame's first report, and after its connection starts over, only the request and the
|
|
60
|
+
* overlay count. A trigger or account button shows its busy look meanwhile. A display hint, not a promise that the
|
|
61
|
+
* hub is ready or will accept a request: the hub decides at the next one.
|
|
62
|
+
*/
|
|
63
|
+
busy: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* Opens the hub's sign-in (or renewal) and resolves with the signed-in EVM address. The address can come with a
|
|
66
|
+
* wallet that is still `pending` (after "Continue as", for one); signing waits until the wallet is active. Rejects
|
|
67
|
+
* with a `PayError`.
|
|
68
|
+
*/
|
|
69
|
+
signIn(): Promise<{
|
|
70
|
+
evmAddress: string;
|
|
71
|
+
}>;
|
|
72
|
+
/**
|
|
73
|
+
* Shows the hub's sign confirm screen for `message` and resolves with the EVM signature (`0x`, 132 characters).
|
|
74
|
+
* With no session, the hub first signs the user in, or offers "Continue as" when the session's user has not
|
|
75
|
+
* authorized this app; it authorizes this app and then shows the confirm, all in one dialog. A confirm cancelled
|
|
76
|
+
* after that sign-in leaves the app signed in. Rejects with a `TypeError` for an empty or oversized message, or a
|
|
77
|
+
* `PayError`.
|
|
78
|
+
*/
|
|
79
|
+
sign(message: string): Promise<string>;
|
|
80
|
+
/**
|
|
81
|
+
* Signs out of Stridge in this browser. The hub ends the session, which signs out every app that shares it, and
|
|
82
|
+
* forgets every app's authorization; use `disconnect()` for this app only. Resolves with nothing signed out when
|
|
83
|
+
* this app is not authorized. Rejects with a `PayError`: `signed-out` when the browser now holds another
|
|
84
|
+
* account's session, which stays signed in.
|
|
85
|
+
*/
|
|
86
|
+
signOut(): Promise<void>;
|
|
87
|
+
/**
|
|
88
|
+
* Disconnects this app only: the hub revokes its authorization, so the status becomes `signed-out` while the user
|
|
89
|
+
* stays signed in to Stridge for every other app. The next `signIn()` asks to continue with no code. Rejects with a
|
|
90
|
+
* `PayError`. A `diagnosticsTarget` requires the current eligible frame and never falls back to a popup.
|
|
91
|
+
*/
|
|
92
|
+
disconnect(options?: PayDisconnectOptions): Promise<void>;
|
|
93
|
+
/**
|
|
94
|
+
* Opens Fund in the hub's Stridge Wallet dialog, on the screen `options.start` names (`fund` by default, or
|
|
95
|
+
* `home`). Every amount, address and linked wallet stays in the hub; this app never sees them. Resolves once the
|
|
96
|
+
* user closes Fund (closing the Stridge window that shows it counts too). It requires a signed-in session whose user authorized this app, signs no one in and renews nothing.
|
|
97
|
+
* It rejects with a `PayError` when the session cannot open Fund, and with `unavailable` when the hub never opened Fund within
|
|
98
|
+
* its limit, which is how a hub that predates Fund shows. Call it in the user's click, since it may open the Stridge
|
|
99
|
+
* window.
|
|
100
|
+
*/
|
|
101
|
+
fund(options?: PayFundOptions): Promise<void>;
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
export { PayAccount, PayAccountStatus, PayKeypairState, PayTransport };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import "../channel/types.js";
|
|
2
|
+
import { PayAccount } from "./types.js";
|
|
3
|
+
//#region src/hooks/usePayAccount.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Reports the provider channel's own authenticated frame/window observations and stable synchronous command
|
|
6
|
+
* closures. Element-connected notices notify the host without mirroring into this hook. Keypair expiry remains
|
|
7
|
+
* a display hint over the channel's observed account.
|
|
8
|
+
*
|
|
9
|
+
* Busy combines reported hub activity with this page's pending request and open overlay. Unknown activity adds
|
|
10
|
+
* nothing. Commands call the channel in the user's task so a Stridge window can open directly from the click.
|
|
11
|
+
*
|
|
12
|
+
* @throws {Error} like {@link usePayChannel} outside a provider.
|
|
13
|
+
*/
|
|
14
|
+
declare function usePayAccount(): PayAccount;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { usePayAccount };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{usePayChannel as e,usePaySnapshot as t}from"./usePaySnapshot.js";import{useKeypairState as n}from"./keypairState.js";import{useMemo as r}from"react";function i(e){let t={status:e.status};return e.evmAddress!==void 0&&(t.evmAddress=e.evmAddress),e.keypairExpiresAt!==void 0&&(t.keypairExpiresAt=e.keypairExpiresAt),t}function a(e){return e.connection===`failed`?{status:`unavailable`}:e.hub===null?{status:`checking`}:i(e.hub)}function o(e){return e.currentTransport??`popup`}function s(){let i=e(),s=t(),c=r(()=>({signIn:()=>i.signIn(),sign:e=>i.sign(e),signOut:()=>i.signOut(),disconnect:e=>i.disconnect(e),fund:e=>i.fund(e)}),[i]),l=a(s),u=n(l),d={status:l.status,keypair:u,transport:o(s),busy:s.hubActivity===!0||s.pending!==null||s.overlayOpen,signIn:c.signIn,sign:c.sign,signOut:c.signOut,disconnect:c.disconnect,fund:c.fund};return l.evmAddress!==void 0&&(d.evmAddress=l.evmAddress),l.keypairExpiresAt!==void 0&&(d.keypairExpiresAt=l.keypairExpiresAt),d}export{a as toPayAccount,o as toPayTransport,s as usePayAccount};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { PaySnapshot } from "../channel/types.js";
|
|
2
|
+
//#region src/hooks/usePaySnapshot.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Subscribes to the channel's snapshot through `useSyncExternalStore` (the same getter for the server snapshot).
|
|
5
|
+
*
|
|
6
|
+
* Contains only observations from the provider's own hub frame and app-owned Stridge windows. Element connected
|
|
7
|
+
* notices do not update this snapshot.
|
|
8
|
+
*
|
|
9
|
+
* @throws {Error} like {@link usePayChannel} outside a provider.
|
|
10
|
+
*/
|
|
11
|
+
declare function usePaySnapshot(): PaySnapshot;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { usePaySnapshot };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{PayChannelContext as e}from"../provider/context.js";import{use as t,useCallback as n,useSyncExternalStore as r}from"react";function i(){let n=t(e);if(n===null)throw Error(`usePayChannel must be used inside <PayProvider>`);return n}function a(){let e=i(),t=n(t=>e.subscribe(t),[e]),a=n(()=>e.getSnapshot(),[e]);return r(t,a,a)}export{i as usePayChannel,a as usePaySnapshot};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { PayError, PayErrorCode, isPayError } from "./errors/PayError.js";
|
|
2
|
+
import { PayConnectionError, PayConnectionState, PayDiagnostics, PayDiagnosticsDetails, PaySnapshot } from "./channel/types.js";
|
|
3
|
+
import { usePaySnapshot } from "./hooks/usePaySnapshot.js";
|
|
4
|
+
import { PayConnectedEvent } from "./core/elementClientTypes.js";
|
|
5
|
+
import { PayDialogAriaHiddenAdapter, PayDialogAriaHiddenSignal, PayDialogAriaHiddenState, PayProviderProps, PayProviderTheme } from "./provider/types.js";
|
|
6
|
+
import { PayProvider } from "./provider/PayProvider.js";
|
|
7
|
+
import { PayCheckoutClosedEvent, PayEvent, PayRequestFailedEvent, PaymentObservedEvent, PaymentOnHoldEvent, PaymentUnconfirmedEvent } from "./react/payEvents.js";
|
|
8
|
+
import { PayElementAmountProps, PayElementDestination, PayElementFallback, PayElementFallbackContext, PayElementFallbackReason, PayElementFirstStep, PayElementMode, PayElementPresentationProps, PayElementProps, PayElementRequestProps } from "./react/types.js";
|
|
9
|
+
import { PayElement } from "./react/PayElement.js";
|
|
10
|
+
export { type PayCheckoutClosedEvent, type PayConnectedEvent, type PayConnectionError, type PayConnectionState, type PayDiagnostics, type PayDiagnosticsDetails, type PayDialogAriaHiddenAdapter, type PayDialogAriaHiddenSignal, type PayDialogAriaHiddenState, PayElement, type PayElementAmountProps, type PayElementDestination, type PayElementFallback, type PayElementFallbackContext, type PayElementFallbackReason, type PayElementFirstStep, type PayElementMode, type PayElementPresentationProps, type PayElementProps, type PayElementRequestProps, PayError, type PayErrorCode, type PayEvent, PayProvider, type PayProviderProps, type PayProviderTheme, type PayRequestFailedEvent, type PaySnapshot, type PaymentObservedEvent, type PaymentOnHoldEvent, type PaymentUnconfirmedEvent, isPayError, usePaySnapshot };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{PayError as e,isPayError as t}from"./errors/PayError.js";import{usePaySnapshot as n}from"./hooks/usePaySnapshot.js";import{PayProvider as r}from"./provider/PayProvider.js";import{PayElement as i}from"./react/PayElement.js";export{i as PayElement,e as PayError,r as PayProvider,t as isPayError,n as usePaySnapshot};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { PayProviderProps } from "./types.js";
|
|
2
|
+
import { ReactNode } from "react";
|
|
3
|
+
//#region src/provider/PayProvider.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Embeds the Stridge hub and publishes its channel to the headless hooks. The app page never renders a ceremony: the
|
|
6
|
+
* hub shows every ceremony inside its own iframe, or in the Stridge window (a window on the hub's origin) when the hub
|
|
7
|
+
* reports the `popup` transport.
|
|
8
|
+
*
|
|
9
|
+
* - **Environment.** `environment` picks the hub the provider frames: `"sandbox"` frames the Stridge sandbox hub;
|
|
10
|
+
* `"live"` has no hub yet and throws, as does any other value.
|
|
11
|
+
* - **One channel per hub and `appId`.** Created with the internal provider channel factory during render
|
|
12
|
+
* without side effects (lazily, and again when the hub or `appId` change),
|
|
13
|
+
* published on `PayChannelContext` around `children`.
|
|
14
|
+
* - **Lifetime.** Render only creates inert objects (`createProviderLifetime`). After commit, an effect takes a lease:
|
|
15
|
+
* the first one claims the page and mounts one light-DOM `<dialog>` holding the hub iframe into `document.body`
|
|
16
|
+
* (closed; the iframe runs the hub's start-up checks), with a random frame name and the title "Stridge Wallet". The pair stays
|
|
17
|
+
* for the provider's lifetime: never moved, renamed or navigated, whatever the overlay or the appearance does.
|
|
18
|
+
* StrictMode's effect replay keeps the same pair (one hub boot); the last release disposes it in a later task, so
|
|
19
|
+
* the iframe stays until then. A new hub or `appId` (or a new `key`) starts a new lifetime that replaces the
|
|
20
|
+
* old one at once.
|
|
21
|
+
* - **One provider per page.** A second `PayProvider` mounted while one owns the page, with the same or another hub
|
|
22
|
+
* and app, throws a configuration error from its effect, for the nearest error boundary, and creates no frame.
|
|
23
|
+
* - **Appearance.** `theme` defaults to `"dark"` and may be `"system"`: the provider resolves it with
|
|
24
|
+
* `matchMedia("(prefers-color-scheme: dark)")` and follows the media query while it is set, so only dark or light
|
|
25
|
+
* reaches the channel and every PayElement. When the resolved theme changes, calls
|
|
26
|
+
* `channel.setAppearance` with the new theme.
|
|
27
|
+
* - **Overlay.** Only the iframe opens it; the Stridge window is its own surface, so none of this runs for it. The channel
|
|
28
|
+
* shows the dialog modally and focuses the iframe in the hub message's own task, and on close returns focus to the
|
|
29
|
+
* invoker, or a documented fallback (`createDialogHost`). While it shows, the page's scroll is locked through an
|
|
30
|
+
* owned rule that never writes the page's inline styles (`createScrollLock`), and the dialog's own `aria-hidden` is
|
|
31
|
+
* kept absent. The browser's close requests do not close it (`closedby="none"`, every `cancel` prevented); a close
|
|
32
|
+
* that still happens leaves Stridge unavailable on the page until the provider mounts again.
|
|
33
|
+
*
|
|
34
|
+
* **Server rendering.** Children render directly, with no app-page wrapper or scope attributes. Render creates only
|
|
35
|
+
* inert objects. `"system"` resolves to the dark scheme on the server and while hydrating, then follows the browser's
|
|
36
|
+
* scheme after mount. Headless state comes from the provider's authenticated channel observations.
|
|
37
|
+
*
|
|
38
|
+
* **The Stridge window's opener.** The Stridge window answers through its opener, so the page must keep that link:
|
|
39
|
+
* `Cross-Origin-Opener-Policy: same-origin` cuts it as soon as the hub page loads; send `same-origin-allow-popups`, or
|
|
40
|
+
* no such header. A cut link rejects the request with `unavailable` and logs a warning that names the header.
|
|
41
|
+
*
|
|
42
|
+
* The dialog and its iframe live outside the React tree. An invalid `environment`, `appId`, or `theme` throws
|
|
43
|
+
* a `TypeError` during render: a configuration error for the nearest error boundary.
|
|
44
|
+
*/
|
|
45
|
+
declare function PayProvider(props: PayProviderProps): ReactNode;
|
|
46
|
+
//#endregion
|
|
47
|
+
export { PayProvider };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use client";import{PayError as e}from"../errors/PayError.js";import{PayChannelContext as t}from"./context.js";import{createProviderChannel as n}from"../channel/createAppChannel.js";import{createDialogAriaHiddenIntent as r}from"../channel/createDialogAriaHiddenIntent.js";import{createElementClient as i}from"../core/createElementClient.js";import{createElementStartGate as a}from"../core/elementStartGate.js";import{subscribeToNothing as o}from"../shared/presentation/subscribeToNothing.js";import{createProviderChannelDisposalBridge as s,createProviderLifetime as c}from"./createProviderLifetime.js";import{PayElementClientContext as l,PayElementFrameContext as u,PayElementThemeContext as d}from"./elementContext.js";import{HubAddressOverrideContext as f,resolveHubAddress as p}from"./hubAddress.js";import{use as m,useEffect as h,useLayoutEffect as g,useRef as _,useState as v,useSyncExternalStore as y}from"react";import{HUB_FRAME_NAME_PATTERN as b,MAX_MESSAGE_ID_LENGTH as x}from"@stridge/pay-sdk";import{jsx as S}from"react/jsx-runtime";const C=`dark`;function w(){return typeof window>`u`||typeof window.matchMedia!=`function`?null:window.matchMedia(`(prefers-color-scheme: dark)`)}function T(e){let t=w();return t===null?()=>{}:(t.addEventListener(`change`,e),()=>{t.removeEventListener(`change`,e)})}function E(){let e=w();return e===null?C:e.matches?`dark`:`light`}function D(){return C}function O(e){let t=e===`system`,n=y(t?T:o,E,D);return t?n:e}const k=Object.freeze({frames:null,port:null}),A=Object.freeze({phase:`none`});function j(e){let t=e.iframe;if(t===null)return null;let n=t.name,r=t.ownerDocument,i=t.contentWindow;return!n||n.length>x||!b.test(n)||i===null?null:{frame:t,name:n,document:r,window:i}}function M(e,t,n){let r=()=>e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&t.document.documentElement.contains(t.frame)&&t.document.defaultView===globalThis.window&&t.frame.contentWindow===t.window;return n()&&r()&&r()&&e.iframe===t.frame&&t.frame.name===t.name&&t.frame.ownerDocument===t.document&&t.frame.isConnected&&n()}function N(t,o,l,u){let d=u===void 0?void 0:r(u),f=s(),p,m,h={disposalBridge:f,...d===void 0?{}:{dialogAriaHiddenIntent:d},bindMenu(e){p=e},bindDiagnostics(e){m=e}},g=n({hubUrl:t,appId:o,appearance:l},h),_=!1,v=l,y,b=A,x=k,S=null,C=!1,w=new Set,T=new Set,E=new Map;function D(){let e=[...E];E.clear();for(let[t,n]of e)n(),t.abort()}let O=c({channel:g,...h,finalize(){let e=b.phase===`none`?null:b.client,t=S;b=A,S=null,T.clear();let n=[];for(let r of[D,()=>t?.(),()=>e?.destroy()])try{r()}catch(e){n.push(e)}if(n.length>0)throw n[0]}}),N=()=>_&&!O.disposed;function P(){let e=b;if(!N()||e.phase!==`started`)return D(),!1;!M(g,e.root,N)&&b===e&&(b={phase:`lost`,client:e.client});let t=b===e&&N();return t||D(),t}function F(e){return P()&&b.phase===`started`&&b.root===e}function I(e){if(!(!N()||w.has(e.evmAddress))){w.add(e.evmAddress);try{y?.(e)}catch{}}}function L(){if(N()){if(b.phase===`started`||b.phase===`lost`){P();return}if(!C){C=!0;try{let e=x;b.phase===`loading`&&!M(g,b.root,N)&&V(),b.phase===`none`&&z(),b.phase===`loading`&&g.getSnapshot().connection===`ready`&&B(),x!==e&&R(x)}finally{C=!1}}}}function R(e){for(let t of T){if(x!==e||e.port!==null&&!P())return;t()}}function z(){let n=j(g);if(n===null||!M(g,n,N))return;let r=a(P),s=i({hubUrl:t,appId:o,appearance:v,hubFrame:n.name,startGate:r.gate,onConnected(e){P()&&I(e)},showMenu(t,r,i){if(!F(n)||p===void 0||r.aborted)return Promise.reject(new e(`cancelled`,`The account menu root is no longer current`));let a=new AbortController,o=()=>{a.abort(),c()},s=()=>r.removeEventListener(`abort`,o),c=()=>{E.delete(a),s()};E.set(a,s),r.addEventListener(`abort`,o,{once:!0}),r.aborted&&a.abort();try{let e=p.showMenu(t,a.signal,i===void 0?void 0:{element:i.element,onEnd(e){c(),F(n)&&!a.signal.aborted&&i.onEnd(e)}});return F(n)||a.abort(),e.catch(e=>{throw c(),e})}catch(e){return c(),a.abort(),Promise.reject(e)}}});if(!M(g,n,N)){s.destroy();return}let c={reserve(e){let t=()=>b.phase===`loading`&&b.frames===c&&M(g,n,N);if(!t())return null;try{let n=s.createHandle(e);if(t())return n;n.destroy()}catch{}return null}};b={phase:`loading`,root:n,client:s,frames:c,start:r},x=Object.freeze({frames:c,port:null})}function B(){if(b.phase!==`loading`)return;let{root:e,client:t,frames:n,start:r}=b;if(!M(g,e,N)){V();return}b={phase:`started`,root:e,client:t},x=Object.freeze({frames:n,port:{createHandle(e){if(!P())throw Error(`PayProvider: the element root binding is no longer current`);let n=t.createHandle(e);if(!P())throw n.destroy(),Error(`PayProvider: the element root changed during handle creation`);return n},adopt(e){if(!P())throw e.destroy(),Error(`PayProvider: the element root binding is no longer current`)}}}),r.open(),P()}function V(){if(b.phase!==`loading`)return;let{client:e}=b;b=A,x=k,e.destroy()}let H={hubOrigin:g.hubOrigin,get iframe(){return g.iframe},getSnapshot:()=>g.getSnapshot(),subscribe:e=>g.subscribe(e),mount:e=>g.mount(e),unmount:()=>g.unmount(),setAppearance:e=>g.setAppearance(e),signIn:()=>g.signIn(),sign:e=>g.sign(e),signOut:()=>g.signOut(),disconnect:e=>g.disconnect(e),fund:e=>g.fund(e),dispose:()=>g.dispose()},U=H.signIn;return H.signIn=()=>{let e=j(g);return U().then(t=>(e!==null&&M(g,e,N)&&I(t),t))},{adapter:u,hubUrl:t,appId:o,channel:H,lifetime:O,composition:{commit(e,t,n){_=!0,y=t,v=e,m?.setEnabled(n),!(!N()||b.phase===`none`)&&b.client.setAppearance(e)},releaseCommit(){_=!1,m?.setEnabled(!1),D()},start(){S===null&&(S=g.subscribe(L));let e=O.acquire();try{L()}catch(e){try{O.dispose()}catch{}throw e}return e},subscribe(e){return T.add(e),()=>{T.delete(e)}},snapshot:()=>x}}}function P(e){let{environment:n,appId:r,children:i,dialogAriaHiddenAdapter:a}=e,o=p(n,m(f)),s=O(e.theme??`dark`),[c,b]=v(()=>N(o,r,{theme:s},a)),x=c;if(c.hubUrl!==o||c.appId!==r)x=N(o,r,{theme:s},a),b(x);else if(c.adapter!==a)throw TypeError(`PayProvider: dialogAriaHiddenAdapter must stay stable for a provider lifetime; change the provider key or hub/app identity to replace it`);let C=x.channel;g(()=>{x.composition.commit({theme:s},e.onConnected,e.diagnostics??!1)},[x,s,e.onConnected,e.diagnostics]),g(()=>()=>x.composition.releaseCommit(),[x]),h(()=>x.composition.start(),[x]);let w=y(x.composition.subscribe,x.composition.snapshot,()=>k),T=_(null);return h(()=>{let e=T.current;e!==null&&e.channel===C&&e.theme!==s&&C.setAppearance({theme:s}),T.current={channel:C,theme:s}},[C,s]),S(u,{value:w.frames,children:S(l,{value:w.port,children:S(d,{value:s,children:S(t,{value:C,children:i})})})})}export{P as PayProvider};
|