@safetech/inheriti-client-sdk 1.17.2 → 1.17.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +12 -3
  2. package/dist/browser.d.ts +91 -0
  3. package/dist/browser.js +1 -0
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +1 -1
  6. package/dist/inheriti-client-sdk.umd.js +99 -61
  7. package/dist/node.d.ts +23 -3
  8. package/dist/node.js +1 -1
  9. package/dist/sdk-types.d.ts +1113 -127
  10. package/dist/src/auth/inheriti-client-provider.d.ts +1 -1
  11. package/dist/src/elements/browser-plan-material-reconstructor.d.ts +23 -0
  12. package/dist/src/elements/core-plan-material-builder.d.ts +41 -0
  13. package/dist/src/elements/elements-api-port.d.ts +163 -3
  14. package/dist/src/elements/elements-client.d.ts +111 -14
  15. package/dist/src/elements/guided-plan-creator.d.ts +47 -0
  16. package/dist/src/elements/http-elements-api-port.d.ts +36 -1
  17. package/dist/src/elements/index.d.ts +14 -1
  18. package/dist/src/elements/master-key-acquisition.d.ts +46 -0
  19. package/dist/src/elements/node-plan-material-reconstructor.d.ts +9 -6
  20. package/dist/src/elements/plan-operation-codec.d.ts +4 -0
  21. package/dist/src/elements/plan-operations.d.ts +218 -0
  22. package/dist/src/elements/polling-shared-plan-event-listener.d.ts +29 -0
  23. package/dist/src/elements/reveal-session-operations.d.ts +13 -0
  24. package/dist/src/elements/scoped-reveal.d.ts +105 -0
  25. package/dist/src/elements/ssdp-v2-plan-material-reconstructor.d.ts +17 -0
  26. package/dist/src/operator-auth/defaults.d.ts +9 -0
  27. package/dist/src/operator-auth/errors.d.ts +11 -0
  28. package/dist/src/operator-auth/http-operator-auth-transport.d.ts +16 -0
  29. package/dist/src/operator-auth/index.d.ts +7 -0
  30. package/dist/src/operator-auth/operator-auth-client.d.ts +35 -0
  31. package/dist/src/operator-auth/operator-session-controller.d.ts +10 -0
  32. package/dist/src/operator-auth/ports.d.ts +53 -0
  33. package/dist/src/operator-auth/types.d.ts +77 -0
  34. package/docs/docs.json +18331 -0
  35. package/docs/elements-shared-mode.md +28 -0
  36. package/docs/operator-auth.md +76 -0
  37. package/docs/plan-operations.md +41 -0
  38. package/index.ts +1 -0
  39. package/node.ts +32 -4
  40. package/package.json +14 -3
package/README.md CHANGED
@@ -1,11 +1,11 @@
1
- # Inheriti Client SDK
1
+ # Inheriti® Client SDK
2
2
 
3
- The **Inheriti Client SDK** is a TypeScript library that enables developers to integrate Inheriti's digital inheritance
3
+ The **Inheriti® Client SDK** is a TypeScript library that enables developers to integrate Inheriti® digital inheritance
4
4
  and protection plan features into their own applications.
5
5
 
6
6
  ## Purpose
7
7
 
8
- This SDK abstracts and simplifies communication with the Inheriti platform by exposing a clean, typed API for:
8
+ This SDK abstracts and simplifies communication with the Inheriti® platform by exposing a clean, typed API for:
9
9
 
10
10
  - Creating and managing protection plans
11
11
  - Handling secure authentication and client keys
@@ -20,3 +20,12 @@ This SDK abstracts and simplifies communication with the Inheriti platform by ex
20
20
  - ✅ Modular and composable architecture
21
21
  - ✅ Compatible with browser and server environments
22
22
 
