@safetech/inheriti-client-sdk 1.17.26 → 1.17.28

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/node-base.js CHANGED
@@ -1 +1 @@
1
- import{createNodeSharedConfigurationSdk as pt,decodeAssetContainer as an}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as or,generateRSAOAEPKeyPair as dr}from"@safetech/inheriti-core-sdk/crypto";var Ee=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Re=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},we=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},M=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await dr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(y=>setTimeout(y,g))),l=!0,c=!1,u,I=()=>u??=(async()=>{let g=new AbortController,y,D=new Promise((b,U)=>{y=setTimeout(()=>{g.abort(),U(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,g.signal),D])}finally{clearTimeout(y)}})(),R,w=new Promise((g,y)=>{R=()=>{l&&I().catch(()=>{}),y(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",R,{once:!0})});w.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),w]);if(g.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let y=(await or(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(y))throw new Error("invalid_master_key_material");return y}if(g.status==="EXPIRED")throw new Re(s.sessionId);await lr(d,a,e)}throw new Ee(s.sessionId)}catch(g){if(l&&(!c||e?.aborted))try{await I()}catch(y){if(e?.aborted)throw new we(y)}throw g}finally{R&&e?.removeEventListener("abort",R)}}};async function lr(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function Se(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(cr(e,n.applicationId)){let i=await n.source?.resolve();return i||Be(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return Be(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function cr(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function Be(n,e,t,r,i){if((await e()).relayAvailable)return new M({...n.relay,api:pr(n.api,t)}).resolve(r,i)}function pr(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function z(n){return`${n.system}:${n.contextId}`}function ae(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var G=class extends Error{constructor(t){super(`master_key_required:${z(t)}`);this.ref=t;this.name="MasterKeyRequired"}},He=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(z(e),t),this}async resolve(e){return this.sources.get(z(e))?.resolve()}};var oe=class{keys=new Map;async store(e,t){let r=z(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(z(e))?.slice()}async remove(e){let t=z(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var de=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 Ae=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},h=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var be=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var _e=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Qe={"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"]},je=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],v=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},x=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function j(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new x("plan_material_field_unknown");if(We(n.dataShards,"data_shards_invalid"),We(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&We(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new x("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new x("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new x("material_operation_invalid")}function We(n,e){if(!Array.isArray(n))throw new x(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new x(e);if(t.data!==void 0&&typeof t.data!="string")throw new x(e)}}function $(n){if(Q(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!gr(n.idempotencyKey))throw new v("idempotency_key_invalid");if(!n.name?.trim())throw new v("plan_name_required");if(!n.assets.length)throw new v("assets_required");let e=new Set;for(let t of n.assets){if(Q(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 v("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!_e.includes(t.type))throw new v("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new v("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 v("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new v("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new v("asset_field_names_invalid");if(ur(t.matchOrigins),!t.isBinary){let s=Qe[t.type];if(!s||i.some(a=>!s.includes(a)))throw new v("asset_field_name_not_canonical")}}if(!n.participants.length)throw new v("participants_required");for(let t of n.participants){if(Q(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!gt(t.routingEmail))throw new v("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new v("participant_relationships_invalid")}mr(n)}function ur(n){if(n===void 0)return;if(!n.length)throw new v("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new v("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new v("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof v?r:new v("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new v("asset_match_origins_duplicated")}function mr(n){let e=n.policy;if(e&&Q(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new v("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){Q(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new v("authentication_mode_invalid")}if(e.moderation){Q(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new v("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new v("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new v("approval_mode_invalid")}let t=e.dms;if(!t)return;Q(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!gt(t.subjectEmail))throw new v("dms_subject_invalid");if(!n.participants.some(s=>mt(s.routingEmail)===mt(t.subjectEmail)))throw new v("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new v("dms_countdown_invalid")}function gr(n){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(n)}function gt(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function mt(n){return n.normalize("NFC").trim().toLowerCase()}function Q(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new v(t)}var le=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)}},ce=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),$(e),Ce(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){$(t);let a=await this.checkpoints.load(e);if(!a)throw new pe("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await ht(t))throw new pe("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Ce(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});Ce(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});Ce(s.signal),j(l);let c=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(c.stage),c.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,c),c}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 ht(e),serverStage:t.stage})}},pe=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function ht(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function Ce(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function ft(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new Ae(r.stage);return n.authorizeRevealAction(e,t)}function hr(n){let e=n?.status;return e===400||e===401||e===403}async function yt(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!hr(s))throw s}return n.releaseRevealMaterial(e,t)}function fr(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?Ir(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":yr.has(n.stage)?"ENDED":"CONTINUING"}var yr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Ir(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Ye=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},_=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function De(n,e,t={},r=!1){if(t.signal?.aborted)throw S();let i=await n.getPlan(e),s=await n.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):It(s.id);if(t.signal?.aborted)throw S();let a=()=>n.prepareReveal(e,t.signal,async c=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(c)});if(r||await a(),t.signal?.aborted)throw S();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(c){if(c?.code!=="merge_process_already_active")throw c;let u=await n.getActivePlanReveal(e);throw!u||u.planId!==e||u.mode!==(t.mode??"DIRECT")||u.protectedCopy!==void 0&&u.protectedCopy!==(t.protectedCopy??!1)?c:It(u.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw S();let c=await Pr(n,d,t);if(t.signal?.aborted||(r&&await a(),t.signal?.aborted)||(B(t,"RELEASING_MATERIAL",c),t.signal?.aborted))throw S();let u=await n.releaseRevealMaterial(c.id,c.materialVersion??"1");if(t.signal?.aborted||(c.mode==="GOVERNED"&&await n.markRevealSharesCollected(c.id),t.signal?.aborted))throw S();let I;try{I=await Sr(n,c,br(u),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(B(t,"RECONSTRUCTING",c),t.signal?.aborted))throw S();try{l=await n.reconstructPlanMaterial(I)}catch(w){throw t.signal?.aborted?S():(await n.reportRevealReconstruction(c.id,{status:"FAILED",errorCode:wr(w)}),w)}if(t.signal?.aborted)throw S();let R=await n.reportRevealReconstruction(c.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(B(t,"OPEN",R),t.signal?.aborted))throw S();return new Ze(n,R,i,l,t.signal)}catch(c){throw l?.fill(0),await Et(n,d.id,t.signal?.aborted?"CANCELED":"ERROR"),c}}function It(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var vr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Pr(n,e,t){let r=await F(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw S();if(t.onSession?.(r),t.onProgress?.({phase:fr(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(vr.has(r.stage))throw new Xe(r.stage);await Je(t.pollIntervalMs??1500,t.signal),r=await F(()=>n.getReveal(e.id,t.signal),t.signal)}}var Xe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function B(n,e,t){n.onProgress?.({phase:e,session:t})}function Je(n,e){return e?.aborted?Promise.reject(S()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(S())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Ze=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,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 Ye;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new _("asset_selector_invalid");if(!this.client.assetDecoder)throw new _("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Er(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new _("asset_not_found");if(d.isBinary)throw new _("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new _("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of r)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new _("asset_value_invalid");return{selector:a.selector,value:Rr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",vt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new _("asset_selector_invalid");if(!this.client.assetDecoder)throw new _("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new _("asset_not_found");if(!r.isBinary)throw new _("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new _("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",vt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Et(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 Er(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new _("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new _("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Rr(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new _("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new _("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Qe[t]:void 0)?.includes(e))return"";throw new _("asset_value_invalid")}return r[e]}function vt(n){if(n instanceof _)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function wr(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Sr(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await F(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new xe;let l=await F(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Pt(l,i.id,e.planId),!l.shares.includes(i.data))throw new L;B(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await F(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw S();if(!c?.trim())throw new L;if(await n.claimRevealCustodianShare(e.id,l.id,c),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw S();return{...t,shares:t.shares.filter(u=>u!==i).concat(l.shares.map((u,I)=>({id:`${l.id}:${I}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new L;if(r.signal?.aborted)throw S();return await n.distributeRevealCustodianShare(e.id),B(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await F(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),B(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Je(r.pollIntervalMs??1500,r.signal),s=await F(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new xe;if(!s.shareId||!s.deviceId)throw new L;B(r,"CONNECTING_SAFEKEY_PRO",e);let d=await F(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw S();if(Pt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new L;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw S();return{...t,shares:t.shares.concat(d.shares.map((l,c)=>({id:`${d.id}:${c}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new L;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),B(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw S();await n.requestRevealCustodianRelease(e.id);let o=await Ar(n,e,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,l)=>({id:`${o.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Pt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new L}async function F(n,e){if(e?.aborted)throw S();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(S()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw S();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Ar(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Te;let s=await F(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Te;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new L}await Je(t.pollIntervalMs??1500,t.signal)}}var L=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},xe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Te=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function br(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Et(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!_r(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function _r(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function S(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var Y=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 oe,this.state=t.state??new de,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Tr(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 h;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new h;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new h;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new h;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return $(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new h;return j(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new le){if(this.requireApplication(),!this.api)throw new h;return new ce(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new G({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return xr(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new G(e);return await this.keyVault.store(e,Cr(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new h;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new h;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new be;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,r){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 G({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ae(e);if(!i)throw new G({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new h;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new h;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new h;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new h;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new h;return this.api.getReveal(e,t)}openReveal(e,t){return De(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(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 h;return yt(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new h;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new h;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new h;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new h;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new h;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new h;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new h;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new h;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new h;return ft(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new h;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new h;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new h;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new h;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new h;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new h;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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=r.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new h;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new et;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new G({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},et=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Cr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function xr(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Tr(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Se({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Se({...e,organizationId:n.organizationId})}var Dr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Or=["DIRECT","GOVERNED"],wt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],kr=["ACTIVE","REVOKED"],Mr=["SK_MOBILE"],Nr=["ACTIVE","INACTIVE"],Kr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function St(n){let e=C(n);return{items:k(e.items).map(_t),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function At(n){let e=C(n);return{total:N(e.total,"total"),items:k(e.items).map(t=>{let r=C(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:m(r.id,"log.id"),planId:m(r.planId,"log.planId"),tenantId:m(r.tenantId,"log.tenantId"),event:m(r.event,"log.event"),occurredOn:m(r.occurredOn,"log.occurredOn"),status:V(r.status),title:m(r.title,"log.title"),details:k(r.details).map(i=>{let s=C(i);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function bt(n){let e=C(n);return{total:N(e.total,"total"),items:k(e.items).map(t=>{let r=C(t);if("eventData"in r)throw new Error("invalid_elements_response");let i=m(r.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:m(r.id,"log.id"),memberId:m(r.memberId,"log.memberId"),source:i,event:m(r.event,"log.event"),occurredOn:m(r.occurredOn,"log.occurredOn"),status:V(r.status)}})}}function Oe(n){let e=C(n),t=_t(e),r=C(e.source),i=m(r.kind,"source.kind");return{...t,assets:k(e.assets).map(s=>{let a=C(s);return{id:m(a.id,"asset.id"),code:V(a.code),type:O(m(a.type,"asset.type"),_e),name:m(a.name,"asset.name"),isBinary:Lr(a.isBinary,"asset.isBinary"),fieldNames:k(a.fieldNames).map(o=>m(o,"asset.fieldNames")),fileName:V(a.fileName),mimeType:V(a.mimeType),size:a.size===void 0||a.size===null?void 0:N(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:k(a.matchOrigins).map(o=>m(o,"asset.matchOrigins"))}}),participants:k(e.participants).map(s=>{let a=C(s);return{id:m(a.id,"participant.id"),displayName:m(a.displayName,"participant.displayName"),relationships:k(a.relationships).map(o=>O(m(o,"relationship"),wt)),lifecycle:O(m(a.lifecycle,"participant.lifecycle"),kr)}}),revealPolicy:(()=>{let s=C(e.revealPolicy);return{masterKeyRelease:O(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:O(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=C(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:N(s.countdownDays,"dms.countdownDays"),countdownHours:N(s.countdownHours,"dms.countdownHours"),countdownMinutes:N(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:O(m(r.system,"source.system"),["INHERITI_BUSINESS"]),status:O(m(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ue(n){let e=C(n);return{operationId:m(e.operationId,"operationId"),stage:O(m(e.stage,"stage"),je),outcome:O(m(e.outcome,"outcome"),Kr),planId:V(e.planId),lastErrorCode:V(e.lastErrorCode),participants:e.participants===void 0?void 0:k(e.participants).map(t=>{let r=C(t);return{clientParticipantRef:m(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(r.planParticipantId,"planParticipantId"),relationships:k(r.relationships).map(i=>Ur(m(i,"relationship"),wt))}})}}function _t(n){let e=C(n),t=C(e.assetSummary),r=C(e.governance),i=C(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:V(e.description),status:O(m(e.status,"status"),Dr),createdAt:m(e.createdAt,"createdAt"),configuredAt:V(e.configuredAt),assetSummary:{count:N(t.count,"assetSummary.count"),types:k(t.types).map(s=>O(m(s,"assetType"),_e)),names:Rt(t.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:O(m(r.mode,"governance.mode"),Or),minimumApprovals:N(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:N(i.owners,"owners"),mergers:N(i.mergers,"mergers"),moderators:N(i.moderators,"moderators")},authentication:Rt(e.authentication).map(s=>{let a=C(s);return{id:O(m(a.id,"authentication.id"),Mr),status:O(m(a.status,"authentication.status"),Nr)}})}}function O(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function Ur(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function C(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Rt(n){return n==null?[]:k(n)}function k(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function m(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function V(n){return n==null?void 0:m(n,"optional")}function N(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function Lr(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}var te=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ct(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.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 n.items.map(({id:e,name:t})=>({id:e,name:t}))}function qr(n,e){if(!e){if(n.length===0)throw new te("organization_required");if(n.length>1)throw new te("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new te("organization_access_denied");return e}function Gr(n){let e=P(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),createdAt:T(e.createdAt),...xt(e)}}function xt(n){if(n.recipientStatuses===void 0)return{};if(!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:n.recipientStatuses.map(e=>{let t=P(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:T(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(r=>{let i=P(r);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:f(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:T(i.revealedAt)}:{}}})}:{}}})}}function Tt(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Gr),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function Dt(n){let e=P(n);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:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=P(t);return{unitId:p(r.unitId),position:f(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function tt(n){let e=P(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),status:e.status}}function Ot(n){let e=P(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:f(e.participantRevision,1),recipients:e.recipients.map(rt)}}function kt(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=P(t);return{parentId:p(r.parentId),sequence:f(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:f(r.participantRevision,1),createdAt:T(r.createdAt),...xt(r)}}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function Mt(n){return{readThroughSequence:f(P(n).readThroughSequence,0)}}function Nt(n){return{clearedThroughSequence:f(P(n).clearedThroughSequence,0)}}function Kt(n){let e=P(n);return{parentId:p(e.parentId),sequence:f(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function P(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function T(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function f(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function rt(n){let e=P(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:f(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function re(n){let e=P(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:T(e.createdAt),updatedAt:T(e.updatedAt)}}function ke(n){let e=P(n);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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:T(e.createdAt),updatedAt:T(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 r=P(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:T(r.createdAt)}}return t}function Ut(n){let e=P(n);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(ke),total:e.total,limit:e.limit,offset:e.offset}}function Lt(n){let e=P(n);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 r=rt(t);return{memberId:r.memberId,name:p(P(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function qt(n){let e=P(n);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 r=P(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(P(r.profilePicture).url)}}}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function Gt(n){let e=P(n);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:p(e.conversationId),messageId:p(e.messageId),participantRevision:f(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(rt),shareLayers:e.shareLayers.map(t=>{let r=P(t),i=p(r.id),s=p(r.dataShareId),a=p(r.keyShareId);if(r.type==="INHERITI_CHAIN")return{id:i,type:r.type,contractAddress:p(r.contractAddress),dataShareId:s,keyShareId:a};if(r.type==="INHERITI_VAULT"||r.type==="GOOGLE_DRIVE"||r.type==="DROPBOX"||r.type==="ONEDRIVE")return{id:i,type:r.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function Me(n){let e=P(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function Ft(n){let e=P(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=P(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:T(r.createdAt),updatedAt:T(r.updatedAt),expiresAt:T(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(s=>{let a=P(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:T(a.consumedAt)}:{}}})),i}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0)}}function Vt(n){let e=P(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:T(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=P(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:f(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function zt(n){let e=P(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:T(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=P(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:f(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function X(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function Z(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var K=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ne=class{constructor(e,t,r,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,r,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":r},i)}confirmFileAccessDelivery(e,t,r){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":r})}createInboxFileAccess(e,t,r,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",r,void 0,void 0,i)}createRevealFileAccess(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,r)}cancelRevealFileAccess(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}cancelInboxFileAccess(e,t,r,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(r)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let r=t;if(typeof r.publicKey!="string"||!r.publicKey||typeof r.fingerprint!="string"||!r.fingerprint||r.status!=="ACTIVE"&&r.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:r.publicKey,fingerprint:r.fingerprint,status:r.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:re(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:re(r)}async registerInboxDevice(e){return re(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return re(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return re(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ke(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Ut(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Lt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return qt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Gt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={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 Me(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",r))}async publishNormalInboxMessage(e,t){return tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){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 Tt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Dt(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 Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){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 kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Kt(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,r){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return Me(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}`,o=await this.requestBinary(a,"PUT",i,s),d=await Ne(o,s);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new K(o.status,X(d),Z(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return Me(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${o}`,l=await this.requestBinary(d,"GET",void 0,a);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let c=Number(l.headers.get("content-length"));if(Number.isFinite(c)&&c>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let u=l.body.getReader(),I=[],R=0;try{for(;;){a?.throwIfAborted();let y=await u.read();if(y.done)break;if(R+=y.value.length,R>14*1024*1024)throw new Error("invalid_inbox_share_size");I.push(y.value)}}catch(y){throw await u.cancel().catch(()=>{}),y}let w=new Uint8Array(R),g=0;for(let y of I)w.set(y,g),g+=y.length;return w}async listInboxMessages(e,t={},r){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 Ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return Vt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,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 r=t.size?`?${t}`:"";return St(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Oe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return At(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let r=new URLSearchParams;t.source&&r.set("source",t.source),t.from&&r.set("from",t.from),t.to&&r.set("to",t.to),t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return bt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){$(e);let{idempotencyKey:t,...r}=e;return ue(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return j(t),ue(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ue(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:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}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,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}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,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;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,r,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[R,w]of Object.entries(s??{}))d.set(R,w);r&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c={method:t,headers:d,body:r?JSON.stringify(r):void 0};a&&(c.signal=a);let u=await this.transport(new URL(e,l),c);a?.throwIfAborted();let I=await Ne(u,a);if(a?.throwIfAborted(),!u.ok)throw new K(u.status,X(I),Z(I),u.headers.get("x-request-id")??void 0);if(!I.ok||I.result===void 0)throw new K(u.status,X(I),Z(I),u.headers.get("x-request-id")??void 0);return I.result}async requestBinary(e,t,r,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),r&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let l=await Ne(d,i);throw new K(d.status,X(l),Z(l),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,r,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[u,I]of Object.entries(r??{}))o.set(u,I);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),c=await Ne(l,s);if(s?.throwIfAborted(),!l.ok||!c.ok)throw new K(l.status,X(c),Z(c),l.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 K(400,"organization_selection_required")}};async function Ne(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Qr}from"@safetech/inheriti-core-sdk/node";async function nt(n,e){if(!e)throw new Error("master_key_required");let t=Fr(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Vr(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return zr(new Uint8Array(o))}function Fr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Vr(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function zr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var me=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await $t("plan_key_unwrap_failed",()=>nt(e.planKey,t)),i=await crypto.subtle.importKey("raw",it(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await $t("plan_share_decryption_failed",()=>Wr(o.data,i));Hr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new Ke("plan_share_reconstruction_failed",Br(o))}}},Ke=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},$r=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 Br(n){let e=n instanceof Error?n.message:void 0;if(e)return $r.has(e)?e:void 0}async function $t(n,e){try{return await e()}catch{throw new Ke(n)}}function Hr(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function Wr(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=it(n.slice(0,t)),i=it(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function it(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var J=class extends me{constructor(e){super(()=>Qr(e))}};var ge=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Oe(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});r!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:a});a?.throwIfAborted();let c;try{c=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||c&&c.ok===!1||i&&c?.result===void 0)throw new K(l.status,c&&X(c),c&&Z(c));return c?.result}};var A={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var H=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},he=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",Bt(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",Bt(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}async request(e,t,r,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(A.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,l=await this.transport(new URL(d,o),{method:r,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),c={};try{c=await l.json()}catch{}if(!l.ok||c.ok!==!0)throw new H(l.status,c.error);return c.result}};function Bt(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var ye=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){fe(e.signal),Yr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return fe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){fe(e.signal);let t=e.encrypted.totalShares+1,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(fe(e.signal),!i.custodianPair)throw new x("custodian_share_required");let s=st(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(st(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(st(i.backupShards),a.symmetricKeyBase64),l=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return fe(e.signal),{protectionProtocol:i.protocol,validatorShares:at(a.encryptedShares),dataShards:at(o.encryptedShares),backupShards:at(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:jr(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:ot(r.encryptedShares[0]),dataShard:ot(r.encryptedShares[1])}}};function st(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function at(n){return n.map(ot)}function ot(n){return{id:n.id,data:n.encryptedData}}function jr(n,e){let t={};for(let r of n){let i=e.assets.find(s=>s.clientAssetRef===r.id);if(!i)throw new x("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Yr(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new x("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new x("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new x("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new x("plan_secrets_declaration_mismatch")}}function fe(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function Ht(n,e,t,r,i,s,a){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(A.invalidShares);let{assets:d,plan:l}=e;l.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let c=n.masterKeySource??new M({api:{startRelaySession:R=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,R),readRelaySession:R=>i.readRelaySession(n.organizationId,R)}}),u=new ye(s,c);a?.("encrypting");let I=await u.encrypt({planId:n.planId,declaration:l,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return a?.("generating_shares"),u.generateShares({planId:n.planId,declaration:l,encrypted:I})}import{PlanAssetDeclaration as Xr}from"@safetech/inheriti-core-sdk/node";function Wt(n){let e=dt({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function dt(n){if(!n.assets.length)throw new v("assets_required");let e=n.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new v("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new v("binary_asset_metadata_invalid");return o}),t=Xr.create(n.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),r=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,n.assets[a].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:r,plan:i}}async function jt(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await Qt(new Uint8Array(await i.arrayBuffer())):i]))})));return Qt(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function Qt(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ie=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(a=>!a?.meta?.name?.trim()))throw new Error(A.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(A.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(A.invalidShares);let r=await jt(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(A.reconciliationRequired);return i.promise}let s=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=dt({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(A.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(Ue(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(A.reconciliationRequired);if(!a&&s)throw new Error(A.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(A.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(A.invalidMasterKeyContext);if(!a){r?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(c){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw c}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await Ht(e,i,o,a,this.port,this.coreSdk,r);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(c){if(!Ue(await this.statusOrMissing(e.organizationId,e.planId)))throw c}r?.("verifying");let l=await this.port.status(e.organizationId,e.planId);return Ue(l)&&this.material.delete(e.planId),{planId:e.planId,status:Ue(l)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(A.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof H&&r.status===404)return;throw r}}};function Ue(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var Le=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,s){let a=await this.getBearerToken();if(!a)throw new Error(A.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),l=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,c=await this.transport(new URL(l,d),{method:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await c.json()}catch{}if(!c.ok||u.ok!==!0){let I=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new H(c.status,I||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var qe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let l=Date.now()+10*6e4;o||t?.("opening_plan");let c=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(c.map(u=>u.id)).size!==c.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,l),assets:c,masterKey:d}),{plan:s,masterKey:d,assets:c}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new M({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},l=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let y=this.approvalError(g);if(y?.startsWith("edit_authentication_")&&d("pending_auth"),y?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let D=g.moderatorParticipants.map(b=>b.memberId??b.userId);D.some(b=>typeof b!="string"||!b)||new Set(D).size!==D.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((b,U)=>{let ie=D[U],ut=b.flows.filter(se=>se.status==="PENDING"&&se.expiresAt&&Number.isFinite(se.expiresAt.getTime())).map(se=>se.expiresAt.getTime());return{id:ie,displayName:a.get(ie)||"Moderator",status:b.status,expiresAt:ut.length?new Date(Math.min(...ut)).toISOString():void 0}})})},c=await s.resume(e.planId,{onViewUpdate:l});if(c?.processId!==e.editId||c.planId&&c.planId!==e.planId)throw new Error("edit_merge_not_ready");l(c),this.assertApprovalOutcome(e.planId,c),c.status!=="READY_TO_REVEAL"&&c.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:l,onApprovalsRequested:()=>d("pending_approvals")});let u=await s.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");l(u),this.assertApprovalOutcome(e.planId,u);let I=u?.status;if(I!=="READY_TO_REVEAL"&&I!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let R=null,w={onRevealed:g=>{R=g},onViewUpdate:l,onRevealStepUpdate:(g,y)=>{if(y==="IN_PROCESS")switch(g){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(w.onCustodianShareRequired=async(g,y)=>{switch(y.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let D=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),D==="SK_MOBILE")return s.distributeCustodianShareViaMobile(y.planId);if(D!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let b=e.proDevice;try{this.assertNotAborted(e.signal);let U=await s.getCustodianShareData(g);this.assertShare(U,y.planId),d("connecting_safekey_pro");let{deviceId:ie}=await b.write(U,e.signal);if(this.assertNotAborted(e.signal),!ie?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(y.planId,U.id,ie,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,U.id);return}finally{b.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let D=e.proDevice;try{if(this.assertNotAborted(e.signal),!y.shareId||!y.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let b=await D.read({shareId:y.shareId,planId:y.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(b,y.planId,y.shareId),b.deviceId!==y.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:b.shares}}finally{D.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),I==="REVEALED"?await s.resumeReveal(e.editId,w,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},w,t),this.assertNotAborted(e.signal),!R)throw new Error("edit_assets_unavailable");return R}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Zr=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),Ge=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,r,i);a?.("preparing");let l=await o.prepare(d);this.assertNotAborted(e.signal);let c={mergeProcessId:e.editId,protectionProtocol:l.protectionProtocol,validatorShares:this.transportShares(l.validatorShares),dataShards:this.transportShares(l.dataShards),backupShards:this.transportShares(l.backupShards),encryptedKey:l.encryptedKey,assetsMetadata:l.assetsMetadata,custodianPair:l.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,c),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:c}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,c,o,d,a)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!r?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,r,i,s,a){let o,d=l=>{let c;switch(l.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":c="distributing_validators";break;case"SHARES_DISTRIBUTION":c="distributing_data";break;case"FINALIZE":c="finalizing";break;default:return}c!==o&&(o=c,a?.(c))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(l){try{if(a?.("verifying"),await this.isCommitted(e,r))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),l}try{if(a?.("verifying"),!await this.isCommitted(e,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Zr(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),l=>l.toString(16).padStart(2,"0")).join("");if(r.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(l=>l.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(r.shares.map(l=>l.id));return!o.some(l=>!d.has(l))}};var Fe=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new qe(e,t,r),this.reconfiguration=new Ge(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(c=>c.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},l=s.map((c,u)=>u===a?d:c);return this.reconfiguration.saveAssets(e,l,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=Wt({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),r.withCustodian,i,a.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function Yt({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),l=new URL(n.endsWith("/")?n:`${n}/`);if(d.origin!==l.origin||!d.pathname.startsWith(l.pathname))throw new Error("unsupported_core_edit_route");let c=d.pathname.slice(l.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(c===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(c==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=Jr(c,d.searchParams,t,r),I=new Headers(o?.headers);I.set("x-organization-id",e),I.set("x-elements-environment",i);let R=l.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return s(new URL(R,l),Object.assign({},o,{headers:I}))}}function Jr(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);if(s){let o=s[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(s[1]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as en}from"@safetech/inheriti-core-sdk/node";function Xt(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),i=ae(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new M({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}}),a=new Y(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,l)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,l)}}});return De(a,e,t,!0)}}}function tn(n){let e=new ge(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...Xt({api:e,reconstructor:new J(n.workerUrl),assetDecoder:en}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as Zt,sealInheritiFile as Jt,readInheritiFileHeader as Fi,openInheritiFile as Vi,InheritiFileInvalid as zi,MAX_INHERITI_FILE_BYTES as er}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as tr,openInheritiFileKey as Hi}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function rn(n){let{reveal:e,api:t,signal:r}=n;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(r);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=n.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(n.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>er-1024*1024)throw new Error("unsupported_protected_asset");let d=Zt(),l,c=!1,u=!1;try{r?.throwIfAborted();let I=await tr(d,i.publicKey);c=!0;let R=await t.createRevealFileAccess(e.session.id,{copyId:n.copyId,envelopeId:n.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:I,openLimit:a},r);if(R.copyId!==n.copyId||R.status!=="PENDING")throw new Error("file_access_create_invalid");let w=await t.getFileAccess(n.copyId,r);for(;w.status==="PENDING";){if(r?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((y,D)=>{let b=()=>{clearTimeout(U),D(r?.reason)},U=setTimeout(()=>{r?.removeEventListener("abort",b),y()},Math.min(500,Math.max(1,s-Date.now())));r?.addEventListener("abort",b,{once:!0})}),w=await t.getFileAccess(n.copyId,r)}if(w.status!=="READY"||w.origin!=="REVEAL"||w.copyId!==n.copyId||w.allowedUses!==a||!w.recipient||!w.deployment||w.expiresAt!==null&&(!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)>s||Date.parse(w.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await Jt({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:w});g.fileKey.fill(0),l=g.fileBytes,r?.throwIfAborted(),await n.save({fileName:o.fileName,fileBytes:l}),u=!0}catch(I){if(c&&!u)try{await t.cancelRevealFileAccess(e.session.id,n.copyId)}catch(R){throw new AggregateError([I,R],"protected_asset_export_and_cleanup_failed",{cause:I})}throw I}finally{d.fill(0),l?.fill(0)}})}import{DataAssetDefinitionService as Us}from"@safetech/inheriti-core-sdk/node";function rr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ve=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),rr(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return rr(new Uint8Array(t))}},ze=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var ve=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},Pe=class extends ve{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},E=class extends ve{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function lt(n){if(n instanceof ve)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var nr=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:W(r,"issuer"),authorizationEndpoint:W(r,"authorization_endpoint"),tokenEndpoint:W(r,"token_endpoint"),deviceAuthorizationEndpoint:q(r,"device_authorization_endpoint"),endSessionEndpoint:q(r,"end_session_endpoint"),revocationEndpoint:q(r,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:W(t,"device_code"),userCode:W(t,"user_code"),verificationUri:W(t,"verification_uri"),verificationUriComplete:q(t,"verification_uri_complete"),expiresInSeconds:ir(t,"expires_in"),intervalSeconds:ct(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 r=await this.form(e,t);return{accessToken:W(r,"access_token"),refreshToken:q(r,"refresh_token"),idToken:q(r,"id_token"),tokenType:W(r,"token_type"),expiresInSeconds:ir(r,"expires_in"),refreshExpiresInSeconds:ct(r,"refresh_expires_in"),scope:q(r,"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 r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let s=q(i,"error")??`oauth_http_${r.status}`;throw new E(s,q(i,"error_description")??s)}return i}};function W(n,e){let t=q(n,e);if(!t)throw new E("invalid_oauth_response",`Missing ${e}`);return t}function q(n,e){return typeof n[e]=="string"?n[e]:void 0}function ir(n,e){let t=ct(n,e);if(t===void 0)throw new E("invalid_oauth_response",`Missing ${e}`);return t}function ct(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var nn=600*1e3,$e=5,sn=5,sr=class{constructor(e){this.options=e;this.crypto=e.crypto??new Ve,this.clock=e.clock??new ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+nn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:r,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",r),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new E("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new E("authorization_transaction_expired");let i=new URL(e),s=new URL(r.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new E("redirect_uri_mismatch");if(i.searchParams.get("state")!==r.state)throw new E("state_mismatch");let a=i.searchParams.get("error");if(a)throw new E(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new E("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:r.codeVerifier,redirectUri:r.redirectUri}),c=await this.acceptTokens(l,r.nonce);return await this.options.sessions.save(c),c}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new E("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max($e,t.intervalSeconds??$e),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new E("device_transaction_missing");let i=r,s=await this.getDiscovery(),a=Math.max($e,i.intervalSeconds??$e),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=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 l=await this.acceptTokens(d);return await this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=lt(d);if(l==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(l==="slow_down"){a+=sn,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new E("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 Pe;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=lt(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Pe):(this.isOfflineSession(e)||await this.options.sessions.clear(),r)}try{if(!t.refreshToken)throw new E("refresh_token_rotation_missing");let r=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(r),r}catch(r){throw await this.options.sessions.clear(),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(ee(e.issuer)!==ee(this.options.configuration.issuer))throw new E("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${ee(t)}|${r}|${i}`}async acceptTokens(e,t,r){if(e.tokenType.toLowerCase()!=="bearer")throw new E("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 E("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new E("token_subject_mismatch")}let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!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&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,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,r){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(i.issuer))throw new E("issuer_mismatch");if(!s.includes(i.audience))throw new E("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new E("client_mismatch");if(e.environment!==i.environment)throw new E("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new E("required_claim_missing");if(r&&e.nonce!==t)throw new E("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(ee(e.issuer)!==ee(r.issuer))throw new E("issuer_mismatch");if(!i.includes(r.clientId))throw new E("client_mismatch");if(e.authorizedParty!==r.clientId)throw new E("client_mismatch");if(!e.subject||!e.sessionId)throw new E("required_claim_missing");if(e.nonce!==t)throw new E("nonce_mismatch")}};function ee(n){return n.replace(/\/+$/u,"")}var ar=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()}}};import{PassphraseMasterKeySource as zs,RawMasterKeySource as $s,deriveMasterKey as Bs,generateHexSeed as Hs,computePassphraseVerifier as Ws}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as js}from"@safetech/inheriti-core-sdk/node";function Ps(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",n.environment),e(s,Object.assign({},a,{headers:o}))},r=n.business?void 0:pt({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new ne(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new Y(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new J(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:an})}function Es(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=pt({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Ie(new he(n.apiUrl,n.environment,n.getBearerToken,e),t)}function Rs(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=pt({apiUrl:t,getBearerToken:n.getBearerToken,transport:Yt({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Fe(new Le(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{te as BusinessOrganizationSelectionError,ye as CorePlanMaterialBuilder,Us as DataAssetDefinitionService,K as ElementsApiRequestFailed,Y as ElementsClient,pe as GuidedCreateRecoveryError,ce as GuidedPlanCreator,ge as HttpAutomationRevealApiPort,ne as HttpElementsApiPort,nr as HttpOperatorAuthTransport,Le as HttpPlanEditPort,he as HttpQuickPlanPort,v as InvalidPlanDeclaration,x as InvalidPlanMaterial,we as MasterKeyRelayCancellationFailed,Re as MasterKeyRelayExpired,Ee as MasterKeyRelayTimedOut,G as MasterKeyRequired,le as MemoryGuidedCreateCheckpointStore,oe as MemoryKeyVault,de as MemoryStatePort,E as OAuthProtocolError,sr as OperatorAuthClient,ve as OperatorAuthError,Pe as OperatorReauthenticationRequired,ar as OperatorSessionController,je as PLAN_CREATION_SERVER_STAGES,zs as PassphraseMasterKeySource,js as PlanAssetDeclaration,H as PlanRequestFailed,Ie as QuickPlanCreator,Fe as QuickPlanEditor,$s as RawMasterKeySource,M as RelayMasterKeySource,He as StaticMasterKeyResolver,ze as SystemOAuthClock,Ve as WebOAuthCrypto,Ws as computePassphraseVerifier,Se as createMasterKeyResolver,tn as createNodeAutomationRevealClient,Ps as createNodeElementsClient,Es as createNodeQuickPlanCreator,Rs as createNodeQuickPlanEditor,an as decodeAssetContainer,Bs as deriveMasterKey,rn as exportProtectedRevealAsset,Hs as generateHexSeed,ae as masterKeyRefFor,z as masterKeyRefKey,lt as oauthErrorCode,qr as selectBusinessOrganization,nt as unwrapDekWithMasterKey,$ as validatePlanCreationInput,j as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as ut,decodeAssetContainer as mn}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as lr,generateRSAOAEPKeyPair as pr}from"@safetech/inheriti-core-sdk/crypto";var Ee=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Re=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},Se=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},K=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await pr();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(g=>new Promise(I=>setTimeout(I,g))),c=!0,l=!1,u,v=()=>u??=(async()=>{let g=new AbortController,I,M=new Promise((b,G)=>{I=setTimeout(()=>{g.abort(),G(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,g.signal),M])}finally{clearTimeout(I)}})(),E,R=new Promise((g,I)=>{E=()=>{c&&v().catch(()=>{}),I(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",E,{once:!0})});R.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),R]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let I=(await lr(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(I))throw new Error("invalid_master_key_material");return I}if(g.status==="EXPIRED")throw new Re(s.sessionId);await ur(d,a,e)}throw new Ee(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await v()}catch(I){if(e?.aborted)throw new Se(I)}throw g}finally{E&&e?.removeEventListener("abort",E)}}};async function ur(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function Ae(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||We(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(mr(e,n.applicationId)){let i=await n.source?.resolve();return i||We(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return We(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function mr(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function We(n,e,t,r,i){if((await e()).relayAvailable)return new K({...n.relay,api:gr(n.api,t)}).resolve(r,i)}function gr(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function H(n){return`${n.system}:${n.contextId}`}function de(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var B=class extends Error{constructor(t){super(`master_key_required:${H(t)}`);this.ref=t;this.name="MasterKeyRequired"}},je=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(H(e),t),this}async resolve(e){return this.sources.get(H(e))?.resolve()}};var ce=class{keys=new Map;async store(e,t){let r=H(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(H(e))?.slice()}async remove(e){let t=H(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var le=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 be=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},h=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var _e=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Ce=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ye={"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"]},Xe=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},x=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function Z(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new x("plan_material_field_unknown");if(Qe(n.dataShards,"data_shards_invalid"),Qe(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&Qe(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new x("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new x("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new x("material_operation_invalid")}function Qe(n,e){if(!Array.isArray(n))throw new x(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new x(e);if(t.data!==void 0&&typeof t.data!="string")throw new x(e)}}function W(n){if(X(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!yr(n.idempotencyKey))throw new P("idempotency_key_invalid");if(!n.name?.trim())throw new P("plan_name_required");if(!n.assets.length)throw new P("assets_required");let e=new Set;for(let t of n.assets){if(X(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 P("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Ce.includes(t.type))throw new P("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new P("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 P("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new P("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new P("asset_field_names_invalid");if(hr(t.matchOrigins),!t.isBinary){let s=Ye[t.type];if(!s||i.some(a=>!s.includes(a)))throw new P("asset_field_name_not_canonical")}}if(!n.participants.length)throw new P("participants_required");for(let t of n.participants){if(X(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ht(t.routingEmail))throw new P("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new P("participant_relationships_invalid")}fr(n)}function hr(n){if(n===void 0)return;if(!n.length)throw new P("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new P("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new P("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof P?r:new P("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new P("asset_match_origins_duplicated")}function fr(n){let e=n.policy;if(e&&X(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new P("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){X(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new P("authentication_mode_invalid")}if(e.moderation){X(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new P("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new P("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new P("approval_mode_invalid")}let t=e.dms;if(!t)return;X(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!ht(t.subjectEmail))throw new P("dms_subject_invalid");if(!n.participants.some(s=>gt(s.routingEmail)===gt(t.subjectEmail)))throw new P("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new P("dms_countdown_invalid")}function yr(n){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(n)}function ht(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function gt(n){return n.normalize("NFC").trim().toLowerCase()}function X(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new P(t)}var pe=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)}},ue=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),W(e),xe(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){W(t);let a=await this.checkpoints.load(e);if(!a)throw new me("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await ft(t))throw new me("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;xe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});xe(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});xe(s.signal),Z(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}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 ft(e),serverStage:t.stage})}},me=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function ft(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function xe(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function yt(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new be(r.stage);return n.authorizeRevealAction(e,t)}function Ir(n){let e=n?.status;return e===400||e===401||e===403}async function It(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!Ir(s))throw s}return n.releaseRevealMaterial(e,t)}function vr(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?wr(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":Pr.has(n.stage)?"ENDED":"CONTINUING"}var Pr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function wr(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Ze=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},_=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function De(n,e,t={},r=!1){if(t.signal?.aborted)throw S();let i=await n.getPlan(e),s=await n.getActivePlanReveal(e);if(s)throw s.planId!==e||s.mode!==(t.mode??"DIRECT")||s.protectedCopy!==void 0&&s.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):vt(s.id);if(t.signal?.aborted)throw S();let a=()=>n.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)});if(r||await a(),t.signal?.aborted)throw S();let o=t.idempotencyKey??crypto.randomUUID(),d;try{d=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:o,...t.protectedCopy?{protectedCopy:!0}:{}})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let u=await n.getActivePlanReveal(e);throw!u||u.planId!==e||u.mode!==(t.mode??"DIRECT")||u.protectedCopy!==void 0&&u.protectedCopy!==(t.protectedCopy??!1)?l:vt(u.id)}if(d.protectedCopy!==void 0&&d.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(d.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let c;try{if(t.signal?.aborted)throw S();let l=await Rr(n,d,t);if(t.signal?.aborted||(r&&await a(),t.signal?.aborted)||(j(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw S();let u=await n.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await n.markRevealSharesCollected(l.id),t.signal?.aborted))throw S();let v;try{v=await _r(n,l,xr(u),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(j(t,"RECONSTRUCTING",l),t.signal?.aborted))throw S();try{c=await n.reconstructPlanMaterial(v)}catch(R){throw t.signal?.aborted?S():(await n.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:br(R)}),R)}if(t.signal?.aborted)throw S();let E=await n.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(j(t,"OPEN",E),t.signal?.aborted))throw S();return new et(n,E,i,c,t.signal)}catch(l){throw c?.fill(0),await Et(n,d.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function vt(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Er=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Rr(n,e,t){let r=await z(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw S();if(t.onSession?.(r),t.onProgress?.({phase:vr(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Er.has(r.stage))throw new Je(r.stage);await tt(t.pollIntervalMs??1500,t.signal),r=await z(()=>n.getReveal(e.id,t.signal),t.signal)}}var Je=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function j(n,e,t){n.onProgress?.({phase:e,session:t})}function tt(n,e){return e?.aborted?Promise.reject(S()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(S())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var et=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,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 Ze;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new _("asset_selector_invalid");if(!this.client.assetDecoder)throw new _("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Sr(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new _("asset_not_found");if(d.isBinary)throw new _("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new _("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of r)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new _("asset_value_invalid");return{selector:a.selector,value:Ar(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Pt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new _("asset_selector_invalid");if(!this.client.assetDecoder)throw new _("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new _("asset_not_found");if(!r.isBinary)throw new _("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new _("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",Pt(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Et(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 Sr(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new _("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new _("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Ar(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new _("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new _("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Ye[t]:void 0)?.includes(e))return"";throw new _("asset_value_invalid")}return r[e]}function Pt(n){if(n instanceof _)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function br(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function _r(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await z(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Te;let c=await z(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(wt(c,i.id,e.planId),!c.shares.includes(i.data))throw new F;j(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await z(()=>r.proDevice.write(c,r.signal),r.signal);if(r.signal?.aborted)throw S();if(!l?.trim())throw new F;if(await n.claimRevealCustodianShare(e.id,c.id,l),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,c.id),r.signal?.aborted))throw S();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,v)=>({id:`${c.id}:${v}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new F;if(r.signal?.aborted)throw S();return await n.distributeRevealCustodianShare(e.id),j(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await z(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),j(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await tt(r.pollIntervalMs??1500,r.signal),s=await z(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Te;if(!s.shareId||!s.deviceId)throw new F;j(r,"CONNECTING_SAFEKEY_PRO",e);let d=await z(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw S();if(wt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new F;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw S();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new F;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),j(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw S();await n.requestRevealCustodianRelease(e.id);let o=await Cr(n,e,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function wt(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new F}async function z(n,e){if(e?.aborted)throw S();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(S()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw S();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Cr(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new ke;let s=await z(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new ke;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new F}await tt(t.pollIntervalMs??1500,t.signal)}}var F=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Te=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 xr(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Et(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Tr(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Tr(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function S(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var J=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 ce,this.state=t.state??new le,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Or(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 h;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new h;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new h;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new h;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return W(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new h;return Z(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new pe){if(this.requireApplication(),!this.api)throw new h;return new ue(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new B({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return Dr(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new B(e);return await this.keyVault.store(e,kr(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new h;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new h;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new _e;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,r){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 B({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=de(e);if(!i)throw new B({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new h;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new h;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new h;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new h;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new h;return this.api.getReveal(e,t)}openReveal(e,t){return De(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(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 h;return It(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new h;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new h;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new h;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new h;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new h;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new h;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new h;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new h;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new h;return yt(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new h;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new h;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new h;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new h;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new h;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new h;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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=r.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new h;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new rt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new B({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},rt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function kr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Dr(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Or(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return Ae({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return Ae({...e,organizationId:n.organizationId})}var Mr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Nr=["DIRECT","GOVERNED"],St=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Ur=["ACTIVE","REVOKED"],Kr=["SK_MOBILE"],Lr=["ACTIVE","INACTIVE"],qr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function At(n){let e=C(n);return{items:U(e.items).map(Ct),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function bt(n){let e=C(n);return{total:L(e.total,"total"),items:U(e.items).map(t=>{let r=C(t);if("eventData"in r)throw new Error("invalid_elements_response");return{id:m(r.id,"log.id"),planId:m(r.planId,"log.planId"),tenantId:m(r.tenantId,"log.tenantId"),event:m(r.event,"log.event"),occurredOn:m(r.occurredOn,"log.occurredOn"),status:$(r.status),title:m(r.title,"log.title"),details:U(r.details).map(i=>{let s=C(i);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function _t(n){let e=C(n);return{total:L(e.total,"total"),items:U(e.items).map(t=>{let r=C(t);if("eventData"in r)throw new Error("invalid_elements_response");let i=m(r.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:m(r.id,"log.id"),memberId:m(r.memberId,"log.memberId"),source:i,event:m(r.event,"log.event"),occurredOn:m(r.occurredOn,"log.occurredOn"),status:$(r.status)}})}}function Oe(n){let e=C(n),t=Ct(e),r=C(e.source),i=m(r.kind,"source.kind");return{...t,assets:U(e.assets).map(s=>{let a=C(s);return{id:m(a.id,"asset.id"),code:$(a.code),type:N(m(a.type,"asset.type"),Ce),name:m(a.name,"asset.name"),isBinary:Fr(a.isBinary,"asset.isBinary"),fieldNames:U(a.fieldNames).map(o=>m(o,"asset.fieldNames")),fileName:$(a.fileName),mimeType:$(a.mimeType),size:a.size===void 0||a.size===null?void 0:L(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:U(a.matchOrigins).map(o=>m(o,"asset.matchOrigins"))}}),participants:U(e.participants).map(s=>{let a=C(s);return{id:m(a.id,"participant.id"),displayName:m(a.displayName,"participant.displayName"),relationships:U(a.relationships).map(o=>N(m(o,"relationship"),St)),lifecycle:N(m(a.lifecycle,"participant.lifecycle"),Ur)}}),revealPolicy:(()=>{let s=C(e.revealPolicy);return{masterKeyRelease:N(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:N(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=C(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:L(s.countdownDays,"dms.countdownDays"),countdownHours:L(s.countdownHours,"dms.countdownHours"),countdownMinutes:L(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:N(m(r.system,"source.system"),["INHERITI_BUSINESS"]),status:N(m(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ge(n){let e=C(n);return{operationId:m(e.operationId,"operationId"),stage:N(m(e.stage,"stage"),Xe),outcome:N(m(e.outcome,"outcome"),qr),planId:$(e.planId),lastErrorCode:$(e.lastErrorCode),participants:e.participants===void 0?void 0:U(e.participants).map(t=>{let r=C(t);return{clientParticipantRef:m(r.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(r.planParticipantId,"planParticipantId"),relationships:U(r.relationships).map(i=>Gr(m(i,"relationship"),St))}})}}function Ct(n){let e=C(n),t=C(e.assetSummary),r=C(e.governance),i=C(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:$(e.description),status:N(m(e.status,"status"),Mr),createdAt:m(e.createdAt,"createdAt"),configuredAt:$(e.configuredAt),assetSummary:{count:L(t.count,"assetSummary.count"),types:U(t.types).map(s=>N(m(s,"assetType"),Ce)),names:Rt(t.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:N(m(r.mode,"governance.mode"),Nr),minimumApprovals:L(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:L(i.owners,"owners"),mergers:L(i.mergers,"mergers"),moderators:L(i.moderators,"moderators")},authentication:Rt(e.authentication).map(s=>{let a=C(s);return{id:N(m(a.id,"authentication.id"),Kr),status:N(m(a.status,"authentication.status"),Lr)}})}}function N(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function Gr(n,e){if(!e.includes(n))throw new Error("invalid_elements_response");return n}function C(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Rt(n){return n==null?[]:U(n)}function U(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function m(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function $(n){return n==null?void 0:m(n,"optional")}function L(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function Fr(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}var ne=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function xt(n){if(!n||typeof n!="object"||!("items"in n)||!Array.isArray(n.items)||!n.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 n.items.map(({id:e,name:t})=>({id:e,name:t}))}function Vr(n,e){if(!e){if(n.length===0)throw new ne("organization_required");if(n.length>1)throw new ne("organization_selection_required");return n[0].id}if(!n.some(({id:t})=>t===e))throw new ne("organization_access_denied");return e}function Br(n){let e=w(n);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:y(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),createdAt:D(e.createdAt),...Tt(e)}}function Tt(n){if(n.recipientStatuses===void 0)return{};if(!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:n.recipientStatuses.map(e=>{let t=w(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:D(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(r=>{let i=w(r);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:y(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:D(i.revealedAt)}:{}}})}:{}}})}}function kt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Br),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0),unreadCount:y(e.unreadCount,0),readThroughSequence:y(e.readThroughSequence,0)}}function Dt(n){let e=w(n);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:p(e.parentId),sequence:y(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let r=w(t);return{unitId:p(r.unitId),position:y(r.position,0),commitment:p(r.commitment),status:p(r.status)}})}}function nt(n){let e=w(n);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:y(e.sequence,1),status:e.status}}function Ot(n){let e=w(n);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:y(e.participantRevision,1),recipients:e.recipients.map(it)}}function Mt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);return{parentId:p(r.parentId),sequence:y(r.sequence,1),senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),participantRevision:y(r.participantRevision,1),createdAt:D(r.createdAt),...Tt(r)}}),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0),unreadCount:y(e.unreadCount,0),readThroughSequence:y(e.readThroughSequence,0)}}function Nt(n){return{readThroughSequence:y(w(n).readThroughSequence,0)}}function Ut(n){return{clearedThroughSequence:y(w(n).clearedThroughSequence,0)}}function Kt(n){let e=w(n);return{parentId:p(e.parentId),sequence:y(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function w(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_inbox_response");return n}function p(n){if(typeof n!="string"||!n)throw new Error("invalid_inbox_response");return n}function D(n){let e=p(n);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function y(n,e){if(!Number.isSafeInteger(n)||n<e)throw new Error("invalid_inbox_response");return n}function it(n){let e=w(n);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:y(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function ie(n){let e=w(n);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:D(e.createdAt),updatedAt:D(e.updatedAt)}}function Me(n){let e=w(n);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:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:D(e.createdAt),updatedAt:D(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 r=w(e.latestMessage);if(r.contentKind!=="TEXT"&&r.contentKind!=="FILE"&&r.contentKind!=="NORMAL"&&r.contentKind!=="MIXED"&&r.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:r.contentKind,senderMemberId:p(r.senderMemberId),createdAt:D(r.createdAt)}}return t}function Lt(n){let e=w(n);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(Me),total:e.total,limit:e.limit,offset:e.offset}}function qt(n){let e=w(n);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 r=it(t);return{memberId:r.memberId,name:p(w(t).name),deviceId:r.deviceId,deviceVersion:r.deviceVersion,encryptionPublicKey:r.encryptionPublicKey,encryptionKeyFingerprint:r.encryptionKeyFingerprint,signingPublicKey:r.signingPublicKey,signingKeyFingerprint:r.signingKeyFingerprint}}),limit:y(e.limit,1),offset:y(e.offset,0),nextOffset:e.nextOffset===null?null:y(e.nextOffset,0)}}function Gt(n){let e=w(n);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 r=w(t);if(typeof r.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(r.memberId),name:p(r.name),ready:r.ready,...r.profilePicture===void 0?{}:{profilePicture:{url:p(w(r.profilePicture).url)}}}}),limit:y(e.limit,1),offset:y(e.offset,0),nextOffset:e.nextOffset===null?null:y(e.nextOffset,0)}}function Ft(n){let e=w(n);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:p(e.conversationId),messageId:p(e.messageId),participantRevision:y(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(it),shareLayers:e.shareLayers.map(t=>{let r=w(t),i=p(r.id),s=p(r.dataShareId),a=p(r.keyShareId);if(r.type==="INHERITI_CHAIN")return{id:i,type:r.type,contractAddress:p(r.contractAddress),dataShareId:s,keyShareId:a};if(r.type==="INHERITI_VAULT"||r.type==="GOOGLE_DRIVE"||r.type==="DROPBOX"||r.type==="ONEDRIVE")return{id:i,type:r.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function Ne(n){let e=w(n);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function Vt(n){let e=w(n);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let r=w(t);if(r.status!=="PREPARING"&&r.status!=="AVAILABLE"&&r.status!=="FAILED"&&r.status!=="DELETING")throw new Error("invalid_inbox_response");if(r.contentKind!==void 0&&r.contentKind!=="TEXT"&&r.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(r.recipientStatus!==void 0&&r.recipientStatus!=="UNREAD"&&r.recipientStatus!=="LEASED"&&r.recipientStatus!=="CONSUMED"&&r.recipientStatus!=="EXPIRED"&&r.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(r.recipientStatuses!==void 0&&!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(r.id),status:r.status,senderMemberId:p(r.senderMemberId),senderDeviceId:p(r.senderDeviceId),createdAt:D(r.createdAt),updatedAt:D(r.updatedAt),expiresAt:D(r.expiresAt)};return r.contentKind&&(i.contentKind=r.contentKind),r.recipientStatus&&(i.recipientStatus=r.recipientStatus),Array.isArray(r.recipientStatuses)&&(i.recipientStatuses=r.recipientStatuses.map(s=>{let a=w(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:D(a.consumedAt)}:{}}})),i}),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0)}}function Bt(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:D(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:y(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId),ciphertext:p(r.ciphertext)}})}}function zt(n){let e=w(n);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:D(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let r=w(t);if(r.kind!=="DATA"&&r.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:r.kind,index:y(r.index,0),shareId:p(r.shareId),layerId:p(r.layerId)}})}}function ee(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function te(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var q=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},se=class{constructor(e,t,r,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,r,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":r},i)}confirmFileAccessDelivery(e,t,r){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":r})}createInboxFileAccess(e,t,r,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",r,void 0,void 0,i)}createRevealFileAccess(e,t,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,r)}cancelRevealFileAccess(e,t,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}cancelInboxFileAccess(e,t,r,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(r)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let r=t;if(typeof r.publicKey!="string"||!r.publicKey||typeof r.fingerprint!="string"||!r.fingerprint||r.status!=="ACTIVE"&&r.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:r.publicKey,fingerprint:r.fingerprint,status:r.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ie(t)}async getMemberInboxDevice(e,t){let r=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return r===null?null:ie(r)}async registerInboxDevice(e){return ie(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ie(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ie(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Me(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Me(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Lt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return qt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let r=new URLSearchParams;e.q!==void 0&&r.set("q",e.q),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let i=r.size?`?${r}`:"";return Gt(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let r={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 Ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",r))}async publishNormalInboxMessage(e,t){return nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},r){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 kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxParent(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Dt(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 Ut(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},r){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 Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,r))}async openNormalInboxMessage(e,t,r,i){let s=new URLSearchParams({deviceId:r});return Kt(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,r){return Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:r}))}async stageInboxFile(e,t,r){return Ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,r))}async uploadInboxFileShare(e,t,r,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}`,o=await this.requestBinary(a,"PUT",i,s),d=await Ue(o,s);if(!d.ok||d.result?.shareId!==r||d.result.status!=="STORED")throw new q(o.status,ee(d),te(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,r){return Ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,r))}async openInboxFile(e,t,r,i){return zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:r},void 0,void 0,i))}async downloadInboxFileShare(e,t,r,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(r)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let u=c.body.getReader(),v=[],E=0;try{for(;;){a?.throwIfAborted();let I=await u.read();if(I.done)break;if(E+=I.value.length,E>14*1024*1024)throw new Error("invalid_inbox_share_size");v.push(I.value)}}catch(I){throw await u.cancel().catch(()=>{}),I}let R=new Uint8Array(E),g=0;for(let I of v)R.set(I,g),g+=I.length;return R}async listInboxMessages(e,t={},r){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 Vt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,r))}async openInboxMessage(e,t,r){return Bt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:r}))}async ackInboxMessage(e,t,r,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:r,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,r,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:r,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(xt)}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 r=t.size?`?${t}`:"";return At(await this.request(`v1/plans${r}`,"GET"))}async getPlan(e){return Oe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let r=new URLSearchParams;t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return bt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let r=new URLSearchParams;t.source&&r.set("source",t.source),t.from&&r.set("from",t.from),t.to&&r.set("to",t.to),t.limit!==void 0&&r.set("limit",String(t.limit)),t.offset!==void 0&&r.set("offset",String(t.offset));let i=r.size?`?${r}`:"";return _t(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){W(e);let{idempotencyKey:t,...r}=e;return ge(await this.request("v1/plan-creations","POST",r,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ge(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return Z(t),ge(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ge(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:r,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":r})}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,r){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:r})}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,r){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,r)}abortPlanAccess(e,t){let r=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${r}?revealId=${encodeURIComponent(t)}`:r,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;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,r,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[E,R]of Object.entries(s??{}))d.set(E,R);r&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:r?JSON.stringify(r):void 0};a&&(l.signal=a);let u=await this.transport(new URL(e,c),l);a?.throwIfAborted();let v=await Ue(u,a);if(a?.throwIfAborted(),!u.ok)throw new q(u.status,ee(v),te(v),u.headers.get("x-request-id")??void 0);if(!v.ok||v.result===void 0)throw new q(u.status,ee(v),te(v),u.headers.get("x-request-id")??void 0);return v.result}async requestBinary(e,t,r,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),r&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:r?Buffer.from(r):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await Ue(d,i);throw new q(d.status,ee(c),te(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,r,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[u,v]of Object.entries(r??{}))o.set(u,v);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await Ue(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new q(c.status,ee(l),te(l),c.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 q(400,"organization_selection_required")}};async function Ue(n,e){try{return await n.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Xr}from"@safetech/inheriti-core-sdk/node";async function st(n,e){if(!e)throw new Error("master_key_required");let t=zr(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=$r(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return Hr(new Uint8Array(o))}function zr(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function $r(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Hr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var he=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await $t("plan_key_unwrap_failed",()=>st(e.planKey,t)),i=await crypto.subtle.importKey("raw",at(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await $t("plan_share_decryption_failed",()=>Yr(o.data,i));Qr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new Ke("plan_share_reconstruction_failed",jr(o))}}},Ke=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},Wr=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 jr(n){let e=n instanceof Error?n.message:void 0;if(e)return Wr.has(e)?e:void 0}async function $t(n,e){try{return await e()}catch{throw new Ke(n)}}function Qr(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function Yr(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=at(n.slice(0,t)),i=at(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function at(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var re=class extends he{constructor(e){super(()=>Xr(e))}};var fe=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Oe(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,r,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});r!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new q(c.status,l&&ee(l),l&&te(l));return l?.result}};var A={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var Q=class extends Error{constructor(t,r){super(r??`plan_request_failed_${t}`);this.status=t;this.code=r}},ye=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,r,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:r,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:r.validatorShares,encryptedKey:r.encryptedKey})}preflight(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",Ht(r))}configure(e,t,r){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",Ht(r))}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}async request(e,t,r,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(A.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:r,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new Q(c.status,l.error);return l.result}};function Ht(n){return{protectionProtocol:n.protectionProtocol,operation:"FINALIZE",dataShards:n.dataShards,backupShards:n.backupShards,encryptedKey:n.encryptedKey,assetsMetadata:n.assetsMetadata,custodianPair:n.custodianShard}}var ve=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Ie(e.signal),Jr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Ie(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Ie(e.signal);let t=e.encrypted.totalShares+1,r=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:r,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Ie(e.signal),!i.custodianPair)throw new x("custodian_share_required");let s=ot(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(ot(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(ot(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return Ie(e.signal),{protectionProtocol:i.protocol,validatorShares:dt(a.encryptedShares),dataShards:dt(o.encryptedShares),backupShards:dt(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:Zr(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let r=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:ct(r.encryptedShares[0]),dataShard:ct(r.encryptedShares[1])}}};function ot(n){return n.map(e=>({id:crypto.randomUUID(),data:e}))}function dt(n){return n.map(ct)}function ct(n){return{id:n.id,data:n.encryptedData}}function Zr(n,e){let t={};for(let r of n){let i=e.assets.find(s=>s.clientAssetRef===r.id);if(!i)throw new x("plan_secrets_declaration_mismatch");t[r.id]={type:r.type,meta:{name:r.meta.name,notes:r.meta.notes,...r.meta.isMedia===void 0?{}:{isMedia:r.meta.isMedia},...r.meta.mimeType===void 0?{}:{mimeType:r.meta.mimeType},...r.meta.fileName===void 0?{}:{fileName:r.meta.fileName},...r.meta.code===void 0?{}:{code:r.meta.code},...r.meta.matchOrigins===void 0?{}:{matchOrigins:[...r.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function Jr(n,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new x("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new x("share_threshold_invalid");if(e.assets.length!==n.assets.length)throw new x("plan_secrets_declaration_mismatch");let t=new Map(n.assets.map(r=>[r.clientAssetRef,r]));for(let r of e.assets){let i=t.get(r.id);if(!i||i.type!==r.type)throw new x("plan_secrets_declaration_mismatch")}}function Ie(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function Wt(n,e,t,r,i,s,a){let o=r.mergeThreshold-(r.withCustodian?1:0);if(typeof r.withCustodian!="boolean"||!Number.isInteger(r.mergeThreshold)||o<1||o>n.totalShares)throw new Error(A.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:r.withCustodian?"FORCE":"BYPASS"};let l=n.masterKeySource??new K({api:{startRelaySession:E=>i.startRelaySession(n.organizationId,t.masterKeyAcquisition,E),readRelaySession:E=>i.readRelaySession(n.organizationId,E)}}),u=new ve(s,l);a?.("encrypting");let v=await u.encrypt({planId:n.planId,declaration:c,secrets:{assets:d,totalShares:n.totalShares,threshold:o}});return a?.("generating_shares"),u.generateShares({planId:n.planId,declaration:c,encrypted:v})}import{PlanAssetDeclaration as en}from"@safetech/inheriti-core-sdk/node";function jt(n){let e=lt({planId:n.planId,title:n.title,assets:[n.asset]});return{asset:e.assets[0],plan:e.plan}}function lt(n){if(!n.assets.length)throw new P("assets_required");let e=n.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new P("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new P("binary_asset_metadata_invalid");return o}),t=en.create(n.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),r=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,n.assets[a].secret]))),i={idempotencyKey:n.planId,name:n.title,assets:r.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:r,plan:i}}async function Yt(n){let e=await Promise.all(n.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([r],[i])=>r.localeCompare(i)).map(async([r,i])=>[r,i instanceof Blob?await Qt(new Uint8Array(await i.arrayBuffer())):i]))})));return Qt(new TextEncoder().encode(JSON.stringify({organizationId:n.organizationId,planId:n.planId,title:n.title,description:n.description??null,audience:n.audience??null,totalShares:n.totalShares,assets:e})))}async function Qt(n){let e=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Pe=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(a=>!a?.meta?.name?.trim()))throw new Error(A.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(A.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(A.invalidShares);let r=await Yt(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==r)throw new Error(A.reconciliationRequired);return i.promise}let s=this.performCreate(e,r,t);this.flights.set(e.planId,{fingerprint:r,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,r){let i=lt({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(A.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(Le(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(A.reconciliationRequired);if(!a&&s)throw new Error(A.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(A.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(A.invalidMasterKeyContext);if(!a){r?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await Wt(e,i,o,a,this.port,this.coreSdk,r);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),r?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),r?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),r?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!Le(await this.statusOrMissing(e.organizationId,e.planId)))throw l}r?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return Le(c)&&this.material.delete(e.planId),{planId:e.planId,status:Le(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(A.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(r){if(r instanceof Q&&r.status===404)return;throw r}}};function Le(n){return n?.status==="PROTECTED"||n?.status==="CONFIGURED"}var qe=class{constructor(e,t,r,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=r;this.transport=i}start(e,t,r,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:r},i)}async listEligibleCandidates(e,t,r){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),r&&i.set("namePrefix",r);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(r))throw new Error("invalid_plan_edit_context");return r}async moderatorNames(e,t){let r=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!r||typeof r!="object")throw new Error("invalid_plan_edit_participants");let i=r;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,r){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(A.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:r});if(!i?.sessionId)throw new Error(A.relayFailed);return i}async readRelaySession(e,t){let r=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!r?.status)throw new Error(A.relayFailed);return r}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(r))}commit(e,t,r){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(r))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,r,i,s){let a=await this.getBearerToken();if(!a)throw new Error(A.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:r,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let v=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new Q(l.status,v||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(r=>!!r&&typeof r.id=="string"&&!!r.id&&typeof r.name=="string"&&r.status==="PROTECTED"&&typeof r.createdAt=="string"&&!!r.assetSummary&&Number.isSafeInteger(r.assetSummary.count)&&r.assetSummary.count>=0&&Array.isArray(r.assetSummary.types)&&r.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(r.assetSummary.names)&&r.assetSummary.names.every(i=>typeof i=="string")&&!!r.governance&&["DIRECT","GOVERNED"].includes(r.governance.mode)&&Number.isSafeInteger(r.governance.minimumApprovals)&&r.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var Ge=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.recoveryStore=r}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let r=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(u=>u.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&r===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),r=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(r>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return r}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new K({api:{startRelaySession:r=>this.port.startRelaySession(e.organizationId,t,r),readRelaySession:r=>this.port.readRelaySession(e.organizationId,r)}}).resolve()}async revealAssets(e,t,r,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let I=this.approvalError(g);if(I?.startsWith("edit_authentication_")&&d("pending_auth"),I?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let M=g.moderatorParticipants.map(b=>b.memberId??b.userId);M.some(b=>typeof b!="string"||!b)||new Set(M).size!==M.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((b,G)=>{let ae=M[G],mt=b.flows.filter(oe=>oe.status==="PENDING"&&oe.expiresAt&&Number.isFinite(oe.expiresAt.getTime())).map(oe=>oe.expiresAt.getTime());return{id:ae,displayName:a.get(ae)||"Moderator",status:b.status,expiresAt:mt.length?new Date(Math.min(...mt)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let u=await s.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let v=u?.status;if(v!=="READY_TO_REVEAL"&&v!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let E=null,R={onRevealed:g=>{E=g},onViewUpdate:c,onRevealStepUpdate:(g,I)=>{if(I==="IN_PROCESS")switch(g){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(r&&(R.onCustodianShareRequired=async(g,I)=>{switch(I.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let M=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),M==="SK_MOBILE")return s.distributeCustodianShareViaMobile(I.planId);if(M!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let b=e.proDevice;try{this.assertNotAborted(e.signal);let G=await s.getCustodianShareData(g);this.assertShare(G,I.planId),d("connecting_safekey_pro");let{deviceId:ae}=await b.write(G,e.signal);if(this.assertNotAborted(e.signal),!ae?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(I.planId,G.id,ae,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,G.id);return}finally{b.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let M=e.proDevice;try{if(this.assertNotAborted(e.signal),!I.shareId||!I.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let b=await M.read({shareId:I.shareId,planId:I.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(b,I.planId,I.shareId),b.deviceId!==I.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:b.shares}}finally{M.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),v==="REVEALED"?await s.resumeReveal(e.editId,R,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},R,t),this.assertNotAborted(e.signal),!E)throw new Error("edit_assets_unavailable");return E}assertApprovalOutcome(e,t){let r=this.approvalError(t);if(r)throw this.clearRevealedAssets(e),new Error(r)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,r){if(!e||!e.id||e.id!==(r??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var tn=n=>JSON.stringify(n??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([r],[i])=>r<i?-1:r>i?1:0))),Fe=class{constructor(e,t,r,i){this.port=e;this.coreSdk=t;this.recoveryStore=r;this.clearRevealedAssets=i}async saveAssets(e,t,r,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,r,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let r=await this.configurationRepository().findByPlanId(e.planId),i=r?.editDistribution??r?.preparedDistribution;if(!t&&(!i||r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!r?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let r=await this.configurationRepository().findByPlanId(e.planId);if(r?.editDistribution&&r.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let r=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await r.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await r.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,r,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:r,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,r,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,r))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,r))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let r=await this.port.commitStatus(e.organizationId,e.editId);if(r.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(r.status)||r.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(tn(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(r.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(r.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Ve=class{constructor(e,t,r){this.port=e;this.coreSdk=t;this.assetAccess=new Ge(e,t,r),this.reconfiguration=new Fe(e,t,r,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,r,i){return this.port.start(e,t,r,i)}async listAssets(e,t){let{assets:r}=await this.assetAccess.loadAssets(e,t);return r.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,r){let{assets:i}=await this.assetAccess.loadAssets(e,r),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=s.map((l,u)=>u===a?d:l);return this.reconfiguration.saveAssets(e,c,r.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:r,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=jt({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),r.withCustodian,i,a.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function Xt({apiUrl:n,organizationId:e,planId:t,editId:r,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(n.endsWith("/")?n:`${n}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=rn(l,d.searchParams,t,r),v=new Headers(o?.headers);v.set("x-organization-id",e),v.set("x-elements-environment",i);let E=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return s(new URL(E,c),Object.assign({},o,{headers:v}))}}function rn(n,e,t,r){if(n==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(n);if(s){let o=s[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(s[1]!==r||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(n);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(r)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(r)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as nn}from"@safetech/inheriti-core-sdk/node";function Zt(n){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let r=await n.api.planKeyReference(e),i=de(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new K({api:{startRelaySession:o=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>n.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>n.api.cancelMasterKeyRelaySession(o,d)}}),a=new J(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}});return De(a,e,t,!0)}}}function sn(n){let e=new fe(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...Zt({api:e,reconstructor:new re(n.workerUrl),assetDecoder:nn}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as Jt,sealInheritiFile as er,readInheritiFileHeader as ji,openInheritiFile as Qi,InheritiFileInvalid as Yi,MAX_INHERITI_FILE_BYTES as tr}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as rr,openInheritiFileKey as Ji}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function an(n){let{reveal:e,api:t,signal:r}=n;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(r);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=n.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(n.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>tr-1024*1024)throw new Error("unsupported_protected_asset");let d=Jt(),c,l=!1,u=!1;try{r?.throwIfAborted();let v=await rr(d,i.publicKey);l=!0;let E=await t.createRevealFileAccess(e.session.id,{copyId:n.copyId,envelopeId:n.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:v,openLimit:a},r);if(E.copyId!==n.copyId||E.status!=="PENDING")throw new Error("file_access_create_invalid");let R=await t.getFileAccess(n.copyId,r);for(;R.status==="PENDING";){if(r?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((I,M)=>{let b=()=>{clearTimeout(G),M(r?.reason)},G=setTimeout(()=>{r?.removeEventListener("abort",b),I()},Math.min(500,Math.max(1,s-Date.now())));r?.addEventListener("abort",b,{once:!0})}),R=await t.getFileAccess(n.copyId,r)}if(R.status!=="READY"||R.origin!=="REVEAL"||R.copyId!==n.copyId||R.allowedUses!==a||!R.recipient||!R.deployment||R.expiresAt!==null&&(!Number.isFinite(Date.parse(R.expiresAt))||Date.parse(R.expiresAt)>s||Date.parse(R.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await er({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:R});g.fileKey.fill(0),c=g.fileBytes,r?.throwIfAborted(),await n.save({fileName:o.fileName,fileBytes:c}),u=!0}catch(v){if(l&&!u)try{await t.cancelRevealFileAccess(e.session.id,n.copyId)}catch(E){throw new AggregateError([v,E],"protected_asset_export_and_cleanup_failed",{cause:v})}throw v}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as zs}from"@safetech/inheriti-core-sdk/node";function nr(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Be=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),nr(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return nr(new Uint8Array(t))}},ze=class{now(){return Date.now()}sleep(e,t){return new Promise((r,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var we=class extends Error{constructor(t,r=t){super(r);this.code=t;this.name="OperatorAuthError"}},O=class extends we{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},f=class extends we{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function $e(n){if(n instanceof we)return n.code;if(typeof n!="object"||n===null)return;let e=n.code??n.error;return typeof e=="string"?e:void 0}var ir=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,r=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:T(r,"issuer"),authorizationEndpoint:T(r,"authorization_endpoint"),tokenEndpoint:T(r,"token_endpoint"),deviceAuthorizationEndpoint:V(r,"device_authorization_endpoint"),endSessionEndpoint:V(r,"end_session_endpoint"),revocationEndpoint:V(r,"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:T(t,"device_code"),userCode:T(t,"user_code"),verificationUri:T(t,"verification_uri"),verificationUriComplete:V(t,"verification_uri_complete"),expiresInSeconds:sr(t,"expires_in"),intervalSeconds:pt(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 revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new f(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,r){let i=await this.businessRequest(e,t,r);return{accessToken:T(i,"accessToken"),refreshToken:T(i,"refreshToken"),accessExpiresAt:T(i,"accessExpiresAt"),sessionExpiresAt:T(i,"sessionExpiresAt"),familyId:T(i,"familyId"),environment:dn(i,"environment"),clientId:T(i,"clientId"),providerIssuer:T(i,"providerIssuer"),providerSubject:T(i,"providerSubject")}}async businessRequest(e,t,r,i){let s=e.endsWith("/")?e:`${e}/`,a=new URL(`operator-sessions/${t}`,s),o=await this.http(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(r)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new f(`business_http_${o.status}`);if(d.ok!==!0||!on(d.result))throw new f("invalid_business_response");return d.result}async token(e,t){let r=await this.form(e,t);return{accessToken:T(r,"access_token"),refreshToken:V(r,"refresh_token"),idToken:V(r,"id_token"),tokenType:T(r,"token_type"),expiresInSeconds:sr(r,"expires_in"),refreshExpiresInSeconds:pt(r,"refresh_expires_in"),scope:V(r,"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 r=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await r.json()}catch{}if(!r.ok){let s=V(i,"error")??`oauth_http_${r.status}`;throw new f(s,V(i,"error_description")??s)}return i}};function on(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function dn(n,e){let t=T(n,e);if(t!=="TEST"&&t!=="LIVE")throw new f("invalid_business_response");return t}function T(n,e){let t=V(n,e);if(!t)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function V(n,e){return typeof n[e]=="string"?n[e]:void 0}function sr(n,e){let t=pt(n,e);if(t===void 0)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function pt(n,e){let t=n[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var cn=600*1e3,He=5,ln=5,ar=5e3,pn=new WeakMap,un=new WeakMap;async function dr(n,e,t){let r=n.get(e),i,s=new Promise(a=>{i=a});n.set(e,s),r&&await r;try{return await t()}finally{n.get(e)===s&&n.delete(e),i()}}function Y(n,e){return dr(pn,n,e)}var or=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new f("business_api_url_required");this.crypto=e.crypto??new Be,this.clock=e.clock??new ze}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),r=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+cn;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:r,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",r),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),r=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!r||r.kind!=="authorization-code")throw new f("authorization_transaction_missing");if(r.expiresAt<=this.clock.now())throw new f("authorization_transaction_expired");let i=new URL(e),s=new URL(r.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new f("redirect_uri_mismatch");if(i.searchParams.get("state")!==r.state)throw new f("state_mismatch");let a=i.searchParams.get("error");if(a)throw new f(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new f("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:r.codeVerifier,redirectUri:r.redirectUri}),l=await this.acceptTokens(c,r.nonce);return await Y(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new f("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),r=Math.max(He,t.intervalSeconds??He),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:r,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+r*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),r=await this.options.transactions.load(t);if(!r||r.kind!=="device-code"||r.consumed)throw new f("device_transaction_missing");let i=r,s=await this.getDiscovery(),a=Math.max(He,i.intervalSeconds??He),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=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(d);return await Y(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=$e(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=ln,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new f("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new O;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new O;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new O;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await Y(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let a=await this.getDiscovery();a.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:a.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((a,o)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,o(new f("provider_revoke_timeout"))},ar)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,r;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{r=setTimeout(()=>{t.abort(),s(new f("business_revoke_timeout"))},ar)})])}finally{r&&clearTimeout(r)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new O;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new O;let r;try{r=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=$e(i);if(s==="business_http_409"){let a=await Y(this.options.sessions,async()=>{let o=await this.options.sessions.load();if(o&&this.isValidBusinessSession(o)&&o.refreshToken!==t.refreshToken&&o.familyId===t.familyId&&o.principal.subject===t.principal.subject)return o;o&&this.sameCredential(o,t)&&await this.options.sessions.clear()});if(a)return a;throw new O}throw s==="business_http_401"?(await this.clearIfCurrent(t),new O):i}try{let i=this.businessSession(r,t.principal,t);if(i.refreshToken===t.refreshToken)throw new f("refresh_token_rotation_missing");return await Y(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new O;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await Y(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await Y(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),dr(un,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new O;let t;try{let r=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:r.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(r){let i=$e(r);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new O):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),r)}try{if(!t.refreshToken)throw new f("refresh_token_rotation_missing");let r=await this.acceptProviderTokens(t,void 0,e);return await Y(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new O;return await this.options.sessions.save(r),r})}catch(r){throw await this.clearIfUnchanged(e),r}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(k(e.issuer)!==k(this.options.configuration.issuer))throw new f("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:r,redirectUri:i}=this.options.configuration;return`${e}|${k(t)}|${r}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let r=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,r)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new f("unsupported_token_type");let r=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(r,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new f("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==r.subject||i.sessionId!==r.sessionId)throw new f("token_subject_mismatch")}return r}async acceptProviderTokens(e,t,r){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new O;let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?r?this.isOfflineSession(r):!0:e.scope.split(/\s+/u).includes("offline_access")),o={accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:o.accessToken,refreshToken:o.refreshToken,idToken:o.idToken,tokenType:o.tokenType,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,offlineAccessGranted:o.offlineAccessGranted,principal:o.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:k(this.options.configuration.issuer),environment:this.options.configuration.environment}:o}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,r=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof r=="object"&&r!==null&&typeof r.issuer=="string"&&typeof r.authorizedParty=="string"&&(r.environment==="TEST"||r.environment==="LIVE")&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&k(t.issuer)===k(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment&&k(r.issuer)===k(this.options.configuration.issuer)&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)}businessSession(e,t,r){if(k(e.providerIssuer)!==k(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||r&&e.familyId!==r.familyId)throw new f("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new f("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,r=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof r=="object"&&r!==null&&typeof r.issuer=="string"&&k(r.issuer)===k(this.options.configuration.issuer)&&typeof r.subject=="string"&&r.subject.length>0&&(typeof r.audience=="string"||Array.isArray(r.audience)&&r.audience.every(i=>typeof i=="string"))&&(typeof r.audience=="string"?[r.audience]:r.audience).includes(this.options.configuration.audience)&&r.authorizedParty===this.options.configuration.clientId&&r.environment===this.options.configuration.environment}assertPrincipal(e,t,r){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(k(e.issuer)!==k(i.issuer))throw new f("issuer_mismatch");if(!s.includes(i.audience))throw new f("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new f("client_mismatch");if(e.environment!==i.environment)throw new f("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new f("required_claim_missing");if(r&&e.nonce!==t)throw new f("nonce_mismatch")}assertIdentity(e,t){let r=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(k(e.issuer)!==k(r.issuer))throw new f("issuer_mismatch");if(!i.includes(r.clientId))throw new f("client_mismatch");if(e.authorizedParty!==r.clientId)throw new f("client_mismatch");if(!e.subject||!e.sessionId)throw new f("required_claim_missing");if(e.nonce!==t)throw new f("nonce_mismatch")}};function k(n){return n.replace(/\/+$/u,"")}var cr=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()}}};import{PassphraseMasterKeySource as Ys,RawMasterKeySource as Xs,deriveMasterKey as Zs,generateHexSeed as Js,computePassphraseVerifier as ea}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as ra}from"@safetech/inheriti-core-sdk/node";function _s(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",n.environment),e(s,Object.assign({},a,{headers:o}))},r=n.business?void 0:ut({apiUrl:n.apiUrl,getBearerToken:n.getBearerToken,transport:t,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners}),i=new se(n.apiUrl,n.environment,n.getBearerToken,t,n.business?{organizationId:n.organizationId}:void 0);return new J(r,{keyVault:n.keyVault,state:n.state,api:i,reconstructor:new re(n.workerUrl),masterKeys:n.masterKeys,masterKey:n.masterKey,applicationId:n.applicationId,organizationId:n.organizationId,assetDecoder:mn})}function Cs(n){let e=n.transport??globalThis.fetch.bind(globalThis),t=ut({apiUrl:new URL(n.apiUrl).origin,getBearerToken:n.getBearerToken,transport:e,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Pe(new ye(n.apiUrl,n.environment,n.getBearerToken,e),t)}function xs(n){if(!n.payloadStorage||!n.secureSessionStorage||!n.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=n.transport??globalThis.fetch.bind(globalThis),t=new URL(n.apiUrl).origin,r=ut({apiUrl:t,getBearerToken:n.getBearerToken,transport:Xt({apiUrl:t,organizationId:n.organizationId,planId:n.planId,editId:n.editId,environment:n.environment,transport:e}),secureSessionStorage:n.secureSessionStorage,payloadStorage:n.payloadStorage,workerUrl:n.workerUrl,reconciliationConcurrency:n.reconciliationConcurrency,eventListeners:n.eventListeners});return new Ve(new qe(n.apiUrl,n.environment,n.getBearerToken,e),r,n.editRecoveryStore)}export{ne as BusinessOrganizationSelectionError,ve as CorePlanMaterialBuilder,zs as DataAssetDefinitionService,q as ElementsApiRequestFailed,J as ElementsClient,me as GuidedCreateRecoveryError,ue as GuidedPlanCreator,fe as HttpAutomationRevealApiPort,se as HttpElementsApiPort,ir as HttpOperatorAuthTransport,qe as HttpPlanEditPort,ye as HttpQuickPlanPort,P as InvalidPlanDeclaration,x as InvalidPlanMaterial,Se as MasterKeyRelayCancellationFailed,Re as MasterKeyRelayExpired,Ee as MasterKeyRelayTimedOut,B as MasterKeyRequired,pe as MemoryGuidedCreateCheckpointStore,ce as MemoryKeyVault,le as MemoryStatePort,f as OAuthProtocolError,or as OperatorAuthClient,we as OperatorAuthError,O as OperatorReauthenticationRequired,cr as OperatorSessionController,Xe as PLAN_CREATION_SERVER_STAGES,Ys as PassphraseMasterKeySource,ra as PlanAssetDeclaration,Q as PlanRequestFailed,Pe as QuickPlanCreator,Ve as QuickPlanEditor,Xs as RawMasterKeySource,K as RelayMasterKeySource,je as StaticMasterKeyResolver,ze as SystemOAuthClock,Be as WebOAuthCrypto,ea as computePassphraseVerifier,Ae as createMasterKeyResolver,sn as createNodeAutomationRevealClient,_s as createNodeElementsClient,Cs as createNodeQuickPlanCreator,xs as createNodeQuickPlanEditor,mn as decodeAssetContainer,Zs as deriveMasterKey,an as exportProtectedRevealAsset,Js as generateHexSeed,de as masterKeyRefFor,H as masterKeyRefKey,$e as oauthErrorCode,Vr as selectBusinessOrganization,st as unwrapDekWithMasterKey,W as validatePlanCreationInput,Z as validatePlanCreationMaterial};