@safetech/inheriti-client-sdk 1.17.19 → 1.17.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{decodeAssetContainer as vt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Me,generateRSAOAEPKeyPair as Ne}from"@safetech/inheriti-core-sdk/crypto";var J=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ee=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},te=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},T=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 Ne();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??(y=>new Promise(h=>setTimeout(h,y))),l=!0,m=!1,S,_=()=>S??=(async()=>{let y=new AbortController,h,De=new Promise((Rt,Oe)=>{h=setTimeout(()=>{y.abort(),Oe(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,y.signal),De])}finally{clearTimeout(h)}})(),L,ge=new Promise((y,h)=>{L=()=>{l&&_().catch(()=>{}),h(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",L,{once:!0})});ge.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),m=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let y=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),ge]);if(y.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(y.status==="DELIVERED"&&y.sealedMasterKey){let h=(await Me(y.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(h))throw new Error("invalid_master_key_material");return h}if(y.status==="EXPIRED")throw new ee(s.sessionId);await ke(d,a,e)}throw new J(s.sessionId)}catch(y){if(l&&(!m||e?.aborted))try{await _()}catch(h){if(e?.aborted)throw new te(h)}throw y}finally{L&&e?.removeEventListener("abort",L)}}};async function ke(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 re(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||ne(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Ke(e,n.applicationId)){let i=await n.source?.resolve();return i||ne(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return ne(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Ke(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function ne(n,e,t,r,i){if((await e()).relayAvailable)return new T({...n.relay,api:Ue(n.api,t)}).resolve(r,i)}function Ue(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 O(n){return`${n.system}:${n.contextId}`}function q(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var w=class extends Error{constructor(t){super(`master_key_required:${O(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var G=class{keys=new Map;async store(e,t){let r=O(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(O(e))?.slice()}async remove(e){let t=O(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var F=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var $=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},c=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var V=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var z=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],se={"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"]};var u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function M(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new P("plan_material_field_unknown");if(ie(n.dataShards,"data_shards_invalid"),ie(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&ie(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new P("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new P("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new P("material_operation_invalid")}function ie(n,e){if(!Array.isArray(n))throw new P(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new P(e);if(t.data!==void 0&&typeof t.data!="string")throw new P(e)}}function D(n){if(C(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ge(n.idempotencyKey))throw new u("idempotency_key_invalid");if(!n.name?.trim())throw new u("plan_name_required");if(!n.assets.length)throw new u("assets_required");let e=new Set;for(let t of n.assets){if(C(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 u("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!z.includes(t.type))throw new u("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new u("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 u("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new u("asset_field_names_invalid");if(Le(t.matchOrigins),!t.isBinary){let s=se[t.type];if(!s||i.some(a=>!s.includes(a)))throw new u("asset_field_name_not_canonical")}}if(!n.participants.length)throw new u("participants_required");for(let t of n.participants){if(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ye(t.routingEmail))throw new u("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new u("participant_relationships_invalid")}qe(n)}function Le(n){if(n===void 0)return;if(!n.length)throw new u("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new u("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof u?r:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function qe(n){let e=n.policy;if(e&&C(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new u("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){C(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){C(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new u("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new u("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new u("approval_mode_invalid")}let t=e.dms;if(!t)return;C(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!ye(t.subjectEmail))throw new u("dms_subject_invalid");if(!n.participants.some(s=>Ie(s.routingEmail)===Ie(t.subjectEmail)))throw new u("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 u("dms_countdown_invalid")}function Ge(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 ye(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function Ie(n){return n.normalize("NFC").trim().toLowerCase()}function C(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new u(t)}var H=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)}},W=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),D(e),B(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={}){D(t);let a=await this.checkpoints.load(e);if(!a)throw new j("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await fe(t))throw new j("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;B(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});B(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});B(s.signal),M(l);let m=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(m.stage),m.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,m),m}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 fe(e),serverStage:t.stage})}},j=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function fe(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 B(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function he(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new $(r.stage);return n.authorizeRevealAction(e,t)}function Fe(n){let e=n?.status;return e===400||e===401||e===403}async function ve(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!Fe(s))throw s}return n.releaseRevealMaterial(e,t)}function $e(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"?ze(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":Ve.has(n.stage)?"ENDED":"CONTINUING"}var Ve=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ze(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 ae=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ee(n,e,t={}){if(t.signal?.aborted)throw p();let r=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Re(i.id);if(t.signal?.aborted||(await n.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw p();let s=t.idempotencyKey??crypto.randomUUID(),a;try{a=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await n.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:Re(l.id)}let o;try{if(t.signal?.aborted)throw p();let d=await He(n,a,t);if(t.signal?.aborted||(A(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw p();let l=await n.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await n.markRevealSharesCollected(d.id),t.signal?.aborted))throw p();let m;try{m=await Xe(n,d,Ze(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(A(t,"RECONSTRUCTING",d),t.signal?.aborted))throw p();try{o=await n.reconstructPlanMaterial(m)}catch(_){throw t.signal?.aborted?p():(await n.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Ye(_)}),_)}if(t.signal?.aborted)throw p();let S=await n.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(A(t,"OPEN",S),t.signal?.aborted))throw p();return new de(n,S,r,o,t.signal)}catch(d){throw o?.fill(0),await Se(n,a.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Re(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Be=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function He(n,e,t){let r=await b(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw p();if(t.onSession?.(r),t.onProgress?.({phase:$e(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Be.has(r.stage))throw new oe(r.stage);await ce(t.pollIntervalMs??1500,t.signal),r=await b(()=>n.getReveal(e.id,t.signal),t.signal)}}var oe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function A(n,e,t){n.onProgress?.({phase:e,session:t})}function ce(n,e){return e?.aborted?Promise.reject(p()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(p())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var de=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 ae;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 I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=We(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("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 I("asset_value_invalid");return{selector:a.selector,value:je(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Pe(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("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 I("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",Pe(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=Se(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 We(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function je(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?se[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function Pe(n){if(n instanceof I)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 Ye(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Xe(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await b(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Y;let l=await b(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(be(l,i.id,e.planId),!l.shares.includes(i.data))throw new R;A(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:m}=await b(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw p();if(!m?.trim())throw new R;if(await n.claimRevealCustodianShare(e.id,l.id,m),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw p();return{...t,shares:t.shares.filter(S=>S!==i).concat(l.shares.map((S,_)=>({id:`${l.id}:${_}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:S})))}}if(d!=="SK_MOBILE")throw new R;if(r.signal?.aborted)throw p();return await n.distributeRevealCustodianShare(e.id),A(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await b(()=>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),A(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ce(r.pollIntervalMs??1500,r.signal),s=await b(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Y;if(!s.shareId||!s.deviceId)throw new R;A(r,"CONNECTING_SAFEKEY_PRO",e);let d=await b(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw p();if(be(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new R;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw p();return{...t,shares:t.shares.concat(d.shares.map((l,m)=>({id:`${d.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new R;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),A(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw p();await n.requestRevealCustodianRelease(e.id);let o=await Qe(n,e.id,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 be(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 R}async function b(n,e){if(e?.aborted)throw p();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(p()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw p();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Qe(n,e,t){let r=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await b(()=>n.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new R}if(Date.now()>=r)throw new le;await ce(t.pollIntervalMs??1500,t.signal)}}var R=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Y=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},le=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ze(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Se(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Je(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 Je(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function p(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var N=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 G,this.state=t.state??new F,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??nt(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 c;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new c;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new c;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return D(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new c;return M(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new H){if(this.requireApplication(),!this.api)throw new c;return new W(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 w({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 tt(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new w(e);return await this.keyVault.store(e,et(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new c;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 c;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new V;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 w({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=q(e);if(!i)throw new w({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new c;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new c;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new c;return this.api.getReveal(e,t)}openReveal(e,t){return Ee(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 c;return ve(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new c;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new c;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new c;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new c;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new c;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new c;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return he(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new c;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new c;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new c;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new c;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new c;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new c;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 c;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 ue;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new w({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ue=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function et(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 tt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function nt(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 re({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return re({...e,organizationId:n.organizationId})}function we(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=q(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new T({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)}});return new N(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)}}}).openReveal(e,t)}}}var rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],it=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],at=["ACTIVE","REVOKED"],ot=["SK_MOBILE"],dt=["ACTIVE","INACTIVE"];function pe(n){let e=v(n),t=lt(e),r=v(e.source),i=g(r.kind,"source.kind");return{...t,assets:x(e.assets).map(s=>{let a=v(s);return{id:g(a.id,"asset.id"),code:k(a.code),type:f(g(a.type,"asset.type"),z),name:g(a.name,"asset.name"),isBinary:ct(a.isBinary,"asset.isBinary"),fieldNames:x(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:k(a.fileName),mimeType:k(a.mimeType),size:a.size===void 0||a.size===null?void 0:E(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:x(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:x(e.participants).map(s=>{let a=v(s);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:x(a.relationships).map(o=>f(g(o,"relationship"),st)),lifecycle:f(g(a.lifecycle,"participant.lifecycle"),at)}}),revealPolicy:(()=>{let s=v(e.revealPolicy);return{masterKeyRelease:f(g(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(g(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=v(e.dms);return{subjectEmail:g(s.subjectEmail,"dms.subjectEmail"),countdownDays:E(s.countdownDays,"dms.countdownDays"),countdownHours:E(s.countdownHours,"dms.countdownHours"),countdownMinutes:E(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:f(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:f(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function lt(n){let e=v(n),t=v(e.assetSummary),r=v(e.governance),i=v(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:k(e.description),status:f(g(e.status,"status"),rt),createdAt:g(e.createdAt,"createdAt"),configuredAt:k(e.configuredAt),assetSummary:{count:E(t.count,"assetSummary.count"),types:x(t.types).map(s=>f(g(s,"assetType"),z)),names:Ae(t.names).map(s=>g(s,"assetSummary.names"))},governance:{mode:f(g(r.mode,"governance.mode"),it),minimumApprovals:E(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:E(i.owners,"owners"),mergers:E(i.mergers,"mergers"),moderators:E(i.moderators,"moderators")},authentication:Ae(e.authentication).map(s=>{let a=v(s);return{id:f(g(a.id,"authentication.id"),ot),status:f(g(a.status,"authentication.status"),dt)}})}}function f(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function v(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Ae(n){return n==null?[]:x(n)}function x(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function k(n){return n==null?void 0:g(n,"optional")}function E(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function ct(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function _e(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 Ce(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var X=class extends Error{constructor(t,r,i){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}};var Q=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 pe(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 m;try{m=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||m&&m.ok===!1||i&&m?.result===void 0)throw new X(l.status,m&&_e(m),m&&Ce(m));return m?.result}};import{createNodeSsdpV2Processor as ht}from"@safetech/inheriti-core-sdk/node";async function xe(n,e){if(!e)throw new Error("master_key_required");let t=ut(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=pt(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return mt(new Uint8Array(o))}function ut(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 pt(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 mt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var K=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Te("plan_key_unwrap_failed",()=>xe(e.planKey,t)),i=await crypto.subtle.importKey("raw",me(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Te("plan_share_decryption_failed",()=>ft(o.data,i));yt(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 Z("plan_share_reconstruction_failed",It(o))}}},Z=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},gt=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 It(n){let e=n instanceof Error?n.message:void 0;if(e)return gt.has(e)?e:void 0}async function Te(n,e){try{return await e()}catch{throw new Z(n)}}function yt(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function ft(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=me(n.slice(0,t)),i=me(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function me(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 U=class extends K{constructor(e){super(()=>ht(e))}};function Bn(n){let e=new Q(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...we({api:e,reconstructor:new U(n.workerUrl),assetDecoder:vt}),getPlan:t=>e.getPlan(t)}}export{Bn as createNodeAutomationRevealClient};
1
+ import{decodeAssetContainer as vt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Me,generateRSAOAEPKeyPair as Ne}from"@safetech/inheriti-core-sdk/crypto";var J=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ee=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},te=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},T=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 Ne();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??(y=>new Promise(h=>setTimeout(h,y))),l=!0,m=!1,S,_=()=>S??=(async()=>{let y=new AbortController,h,De=new Promise((Rt,Oe)=>{h=setTimeout(()=>{y.abort(),Oe(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,y.signal),De])}finally{clearTimeout(h)}})(),L,ge=new Promise((y,h)=>{L=()=>{l&&_().catch(()=>{}),h(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",L,{once:!0})});ge.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),m=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let y=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),ge]);if(y.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(y.status==="DELIVERED"&&y.sealedMasterKey){let h=(await Me(y.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(h))throw new Error("invalid_master_key_material");return h}if(y.status==="EXPIRED")throw new ee(s.sessionId);await ke(d,a,e)}throw new J(s.sessionId)}catch(y){if(l&&(!m||e?.aborted))try{await _()}catch(h){if(e?.aborted)throw new te(h)}throw y}finally{L&&e?.removeEventListener("abort",L)}}};async function ke(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 re(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||ne(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Ke(e,n.applicationId)){let i=await n.source?.resolve();return i||ne(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return ne(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Ke(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function ne(n,e,t,r,i){if((await e()).relayAvailable)return new T({...n.relay,api:Ue(n.api,t)}).resolve(r,i)}function Ue(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 O(n){return`${n.system}:${n.contextId}`}function q(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var w=class extends Error{constructor(t){super(`master_key_required:${O(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var G=class{keys=new Map;async store(e,t){let r=O(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(O(e))?.slice()}async remove(e){let t=O(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var F=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var $=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},c=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var V=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var z=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],se={"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"]};var u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function M(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new P("plan_material_field_unknown");if(ie(n.dataShards,"data_shards_invalid"),ie(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&ie(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new P("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new P("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new P("material_operation_invalid")}function ie(n,e){if(!Array.isArray(n))throw new P(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new P(e);if(t.data!==void 0&&typeof t.data!="string")throw new P(e)}}function D(n){if(C(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ge(n.idempotencyKey))throw new u("idempotency_key_invalid");if(!n.name?.trim())throw new u("plan_name_required");if(!n.assets.length)throw new u("assets_required");let e=new Set;for(let t of n.assets){if(C(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 u("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!z.includes(t.type))throw new u("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new u("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 u("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new u("asset_field_names_invalid");if(Le(t.matchOrigins),!t.isBinary){let s=se[t.type];if(!s||i.some(a=>!s.includes(a)))throw new u("asset_field_name_not_canonical")}}if(!n.participants.length)throw new u("participants_required");for(let t of n.participants){if(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ye(t.routingEmail))throw new u("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new u("participant_relationships_invalid")}qe(n)}function Le(n){if(n===void 0)return;if(!n.length)throw new u("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new u("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof u?r:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function qe(n){let e=n.policy;if(e&&C(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new u("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){C(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){C(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new u("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new u("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new u("approval_mode_invalid")}let t=e.dms;if(!t)return;C(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!ye(t.subjectEmail))throw new u("dms_subject_invalid");if(!n.participants.some(s=>Ie(s.routingEmail)===Ie(t.subjectEmail)))throw new u("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 u("dms_countdown_invalid")}function Ge(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 ye(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function Ie(n){return n.normalize("NFC").trim().toLowerCase()}function C(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new u(t)}var H=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)}},W=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),D(e),B(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={}){D(t);let a=await this.checkpoints.load(e);if(!a)throw new j("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await fe(t))throw new j("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;B(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});B(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});B(s.signal),M(l);let m=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(m.stage),m.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,m),m}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 fe(e),serverStage:t.stage})}},j=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function fe(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 B(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function he(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new $(r.stage);return n.authorizeRevealAction(e,t)}function Fe(n){let e=n?.status;return e===400||e===401||e===403}async function ve(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!Fe(s))throw s}return n.releaseRevealMaterial(e,t)}function $e(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"?ze(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":Ve.has(n.stage)?"ENDED":"CONTINUING"}var Ve=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ze(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 ae=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ee(n,e,t={}){if(t.signal?.aborted)throw p();let r=await n.getPlan(e),i=await n.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Re(i.id);if(t.signal?.aborted||(await n.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw p();let s=t.idempotencyKey??crypto.randomUUID(),a;try{a=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await n.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:Re(l.id)}let o;try{if(t.signal?.aborted)throw p();let d=await He(n,a,t);if(t.signal?.aborted||(A(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw p();let l=await n.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await n.markRevealSharesCollected(d.id),t.signal?.aborted))throw p();let m;try{m=await Xe(n,d,Ze(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(A(t,"RECONSTRUCTING",d),t.signal?.aborted))throw p();try{o=await n.reconstructPlanMaterial(m)}catch(_){throw t.signal?.aborted?p():(await n.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Ye(_)}),_)}if(t.signal?.aborted)throw p();let S=await n.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(A(t,"OPEN",S),t.signal?.aborted))throw p();return new de(n,S,r,o,t.signal)}catch(d){throw o?.fill(0),await Se(n,a.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Re(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var Be=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function He(n,e,t){let r=await b(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw p();if(t.onSession?.(r),t.onProgress?.({phase:$e(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(Be.has(r.stage))throw new oe(r.stage);await ce(t.pollIntervalMs??1500,t.signal),r=await b(()=>n.getReveal(e.id,t.signal),t.signal)}}var oe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function A(n,e,t){n.onProgress?.({phase:e,session:t})}function ce(n,e){return e?.aborted?Promise.reject(p()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(p())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var de=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 ae;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 I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=We(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("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 I("asset_value_invalid");return{selector:a.selector,value:je(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Pe(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("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 I("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",Pe(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=Se(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 We(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function je(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?se[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function Pe(n){if(n instanceof I)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 Ye(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Xe(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await b(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Y;let l=await b(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(be(l,i.id,e.planId),!l.shares.includes(i.data))throw new R;A(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:m}=await b(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw p();if(!m?.trim())throw new R;if(await n.claimRevealCustodianShare(e.id,l.id,m),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw p();return{...t,shares:t.shares.filter(S=>S!==i).concat(l.shares.map((S,_)=>({id:`${l.id}:${_}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:S})))}}if(d!=="SK_MOBILE")throw new R;if(r.signal?.aborted)throw p();return await n.distributeRevealCustodianShare(e.id),A(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await b(()=>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),A(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ce(r.pollIntervalMs??1500,r.signal),s=await b(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Y;if(!s.shareId||!s.deviceId)throw new R;A(r,"CONNECTING_SAFEKEY_PRO",e);let d=await b(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw p();if(be(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new R;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw p();return{...t,shares:t.shares.concat(d.shares.map((l,m)=>({id:`${d.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new R;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),A(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw p();await n.requestRevealCustodianRelease(e.id);let o=await Qe(n,e.id,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 be(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 R}async function b(n,e){if(e?.aborted)throw p();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(p()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw p();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Qe(n,e,t){let r=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await b(()=>n.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new R}if(Date.now()>=r)throw new le;await ce(t.pollIntervalMs??1500,t.signal)}}var R=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Y=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},le=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ze(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Se(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!Je(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 Je(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function p(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var N=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 G,this.state=t.state??new F,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??nt(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 c;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new c;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new c;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return D(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new c;return M(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new H){if(this.requireApplication(),!this.api)throw new c;return new W(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 w({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 tt(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new w(e);return await this.keyVault.store(e,et(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new c;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 c;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new V;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 w({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=q(e);if(!i)throw new w({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new c;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new c;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new c;return this.api.getReveal(e,t)}openReveal(e,t){return Ee(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 c;return ve(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new c;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new c;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new c;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new c;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new c;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new c;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return he(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new c;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new c;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new c;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new c;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new c;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new c;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 c;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 ue;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new w({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ue=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function et(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 tt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function nt(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 re({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return re({...e,organizationId:n.organizationId})}function we(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=q(r);if(!r.masterKeyWrapped||!i||r.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new T({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)}});return new N(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)}}}).openReveal(e,t)}}}var rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],it=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],at=["ACTIVE","REVOKED"],ot=["SK_MOBILE"],dt=["ACTIVE","INACTIVE"];function pe(n){let e=v(n),t=lt(e),r=v(e.source),i=g(r.kind,"source.kind");return{...t,assets:x(e.assets).map(s=>{let a=v(s);return{id:g(a.id,"asset.id"),code:k(a.code),type:f(g(a.type,"asset.type"),z),name:g(a.name,"asset.name"),isBinary:ct(a.isBinary,"asset.isBinary"),fieldNames:x(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:k(a.fileName),mimeType:k(a.mimeType),size:a.size===void 0||a.size===null?void 0:E(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:x(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:x(e.participants).map(s=>{let a=v(s);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:x(a.relationships).map(o=>f(g(o,"relationship"),st)),lifecycle:f(g(a.lifecycle,"participant.lifecycle"),at)}}),revealPolicy:(()=>{let s=v(e.revealPolicy);return{masterKeyRelease:f(g(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(g(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=v(e.dms);return{subjectEmail:g(s.subjectEmail,"dms.subjectEmail"),countdownDays:E(s.countdownDays,"dms.countdownDays"),countdownHours:E(s.countdownHours,"dms.countdownHours"),countdownMinutes:E(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:f(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:f(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function lt(n){let e=v(n),t=v(e.assetSummary),r=v(e.governance),i=v(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:k(e.description),status:f(g(e.status,"status"),rt),createdAt:g(e.createdAt,"createdAt"),configuredAt:k(e.configuredAt),assetSummary:{count:E(t.count,"assetSummary.count"),types:x(t.types).map(s=>f(g(s,"assetType"),z)),names:Ae(t.names).map(s=>g(s,"assetSummary.names"))},governance:{mode:f(g(r.mode,"governance.mode"),it),minimumApprovals:E(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:E(i.owners,"owners"),mergers:E(i.mergers,"mergers"),moderators:E(i.moderators,"moderators")},authentication:Ae(e.authentication).map(s=>{let a=v(s);return{id:f(g(a.id,"authentication.id"),ot),status:f(g(a.status,"authentication.status"),dt)}})}}function f(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function v(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function Ae(n){return n==null?[]:x(n)}function x(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function k(n){return n==null?void 0:g(n,"optional")}function E(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function ct(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function _e(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 Ce(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var X=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}};var Q=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 pe(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 m;try{m=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||m&&m.ok===!1||i&&m?.result===void 0)throw new X(l.status,m&&_e(m),m&&Ce(m));return m?.result}};import{createNodeSsdpV2Processor as ht}from"@safetech/inheriti-core-sdk/node";async function xe(n,e){if(!e)throw new Error("master_key_required");let t=ut(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=pt(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return mt(new Uint8Array(o))}function ut(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 pt(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 mt(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var K=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Te("plan_key_unwrap_failed",()=>xe(e.planKey,t)),i=await crypto.subtle.importKey("raw",me(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Te("plan_share_decryption_failed",()=>ft(o.data,i));yt(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 Z("plan_share_reconstruction_failed",It(o))}}},Z=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},gt=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 It(n){let e=n instanceof Error?n.message:void 0;if(e)return gt.has(e)?e:void 0}async function Te(n,e){try{return await e()}catch{throw new Z(n)}}function yt(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function ft(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=me(n.slice(0,t)),i=me(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function me(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 U=class extends K{constructor(e){super(()=>ht(e))}};function Bn(n){let e=new Q(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{...we({api:e,reconstructor:new U(n.workerUrl),assetDecoder:vt}),getPlan:t=>e.getPlan(t)}}export{Bn as createNodeAutomationRevealClient};