@safetech/inheriti-client-sdk 1.17.20 → 1.17.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{decodeAssetContainer as vn}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as Ct,generateRSAOAEPKeyPair as Tt}from"@safetech/inheriti-core-sdk/crypto";var de=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},le=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ce=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},X=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await Tt();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),o=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),l=this.options.sleep??(E=>new Promise(v=>setTimeout(v,E))),c=!0,I=!1,b,R=()=>b??=(async()=>{let E=new AbortController,v,xt=new Promise((Pn,_t)=>{v=setTimeout(()=>{E.abort(),_t(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,E.signal),xt])}finally{clearTimeout(v)}})(),_,G=new Promise((E,v)=>{_=()=>{c&&R().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});G.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),I=!0;Date.now()<a;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let E=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),G]);if(E.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(E.status==="DELIVERED"&&E.sealedMasterKey){let v=(await Ct(E.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(v))throw new Error("invalid_master_key_material");return v}if(E.status==="EXPIRED")throw new le(s.sessionId);await Ot(l,o,e)}throw new de(s.sessionId)}catch(E){if(c&&(!I||e?.aborted))try{await R()}catch(v){if(e?.aborted)throw new ce(v)}throw E}finally{_&&e?.removeEventListener("abort",_)}}};async function Ot(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function ue(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||_e(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Dt(e,r.applicationId)){let i=await r.source?.resolve();return i||_e(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return _e(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Dt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function _e(r,e,t,n,i){if((await e()).relayAvailable)return new X({...r.relay,api:Mt(r.api,t)}).resolve(n,i)}function Mt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function K(r){return`${r.system}:${r.contextId}`}function Te(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var D=class extends Error{constructor(t){super(`master_key_required:${K(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Ce=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(K(e),t),this}async resolve(e){return this.sources.get(K(e))?.resolve()}};var Q=class{keys=new Map;async store(e,t){let n=K(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(K(e))?.slice()}async remove(e){let t=K(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var Z=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 pe=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var J=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var me=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],De={"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"]},He=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],f=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function B(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new M("plan_material_field_unknown");if(Oe(r.dataShards,"data_shards_invalid"),Oe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Oe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new M("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new M("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new M("material_operation_invalid")}function Oe(r,e){if(!Array.isArray(r))throw new M(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new M(e);if(t.data!==void 0&&typeof t.data!="string")throw new M(e)}}function F(r){if(z(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Kt(r.idempotencyKey))throw new f("idempotency_key_invalid");if(!r.name?.trim())throw new f("plan_name_required");if(!r.assets.length)throw new f("assets_required");let e=new Set;for(let t of r.assets){if(z(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 f("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!me.includes(t.type))throw new f("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new f("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new f("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new f("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new f("asset_field_names_invalid");if(kt(t.matchOrigins),!t.isBinary){let s=De[t.type];if(!s||i.some(o=>!s.includes(o)))throw new f("asset_field_name_not_canonical")}}if(!r.participants.length)throw new f("participants_required");for(let t of r.participants){if(z(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!We(t.routingEmail))throw new f("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new f("participant_relationships_invalid")}Nt(r)}function kt(r){if(r===void 0)return;if(!r.length)throw new f("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new f("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new f("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof f?n:new f("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new f("asset_match_origins_duplicated")}function Nt(r){let e=r.policy;if(e&&z(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new f("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){z(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new f("authentication_mode_invalid")}if(e.moderation){z(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(s.length===0)throw new f("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new f("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new f("approval_mode_invalid")}let t=e.dms;if(!t)return;z(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!We(t.subjectEmail))throw new f("dms_subject_invalid");if(!r.participants.some(s=>$e(s.routingEmail)===$e(t.subjectEmail)))throw new f("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new f("dms_countdown_invalid")}function Kt(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 We(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function $e(r){return r.normalize("NFC").trim().toLowerCase()}function z(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new f(t)}var he=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)}},fe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),F(e),ge(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,i,s={}){F(t);let o=await this.checkpoints.load(e);if(!o)throw new ye("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await je(t))throw new ye("creation_declaration_mismatch");let a=await this.api.getPlanCreation(e);if(s.onProgress?.(a.stage),a.outcome==="COMPLETED"||a.outcome==="CANCELED")return await this.checkpoints.remove(e),a;if(a.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!a.planId)return a;ge(s.signal),s.onProgress?.("ENCRYPTING");let l=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});ge(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:a.planId,declaration:t,encrypted:l,signal:s.signal});ge(s.signal),B(c);let I=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(I.stage),I.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,I),I}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 je(e),serverStage:t.stage})}},ye=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function je(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,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.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 ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ye(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new pe(n.stage);return r.authorizeRevealAction(e,t)}function Ut(r){let e=r?.status;return e===400||e===401||e===403}async function Xe(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Ut(s))throw s}return r.releaseRevealMaterial(e,t)}function et(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"?qt(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":Lt.has(r.stage)?"ENDED":"CONTINUING"}var Lt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function qt(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 Ie=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ne(r,e,t={}){if(t.signal?.aborted)throw y();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Qe(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)}),t.signal?.aborted))throw y();let s=t.idempotencyKey??crypto.randomUUID(),o;try{o=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?l:Qe(c.id)}let a;try{if(t.signal?.aborted)throw y();let l=await zt(r,o,t);if(t.signal?.aborted||(U(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw y();let c=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw y();let I;try{I=await Bt(r,l,Ht(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(U(t,"RECONSTRUCTING",l),t.signal?.aborted))throw y();try{a=await r.reconstructPlanMaterial(I)}catch(R){throw t.signal?.aborted?y():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:Vt(R)}),R)}if(t.signal?.aborted)throw y();let b=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(U(t,"OPEN",b),t.signal?.aborted))throw y();return new Me(r,b,n,a,t.signal)}catch(l){throw a?.fill(0),await nt(r,o.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function Qe(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Gt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function zt(r,e,t){let n=await k(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw y();if(t.onSession?.(n),t.onProgress?.({phase:et(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Gt.has(n.stage))throw new ve(n.stage);await Ke(t.pollIntervalMs??1500,t.signal),n=await k(()=>r.getReveal(e.id,t.signal),t.signal)}}var ve=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function U(r,e,t){r.onProgress?.({phase:e,session:t})}function Ke(r,e){return e?.aborted?Promise.reject(y()):new Promise((t,n)=>{let i=setTimeout(o,Math.max(0,r)),s=()=>{clearTimeout(i),n(y())};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Me=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let o=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(o,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Ie;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=e.map(({selector:s,options:o={}})=>{let a=tt(s),l=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!l)throw new P("asset_not_found");if(l.isBinary)throw new P("action_not_allowed");if(!l.fieldNames.includes(a.field))throw new P("asset_field_not_found");return{selector:`${a.asset}.${a.field}`,assetCode:a.asset,asset:l,field:a.field,options:o}}),i=[];try{for(let o of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:o.options.idempotencyKey??crypto.randomUUID(),assetId:o.asset.id,fieldName:o.field,action:o.options.action??"VIEW_FIELD",...o.options.destination===void 0?{}:{destination:o.options.destination},...o.options.origin===void 0?{}:{origin:o.options.origin}}));let s=n.map(o=>{let a=this.client.assetDecoder(this.material).find(l=>l.id===o.asset.id||l.id===o.assetCode);if(!a)throw new P("asset_value_invalid");return{selector:o.selector,value:Ft(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",Ze(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=this.plan.assets.find(o=>o.code===e||o.id===e);if(!n)throw new P("asset_not_found");if(!n.isBinary)throw new P("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let o=this.client.assetDecoder(this.material).find(a=>a.id===n.id||a.id===n.code);if(!o||!(o.data instanceof Uint8Array))throw new P("asset_value_invalid");s=o.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(o){throw await this.reportAction(i.id,"FAILED",Ze(o)),o}finally{s?.fill(0)}await this.reportAction(i.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=nt(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function tt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new P("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new P("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Ft(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new P("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new P("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?De[t]:void 0)?.includes(e))return"";throw new P("asset_value_invalid")}return n[e]}function Ze(r){if(r instanceof P)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"}function Vt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Bt(r,e,t,n){let i=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(i){let l=await k(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new Pe;let c=await k(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Je(c,i.id,e.planId),!c.shares.includes(i.data))throw new C;U(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:I}=await k(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw y();if(!I?.trim())throw new C;if(await r.claimRevealCustodianShare(e.id,c.id,I),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw y();return{...t,shares:t.shares.filter(b=>b!==i).concat(c.shares.map((b,R)=>({id:`${c.id}:${R}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:b})))}}if(l!=="SK_MOBILE")throw new C;if(n.signal?.aborted)throw y();return await r.distributeRevealCustodianShare(e.id),U(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await k(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),U(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await Ke(n.pollIntervalMs??1500,n.signal),s=await k(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Pe;if(!s.shareId||!s.deviceId)throw new C;U(n,"CONNECTING_SAFEKEY_PRO",e);let l=await k(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw y();if(Je(l,s.shareId,e.planId),l.deviceId!==s.deviceId)throw new C;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw y();return{...t,shares:t.shares.concat(l.shares.map((c,I)=>({id:`${l.id}:${I}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new C;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),U(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw y();await r.requestRevealCustodianRelease(e.id);let a=await $t(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((l,c)=>({id:`${a.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function Je(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new C}async function k(r,e){if(e?.aborted)throw y();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(y()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw y();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function $t(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await k(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new C}if(Date.now()>=n)throw new ke;await Ke(t.pollIntervalMs??1500,t.signal)}}var C=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Pe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},ke=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ht(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function nt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Wt(o))throw o}return}let n=new AbortController,i,s=new Promise((o,a)=>{i=setTimeout(()=>{n.abort(),a(new Error("reveal_cancellation_timed_out"))},5e3)});try{let o=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(o.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(o){if(o?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:o}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Wt(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function y(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ee=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new Q,this.state=t.state??new Z,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Xt(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return F(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return B(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new he){if(this.requireApplication(),!this.api)throw new p;return new fe(this.api,e)}createPlan(e){return this.requireApplication(),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(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new D({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return Yt(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new D(e);return await this.keyVault.store(e,jt(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}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 p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new J;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new D({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Te(e);if(!i)throw new D({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}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)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new p;return this.api.getReveal(e,t)}openReveal(e,t){return Ne(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return Xe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new p;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return Ye(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(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 n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=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(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),a=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),l=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(o,a,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 p;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)}requireApplication(){if(!this.applicationId)throw new D({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Re=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function jt(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 Yt(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Xt(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ue({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ue({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as sn,createSsdpV2Processor as on}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Ue(r,e){if(!e)throw new Error("master_key_required");let t=Qt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Zt(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return Jt(new Uint8Array(a))}function Qt(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 Zt(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 Jt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var te=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await rt("plan_key_unwrap_failed",()=>Ue(e.planKey,t)),i=await crypto.subtle.importKey("raw",Le(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],o=[];for(let a of e.shares){let l=await rt("plan_share_decryption_failed",()=>rn(a.data,i));nn(a.shareType)?o.push(l):s.push(l)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:o}).result}catch(a){throw new we("plan_share_reconstruction_failed",tn(a))}}},we=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},en=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function tn(r){let e=r instanceof Error?r.message:void 0;if(e)return en.has(e)?e:void 0}async function rt(r,e){try{return await e()}catch{throw new we(r)}}function nn(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function rn(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Le(r.slice(0,t)),i=Le(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Le(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var ne=class extends te{constructor(e={}){let t=e.processor??on(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:sn(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var an=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],dn=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ln=["ACTIVE","REVOKED"],cn=["SK_MOBILE"],un=["ACTIVE","INACTIVE"],pn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ot(r){let e=w(r);return{items:A(e.items).map(lt),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function at(r){let e=w(r);return{total:T(e.total,"total"),items:A(e.items).map(t=>{let n=w(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:u(n.id,"log.id"),planId:u(n.planId,"log.planId"),tenantId:u(n.tenantId,"log.tenantId"),event:u(n.event,"log.event"),occurredOn:u(n.occurredOn,"log.occurredOn"),status:L(n.status),title:u(n.title,"log.title"),details:A(n.details).map(i=>{let s=w(i);return{label:u(s.label,"log.detail.label"),value:u(s.value,"log.detail.value")}})}})}}function dt(r){let e=w(r),t=lt(e),n=w(e.source),i=u(n.kind,"source.kind");return{...t,assets:A(e.assets).map(s=>{let o=w(s);return{id:u(o.id,"asset.id"),code:L(o.code),type:S(u(o.type,"asset.type"),me),name:u(o.name,"asset.name"),isBinary:gn(o.isBinary,"asset.isBinary"),fieldNames:A(o.fieldNames).map(a=>u(a,"asset.fieldNames")),fileName:L(o.fileName),mimeType:L(o.mimeType),size:o.size===void 0||o.size===null?void 0:T(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:A(o.matchOrigins).map(a=>u(a,"asset.matchOrigins"))}}),participants:A(e.participants).map(s=>{let o=w(s);return{id:u(o.id,"participant.id"),displayName:u(o.displayName,"participant.displayName"),relationships:A(o.relationships).map(a=>S(u(a,"relationship"),st)),lifecycle:S(u(o.lifecycle,"participant.lifecycle"),ln)}}),revealPolicy:(()=>{let s=w(e.revealPolicy);return{masterKeyRelease:S(u(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:S(u(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=w(e.dms);return{subjectEmail:u(s.subjectEmail,"dms.subjectEmail"),countdownDays:T(s.countdownDays,"dms.countdownDays"),countdownHours:T(s.countdownHours,"dms.countdownHours"),countdownMinutes:T(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:S(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:S(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function re(r){let e=w(r);return{operationId:u(e.operationId,"operationId"),stage:S(u(e.stage,"stage"),He),outcome:S(u(e.outcome,"outcome"),pn),planId:L(e.planId),lastErrorCode:L(e.lastErrorCode),participants:e.participants===void 0?void 0:A(e.participants).map(t=>{let n=w(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:A(n.relationships).map(i=>mn(u(i,"relationship"),st))}})}}function lt(r){let e=w(r),t=w(e.assetSummary),n=w(e.governance),i=w(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:L(e.description),status:S(u(e.status,"status"),an),createdAt:u(e.createdAt,"createdAt"),configuredAt:L(e.configuredAt),assetSummary:{count:T(t.count,"assetSummary.count"),types:A(t.types).map(s=>S(u(s,"assetType"),me)),names:it(t.names).map(s=>u(s,"assetSummary.names"))},governance:{mode:S(u(n.mode,"governance.mode"),dn),minimumApprovals:T(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:T(i.owners,"owners"),mergers:T(i.mergers,"mergers"),moderators:T(i.moderators,"moderators")},authentication:it(e.authentication).map(s=>{let o=w(s);return{id:S(u(o.id,"authentication.id"),cn),status:S(u(o.status,"authentication.status"),un)}})}}function S(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function mn(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function w(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function it(r){return r==null?[]:A(r)}function A(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 L(r){return r==null?void 0:u(r,"optional")}function T(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function gn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var $=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function ct(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function hn(r,e){if(!e){if(r.length===0)throw new $("organization_required");if(r.length>1)throw new $("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new $("organization_access_denied");return e}function fn(r){let e=h(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),createdAt:x(e.createdAt)}}function ut(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(fn),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function pt(r){let e=h(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=h(t);return{unitId:d(n.unitId),position:m(n.position,0),commitment:d(n.commitment),status:d(n.status)}})}}function qe(r){let e=h(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),status:e.status}}function mt(r){let e=h(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),parentId:d(e.parentId),participantRevision:m(e.participantRevision,1),recipients:e.recipients.map(Ge)}}function gt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);return{parentId:d(n.parentId),sequence:m(n.sequence,1),senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),participantRevision:m(n.participantRevision,1),createdAt:x(n.createdAt)}}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function ht(r){return{readThroughSequence:m(h(r).readThroughSequence,0)}}function ft(r){return{clearedThroughSequence:m(h(r).clearedThroughSequence,0)}}function yt(r){let e=h(r);return{parentId:d(e.parentId),sequence:m(e.sequence,1),senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),canonicalManifest:d(e.canonicalManifest),frame:d(e.frame),signature:d(e.signature),wrappedContentKey:d(e.wrappedContentKey),senderSigningPublicKey:d(e.senderSigningPublicKey)}}function h(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function d(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function x(r){let e=d(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function m(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Ge(r){let e=h(r);return{memberId:d(e.memberId),deviceId:d(e.deviceId),deviceVersion:m(e.deviceVersion,1),encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint)}}function H(r){let e=h(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:d(e.id),tenantId:d(e.tenantId),memberId:d(e.memberId),version:e.version,encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint),status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)}}function be(r){let e=h(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:d(e.id),tenantId:d(e.tenantId),creatorMemberId:d(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(d),participantRevision:e.participantRevision,status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=h(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:d(n.senderMemberId),createdAt:x(n.createdAt)}}return t}function It(r){let e=h(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(be),total:e.total,limit:e.limit,offset:e.offset}}function vt(r){let e=h(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Ge(t);return{memberId:n.memberId,name:d(h(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Pt(r){let e=h(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(n.memberId),name:d(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:d(h(n.profilePicture).url)}}}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Rt(r){let e=h(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),messageId:d(e.messageId),participantRevision:m(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Ge),shareLayers:e.shareLayers.map(t=>{let n=h(t),i=d(n.id),s=d(n.dataShareId),o=d(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:d(n.contractAddress),dataShareId:s,keyShareId:o};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function Ee(r){let e=h(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:d(e.messageId),status:e.status}}function wt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:d(n.id),status:n.status,senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),createdAt:x(n.createdAt),updatedAt:x(n.updatedAt),expiresAt:x(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=h(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:d(o.memberId),status:o.status}})),i}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0)}}function bt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId),ciphertext:d(n.ciphertext)}})}}function Et(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId)}})}}function ie(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function se(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var N=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},W=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:H(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:H(n)}async registerInboxDevice(e){return H(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return H(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return H(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return be(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return It(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return vt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Pt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Rt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return pt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,a=await this.requestBinary(o,"PUT",i,s),l=await Se(a,s);if(!l.ok||l.result?.shareId!==n||l.result.status!=="STORED")throw new N(a.status,ie(l),se(l))}async publishInboxFile(e,t,n){return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return Et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,o){let a=new URLSearchParams({deviceId:i,leaseId:s}),l=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${a}`,c=await this.requestBinary(l,"GET",void 0,o);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let I=Number(c.headers.get("content-length"));if(Number.isFinite(I)&&I>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let b=c.body.getReader(),R=[],_=0;try{for(;;){o?.throwIfAborted();let v=await b.read();if(v.done)break;if(_+=v.value.length,_>14*1024*1024)throw new Error("invalid_inbox_share_size");R.push(v.value)}}catch(v){throw await b.cancel().catch(()=>{}),v}let G=new Uint8Array(_),E=0;for(let v of R)G.set(v,E),E+=v.length;return G}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(ct)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}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 i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return ot(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return dt(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return at(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){F(e);let{idempotencyKey:t,...n}=e;return re(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return B(t),re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return re(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,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}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,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}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`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}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,i,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let l=new Headers({"x-elements-environment":this.environment});a&&l.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&l.set("x-organization-id",this.business.organizationId),i?.requestId&&l.set("x-elements-step-up-request",i.requestId);for(let[_,G]of Object.entries(s??{}))l.set(_,G);n&&l.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,I={method:t,headers:l,body:n?JSON.stringify(n):void 0};o&&(I.signal=o);let b=await this.transport(new URL(e,c),I);o?.throwIfAborted();let R=await Se(b,o);if(o?.throwIfAborted(),!b.ok)throw new N(b.status,ie(R),se(R));if(!R.ok||R.result===void 0)throw new N(b.status,ie(R),se(R));return R.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),n&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,a),{method:t,headers:o,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!l.ok){let c=await Se(l,i);throw new N(l.status,ie(c),se(c))}return l}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,s),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),a=await Se(o);if(!o.ok||!a.ok)throw new N(o.status,ie(a),se(a))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Se(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{PassphraseMasterKeySource as Or,RawMasterKeySource as Dr,computePassphraseVerifier as Mr,deriveMasterKey as kr,generateHexSeed as Nr}from"@safetech/inheriti-core-sdk/crypto";function St(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var oe=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),St(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return St(new Uint8Array(t))}},ae=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(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"}},g=class extends j{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ae(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 ze=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:q(n,"issuer"),authorizationEndpoint:q(n,"authorization_endpoint"),tokenEndpoint:q(n,"token_endpoint"),deviceAuthorizationEndpoint:O(n,"device_authorization_endpoint"),endSessionEndpoint:O(n,"end_session_endpoint"),revocationEndpoint:O(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:q(t,"device_code"),userCode:q(t,"user_code"),verificationUri:q(t,"verification_uri"),verificationUriComplete:O(t,"verification_uri_complete"),expiresInSeconds:At(t,"expires_in"),intervalSeconds:Fe(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:q(n,"access_token"),refreshToken:O(n,"refresh_token"),idToken:O(n,"id_token"),tokenType:q(n,"token_type"),expiresInSeconds:At(n,"expires_in"),refreshExpiresInSeconds:Fe(n,"refresh_expires_in"),scope:O(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),i={};try{i=await n.json()}catch{}if(!n.ok){let s=O(i,"error")??`oauth_http_${n.status}`;throw new g(s,O(i,"error_description")??s)}return i}};function q(r,e){let t=O(r,e);if(!t)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function O(r,e){return typeof r[e]=="string"?r[e]:void 0}function At(r,e){let t=Fe(r,e);if(t===void 0)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function Fe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var yn=600*1e3,xe=5,In=5,Ve=class{constructor(e){this.options=e;this.crypto=e.crypto??new oe,this.clock=e.clock??new ae}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),s=await this.crypto.sha256UrlSafe(i),o=this.clock.now()+yn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let a=new URL(e.authorizationEndpoint);return a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.options.configuration.clientId),a.searchParams.set("redirect_uri",this.options.configuration.redirectUri),a.searchParams.set("scope",this.options.configuration.scopes.join(" ")),a.searchParams.set("state",t),a.searchParams.set("nonce",n),a.searchParams.set("code_challenge",s),a.searchParams.set("code_challenge_method","S256"),{authorizationUrl:a.toString(),expiresAt:o}}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 g("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new g("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new g("redirect_uri_mismatch");let o=i.searchParams.get("error");if(o)throw new g(o,i.searchParams.get("error_description")??o);if(i.searchParams.get("state")!==n.state)throw new g("state_mismatch");let a=i.searchParams.get("code");if(!a)throw new g("authorization_code_missing");let l=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),I=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(I),I}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new g("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(xe,t.intervalSeconds??xe),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+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 g("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(xe,i.intervalSeconds??xe),a=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(a>=i.expiresAt);){await this.clock.sleep(Math.max(0,a-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=Ae(l);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=In,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new g("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 g("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=Ae(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(V(e.issuer)!==V(this.options.configuration.issuer))throw new g("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${V(t)}|${n}|${i}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new g("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 g("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 g("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(i.issuer))throw new g("issuer_mismatch");if(!s.includes(i.audience))throw new g("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new g("client_mismatch");if(e.environment!==i.environment)throw new g("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new g("required_claim_missing");if(n&&e.nonce!==t)throw new g("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(n.issuer))throw new g("issuer_mismatch");if(!i.includes(n.clientId))throw new g("client_mismatch");if(e.authorizedParty!==n.clientId)throw new g("client_mismatch");if(!e.subject||!e.sessionId)throw new g("required_claim_missing");if(e.nonce!==t)throw new g("nonce_mismatch")}};function V(r){return r.replace(/\/+$/u,"")}var Be=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 W(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new ee(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:vn,reconstructor:r.reconstructor??new ne(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{ne as BrowserPlanMaterialReconstructor,$ as BusinessOrganizationSelectionError,Re as CoreSdkContainerRequired,N as ElementsApiRequestFailed,ee as ElementsClient,W as HttpElementsApiPort,ze as HttpOperatorAuthTransport,ce as MasterKeyRelayCancellationFailed,le as MasterKeyRelayExpired,de as MasterKeyRelayTimedOut,D as MasterKeyRequired,Q as MemoryKeyVault,Z as MemoryStatePort,g as OAuthProtocolError,Ve as OperatorAuthClient,j as OperatorAuthError,Y as OperatorReauthenticationRequired,Be as OperatorSessionController,Or as PassphraseMasterKeySource,J as PlanMaterialReconstructorRequired,Dr as RawMasterKeySource,X as RelayMasterKeySource,ve as RevealAuthorizationEnded,P as RevealFieldAccessError,Ie as RevealHandleClosed,Ce as StaticMasterKeyResolver,ae as SystemOAuthClock,oe as WebOAuthCrypto,Mr as computePassphraseVerifier,wr as createBrowserElementsClient,ue as createMasterKeyResolver,vn as decodeAssetContainer,kr as deriveMasterKey,Nr as generateHexSeed,Te as masterKeyRefFor,K as masterKeyRefKey,Ae as oauthErrorCode,Ne as openScopedReveal,tt as parseAssetFieldSelector,et as revealPhaseOf,hn as selectBusinessOrganization,Ue as unwrapDekWithMasterKey};
1
+ import{decodeAssetContainer as vn}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as Ct,generateRSAOAEPKeyPair as Tt}from"@safetech/inheriti-core-sdk/crypto";var de=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},le=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ce=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},X=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await Tt();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),o=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),l=this.options.sleep??(E=>new Promise(v=>setTimeout(v,E))),c=!0,I=!1,R,w=()=>R??=(async()=>{let E=new AbortController,v,xt=new Promise((Pn,_t)=>{v=setTimeout(()=>{E.abort(),_t(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,E.signal),xt])}finally{clearTimeout(v)}})(),_,G=new Promise((E,v)=>{_=()=>{c&&w().catch(()=>{}),v(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});G.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),I=!0;Date.now()<a;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let E=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),G]);if(E.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(E.status==="DELIVERED"&&E.sealedMasterKey){let v=(await Ct(E.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(v))throw new Error("invalid_master_key_material");return v}if(E.status==="EXPIRED")throw new le(s.sessionId);await Ot(l,o,e)}throw new de(s.sessionId)}catch(E){if(c&&(!I||e?.aborted))try{await w()}catch(v){if(e?.aborted)throw new ce(v)}throw E}finally{_&&e?.removeEventListener("abort",_)}}};async function Ot(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function ue(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||_e(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Dt(e,r.applicationId)){let i=await r.source?.resolve();return i||_e(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return _e(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Dt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function _e(r,e,t,n,i){if((await e()).relayAvailable)return new X({...r.relay,api:Mt(r.api,t)}).resolve(n,i)}function Mt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function K(r){return`${r.system}:${r.contextId}`}function Te(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var D=class extends Error{constructor(t){super(`master_key_required:${K(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Ce=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(K(e),t),this}async resolve(e){return this.sources.get(K(e))?.resolve()}};var Q=class{keys=new Map;async store(e,t){let n=K(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(K(e))?.slice()}async remove(e){let t=K(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var Z=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 pe=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var J=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var me=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],De={"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"]},He=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],f=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function B(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new M("plan_material_field_unknown");if(Oe(r.dataShards,"data_shards_invalid"),Oe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Oe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new M("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new M("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new M("material_operation_invalid")}function Oe(r,e){if(!Array.isArray(r))throw new M(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new M(e);if(t.data!==void 0&&typeof t.data!="string")throw new M(e)}}function F(r){if(z(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Kt(r.idempotencyKey))throw new f("idempotency_key_invalid");if(!r.name?.trim())throw new f("plan_name_required");if(!r.assets.length)throw new f("assets_required");let e=new Set;for(let t of r.assets){if(z(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 f("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!me.includes(t.type))throw new f("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new f("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new f("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new f("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new f("asset_field_names_invalid");if(kt(t.matchOrigins),!t.isBinary){let s=De[t.type];if(!s||i.some(o=>!s.includes(o)))throw new f("asset_field_name_not_canonical")}}if(!r.participants.length)throw new f("participants_required");for(let t of r.participants){if(z(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!We(t.routingEmail))throw new f("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new f("participant_relationships_invalid")}Nt(r)}function kt(r){if(r===void 0)return;if(!r.length)throw new f("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new f("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new f("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof f?n:new f("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new f("asset_match_origins_duplicated")}function Nt(r){let e=r.policy;if(e&&z(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new f("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){z(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new f("authentication_mode_invalid")}if(e.moderation){z(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(s.length===0)throw new f("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new f("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new f("approval_mode_invalid")}let t=e.dms;if(!t)return;z(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!We(t.subjectEmail))throw new f("dms_subject_invalid");if(!r.participants.some(s=>$e(s.routingEmail)===$e(t.subjectEmail)))throw new f("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new f("dms_countdown_invalid")}function Kt(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 We(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function $e(r){return r.normalize("NFC").trim().toLowerCase()}function z(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new f(t)}var he=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)}},fe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),F(e),ge(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,i,s={}){F(t);let o=await this.checkpoints.load(e);if(!o)throw new ye("creation_checkpoint_missing");if(o.idempotencyKey!==t.idempotencyKey||o.declarationHash!==await je(t))throw new ye("creation_declaration_mismatch");let a=await this.api.getPlanCreation(e);if(s.onProgress?.(a.stage),a.outcome==="COMPLETED"||a.outcome==="CANCELED")return await this.checkpoints.remove(e),a;if(a.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!a.planId)return a;ge(s.signal),s.onProgress?.("ENCRYPTING");let l=await i.encrypt({planId:a.planId,declaration:t,secrets:n,signal:s.signal});ge(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:a.planId,declaration:t,encrypted:l,signal:s.signal});ge(s.signal),B(c);let I=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(I.stage),I.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,I),I}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 je(e),serverStage:t.stage})}},ye=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function je(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,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.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 ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ye(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new pe(n.stage);return r.authorizeRevealAction(e,t)}function Ut(r){let e=r?.status;return e===400||e===401||e===403}async function Xe(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Ut(s))throw s}return r.releaseRevealMaterial(e,t)}function et(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"?qt(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":Lt.has(r.stage)?"ENDED":"CONTINUING"}var Lt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function qt(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 Ie=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ne(r,e,t={}){if(t.signal?.aborted)throw y();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Qe(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)}),t.signal?.aborted))throw y();let s=t.idempotencyKey??crypto.randomUUID(),o;try{o=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?l:Qe(c.id)}let a;try{if(t.signal?.aborted)throw y();let l=await zt(r,o,t);if(t.signal?.aborted||(U(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw y();let c=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw y();let I;try{I=await Bt(r,l,Ht(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(U(t,"RECONSTRUCTING",l),t.signal?.aborted))throw y();try{a=await r.reconstructPlanMaterial(I)}catch(w){throw t.signal?.aborted?y():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:Vt(w)}),w)}if(t.signal?.aborted)throw y();let R=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(U(t,"OPEN",R),t.signal?.aborted))throw y();return new Me(r,R,n,a,t.signal)}catch(l){throw a?.fill(0),await nt(r,o.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function Qe(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Gt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function zt(r,e,t){let n=await k(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw y();if(t.onSession?.(n),t.onProgress?.({phase:et(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Gt.has(n.stage))throw new ve(n.stage);await Ke(t.pollIntervalMs??1500,t.signal),n=await k(()=>r.getReveal(e.id,t.signal),t.signal)}}var ve=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function U(r,e,t){r.onProgress?.({phase:e,session:t})}function Ke(r,e){return e?.aborted?Promise.reject(y()):new Promise((t,n)=>{let i=setTimeout(o,Math.max(0,r)),s=()=>{clearTimeout(i),n(y())};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Me=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let o=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(o,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Ie;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=e.map(({selector:s,options:o={}})=>{let a=tt(s),l=this.plan.assets.find(c=>(c.code??c.id)===a.asset);if(!l)throw new P("asset_not_found");if(l.isBinary)throw new P("action_not_allowed");if(!l.fieldNames.includes(a.field))throw new P("asset_field_not_found");return{selector:`${a.asset}.${a.field}`,assetCode:a.asset,asset:l,field:a.field,options:o}}),i=[];try{for(let o of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:o.options.idempotencyKey??crypto.randomUUID(),assetId:o.asset.id,fieldName:o.field,action:o.options.action??"VIEW_FIELD",...o.options.destination===void 0?{}:{destination:o.options.destination},...o.options.origin===void 0?{}:{origin:o.options.origin}}));let s=n.map(o=>{let a=this.client.assetDecoder(this.material).find(l=>l.id===o.asset.id||l.id===o.assetCode);if(!a)throw new P("asset_value_invalid");return{selector:o.selector,value:Ft(a.data,o.field,o.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(o=>this.reportAction(o.id,"FAILED",Ze(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=this.plan.assets.find(o=>o.code===e||o.id===e);if(!n)throw new P("asset_not_found");if(!n.isBinary)throw new P("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let o=this.client.assetDecoder(this.material).find(a=>a.id===n.id||a.id===n.code);if(!o||!(o.data instanceof Uint8Array))throw new P("asset_value_invalid");s=o.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(o){throw await this.reportAction(i.id,"FAILED",Ze(o)),o}finally{s?.fill(0)}await this.reportAction(i.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=nt(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function tt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new P("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new P("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Ft(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new P("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new P("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?De[t]:void 0)?.includes(e))return"";throw new P("asset_value_invalid")}return n[e]}function Ze(r){if(r instanceof P)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"}function Vt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Bt(r,e,t,n){let i=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(i){let l=await k(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new Pe;let c=await k(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Je(c,i.id,e.planId),!c.shares.includes(i.data))throw new C;U(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:I}=await k(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw y();if(!I?.trim())throw new C;if(await r.claimRevealCustodianShare(e.id,c.id,I),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw y();return{...t,shares:t.shares.filter(R=>R!==i).concat(c.shares.map((R,w)=>({id:`${c.id}:${w}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:R})))}}if(l!=="SK_MOBILE")throw new C;if(n.signal?.aborted)throw y();return await r.distributeRevealCustodianShare(e.id),U(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await k(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),U(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await Ke(n.pollIntervalMs??1500,n.signal),s=await k(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Pe;if(!s.shareId||!s.deviceId)throw new C;U(n,"CONNECTING_SAFEKEY_PRO",e);let l=await k(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw y();if(Je(l,s.shareId,e.planId),l.deviceId!==s.deviceId)throw new C;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw y();return{...t,shares:t.shares.concat(l.shares.map((c,I)=>({id:`${l.id}:${I}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new C;let o={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(o),U(n,"WAITING_FOR_CUSTODIAN",o),n.signal?.aborted)throw y();await r.requestRevealCustodianRelease(e.id);let a=await $t(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(a.shares.map((l,c)=>({id:`${a.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function Je(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new C}async function k(r,e){if(e?.aborted)throw y();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(y()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw y();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function $t(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await k(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new C}if(Date.now()>=n)throw new ke;await Ke(t.pollIntervalMs??1500,t.signal)}}var C=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Pe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},ke=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ht(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function nt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(o){if(!Wt(o))throw o}return}let n=new AbortController,i,s=new Promise((o,a)=>{i=setTimeout(()=>{n.abort(),a(new Error("reveal_cancellation_timed_out"))},5e3)});try{let o=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(o.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(o){if(o?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:o}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Wt(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function y(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ee=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new Q,this.state=t.state??new Z,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Xt(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return F(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return B(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new he){if(this.requireApplication(),!this.api)throw new p;return new fe(this.api,e)}createPlan(e){return this.requireApplication(),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(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new D({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return Yt(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new D(e);return await this.keyVault.store(e,jt(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}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 p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new J;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new D({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Te(e);if(!i)throw new D({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}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)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new p;return this.api.getReveal(e,t)}openReveal(e,t){return Ne(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return Xe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new p;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return Ye(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(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 n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=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(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),o=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),a=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),l=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(o,a,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 p;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)}requireApplication(){if(!this.applicationId)throw new D({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Re=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function jt(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 Yt(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Xt(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ue({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ue({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as sn,createSsdpV2Processor as on}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Ue(r,e){if(!e)throw new Error("master_key_required");let t=Qt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Zt(r),s=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,o);return Jt(new Uint8Array(a))}function Qt(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 Zt(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 Jt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var te=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await rt("plan_key_unwrap_failed",()=>Ue(e.planKey,t)),i=await crypto.subtle.importKey("raw",Le(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],o=[];for(let a of e.shares){let l=await rt("plan_share_decryption_failed",()=>rn(a.data,i));nn(a.shareType)?o.push(l):s.push(l)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:o}).result}catch(a){throw new we("plan_share_reconstruction_failed",tn(a))}}},we=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},en=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function tn(r){let e=r instanceof Error?r.message:void 0;if(e)return en.has(e)?e:void 0}async function rt(r,e){try{return await e()}catch{throw new we(r)}}function nn(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function rn(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Le(r.slice(0,t)),i=Le(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Le(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var ne=class extends te{constructor(e={}){let t=e.processor??on(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:sn(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var an=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],dn=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ln=["ACTIVE","REVOKED"],cn=["SK_MOBILE"],un=["ACTIVE","INACTIVE"],pn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ot(r){let e=b(r);return{items:A(e.items).map(lt),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function at(r){let e=b(r);return{total:T(e.total,"total"),items:A(e.items).map(t=>{let n=b(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:u(n.id,"log.id"),planId:u(n.planId,"log.planId"),tenantId:u(n.tenantId,"log.tenantId"),event:u(n.event,"log.event"),occurredOn:u(n.occurredOn,"log.occurredOn"),status:L(n.status),title:u(n.title,"log.title"),details:A(n.details).map(i=>{let s=b(i);return{label:u(s.label,"log.detail.label"),value:u(s.value,"log.detail.value")}})}})}}function dt(r){let e=b(r),t=lt(e),n=b(e.source),i=u(n.kind,"source.kind");return{...t,assets:A(e.assets).map(s=>{let o=b(s);return{id:u(o.id,"asset.id"),code:L(o.code),type:S(u(o.type,"asset.type"),me),name:u(o.name,"asset.name"),isBinary:gn(o.isBinary,"asset.isBinary"),fieldNames:A(o.fieldNames).map(a=>u(a,"asset.fieldNames")),fileName:L(o.fileName),mimeType:L(o.mimeType),size:o.size===void 0||o.size===null?void 0:T(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:A(o.matchOrigins).map(a=>u(a,"asset.matchOrigins"))}}),participants:A(e.participants).map(s=>{let o=b(s);return{id:u(o.id,"participant.id"),displayName:u(o.displayName,"participant.displayName"),relationships:A(o.relationships).map(a=>S(u(a,"relationship"),st)),lifecycle:S(u(o.lifecycle,"participant.lifecycle"),ln)}}),revealPolicy:(()=>{let s=b(e.revealPolicy);return{masterKeyRelease:S(u(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:S(u(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=b(e.dms);return{subjectEmail:u(s.subjectEmail,"dms.subjectEmail"),countdownDays:T(s.countdownDays,"dms.countdownDays"),countdownHours:T(s.countdownHours,"dms.countdownHours"),countdownMinutes:T(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:S(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:S(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function re(r){let e=b(r);return{operationId:u(e.operationId,"operationId"),stage:S(u(e.stage,"stage"),He),outcome:S(u(e.outcome,"outcome"),pn),planId:L(e.planId),lastErrorCode:L(e.lastErrorCode),participants:e.participants===void 0?void 0:A(e.participants).map(t=>{let n=b(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:A(n.relationships).map(i=>mn(u(i,"relationship"),st))}})}}function lt(r){let e=b(r),t=b(e.assetSummary),n=b(e.governance),i=b(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:L(e.description),status:S(u(e.status,"status"),an),createdAt:u(e.createdAt,"createdAt"),configuredAt:L(e.configuredAt),assetSummary:{count:T(t.count,"assetSummary.count"),types:A(t.types).map(s=>S(u(s,"assetType"),me)),names:it(t.names).map(s=>u(s,"assetSummary.names"))},governance:{mode:S(u(n.mode,"governance.mode"),dn),minimumApprovals:T(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:T(i.owners,"owners"),mergers:T(i.mergers,"mergers"),moderators:T(i.moderators,"moderators")},authentication:it(e.authentication).map(s=>{let o=b(s);return{id:S(u(o.id,"authentication.id"),cn),status:S(u(o.status,"authentication.status"),un)}})}}function S(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function mn(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function b(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function it(r){return r==null?[]:A(r)}function A(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 L(r){return r==null?void 0:u(r,"optional")}function T(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function gn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var $=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function ct(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function hn(r,e){if(!e){if(r.length===0)throw new $("organization_required");if(r.length>1)throw new $("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new $("organization_access_denied");return e}function fn(r){let e=h(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),createdAt:x(e.createdAt)}}function ut(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(fn),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function pt(r){let e=h(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=h(t);return{unitId:d(n.unitId),position:m(n.position,0),commitment:d(n.commitment),status:d(n.status)}})}}function qe(r){let e=h(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:m(e.sequence,1),status:e.status}}function mt(r){let e=h(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),parentId:d(e.parentId),participantRevision:m(e.participantRevision,1),recipients:e.recipients.map(Ge)}}function gt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);return{parentId:d(n.parentId),sequence:m(n.sequence,1),senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),participantRevision:m(n.participantRevision,1),createdAt:x(n.createdAt)}}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0),unreadCount:m(e.unreadCount,0),readThroughSequence:m(e.readThroughSequence,0)}}function ht(r){return{readThroughSequence:m(h(r).readThroughSequence,0)}}function ft(r){return{clearedThroughSequence:m(h(r).clearedThroughSequence,0)}}function yt(r){let e=h(r);return{parentId:d(e.parentId),sequence:m(e.sequence,1),senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:m(e.participantRevision,1),canonicalManifest:d(e.canonicalManifest),frame:d(e.frame),signature:d(e.signature),wrappedContentKey:d(e.wrappedContentKey),senderSigningPublicKey:d(e.senderSigningPublicKey)}}function h(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function d(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function x(r){let e=d(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function m(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Ge(r){let e=h(r);return{memberId:d(e.memberId),deviceId:d(e.deviceId),deviceVersion:m(e.deviceVersion,1),encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint)}}function H(r){let e=h(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:d(e.id),tenantId:d(e.tenantId),memberId:d(e.memberId),version:e.version,encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint),status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)}}function be(r){let e=h(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:d(e.id),tenantId:d(e.tenantId),creatorMemberId:d(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(d),participantRevision:e.participantRevision,status:e.status,createdAt:x(e.createdAt),updatedAt:x(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=h(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:d(n.senderMemberId),createdAt:x(n.createdAt)}}return t}function It(r){let e=h(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(be),total:e.total,limit:e.limit,offset:e.offset}}function vt(r){let e=h(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Ge(t);return{memberId:n.memberId,name:d(h(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Pt(r){let e=h(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(n.memberId),name:d(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:d(h(n.profilePicture).url)}}}}),limit:m(e.limit,1),offset:m(e.offset,0),nextOffset:e.nextOffset===null?null:m(e.nextOffset,0)}}function Rt(r){let e=h(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),messageId:d(e.messageId),participantRevision:m(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Ge),shareLayers:e.shareLayers.map(t=>{let n=h(t),i=d(n.id),s=d(n.dataShareId),o=d(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:d(n.contractAddress),dataShareId:s,keyShareId:o};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function Ee(r){let e=h(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:d(e.messageId),status:e.status}}function wt(r){let e=h(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=h(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:d(n.id),status:n.status,senderMemberId:d(n.senderMemberId),senderDeviceId:d(n.senderDeviceId),createdAt:x(n.createdAt),updatedAt:x(n.updatedAt),expiresAt:x(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let o=h(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:d(o.memberId),status:o.status}})),i}),total:m(e.total,0),limit:m(e.limit,1),offset:m(e.offset,0)}}function bt(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId),ciphertext:d(n.ciphertext)}})}}function Et(r){let e=h(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:x(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:m(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(t=>{let n=h(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:m(n.index,0),shareId:d(n.shareId),layerId:d(n.layerId)}})}}function ie(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function se(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var N=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},W=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:H(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:H(n)}async registerInboxDevice(e){return H(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return H(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return H(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return be(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return It(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return vt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Pt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Rt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return pt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return ht(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,a=await this.requestBinary(o,"PUT",i,s),l=await Se(a,s);if(!l.ok||l.result?.shareId!==n||l.result.status!=="STORED")throw new N(a.status,ie(l),se(l),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return Et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,o){let a=new URLSearchParams({deviceId:i,leaseId:s}),l=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${a}`,c=await this.requestBinary(l,"GET",void 0,o);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let I=Number(c.headers.get("content-length"));if(Number.isFinite(I)&&I>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let R=c.body.getReader(),w=[],_=0;try{for(;;){o?.throwIfAborted();let v=await R.read();if(v.done)break;if(_+=v.value.length,_>14*1024*1024)throw new Error("invalid_inbox_share_size");w.push(v.value)}}catch(v){throw await R.cancel().catch(()=>{}),v}let G=new Uint8Array(_),E=0;for(let v of w)G.set(v,E),E+=v.length;return G}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(ct)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}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 i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return ot(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return dt(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return at(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){F(e);let{idempotencyKey:t,...n}=e;return re(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return B(t),re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return re(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,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}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,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}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`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}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,i,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let l=new Headers({"x-elements-environment":this.environment});a&&l.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&l.set("x-organization-id",this.business.organizationId),i?.requestId&&l.set("x-elements-step-up-request",i.requestId);for(let[_,G]of Object.entries(s??{}))l.set(_,G);n&&l.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,I={method:t,headers:l,body:n?JSON.stringify(n):void 0};o&&(I.signal=o);let R=await this.transport(new URL(e,c),I);o?.throwIfAborted();let w=await Se(R,o);if(o?.throwIfAborted(),!R.ok)throw new N(R.status,ie(w),se(w),R.headers.get("x-request-id")??void 0);if(!w.ok||w.result===void 0)throw new N(R.status,ie(w),se(w),R.headers.get("x-request-id")??void 0);return w.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),n&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,a),{method:t,headers:o,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!l.ok){let c=await Se(l,i);throw new N(l.status,ie(c),se(c),l.headers.get("x-request-id")??void 0)}return l}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,s),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),a=await Se(o);if(!o.ok||!a.ok)throw new N(o.status,ie(a),se(a),o.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Se(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{PassphraseMasterKeySource as Or,RawMasterKeySource as Dr,computePassphraseVerifier as Mr,deriveMasterKey as kr,generateHexSeed as Nr}from"@safetech/inheriti-core-sdk/crypto";function St(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var oe=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),St(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return St(new Uint8Array(t))}},ae=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(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"}},g=class extends j{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ae(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 ze=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:q(n,"issuer"),authorizationEndpoint:q(n,"authorization_endpoint"),tokenEndpoint:q(n,"token_endpoint"),deviceAuthorizationEndpoint:O(n,"device_authorization_endpoint"),endSessionEndpoint:O(n,"end_session_endpoint"),revocationEndpoint:O(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:q(t,"device_code"),userCode:q(t,"user_code"),verificationUri:q(t,"verification_uri"),verificationUriComplete:O(t,"verification_uri_complete"),expiresInSeconds:At(t,"expires_in"),intervalSeconds:Fe(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:q(n,"access_token"),refreshToken:O(n,"refresh_token"),idToken:O(n,"id_token"),tokenType:q(n,"token_type"),expiresInSeconds:At(n,"expires_in"),refreshExpiresInSeconds:Fe(n,"refresh_expires_in"),scope:O(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),i={};try{i=await n.json()}catch{}if(!n.ok){let s=O(i,"error")??`oauth_http_${n.status}`;throw new g(s,O(i,"error_description")??s)}return i}};function q(r,e){let t=O(r,e);if(!t)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function O(r,e){return typeof r[e]=="string"?r[e]:void 0}function At(r,e){let t=Fe(r,e);if(t===void 0)throw new g("invalid_oauth_response",`Missing ${e}`);return t}function Fe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var yn=600*1e3,xe=5,In=5,Ve=class{constructor(e){this.options=e;this.crypto=e.crypto??new oe,this.clock=e.clock??new ae}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),s=await this.crypto.sha256UrlSafe(i),o=this.clock.now()+yn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let a=new URL(e.authorizationEndpoint);return a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.options.configuration.clientId),a.searchParams.set("redirect_uri",this.options.configuration.redirectUri),a.searchParams.set("scope",this.options.configuration.scopes.join(" ")),a.searchParams.set("state",t),a.searchParams.set("nonce",n),a.searchParams.set("code_challenge",s),a.searchParams.set("code_challenge_method","S256"),{authorizationUrl:a.toString(),expiresAt:o}}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 g("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new g("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new g("redirect_uri_mismatch");let o=i.searchParams.get("error");if(o)throw new g(o,i.searchParams.get("error_description")??o);if(i.searchParams.get("state")!==n.state)throw new g("state_mismatch");let a=i.searchParams.get("code");if(!a)throw new g("authorization_code_missing");let l=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:a,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),I=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(I),I}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new g("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(xe,t.intervalSeconds??xe),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+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 g("device_transaction_missing");let i=n,s=await this.getDiscovery(),o=Math.max(xe,i.intervalSeconds??xe),a=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(a>=i.expiresAt);){await this.clock.sleep(Math.max(0,a-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=Ae(l);if(c==="authorization_pending"){a=this.clock.now()+o*1e3;continue}if(c==="slow_down"){o+=In,a=this.clock.now()+o*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new g("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;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=Ae(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Y):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new g("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(V(e.issuer)!==V(this.options.configuration.issuer))throw new g("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${V(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new g("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new g("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==i.subject||a.sessionId!==i.sessionId)throw new g("token_subject_mismatch")}let s=this.clock.now(),o=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&o?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:o,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(i.issuer))throw new g("issuer_mismatch");if(!s.includes(i.audience))throw new g("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new g("client_mismatch");if(e.environment!==i.environment)throw new g("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new g("required_claim_missing");if(n&&e.nonce!==t)throw new g("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(n.issuer))throw new g("issuer_mismatch");if(!i.includes(n.clientId))throw new g("client_mismatch");if(e.authorizedParty!==n.clientId)throw new g("client_mismatch");if(!e.subject||!e.sessionId)throw new g("required_claim_missing");if(e.nonce!==t)throw new g("nonce_mismatch")}};function V(r){return r.replace(/\/+$/u,"")}var Be=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 W(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new ee(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:vn,reconstructor:r.reconstructor??new ne(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{ne as BrowserPlanMaterialReconstructor,$ as BusinessOrganizationSelectionError,Re as CoreSdkContainerRequired,N as ElementsApiRequestFailed,ee as ElementsClient,W as HttpElementsApiPort,ze as HttpOperatorAuthTransport,ce as MasterKeyRelayCancellationFailed,le as MasterKeyRelayExpired,de as MasterKeyRelayTimedOut,D as MasterKeyRequired,Q as MemoryKeyVault,Z as MemoryStatePort,g as OAuthProtocolError,Ve as OperatorAuthClient,j as OperatorAuthError,Y as OperatorReauthenticationRequired,Be as OperatorSessionController,Or as PassphraseMasterKeySource,J as PlanMaterialReconstructorRequired,Dr as RawMasterKeySource,X as RelayMasterKeySource,ve as RevealAuthorizationEnded,P as RevealFieldAccessError,Ie as RevealHandleClosed,Ce as StaticMasterKeyResolver,ae as SystemOAuthClock,oe as WebOAuthCrypto,Mr as computePassphraseVerifier,wr as createBrowserElementsClient,ue as createMasterKeyResolver,vn as decodeAssetContainer,kr as deriveMasterKey,Nr as generateHexSeed,Te as masterKeyRefFor,K as masterKeyRefKey,Ae as oauthErrorCode,Ne as openScopedReveal,tt as parseAssetFieldSelector,et as revealPhaseOf,hn as selectBusinessOrganization,Ue as unwrapDekWithMasterKey};