23
+ ## Elements operator authentication
24
+
25
+ New integrations should use the host-neutral `OperatorAuthClient` for OIDC authorization code/PKCE or device
26
+ authorization. Hosts retain control of secure storage and platform UI; the SDK validates protocol state and
27
+ serializes rotating refresh tokens. See [Operator OAuth and sessions](docs/operator-auth.md) for wiring, BFF
28
+ boundaries, and migration guidance for the existing `connect` API.
29
+
30
+ The typed list, detail, and resumable creation facade is documented in
31
+ [Application plan operations](docs/plan-operations.md).
@@ -0,0 +1,91 @@
1
+ /**
2
+ * The React-free entry for a bundled browser host.
3
+ *
4
+ * The root barrel re-exports the React-flavoured Core SDK and imports react, react-dom, zustand and
5
+ * @tanstack/react-query, so a Chrome extension or any other bundled host that reached for it pulled
6
+ * a UI framework into a service worker that has no DOM to render into. Everything named here is
7
+ * transport and protocol only: the Elements API port and the operator-auth runtime, whose Core SDK
8
+ * imports are all `import type` and therefore erased.
9
+ *
10
+ * Reveal is here too, through `createBrowserElementsClient`. It reaches Core only at entries that
11
+ * are themselves React-free and platform-neutral — `/workers/ssdp-v2` for reconstruction,
12
+ * `/core/protocols/ssdp+` for the asset container, `/crypto` for key derivation — never `/node`,
13
+ * whose SDK container a reveal does not use.
14
+ *
15
+ * A Node host uses `@safetech/inheriti-client-sdk/node` instead, which additionally carries the
16
+ * guided plan-creation machinery that does need Core's container.
17
+ */
18
+ import { decodeAssetContainer } from '@safetech/inheriti-core-sdk/core/protocols/ssdp+';
19
+ import ElementsClient from './src/elements/elements-client';
20
+ import BrowserPlanMaterialReconstructor from './src/elements/browser-plan-material-reconstructor';
21
+ import type { BrowserPlanMaterialReconstructorOptions } from './src/elements/browser-plan-material-reconstructor';
22
+ import type { KeyVault } from './src/elements/key-vault';
23
+ import type { MasterKeyResolver } from './src/elements/master-key';
24
+ import type { ElementsClientOptions } from './src/elements/elements-client';
25
+ import type { PlanMaterialReconstructor } from './src/elements/plan-material-reconstructor';
26
+ import type { StatePort } from './src/elements/state-port';
27
+ export interface BrowserElementsClientOptions {
28
+ apiUrl: string;
29
+ environment: 'TEST' | 'LIVE';
30
+ getBearerToken: () => Promise<string | null>;
31
+ /** The Application this client acts for; the reveal path resolves its key under this id. */
32
+ applicationId: string;
33
+ /**
34
+ * Resolves master keys per plan reference. A host that composes its own custody passes this;
35
+ * one that only declares what it holds passes `masterKey` instead and lets the client compose
36
+ * acquisition — including asking the device that holds the key.
37
+ */
38
+ masterKeys?: MasterKeyResolver;
39
+ /** What custody this host holds locally. See `ElementsClientOptions['masterKey']`. */
40
+ masterKey?: ElementsClientOptions['masterKey'];
41
+ transport?: typeof fetch;
42
+ keyVault?: KeyVault;
43
+ state?: StatePort;
44
+ /** Overrides reconstruction wholesale; otherwise a `BrowserPlanMaterialReconstructor` is built. */
45
+ reconstructor?: PlanMaterialReconstructor;
46
+ reconstruction?: BrowserPlanMaterialReconstructorOptions;
47
+ }
48
+ /**
49
+ * A reveal-capable Elements client for a bundled browser host.
50
+ *
51
+ * It carries no `SDKContainer`, and that is the point rather than an omission: the container is
52
+ * reached only by `createPlan` and `configurePlan`, so a host that reveals but does not create
53
+ * needs none, and Core's Node-only container never has to be ported to the browser. Calling a
54
+ * creation method on this client raises `CoreSdkContainerRequired` instead of failing obscurely.
55
+ */
56
+ export declare function createBrowserElementsClient(options: BrowserElementsClientOptions): ElementsClient;
57
+ export { ElementsClient, BrowserPlanMaterialReconstructor, decodeAssetContainer };
58
+ export { CoreSdkContainerRequired } from './src/elements/elements-client';
59
+ export type { BrowserPlanMaterialReconstructorOptions };
60
+ export type { DecodedPlanAsset, PlanAssetContainerDecoder } from './src/elements/elements-client';
61
+ export type { PlanMaterialReconstructor } from './src/elements/plan-material-reconstructor';
62
+ export { PlanMaterialReconstructorRequired } from './src/elements/plan-material-reconstructor';
63
+ export { MasterKeyRequired, StaticMasterKeyResolver, masterKeyRefFor, masterKeyRefKey } from './src/elements/master-key';
64
+ export type { MasterKeyRef, MasterKeyResolver } from './src/elements/master-key';
65
+ export { unwrapDekWithMasterKey } from './src/elements/unwrap-dek';
66
+ export { RelayMasterKeySource, MasterKeyRelayExpired, MasterKeyRelayTimedOut } from './src/elements/relay-master-key-source';
67
+ export { createMasterKeyResolver } from './src/elements/master-key-acquisition';
68
+ export type { MasterKeySource } from '@safetech/inheriti-core-sdk';
69
+ export type { DeclaredMasterKeySource, MasterKeyAcquisitionOptions } from './src/elements/master-key-acquisition';
70
+ export type { MasterKeyAcquisition, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState } from './src/elements/elements-api-port';
71
+ export type { MasterKeyRelayPort } from './src/elements/relay-master-key-source';
72
+ export { PassphraseMasterKeySource, RawMasterKeySource, computePassphraseVerifier, deriveMasterKey, generateHexSeed } from '@safetech/inheriti-core-sdk/crypto';
73
+ export type { MasterKeySource } from '@safetech/inheriti-core-sdk/crypto';
74
+ export { MemoryKeyVault } from './src/elements/key-vault';
75
+ export type { KeyVault } from './src/elements/key-vault';
76
+ export { MemoryStatePort } from './src/elements/state-port';
77
+ export type { StatePort } from './src/elements/state-port';
78
+ export { openScopedReveal, revealPhaseOf, RevealAuthorizationEnded, RevealFieldAccessError, RevealHandleClosed, parseAssetFieldSelector } from './src/elements/scoped-reveal';
79
+ export type { AssetFieldSelector, OpenRevealOptions, RevealFieldOptions, RevealHandle, RevealPhase, RevealProgress } from './src/elements/scoped-reveal';
80
+ export type { CollectedPlanMaterial, GovernedRevealSession, GovernedRevealState, PlanKeyReference } from './src/elements/elements-api-port';
81
+ export { default as HttpElementsApiPort, ElementsApiRequestFailed } from './src/elements/http-elements-api-port';
82
+ export { SystemOAuthClock, WebOAuthCrypto } from './src/operator-auth/defaults';
83
+ export { HttpOperatorAuthTransport } from './src/operator-auth/http-operator-auth-transport';
84
+ export { OperatorAuthClient } from './src/operator-auth/operator-auth-client';
85
+ export { OperatorSessionController } from './src/operator-auth/operator-session-controller';
86
+ export { OAuthProtocolError, OperatorAuthError, OperatorReauthenticationRequired, oauthErrorCode } from './src/operator-auth/errors';
87
+ export type * from './src/operator-auth/ports';
88
+ export type * from './src/operator-auth/types';
89
+ export type { ElementsApiPort, StepUpReadContext } from './src/elements/elements-api-port';
90
+ export type { RevealAction, RevealActionDestination, RevealActionOutcome, RevealActionType, RevealCloseReason, RevealMode, RevealSession, RevealStage, } from './src/elements/elements-api-port';
91
+ export type { ListPlansInput, PlanDetail, PlanPage, PlanSummary } from './src/elements/plan-operations';
@@ -0,0 +1 @@
1
+ import{decodeAssetContainer as Tt}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as ze,generateRSAOAEPKeyPair as He}from"@safetech/inheriti-core-sdk/crypto";var H=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},W=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},x=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await He(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,s=Date.now()+(this.options.timeoutMs??600*1e3),i=this.options.sleep??(o=>new Promise(l=>setTimeout(l,o)));for(;Date.now()<s;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let l=(await ze(o.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(l))throw new Error("invalid_master_key_material");return l}if(o.status==="EXPIRED")throw new W(n.sessionId);await i(a)}throw new H(n.sessionId)}};function se(r){return{resolve:async e=>{if(We(e,r.applicationId)){let t=await r.source?.resolve();return t||Ie(r,()=>r.api.masterKeyAcquisition())}return Ie(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId))}}}function We(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ie(r,e){if((await e()).relayAvailable)return new x({...r.relay,api:$e(r.api)}).resolve()}function $e(r){return{startRelaySession:e=>r.startMasterKeyRelaySession(e),readRelaySession:e=>r.readMasterKeyRelaySession(e)}}function I(r){return`${r.system}:${r.contextId}`}function oe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var A=class extends Error{constructor(t){super(`master_key_required:${I(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ie=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(I(e),t),this}async resolve(e){return this.sources.get(I(e))?.resolve()}};var b=class{keys=new Map;async store(e,t){this.keys.set(I(e),t.slice())}async load(e){return this.keys.get(I(e))?.slice()}async remove(e){this.keys.delete(I(e))}};var K=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var $=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},d=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var U=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var j=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],je={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},we=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function O(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new P("plan_material_field_unknown");if(le(r.dataShards,"data_shards_invalid"),le(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&le(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new P("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new P("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new P("material_operation_invalid")}function le(r,e){if(!Array.isArray(r))throw new P(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new P(e);if(t.data!==void 0&&typeof t.data!="string")throw new P(e)}}function C(r){if(S(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Xe(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(S(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!j.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(s=>!s.trim()))throw new m("asset_field_names_invalid");if(Ye(t.matchOrigins),!t.isBinary){let s=je[t.type];if(!s||a.some(i=>!s.includes(i)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(S(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Se(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}Qe(r)}function Ye(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function Qe(r){let e=r.policy;if(e&&S(e,["authentication","moderation","dms","masterKeyRelease","custodian"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){S(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){S(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(s.length===0)throw new m("moderation_requires_moderators");let i=e.moderation.minimumApprovals;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>s.length))throw new m("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;S(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Se(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(s=>Ae(s.routingEmail)===Ae(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new m("dms_countdown_invalid")}function Xe(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Se(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Ae(r){return r.normalize("NFC").trim().toLowerCase()}function S(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var Q=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},X=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),C(e),Y(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,s={}){C(t);let i=await this.checkpoints.load(e);if(!i)throw new Z("creation_checkpoint_missing");if(i.idempotencyKey!==t.idempotencyKey||i.declarationHash!==await Ce(t))throw new Z("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Y(s.signal),s.onProgress?.("ENCRYPTING");let l=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});Y(s.signal),s.onProgress?.("GENERATING_SHARES");let u=await a.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:s.signal});Y(s.signal),O(u);let h=await this.api.supplyPlanCreationMaterial(e,u);return s.onProgress?.(h.stage),h.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,h),h}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Ce(e),serverStage:t.stage})}},Z=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Ce(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Y(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Te(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new $(n.stage);return r.authorizeRevealAction(e,t)}function Ze(r){let e=r?.status;return e===400||e===401||e===403}async function _e(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(s){if(!Ze(s))throw s}return r.releaseRevealMaterial(e,t)}function Oe(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?et(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Je.has(r.stage)?"ENDED":"CONTINUING"}var Je=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function et(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var J=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ue(r,e,t={}){if(t.signal?.aborted)throw pe();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let a=t.idempotencyKey??crypto.randomUUID(),s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),i;try{let o=await rt(r,s,t);L(t,"RELEASING_MATERIAL",o);let l=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let u=await st(r,o,n,ot(l),t);L(t,"RECONSTRUCTING",o),i=await r.reconstructPlanMaterial(u);let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return L(t,"OPEN",h),new ce(r,h,n,i,t.signal)}catch(o){throw i?.fill(0),await lt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var tt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function rt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:Oe(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(tt.has(n.stage))throw new ee(n.stage);await me(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var ee=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function L(r,e,t){r.onProgress?.({phase:e,session:t})}function me(r,e){return e?.aborted?Promise.reject(pe()):new Promise((t,n)=>{let a=setTimeout(i,Math.max(0,r)),s=()=>{clearTimeout(a),n(pe())};function i(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var ce=class{constructor(e,t,n,a,s){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let i=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(i,2147483647)),this.abortListener=s?()=>{this.close("CANCELED")}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new J;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=e.map(({selector:s,options:i={}})=>{let o=De(s),l=this.plan.assets.find(u=>(u.code??u.id)===o.asset);if(!l)throw new y("asset_not_found");if(l.isBinary)throw new y("action_not_allowed");if(!l.fieldNames.includes(o.field))throw new y("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:l,field:o.field,options:i}}),a=[];try{for(let i of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:i.options.idempotencyKey??crypto.randomUUID(),assetId:i.asset.id,fieldName:i.field,action:i.options.action??"VIEW_FIELD",...i.options.destination===void 0?{}:{destination:i.options.destination},...i.options.origin===void 0?{}:{origin:i.options.origin}}));let s=n.map(i=>{let o=this.client.assetDecoder(this.material).find(l=>l.id===i.asset.id||l.id===i.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:i.selector,value:nt(o.data,i.field)}});await t(s)}catch(s){throw await Promise.all(a.map(i=>this.reportAction(i.id,"FAILED",at(s)))),s}await Promise.all(a.map(s=>this.reportAction(s.id,"SUCCEEDED")))}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!ke(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function De(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new y("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new y("asset_selector_invalid");return{asset:r.asset,field:r.field}}function nt(r,e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("asset_value_invalid")}if(!t||typeof t!="object"||Array.isArray(t)||!(e in t))throw new y("asset_value_invalid");return t[e]}function at(r){if(r instanceof y)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}async function st(r,e,t,n,a){if(t.revealPolicy?.custodian!=="FORCE"||n.shares.some(l=>l.shareType==="CUSTODIAN_KEY_SHARD"))return n;let s=await r.getRevealCustodianAccess(e.id);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};a.onSession?.(l),L(a,"WAITING_FOR_CUSTODIAN_CLAIM",l),await me(a.pollIntervalMs??1500,a.signal),s=await r.getRevealCustodianAccess(e.id)}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new te;let i={...e,stage:"WAITING_FOR_CUSTODIAN"};a.onSession?.(i),L(a,"WAITING_FOR_CUSTODIAN",i),await r.requestRevealCustodianRelease(e.id);let o=await it(r,e.id,a);return Object.assign({},n,{shares:n.shares.concat(o.shares.map((l,u)=>({id:`${o.id}:${u}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}async function it(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let s=a;if(s.shares?.length)return s;throw new te}if(Date.now()>=n)throw new de;await me(t.pollIntervalMs??1500,t.signal)}}var te=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},de=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function ot(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function lt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!ke(n))throw n}}function ke(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function pe(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var G=class{constructor(e,t={}){this.coreSdk=e;this.keyVault=t.keyVault??new b,this.state=t.state??new K,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??ct(t),this.applicationId=t.applicationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;assetDecoder;listPlans(e){if(!this.api)throw new d;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new d;return this.api.getPlan(e)}startPlanCreation(e){if(!this.api)throw new d;return C(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(!this.api)throw new d;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(!this.api)throw new d;return O(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new Q){if(!this.api)throw new d;return new X(this.api,e)}createPlan(e){return this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){if(!this.applicationId)throw new A({system:"INHERITI_ELEMENTS",contextId:"application"});let e={system:"INHERITI_ELEMENTS",contextId:this.applicationId},t=await this.keyVault.load(e);if(t)return Ne(t);let n=await this.masterKeys?.resolve(e);if(!n)throw new A(e);return await this.keyVault.store(e,Me(n)),n}async prepareReveal(e){if(!this.api)throw new d;let t=await this.api.planKeyReference(e);if(!t.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new d;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new U;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let t=oe(e);if(!t)throw new A({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Ne(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new A(t);return await this.keyVault.store(t,Me(a)),a}initializeGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new d;return this.api.startReveal(e,t)}getReveal(e){if(!this.api)throw new d;return this.api.getReveal(e)}openReveal(e,t){return ue(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let s=await n(a);return await a.close("COMPLETED"),s}catch(s){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new d;return _e(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(e)}requestRevealCustodianRelease(e){if(!this.api)throw new d;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new d;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new d;return this.api.getRevealCustodianShare(e)}reportRevealReconstruction(e,t){if(!this.api)throw new d;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new d;return this.api.closeReveal(e,t)}abortPlanAccess(e){if(!this.api)throw new d;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new d;return Te(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new d;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new d;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new d;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new d;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new d;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new d;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(u=>Object.assign({},u,{shareType:"VALIDATOR_SHARD"})),i=a.dataShards.map(u=>Object.assign({},u,{shareType:"DATA_SHARD"})),o=a.backupShards.map(u=>Object.assign({},u,{shareType:"BACKUP_SHARD"})),l=a.keyShards.map(u=>Object.assign({},u,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:s.concat(i,o,l),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new d;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new re;return this.coreSdk.getService(e).execute(t)}},re=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Me(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ne(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function ct(r){if(!r.api||!r.applicationId)return;let e={api:r.api,applicationId:r.applicationId,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};return se(e)}import{createBrowserSsdpV2WorkerFactory as yt,createSsdpV2Processor as ft}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function he(r,e){if(!e)throw new Error("master_key_required");let t=dt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=pt(r),s=a.slice(0,12),i=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,i);return ut(new Uint8Array(o))}function dt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pt(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function ut(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var V=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await he(e.planKey,t),a=await crypto.subtle.importKey("raw",ye(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],i=[];for(let o of e.shares){let l=await ht(o.data,a);mt(o.shareType)?i.push(l):s.push(l)}return this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:i}).result}};function mt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function ht(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=ye(r.slice(0,t)),a=ye(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(s)}function ye(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let a=0;a<e.length;a+=1)n[a]=e.charCodeAt(a);return t}var F=class extends V{constructor(e={}){let t=e.processor??ft(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:yt(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var Rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],gt=["DIRECT","GOVERNED"],be=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],vt=["ACTIVE","REVOKED"],Pt=["SK_MOBILE"],Et=["ACTIVE","INACTIVE"],It=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ke(r){let e=R(r);return{items:g(e.items).map(Le),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function Ue(r){let e=R(r),t=Le(e),n=R(e.source),a=p(n.kind,"source.kind");return{...t,assets:g(e.assets).map(s=>{let i=R(s);return{id:p(i.id,"asset.id"),code:T(i.code),type:f(p(i.type,"asset.type"),j),name:p(i.name,"asset.name"),isBinary:wt(i.isBinary,"asset.isBinary"),fieldNames:g(i.fieldNames).map(o=>p(o,"asset.fieldNames")),fileName:T(i.fileName),mimeType:T(i.mimeType),size:i.size===void 0||i.size===null?void 0:E(i.size,"asset.size"),matchOrigins:i.matchOrigins===void 0?void 0:g(i.matchOrigins).map(o=>p(o,"asset.matchOrigins"))}}),participants:g(e.participants).map(s=>{let i=R(s);return{id:p(i.id,"participant.id"),displayName:p(i.displayName,"participant.displayName"),relationships:g(i.relationships).map(o=>f(p(o,"relationship"),be)),lifecycle:f(p(i.lifecycle,"participant.lifecycle"),vt)}}),revealPolicy:(()=>{let s=R(e.revealPolicy);return{masterKeyRelease:f(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(p(s.custodian,"custodian"),["FORCE","BYPASS"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=R(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:E(s.countdownDays,"dms.countdownDays"),countdownHours:E(s.countdownHours,"dms.countdownHours"),countdownMinutes:E(s.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:f(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:f(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function q(r){let e=R(r);return{operationId:p(e.operationId,"operationId"),stage:f(p(e.stage,"stage"),we),outcome:f(p(e.outcome,"outcome"),It),planId:T(e.planId),lastErrorCode:T(e.lastErrorCode),participants:e.participants===void 0?void 0:g(e.participants).map(t=>{let n=R(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:g(n.relationships).map(a=>At(p(a,"relationship"),be))}})}}function Le(r){let e=R(r),t=R(e.assetSummary),n=R(e.governance),a=R(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:T(e.description),status:f(p(e.status,"status"),Rt),createdAt:p(e.createdAt,"createdAt"),configuredAt:T(e.configuredAt),assetSummary:{count:E(t.count,"assetSummary.count"),types:g(t.types).map(s=>f(p(s,"assetType"),j)),names:xe(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:f(p(n.mode,"governance.mode"),gt),minimumApprovals:E(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:E(a.owners,"owners"),mergers:E(a.mergers,"mergers"),moderators:E(a.moderators,"moderators")},authentication:xe(e.authentication).map(s=>{let i=R(s);return{id:f(p(i.id,"authentication.id"),Pt),status:f(p(i.status,"authentication.status"),Et)}})}}function f(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function At(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function R(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function xe(r){return r==null?[]:g(r)}function g(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function T(r){return r==null?void 0:p(r,"optional")}function E(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function wt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function fe(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function Re(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var D=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},k=class{constructor(e,t,n,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Ke(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ue(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async startPlanCreation(e){C(e);let{idempotencyKey:t,...n}=e;return q(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return O(t),q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,s){let i=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});i&&o.set("authorization",`Bearer ${i}`),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[qe,Be]of Object.entries(s??{}))o.set(qe,Be);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Ge(u);if(!u.ok)throw new D(u.status,fe(h),Re(h));if(!h.ok||h.result===void 0)throw new D(u.status,fe(h),Re(h));return h.result}async requestWithoutResult(e){let t=await this.getBearerToken(),n=new Headers({"x-elements-environment":this.environment});t&&n.set("authorization",`Bearer ${t}`);let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:n}),i=await Ge(s);if(!s.ok||!i.ok)throw new D(s.status,fe(i),Re(i))}};async function Ge(r){try{return await r.json()}catch{return{ok:!1}}}import{PassphraseMasterKeySource as Nr,RawMasterKeySource as xr,computePassphraseVerifier as br,deriveMasterKey as Kr,generateHexSeed as Ur}from"@safetech/inheriti-core-sdk/crypto";function Ve(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var B=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ve(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Ve(new Uint8Array(t))}},z=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var M=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},N=class extends M{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},c=class extends M{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function ne(r){if(r instanceof M)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var ge=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:w(n,"issuer"),authorizationEndpoint:w(n,"authorization_endpoint"),tokenEndpoint:w(n,"token_endpoint"),deviceAuthorizationEndpoint:v(n,"device_authorization_endpoint"),endSessionEndpoint:v(n,"end_session_endpoint"),revocationEndpoint:v(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:w(t,"device_code"),userCode:w(t,"user_code"),verificationUri:w(t,"verification_uri"),verificationUriComplete:v(t,"verification_uri_complete"),expiresInSeconds:Fe(t,"expires_in"),intervalSeconds:ve(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:w(n,"access_token"),refreshToken:v(n,"refresh_token"),idToken:v(n,"id_token"),tokenType:w(n,"token_type"),expiresInSeconds:Fe(n,"expires_in"),refreshExpiresInSeconds:ve(n,"refresh_expires_in"),scope:v(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let s=v(a,"error")??`oauth_http_${n.status}`;throw new c(s,v(a,"error_description")??s)}return a}};function w(r,e){let t=v(r,e);if(!t)throw new c("invalid_oauth_response",`Missing ${e}`);return t}function v(r,e){return typeof r[e]=="string"?r[e]:void 0}function Fe(r,e){let t=ve(r,e);if(t===void 0)throw new c("invalid_oauth_response",`Missing ${e}`);return t}function ve(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var St=600*1e3,ae=5,Ct=5,Pe=class{constructor(e){this.options=e;this.crypto=e.crypto??new B,this.clock=e.clock??new z}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),s=await this.crypto.sha256UrlSafe(a),i=this.clock.now()+St;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:i});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",s),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:i}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new c("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new c("authorization_transaction_expired");let a=new URL(e),s=new URL(n.redirectUri);if(a.origin!==s.origin||a.pathname!==s.pathname)throw new c("redirect_uri_mismatch");let i=a.searchParams.get("error");if(i)throw new c(i,a.searchParams.get("error_description")??i);if(a.searchParams.get("state")!==n.state)throw new c("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new c("authorization_code_missing");let l=await this.getDiscovery(),u=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(u,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new c("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(ae,t.intervalSeconds??ae),a=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new c("device_transaction_missing");let a=n,s=await this.getDiscovery(),i=Math.max(ae,a.intervalSeconds??ae),o=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(o>=a.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let u=await this.acceptTokens(l);return await this.options.sessions.save(u),await this.options.transactions.remove(t),u}catch(l){let u=ne(l);if(u==="authorization_pending"){o=this.clock.now()+i*1e3;continue}if(u==="slow_down"){i+=Ct,o=this.clock.now()+i*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new c("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new N;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new c("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=ne(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new N:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(_(e.issuer)!==_(this.options.configuration.issuer))throw new c("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${_(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new c("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new c("id_token_validation_required");let s=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(s,t),s.subject!==n.subject||s.sessionId!==n.sessionId)throw new c("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(a.issuer))throw new c("issuer_mismatch");if(!s.includes(a.audience))throw new c("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new c("client_mismatch");if(e.environment!==a.environment)throw new c("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new c("required_claim_missing");if(n&&e.nonce!==t)throw new c("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(n.issuer))throw new c("issuer_mismatch");if(!a.includes(n.clientId))throw new c("client_mismatch");if(e.authorizedParty!==n.clientId)throw new c("client_mismatch");if(!e.subject||!e.sessionId)throw new c("required_claim_missing");if(e.nonce!==t)throw new c("nonce_mismatch")}};function _(r){return r.replace(/\/+$/u,"")}var Ee=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function wr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new k(r.apiUrl,r.environment,r.getBearerToken,e);return new G(void 0,{api:t,applicationId:r.applicationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:Tt,reconstructor:r.reconstructor??new F(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{F as BrowserPlanMaterialReconstructor,re as CoreSdkContainerRequired,D as ElementsApiRequestFailed,G as ElementsClient,k as HttpElementsApiPort,ge as HttpOperatorAuthTransport,W as MasterKeyRelayExpired,H as MasterKeyRelayTimedOut,A as MasterKeyRequired,b as MemoryKeyVault,K as MemoryStatePort,c as OAuthProtocolError,Pe as OperatorAuthClient,M as OperatorAuthError,N as OperatorReauthenticationRequired,Ee as OperatorSessionController,Nr as PassphraseMasterKeySource,U as PlanMaterialReconstructorRequired,xr as RawMasterKeySource,x as RelayMasterKeySource,ee as RevealAuthorizationEnded,y as RevealFieldAccessError,J as RevealHandleClosed,ie as StaticMasterKeyResolver,z as SystemOAuthClock,B as WebOAuthCrypto,br as computePassphraseVerifier,wr as createBrowserElementsClient,se as createMasterKeyResolver,Tt as decodeAssetContainer,Kr as deriveMasterKey,Ur as generateHexSeed,oe as masterKeyRefFor,I as masterKeyRefKey,ne as oauthErrorCode,ue as openScopedReveal,De as parseAssetFieldSelector,Oe as revealPhaseOf,he as unwrapDekWithMasterKey};
package/dist/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export { default as useClient } from "./src/auth/use-client";
6
6
  export { getAvailableEnvs } from "./src/auth/get-available-envs";
7
7
  export { SDKContainer };
8
8
  export * from './src/elements';
9
+ export * from './src/operator-auth';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SDKContainer as dt}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as F,useEffect as B,createContext as W,useMemo as q}from"react";import{CoreProvider as X,HttpClientFactory as Q,AuthModule as J,AuthStateProvider as Z,AuthSessionRestorer as ee,useClient as te}from"@safetech/inheriti-core-sdk";function f(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},a=t[e]??t.development;return r==""?a:`${a}/${r}`}import w from"react";import be from"react-dom";function O(r){if(!r||typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}var xe=Array(12).fill(0);var C=1,k=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;let{message:a,...o}=e,s=typeof e?.id=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:C++,d=this.toasts.find(i=>i.id===s),c=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),d?this.toasts=this.toasts.map(i=>i.id===s?(this.publish({...i,...e,id:s,title:a}),{...i,...e,id:s,dismissible:c,title:a}):i):this.addToast({title:a,...o,dismissible:c,id:s}),s},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(a=>a({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let a;t.loading!==void 0&&(a=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let o=Promise.resolve(e instanceof Function?e():e),s=a!==void 0,d,c=o.then(async n=>{if(d=["resolve",n],w.isValidElement(n))s=!1,this.create({id:a,type:"default",message:n});else if(z(n)&&!n.ok){s=!1;let l=typeof t.error=="function"?await t.error(`HTTP error! status: ${n.status}`):t.error,h=typeof t.description=="function"?await t.description(`HTTP error! status: ${n.status}`):t.description,x=typeof l=="object"&&!w.isValidElement(l)?l:{message:l};this.create({id:a,type:"error",description:h,...x})}else if(n instanceof Error){s=!1;let l=typeof t.error=="function"?await t.error(n):t.error,h=typeof t.description=="function"?await t.description(n):t.description,x=typeof l=="object"&&!w.isValidElement(l)?l:{message:l};this.create({id:a,type:"error",description:h,...x})}else if(t.success!==void 0){s=!1;let l=typeof t.success=="function"?await t.success(n):t.success,h=typeof t.description=="function"?await t.description(n):t.description,x=typeof l=="object"&&!w.isValidElement(l)?l:{message:l};this.create({id:a,type:"success",description:h,...x})}}).catch(async n=>{if(d=["reject",n],t.error!==void 0){s=!1;let m=typeof t.error=="function"?await t.error(n):t.error,l=typeof t.description=="function"?await t.description(n):t.description,I=typeof m=="object"&&!w.isValidElement(m)?m:{message:m};this.create({id:a,type:"error",description:l,...I})}}).finally(()=>{s&&(this.dismiss(a),a=void 0),t.finally==null||t.finally.call(t)}),i=()=>new Promise((n,m)=>c.then(()=>d[0]==="reject"?m(d[1]):n(d[1])).catch(m));return typeof a!="string"&&typeof a!="number"?{unwrap:i}:Object.assign(a,{unwrap:i})},this.custom=(e,t)=>{let a=t?.id||C++;return this.create({jsx:e(a),id:a,...t}),a},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},u=new k,L=(r,e)=>{let t=e?.id||C++;return u.addToast({title:r,...e,id:t}),t},z=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",j=L,Y=()=>u.toasts,$=()=>u.getActiveToasts(),y=Object.assign(j,{success:u.success,info:u.info,warning:u.warning,error:u.error,custom:u.custom,message:u.message,promise:u.promise,dismiss:u.dismiss,loading:u.loading},{getHistory:Y,getToasts:$});O("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");var N={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{y.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{y.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{y.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{y.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{y.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as ne,jsx as v}from"react/jsx-runtime";var re="inheriti_client_merging_process",K=W(null);function H({children:r,clientId:e,options:t}){let a=t?.env??"development",o={key:e??"",options:{env:a}},s=F(Q.create({apiUrl:f("",a),errorHandlingStrategy:N}));B(()=>{s.current?.setApiUrl(f("",a))},[a]);let d=q(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:re}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return v(K.Provider,{value:s.current,children:v(Z,{children:v(X,{modules:{auth:J},moduleConfigs:d,children:v(ee,{children:v(ae,{client:o,children:r})})})})})}function ae({children:r,client:e}){let{connect:t,isConnected:a}=te();return B(()=>{!e?.key||a||t(e)},[e.key]),v(ne,{children:r})}import{useContext as oe,useCallback as se}from"react";import{useClient as ie}from"@safetech/inheriti-core-sdk";function U(){let{connect:r,...e}=ie(),t=oe(K),a=se(async o=>(o?.options?.env&&t?.setApiUrl(f("",o.options.env)),r(o)),[r,t]);return{...e,connect:a}}function le(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",a=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",o=f("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:a,demoKeyApiUrl:o}}function g(r){return`${r.system}:${r.contextId}`}function _(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var b=class extends Error{constructor(t){super(`master_key_required:${g(t)}`);this.ref=t;this.name="MasterKeyRequired"}},A=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(g(e),t),this}async resolve(e){return this.sources.get(g(e))?.resolve()}};var E=class{keys=new Map;async store(e,t){this.keys.set(g(e),t.slice())}async load(e){return this.keys.get(g(e))?.slice()}async remove(e){this.keys.delete(g(e))}};var R=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var S=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var P=class{constructor(e,t={}){this.coreSdk=e;this.keyVault=t.keyVault??new E,this.state=t.state??new R,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys,this.applicationId=t.applicationId}keyVault;state;api;reconstructor;masterKeys;applicationId;createPlan(e){return this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=e.masterKey??await this.applicationMasterKey(),a=t?Object.assign({},e,{masterKey:t}):e;return this.useCase("ConfigureSharedProtectionPlanUseCase",a)}async applicationMasterKey(){if(!this.applicationId)return;let e={system:"INHERITI_ELEMENTS",contextId:this.applicationId},t=await this.keyVault.load(e);if(t)return V(t);let a=await this.masterKeys?.resolve(e);return a&&await this.keyVault.store(e,G(a)),a}async prepareReveal(e){if(!this.api)throw new p;let t=await this.api.planKeyReference(e);return t.masterKeyWrapped?{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}:{masterKeyWrapped:!1}}async revealPlan(e,t){await this.prepareReveal(e);let a=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(a)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new S;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async resolveMasterKey(e){if(!e.masterKeyWrapped)return;let t=_(e);if(!t)throw new b({system:"INHERITI_ELEMENTS",contextId:e.planId});let a=await this.keyVault.load(t);if(a)return V(a);let o=await this.masterKeys?.resolve(t);if(!o)throw new b(t);return await this.keyVault.store(t,G(o)),o}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let a=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),o=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=a.validatorShares.map(n=>Object.assign({},n,{shareType:"VALIDATOR_SHARD"})),d=o.dataShards.map(n=>Object.assign({},n,{shareType:"DATA_SHARD"})),c=o.backupShards.map(n=>Object.assign({},n,{shareType:"BACKUP_SHARD"})),i=o.keyShards.map(n=>Object.assign({},n,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:o.dek||a.dek,shares:s.concat(d,c,i),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let a=await this.reconstructPlanMaterial(t);if(!this.api)throw new p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),a}useCase(e,t){return this.coreSdk.getService(e).execute(t)}};function de(r){return new P(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId})}function G(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function V(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}async function ce(r,e){if(!e)throw new Error("master_key_required");let t=ue(e),a=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),o=pe(r),s=o.slice(0,12),d=o.slice(12),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},a,d);return me(new Uint8Array(c))}function ue(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pe(r){let e=atob(r),t=new Uint8Array(e.length);for(let a=0;a<e.length;a+=1)t[a]=e.charCodeAt(a);return t}function me(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}import{decryptRSAOAEP as fe,generateRSAOAEPKeyPair as ge}from"@safetech/inheriti-core-sdk";var M=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},T=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},D=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await ge(),a=await this.options.api.startRelaySession(e),o=this.options.pollIntervalMs??2e3,s=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(c=>new Promise(i=>setTimeout(i,c)));for(;Date.now()<s;){let c=await this.options.api.readRelaySession(a.sessionId);if(c.status==="DELIVERED"&&c.sealedMasterKey){let i=(await fe(c.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(i))throw new Error("invalid_master_key_material");return i}if(c.status==="EXPIRED")throw new T(a.sessionId);await d(o)}throw new M(a.sessionId)}};export{p as ElementsApiPortRequired,P as ElementsClient,H as InheritiClientProvider,T as MasterKeyRelayExpired,M as MasterKeyRelayTimedOut,b as MasterKeyRequired,E as MemoryKeyVault,R as MemoryStatePort,S as PlanMaterialReconstructorRequired,D as RelayMasterKeySource,dt as SDKContainer,A as StaticMasterKeyResolver,de as createElementsClient,le as getAvailableEnvs,_ as masterKeyRefFor,g as masterKeyRefKey,ce as unwrapDekWithMasterKey,U as useClient};
1
+ import{SDKContainer as Jn}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as ht,useEffect as Me,createContext as ft,useMemo as yt}from"react";import{CoreProvider as gt,HttpClientFactory as vt,AuthModule as Rt,AuthStateProvider as wt,AuthSessionRestorer as Pt,useClient as Et}from"@safetech/inheriti-core-sdk";function A(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},n=t[e]??t.development;return r==""?n:`${n}/${r}`}import L from"react";import Rr from"react-dom";function lt(r){if(!r||typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}var wr=Array(12).fill(0);var pe=1,me=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;let{message:n,...a}=e,o=typeof e?.id=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:pe++,s=this.toasts.find(c=>c.id===o),i=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),s?this.toasts=this.toasts.map(c=>c.id===o?(this.publish({...c,...e,id:o,title:n}),{...c,...e,id:o,dismissible:i,title:n}):c):this.addToast({title:n,...a,dismissible:i,id:o}),o},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(n=>n({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let a=Promise.resolve(e instanceof Function?e():e),o=n!==void 0,s,i=a.then(async l=>{if(s=["resolve",l],L.isValidElement(l))o=!1,this.create({id:n,type:"default",message:l});else if(dt(l)&&!l.ok){o=!1;let f=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,I=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,U=typeof f=="object"&&!L.isValidElement(f)?f:{message:f};this.create({id:n,type:"error",description:I,...U})}else if(l instanceof Error){o=!1;let f=typeof t.error=="function"?await t.error(l):t.error,I=typeof t.description=="function"?await t.description(l):t.description,U=typeof f=="object"&&!L.isValidElement(f)?f:{message:f};this.create({id:n,type:"error",description:I,...U})}else if(t.success!==void 0){o=!1;let f=typeof t.success=="function"?await t.success(l):t.success,I=typeof t.description=="function"?await t.description(l):t.description,U=typeof f=="object"&&!L.isValidElement(f)?f:{message:f};this.create({id:n,type:"success",description:I,...U})}}).catch(async l=>{if(s=["reject",l],t.error!==void 0){o=!1;let h=typeof t.error=="function"?await t.error(l):t.error,f=typeof t.description=="function"?await t.description(l):t.description,X=typeof h=="object"&&!L.isValidElement(h)?h:{message:h};this.create({id:n,type:"error",description:f,...X})}}).finally(()=>{o&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),c=()=>new Promise((l,h)=>i.then(()=>s[0]==="reject"?h(s[1]):l(s[1])).catch(h));return typeof n!="string"&&typeof n!="number"?{unwrap:c}:Object.assign(n,{unwrap:c})},this.custom=(e,t)=>{let n=t?.id||pe++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},w=new me,ct=(r,e)=>{let t=e?.id||pe++;return w.addToast({title:r,...e,id:t}),t},dt=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",ut=ct,pt=()=>w.toasts,mt=()=>w.getActiveToasts(),N=Object.assign(ut,{success:w.success,info:w.info,warning:w.warning,error:w.error,custom:w.custom,message:w.message,promise:w.promise,dismiss:w.dismiss,loading:w.loading},{getHistory:pt,getToasts:mt});lt("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");var Ne={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{N.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{N.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{N.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{N.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{N.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as At,jsx as M}from"react/jsx-runtime";var St="inheriti_client_merging_process",he=ft(null);function ke({children:r,clientId:e,options:t}){let n=t?.env??"development",a={key:e??"",options:{env:n}},o=ht(vt.create({apiUrl:A("",n),errorHandlingStrategy:Ne}));Me(()=>{o.current?.setApiUrl(A("",n))},[n]);let s=yt(()=>({core:{httpClient:o.current},"protection-plan":{authTokens:{mergingProcessKey:St}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return M(he.Provider,{value:o.current,children:M(wt,{children:M(gt,{modules:{auth:Rt},moduleConfigs:s,children:M(Pt,{children:M(It,{client:a,children:r})})})})})}function It({children:r,client:e}){let{connect:t,isConnected:n}=Et();return Me(()=>{!e?.key||n||t(e)},[e.key]),M(At,{children:r})}import{useContext as Ct,useCallback as Tt}from"react";import{useClient as bt}from"@safetech/inheriti-core-sdk";function Ke(){let{connect:r,...e}=bt(),t=Ct(he),n=Tt(async a=>(a?.options?.env&&t?.setApiUrl(A("",a.options.env)),r(a)),[r,t]);return{...e,connect:n}}function _t(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",n=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",a=A("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:a}}import{decryptRSAOAEP as xt,generateRSAOAEPKeyPair as Dt}from"@safetech/inheriti-core-sdk/crypto";var Q=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Z=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},G=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await Dt(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),s=this.options.sleep??(i=>new Promise(c=>setTimeout(c,i)));for(;Date.now()<o;){let i=await this.options.api.readRelaySession(n.sessionId);if(i.status==="DELIVERED"&&i.sealedMasterKey){let c=(await xt(i.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(c))throw new Error("invalid_master_key_material");return c}if(i.status==="EXPIRED")throw new Z(n.sessionId);await s(a)}throw new Q(n.sessionId)}};function fe(r){return{resolve:async e=>{if(Ot(e,r.applicationId)){let t=await r.source?.resolve();return t||Ue(r,()=>r.api.masterKeyAcquisition())}return Ue(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId))}}}function Ot(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ue(r,e){if((await e()).relayAvailable)return new G({...r.relay,api:Nt(r.api)}).resolve()}function Nt(r){return{startRelaySession:e=>r.startMasterKeyRelaySession(e),readRelaySession:e=>r.readMasterKeyRelaySession(e)}}function C(r){return`${r.system}:${r.contextId}`}function ge(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var T=class extends Error{constructor(t){super(`master_key_required:${C(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ye=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(C(e),t),this}async resolve(e){return this.sources.get(C(e))?.resolve()}};var V=class{keys=new Map;async store(e,t){this.keys.set(C(e),t.slice())}async load(e){return this.keys.get(C(e))?.slice()}async remove(e){this.keys.delete(C(e))}};var B=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var F=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},d=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var H=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var J=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Mt={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},Ge=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function k(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new y("plan_material_field_unknown");if(ve(r.dataShards,"data_shards_invalid"),ve(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ve(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new y("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new y("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new y("material_operation_invalid")}function ve(r,e){if(!Array.isArray(r))throw new y(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new y(e);if(t.data!==void 0&&typeof t.data!="string")throw new y(e)}}function x(r){if(_(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ut(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(_(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!J.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(o=>!o.trim()))throw new m("asset_field_names_invalid");if(kt(t.matchOrigins),!t.isBinary){let o=Mt[t.type];if(!o||a.some(s=>!o.includes(s)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(_(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ve(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}Kt(r)}function kt(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function Kt(r){let e=r.policy;if(e&&_(e,["authentication","moderation","dms","masterKeyRelease","custodian"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){_(e.authentication,["mode"],"plan_authentication_field_unknown");let o=e.authentication.mode;if(o!==void 0&&o!=="EXCLUSIVE"&&o!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){_(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let o=r.participants.filter(c=>c.relationships.includes("MODERATOR"));if(o.length===0)throw new m("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>o.length))throw new m("minimum_approvals_invalid");let i=e.moderation.approvalMode;if(i!==void 0&&i!=="THRESHOLD"&&i!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;_(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Ve(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(o=>Le(o.routingEmail)===Le(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new m("dms_countdown_invalid")}function Ut(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ve(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Le(r){return r.normalize("NFC").trim().toLowerCase()}function _(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var te=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},re=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),x(e),ee(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,o={}){x(t);let s=await this.checkpoints.load(e);if(!s)throw new ne("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Be(t))throw new ne("creation_declaration_mismatch");let i=await this.api.getPlanCreation(e);if(o.onProgress?.(i.stage),i.outcome==="COMPLETED"||i.outcome==="CANCELED")return await this.checkpoints.remove(e),i;if(i.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!i.planId)return i;ee(o.signal),o.onProgress?.("ENCRYPTING");let c=await a.encrypt({planId:i.planId,declaration:t,secrets:n,signal:o.signal});ee(o.signal),o.onProgress?.("GENERATING_SHARES");let l=await a.generateShares({planId:i.planId,declaration:t,encrypted:c,signal:o.signal});ee(o.signal),k(l);let h=await this.api.supplyPlanCreationMaterial(e,l);return o.onProgress?.(h.stage),h.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,h),h}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Be(e),serverStage:t.stage})}},ne=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Be(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ee(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Fe(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new F(n.stage);return r.authorizeRevealAction(e,t)}function Lt(r){let e=r?.status;return e===400||e===401||e===403}async function He(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(o){if(!Lt(o))throw o}return r.releaseRevealMaterial(e,t)}function qe(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Vt(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Gt.has(r.stage)?"ENDED":"CONTINUING"}var Gt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Vt(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ae=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},g=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ze(r,e,t={}){if(t.signal?.aborted)throw Ee();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let a=t.idempotencyKey??crypto.randomUUID(),o=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),s;try{let i=await Ft(r,o,t);q(t,"RELEASING_MATERIAL",i);let c=await r.releaseRevealMaterial(i.id,i.materialVersion??"1");i.mode==="GOVERNED"&&await r.markRevealSharesCollected(i.id);let l=await zt(r,i,n,Wt(c),t);q(t,"RECONSTRUCTING",i),s=await r.reconstructPlanMaterial(l);let h=await r.reportRevealReconstruction(i.id,{status:"SUCCEEDED"});return q(t,"OPEN",h),new we(r,h,n,s,t.signal)}catch(i){throw s?.fill(0),await jt(r,o.id,t.signal?.aborted?"CANCELED":"ERROR"),i}}var Bt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Ft(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:qe(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Bt.has(n.stage))throw new Re(n.stage);await Se(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var Re=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function q(r,e,t){r.onProgress?.({phase:e,session:t})}function Se(r,e){return e?.aborted?Promise.reject(Ee()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),o=()=>{clearTimeout(a),n(Ee())};function s(){e?.removeEventListener("abort",o),t()}e?.addEventListener("abort",o,{once:!0})})}var we=class{constructor(e,t,n,a,o){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=o?()=>{this.close("CANCELED")}:void 0,o&&this.abortListener&&o.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ae;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new g("asset_selector_invalid");if(!this.client.assetDecoder)throw new g("asset_decoder_required");let n=e.map(({selector:o,options:s={}})=>{let i=$e(o),c=this.plan.assets.find(l=>(l.code??l.id)===i.asset);if(!c)throw new g("asset_not_found");if(c.isBinary)throw new g("action_not_allowed");if(!c.fieldNames.includes(i.field))throw new g("asset_field_not_found");return{selector:`${i.asset}.${i.field}`,assetCode:i.asset,asset:c,field:i.field,options:s}}),a=[];try{for(let s of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let o=n.map(s=>{let i=this.client.assetDecoder(this.material).find(c=>c.id===s.asset.id||c.id===s.assetCode);if(!i)throw new g("asset_value_invalid");return{selector:s.selector,value:Ht(i.data,s.field)}});await t(o)}catch(o){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",qt(o)))),o}await Promise.all(a.map(o=>this.reportAction(o.id,"SUCCEEDED")))}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!We(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function $e(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new g("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new g("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Ht(r,e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new g("asset_value_invalid")}if(!t||typeof t!="object"||Array.isArray(t)||!(e in t))throw new g("asset_value_invalid");return t[e]}function qt(r){if(r instanceof g)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}async function zt(r,e,t,n,a){if(t.revealPolicy?.custodian!=="FORCE"||n.shares.some(c=>c.shareType==="CUSTODIAN_KEY_SHARD"))return n;let o=await r.getRevealCustodianAccess(e.id);for(;o.status==="PENDING"||o.status==="DISTRIBUTED";){let c={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};a.onSession?.(c),q(a,"WAITING_FOR_CUSTODIAN_CLAIM",c),await Se(a.pollIntervalMs??1500,a.signal),o=await r.getRevealCustodianAccess(e.id)}if(o.status!=="CLAIMED"||o.deviceType!=="SK_MOBILE")throw new oe;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};a.onSession?.(s),q(a,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let i=await $t(r,e.id,a);return Object.assign({},n,{shares:n.shares.concat(i.shares.map((c,l)=>({id:`${i.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:c})))})}async function $t(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let o=a;if(o.shares?.length)return o;throw new oe}if(Date.now()>=n)throw new Pe;await Se(t.pollIntervalMs??1500,t.signal)}}var oe=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Pe=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Wt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function jt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!We(n))throw n}}function We(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function Ee(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var z=class{constructor(e,t={}){this.coreSdk=e;this.keyVault=t.keyVault??new V,this.state=t.state??new B,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Xt(t),this.applicationId=t.applicationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;assetDecoder;listPlans(e){if(!this.api)throw new d;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new d;return this.api.getPlan(e)}startPlanCreation(e){if(!this.api)throw new d;return x(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(!this.api)throw new d;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(!this.api)throw new d;return k(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new te){if(!this.api)throw new d;return new re(this.api,e)}createPlan(e){return this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){if(!this.applicationId)throw new T({system:"INHERITI_ELEMENTS",contextId:"application"});let e={system:"INHERITI_ELEMENTS",contextId:this.applicationId},t=await this.keyVault.load(e);if(t)return Ye(t);let n=await this.masterKeys?.resolve(e);if(!n)throw new T(e);return await this.keyVault.store(e,je(n)),n}async prepareReveal(e){if(!this.api)throw new d;let t=await this.api.planKeyReference(e);if(!t.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new d;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new H;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let t=ge(e);if(!t)throw new T({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Ye(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new T(t);return await this.keyVault.store(t,je(a)),a}initializeGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new d;return this.api.startReveal(e,t)}getReveal(e){if(!this.api)throw new d;return this.api.getReveal(e)}openReveal(e,t){return ze(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let o=await n(a);return await a.close("COMPLETED"),o}catch(o){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),o}}async releaseRevealMaterial(e,t){if(!this.api)throw new d;return He(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(e)}requestRevealCustodianRelease(e){if(!this.api)throw new d;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new d;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new d;return this.api.getRevealCustodianShare(e)}reportRevealReconstruction(e,t){if(!this.api)throw new d;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new d;return this.api.closeReveal(e,t)}abortPlanAccess(e){if(!this.api)throw new d;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new d;return Fe(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new d;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new d;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new d;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new d;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new d;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new d;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let o=n.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),i=a.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),c=a.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:o.concat(s,i,c),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new d;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new Ie;return this.coreSdk.getService(e).execute(t)}},Ie=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Yt(r){return new z(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId,assetDecoder:r.assetDecoder})}function je(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ye(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Xt(r){if(!r.api||!r.applicationId)return;let e={api:r.api,applicationId:r.applicationId,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};return fe(e)}var Qt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Zt=["DIRECT","GOVERNED"],Qe=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Jt=["ACTIVE","REVOKED"],er=["SK_MOBILE"],tr=["ACTIVE","INACTIVE"],rr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ze(r){let e=R(r);return{items:P(e.items).map(et),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function Je(r){let e=R(r),t=et(e),n=R(e.source),a=u(n.kind,"source.kind");return{...t,assets:P(e.assets).map(o=>{let s=R(o);return{id:u(s.id,"asset.id"),code:D(s.code),type:v(u(s.type,"asset.type"),J),name:u(s.name,"asset.name"),isBinary:ar(s.isBinary,"asset.isBinary"),fieldNames:P(s.fieldNames).map(i=>u(i,"asset.fieldNames")),fileName:D(s.fileName),mimeType:D(s.mimeType),size:s.size===void 0||s.size===null?void 0:S(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:P(s.matchOrigins).map(i=>u(i,"asset.matchOrigins"))}}),participants:P(e.participants).map(o=>{let s=R(o);return{id:u(s.id,"participant.id"),displayName:u(s.displayName,"participant.displayName"),relationships:P(s.relationships).map(i=>v(u(i,"relationship"),Qe)),lifecycle:v(u(s.lifecycle,"participant.lifecycle"),Jt)}}),revealPolicy:(()=>{let o=R(e.revealPolicy);return{masterKeyRelease:v(u(o.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:v(u(o.custodian,"custodian"),["FORCE","BYPASS"])}})(),dms:e.dms===void 0?void 0:(()=>{let o=R(e.dms);return{subjectEmail:u(o.subjectEmail,"dms.subjectEmail"),countdownDays:S(o.countdownDays,"dms.countdownDays"),countdownHours:S(o.countdownHours,"dms.countdownHours"),countdownMinutes:S(o.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:v(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:v(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function $(r){let e=R(r);return{operationId:u(e.operationId,"operationId"),stage:v(u(e.stage,"stage"),Ge),outcome:v(u(e.outcome,"outcome"),rr),planId:D(e.planId),lastErrorCode:D(e.lastErrorCode),participants:e.participants===void 0?void 0:P(e.participants).map(t=>{let n=R(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:P(n.relationships).map(a=>nr(u(a,"relationship"),Qe))}})}}function et(r){let e=R(r),t=R(e.assetSummary),n=R(e.governance),a=R(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:D(e.description),status:v(u(e.status,"status"),Qt),createdAt:u(e.createdAt,"createdAt"),configuredAt:D(e.configuredAt),assetSummary:{count:S(t.count,"assetSummary.count"),types:P(t.types).map(o=>v(u(o,"assetType"),J)),names:Xe(t.names).map(o=>u(o,"assetSummary.names"))},governance:{mode:v(u(n.mode,"governance.mode"),Zt),minimumApprovals:S(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:S(a.owners,"owners"),mergers:S(a.mergers,"mergers"),moderators:S(a.moderators,"moderators")},authentication:Xe(e.authentication).map(o=>{let s=R(o);return{id:v(u(s.id,"authentication.id"),er),status:v(u(s.status,"authentication.status"),tr)}})}}function v(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function nr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function R(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Xe(r){return r==null?[]:P(r)}function P(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function u(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function D(r){return r==null?void 0:u(r,"optional")}function S(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function ar(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function Ae(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function Ce(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var K=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},se=class{constructor(e,t,n,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Ze(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Je(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async startPlanCreation(e){x(e);let{idempotencyKey:t,...n}=e;return $(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return $(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return k(t),$(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return $(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...o}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",o,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,o){let s=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});s&&i.set("authorization",`Bearer ${s}`),a?.requestId&&i.set("x-elements-step-up-request",a.requestId);for(let[f,I]of Object.entries(o??{}))i.set(f,I);n&&i.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,c),{method:t,headers:i,body:n?JSON.stringify(n):void 0}),h=await tt(l);if(!l.ok)throw new K(l.status,Ae(h),Ce(h));if(!h.ok||h.result===void 0)throw new K(l.status,Ae(h),Ce(h));return h.result}async requestWithoutResult(e){let t=await this.getBearerToken(),n=new Headers({"x-elements-environment":this.environment});t&&n.set("authorization",`Bearer ${t}`);let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,a),{method:"POST",headers:n}),s=await tt(o);if(!o.ok||!s.ok)throw new K(o.status,Ae(s),Ce(s))}};async function tt(r){try{return await r.json()}catch{return{ok:!1}}}async function or(r,e){if(!e)throw new Error("master_key_required");let t=sr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=ir(r),o=a.slice(0,12),s=a.slice(12),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:o},n,s);return lr(new Uint8Array(i))}function sr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function ir(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function lr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}import{MergeProcessReconciliationLoop as cr}from"@safetech/inheriti-core-sdk/shared-configuration";var dr=new Set(["COMPLETED","ABORTED","EXPIRED"]),Te=class{constructor(e,t=new ie,n=new le,a=Math.random){this.api=e;this.loop=new cr(t,n,a)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,a,o=!1,s=this.loop.start(e,async()=>{let i=await this.api.getGovernedReveal(e),c=i.approvalProcess?.status??"",l=ur(i);n!==void 0&&l!==n&&await t.onProcessUpdated?.(),a!==void 0&&c!==a&&await t.onApprovalUpdated?.(),n=l,a=c;let h=dr.has(i.status);if(i.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),i.status==="ABORTED"&&await t.onForceAborted?.(e),h)return{transitionKey:l,shouldPoll:!1,terminal:!0};if(!o){let f=await this.api.getCustodianShare(e);"status"in f||(o=!0,await t.onCustodianShareReceived?.(e,f))}return{transitionKey:l,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,s)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function ur(r){return`${r.status}:${r.approvalProcess?.status??""}`}var ie=class{visibility(){return typeof document<"u"&&document.visibilityState==="hidden"?"hidden":"visible"}isOnline(){return typeof navigator>"u"||navigator.onLine!==!1}now(){return Date.now()}schedule(e,t){let n=setTimeout(e,t);return()=>clearTimeout(n)}onRecovery(e){return typeof globalThis.addEventListener!="function"?()=>{}:(globalThis.addEventListener("online",e),globalThis.addEventListener("visibilitychange",e),()=>{globalThis.removeEventListener("online",e),globalThis.removeEventListener("visibilitychange",e)})}},le=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var rt=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){let t=e.declaration.policy?.custodian==="FORCE";W(e.signal),mr(e.declaration,e.secrets,t);let n=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return W(e.signal),{data:n,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,withCustodian:t,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){W(e.signal);let t=e.encrypted.totalShares+(e.encrypted.withCustodian?1:0),n=e.encrypted.threshold+(e.encrypted.withCustodian?1:0),a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:e.encrypted.withCustodian,protocol:"SSDP_PLUS_V2",planId:e.planId});W(e.signal);let o=be(a.keyShards),s=await this.sealer.encryptShares(o,void 0,e.encrypted.masterKey),i=await this.sealer.encryptShares(be(a.dataShards),s.symmetricKeyBase64),c=await this.sealer.encryptShares(be(a.backupShards),s.symmetricKeyBase64),l=a.custodianPair?await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64):void 0;return W(e.signal),{protectionProtocol:a.protocol,validatorShares:_e(s.encryptedShares),dataShards:_e(i.encryptedShares),backupShards:_e(c.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:pr(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:xe(n.encryptedShares[0]),dataShard:xe(n.encryptedShares[1])}}};function be(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function _e(r){return r.map(xe)}function xe(r){return{id:r.id,data:r.encryptedData}}function pr(r,e){let t={};for(let n of r){let a=e.assets.find(o=>o.clientAssetRef===n.id);if(!a)throw new y("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function mr(r,e,t){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new y("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new y("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new y("plan_secrets_declaration_mismatch");let n=new Map(r.assets.map(a=>[a.clientAssetRef,a]));for(let a of e.assets){let o=n.get(a.id);if(!o||o.type!==a.type)throw new y("plan_secrets_declaration_mismatch")}}function W(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function nt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var ce=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),nt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return nt(new Uint8Array(t))}},de=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let o=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(o),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var j=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Y=class extends j{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},p=class extends j{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function De(r){if(r instanceof j)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var at=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:b(n,"issuer"),authorizationEndpoint:b(n,"authorization_endpoint"),tokenEndpoint:b(n,"token_endpoint"),deviceAuthorizationEndpoint:E(n,"device_authorization_endpoint"),endSessionEndpoint:E(n,"end_session_endpoint"),revocationEndpoint:E(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:b(t,"device_code"),userCode:b(t,"user_code"),verificationUri:b(t,"verification_uri"),verificationUriComplete:E(t,"verification_uri_complete"),expiresInSeconds:ot(t,"expires_in"),intervalSeconds:Oe(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:b(n,"access_token"),refreshToken:E(n,"refresh_token"),idToken:E(n,"id_token"),tokenType:b(n,"token_type"),expiresInSeconds:ot(n,"expires_in"),refreshExpiresInSeconds:Oe(n,"refresh_expires_in"),scope:E(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let o=E(a,"error")??`oauth_http_${n.status}`;throw new p(o,E(a,"error_description")??o)}return a}};function b(r,e){let t=E(r,e);if(!t)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function E(r,e){return typeof r[e]=="string"?r[e]:void 0}function ot(r,e){let t=Oe(r,e);if(t===void 0)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function Oe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var hr=600*1e3,ue=5,fr=5,st=class{constructor(e){this.options=e;this.crypto=e.crypto??new ce,this.clock=e.clock??new de}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),o=await this.crypto.sha256UrlSafe(a),s=this.clock.now()+hr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let i=new URL(e.authorizationEndpoint);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.options.configuration.clientId),i.searchParams.set("redirect_uri",this.options.configuration.redirectUri),i.searchParams.set("scope",this.options.configuration.scopes.join(" ")),i.searchParams.set("state",t),i.searchParams.set("nonce",n),i.searchParams.set("code_challenge",o),i.searchParams.set("code_challenge_method","S256"),{authorizationUrl:i.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new p("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new p("authorization_transaction_expired");let a=new URL(e),o=new URL(n.redirectUri);if(a.origin!==o.origin||a.pathname!==o.pathname)throw new p("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new p(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new p("state_mismatch");let i=a.searchParams.get("code");if(!i)throw new p("authorization_code_missing");let c=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:c.tokenEndpoint,clientId:this.options.configuration.clientId,code:i,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new p("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(ue,t.intervalSeconds??ue),a=this.clock.now(),o={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),o),o}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new p("device_transaction_missing");let a=n,o=await this.getDiscovery(),s=Math.max(ue,a.intervalSeconds??ue),i=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(i>=a.expiresAt);){await this.clock.sleep(Math.max(0,i-this.clock.now()),e);try{let c=await this.options.transport.pollDeviceToken({tokenEndpoint:o.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let l=await this.acceptTokens(c);return await this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(c){let l=De(c);if(l==="authorization_pending"){i=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=fr,i=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),c}}throw await this.options.transactions.remove(t),new p("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new Y;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new p("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=De(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new Y:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(O(e.issuer)!==O(this.options.configuration.issuer))throw new p("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${O(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new p("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new p("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==n.subject||o.sessionId!==n.sessionId)throw new p("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,o=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(a.issuer))throw new p("issuer_mismatch");if(!o.includes(a.audience))throw new p("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new p("client_mismatch");if(e.environment!==a.environment)throw new p("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new p("required_claim_missing");if(n&&e.nonce!==t)throw new p("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(n.issuer))throw new p("issuer_mismatch");if(!a.includes(n.clientId))throw new p("client_mismatch");if(e.authorizedParty!==n.clientId)throw new p("client_mismatch");if(!e.subject||!e.sessionId)throw new p("required_claim_missing");if(e.nonce!==t)throw new p("nonce_mismatch")}};function O(r){return r.replace(/\/+$/u,"")}var it=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};export{J as CANONICAL_PLAN_ASSET_TYPES,Mt as CANONICAL_STRUCTURED_ASSET_FIELDS,rt as CorePlanMaterialBuilder,d as ElementsApiPortRequired,K as ElementsApiRequestFailed,z as ElementsClient,ne as GuidedCreateRecoveryError,re as GuidedPlanCreator,ie as HostProcessRuntimeEnvironment,se as HttpElementsApiPort,at as HttpOperatorAuthTransport,ke as InheritiClientProvider,m as InvalidPlanDeclaration,y as InvalidPlanMaterial,le as LocalProcessReconciliationOwnership,Z as MasterKeyRelayExpired,Q as MasterKeyRelayTimedOut,T as MasterKeyRequired,te as MemoryGuidedCreateCheckpointStore,V as MemoryKeyVault,B as MemoryStatePort,p as OAuthProtocolError,st as OperatorAuthClient,j as OperatorAuthError,Y as OperatorReauthenticationRequired,it as OperatorSessionController,Ge as PLAN_CREATION_SERVER_STAGES,H as PlanMaterialReconstructorRequired,Te as PollingSharedPlanEventListener,G as RelayMasterKeySource,F as RevealActionsNotOpen,g as RevealFieldAccessError,ae as RevealHandleClosed,Jn as SDKContainer,ye as StaticMasterKeyResolver,de as SystemOAuthClock,ce as WebOAuthCrypto,Yt as createElementsClient,fe as createMasterKeyResolver,_t as getAvailableEnvs,ge as masterKeyRefFor,C as masterKeyRefKey,De as oauthErrorCode,$e as parseAssetFieldSelector,qe as revealPhaseOf,or as unwrapDekWithMasterKey,Ke as useClient,x as validatePlanCreationInput,k as validatePlanCreationMaterial};