@safetech/inheriti-client-sdk 1.17.13 → 1.17.14
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.d.ts
CHANGED
|
@@ -70,7 +70,7 @@ export { QuickPlanCreator } from './src/business/quick-plan/quick-plan-creator';
|
|
|
70
70
|
export { HttpQuickPlanPort, PlanRequestFailed } from './src/business/quick-plan/http-quick-plan-port';
|
|
71
71
|
export { HttpPlanEditPort };
|
|
72
72
|
export { QuickPlanEditor };
|
|
73
|
-
export type { AddPlanAssetInput, ReplacePlanAssetInput, PlanEditAssetReference, PlanEditAssetSummary, EditRecoveryRecord, EditRecoveryStore, QuickPlanEditPhase } from './src/business/plan-edit/quick-plan-editor';
|
|
73
|
+
export type { AddPlanAssetInput, ReplacePlanAssetInput, PlanEditAssetReference, PlanEditAssetSummary, EditRecoveryRecord, EditRecoveryStore, QuickPlanEditPhase, QuickPlanEditApprovalProgress, QuickPlanEditProgress } from './src/business/plan-edit/quick-plan-editor';
|
|
74
74
|
export type { EditSession, ReconfigureMaterial, PlanEditCandidate, PlanEditCandidatePage, PlanEditContext } from './src/business/plan-edit/http-plan-edit-port';
|
|
75
75
|
export type { QuickPlanInput, QuickPlanCreateContext, QuickPlanPort } from './src/business/quick-plan/contract';
|
|
76
76
|
export type { CorePlanSecrets } from './src/elements/core-plan-material-builder';
|
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createNodeSharedConfigurationSdk as We,decodeAssetContainer as vr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as wt,generateRSAOAEPKeyPair as _t}from"@safetech/inheriti-core-sdk/crypto";var oe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},de=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},le=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},b=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:a}=await _t();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let i=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(S=>new Promise(_=>setTimeout(_,S))),l=!0,c=!1,g,v=()=>g??=Promise.resolve().then(()=>this.options.api.cancelRelaySession?.(i.sessionId)),y,w=new Promise((S,_)=>{y=()=>{l&&v().catch(()=>{}),_(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",y,{once:!0})});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let S=await Promise.race([this.options.api.readRelaySession(i.sessionId),w]);if(S.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(S.status==="DELIVERED"&&S.sealedMasterKey){let _=(await wt(S.sealedMasterKey,a)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(_))throw new Error("invalid_master_key_material");return _}if(S.status==="EXPIRED")throw new de(i.sessionId);await At(d,s,e)}throw new oe(i.sessionId)}catch(S){if(l&&(!c||e?.aborted))try{await v()}catch(_){if(e?.aborted)throw new le(_)}throw S}finally{y&&e?.removeEventListener("abort",y)}}};async function At(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,a)=>{let i=()=>a(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",i,{once:!0}),r(e).then(n,a).finally(()=>t.removeEventListener("abort",i))})}function ce(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let a=await r.source?.resolve();return a||Ce(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Ct(e,r.applicationId)){let a=await r.source?.resolve();return a||Ce(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Ce(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Ct(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ce(r,e,t,n,a){if((await e()).relayAvailable)return new b({...r.relay,api:Tt(r.api,t)}).resolve(n,a)}function Tt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t),cancelRelaySession:t=>r.cancelMasterKeyRelaySession(t)}}function x(r){return`${r.system}:${r.contextId}`}function De(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var O=class extends Error{constructor(t){super(`master_key_required:${x(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Te=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(x(e),t),this}async resolve(e){return this.sources.get(x(e))?.resolve()}};var H=class{keys=new Map;async store(e,t){this.keys.set(x(e),t.slice())}async load(e){return this.keys.get(x(e))?.slice()}async remove(e){this.keys.delete(x(e))}};var $=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var pe=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},u=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ue=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var me=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Dt={"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"]},be=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function z(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new P("plan_material_field_unknown");if(ke(r.dataShards,"data_shards_invalid"),ke(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ke(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new P("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new P("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new P("material_operation_invalid")}function ke(r,e){if(!Array.isArray(r))throw new P(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new P(e);if(t.data!==void 0&&typeof t.data!="string")throw new P(e)}}function N(r){if(G(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ot(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(G(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!me.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new m("asset_field_names_invalid");if(kt(t.matchOrigins),!t.isBinary){let i=Dt[t.type];if(!i||a.some(s=>!i.includes(s)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(G(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ye(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}bt(r)}function kt(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function bt(r){let e=r.policy;if(e&&G(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){G(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){G(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new m("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.length))throw new m("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;G(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Ye(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(i=>je(i.routingEmail)===je(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new m("dms_countdown_invalid")}function Ot(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ye(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function je(r){return r.normalize("NFC").trim().toLowerCase()}function G(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var W=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)}},Q=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),N(e),he(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,i={}){N(t);let s=await this.checkpoints.load(e);if(!s)throw new j("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Xe(t))throw new j("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.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;he(i.signal),i.onProgress?.("ENCRYPTING");let d=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});he(i.signal),i.onProgress?.("GENERATING_SHARES");let l=await a.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});he(i.signal),z(l);let c=await this.api.supplyPlanCreationMaterial(e,l);return i.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 Xe(e),serverStage:t.stage})}},j=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Xe(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function he(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ze(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new pe(n.stage);return r.authorizeRevealAction(e,t)}function xt(r){let e=r?.status;return e===400||e===401||e===403}async function Je(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!xt(i))throw i}return r.releaseRevealMaterial(e,t)}function Nt(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?Kt(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Mt.has(r.stage)?"ENDED":"CONTINUING"}var Mt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Kt(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Oe=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 nt(r,e,t={}){if(t.signal?.aborted)throw R();let n=await r.getPlan(e),a=await r.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):et(a.id);if(t.signal?.aborted||(t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e,t.signal,t.onRelaySession),t.signal?.aborted))throw R();let i=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:i})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await r.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:et(l.id)}let o;try{if(t.signal?.aborted)throw R();let d=await Lt(r,s,t);if(t.signal?.aborted)throw R();M(t,"RELEASING_MATERIAL",d);let l=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted)throw R();d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id);let c;try{c=await Vt(r,d,Ft(l),t)}finally{t.proDevice?.clearPin?.()}M(t,"RECONSTRUCTING",d);try{o=await r.reconstructPlanMaterial(c)}catch(v){throw await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:qt(v)}),v}let g=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});return M(t,"OPEN",g),new Ne(r,g,n,o,t.signal)}catch(d){throw o?.fill(0),await Ht(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function et(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Ut=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Lt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.signal?.aborted)throw R();if(t.onSession?.(n),t.onProgress?.({phase:Nt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Ut.has(n.stage))throw new xe(n.stage);await Ke(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var xe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function M(r,e,t){r.onProgress?.({phase:e,session:t})}function Ke(r,e){return e?.aborted?Promise.reject(R()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(R())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var Ne=class{constructor(e,t,n,a,i){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=i?()=>{this.close("CANCELED")}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Oe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=Gt(i),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:s}}),a=[];try{for(let s of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let i=n.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new I("asset_value_invalid");return{selector:s.selector,value:zt(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",tt(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.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 n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new I("asset_not_found");if(!n.isBinary)throw new I("action_not_allowed");let a=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),i;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new I("asset_value_invalid");i=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:i})}catch(s){throw await this.reportAction(a.id,"FAILED",tt(s)),s}finally{i?.fill(0)}await this.reportAction(a.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!at(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function Gt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new I("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new I("asset_selector_invalid");return{asset:r.asset,field:r.field}}function zt(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new I("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new I("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new I("asset_value_invalid")}return n[e]}function tt(r){if(r instanceof I)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function qt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Vt(r,e,t,n){let a=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(a){let d=await ge(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new ye;let l=await ge(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(rt(l,a.id,e.planId),!l.shares.includes(a.data))throw new T;M(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await ge(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw R();if(!c?.trim())throw new T;if(await r.claimRevealCustodianShare(e.id,l.id,c),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw R();return{...t,shares:t.shares.filter(g=>g!==a).concat(l.shares.map((g,v)=>({id:`${l.id}:${v}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:g})))}}if(d!=="SK_MOBILE")throw new T;return await r.distributeRevealCustodianShare(e.id),M(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),M(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Ke(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new ye;if(!i.shareId||!i.deviceId)throw new T;M(n,"CONNECTING_SAFEKEY_PRO",e);let d=await ge(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw R();if(rt(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new T;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw R();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(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new T;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),M(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await Bt(r,e.id,n);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 rt(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new T}async function ge(r,e){if(e?.aborted)throw R();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(R()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw R();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Bt(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let i=a;if(i.shares?.length)return i;throw new T}if(Date.now()>=n)throw new Me;await Ke(t.pollIntervalMs??1500,t.signal)}}var T=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ye=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Me=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Ft(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Ht(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!at(n))throw n}}function at(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function R(){let r=new Error("reveal_canceled");return r.name="AbortError",r}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 H,this.state=t.state??new $,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Qt(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 u;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new u;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new u;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return N(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new u;return z(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new W){if(this.requireApplication(),!this.api)throw new u;return new Q(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new O({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let a=await this.keyVault.load(e);if(a)return Wt(a);let i=await this.masterKeys?.resolve(e,t,n);if(!i)throw new O(e);return await this.keyVault.store(e,$t(i)),i}async prepareReveal(e,t,n){if(!this.api)throw new u;let a=await this.api.planKeyReference(e);if(!a.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(a,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new u;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ue;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new O({system:"INHERITI_BUSINESS",contextId:this.organizationId});let a=De(e);if(!a)throw new O({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(a,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new u;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new u;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e){if(!this.api)throw new u;return this.api.getReveal(e)}openReveal(e,t){return nt(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let i=await n(a);return await a.close("COMPLETED"),i}catch(i){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new u;return Je(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new u;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new u;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new u;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new u;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new u;return this.api.getRevealCustodianShare(e)}getRevealCustodianClaimable(e){if(!this.api)throw new u;return this.api.getRevealCustodianClaimable(e)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new u;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new u;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new u;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new u;return this.api.closeReveal(e,t)}abortPlanAccess(e,t){if(!this.api)throw new u;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e){if(!this.api)throw new u;return this.api.cancelMasterKeyRelaySession(e)}async authorizeRevealAction(e,t){if(!this.api)throw new u;return Ze(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new u;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new u;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new u;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new u;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new u;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new u;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=n.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=a.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=a.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:i.concat(s,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new u;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new Ue;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new O({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 $t(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Wt(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Qt(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ce({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ce({...e,organizationId:r.organizationId})}var jt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Yt=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Xt=["ACTIVE","REVOKED"],Zt=["SK_MOBILE"],Jt=["ACTIVE","INACTIVE"],er=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ot(r){let e=E(r);return{items:C(e.items).map(ct),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function dt(r){let e=E(r);return{total:D(e.total,"total"),items:C(e.items).map(t=>{let n=E(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),planId:p(n.planId,"log.planId"),tenantId:p(n.tenantId,"log.tenantId"),event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:K(n.status),title:p(n.title,"log.title"),details:C(n.details).map(a=>{let i=E(a);return{label:p(i.label,"log.detail.label"),value:p(i.value,"log.detail.value")}})}})}}function lt(r){let e=E(r),t=ct(e),n=E(e.source),a=p(n.kind,"source.kind");return{...t,assets:C(e.assets).map(i=>{let s=E(i);return{id:p(s.id,"asset.id"),code:K(s.code),type:A(p(s.type,"asset.type"),me),name:p(s.name,"asset.name"),isBinary:rr(s.isBinary,"asset.isBinary"),fieldNames:C(s.fieldNames).map(o=>p(o,"asset.fieldNames")),fileName:K(s.fileName),mimeType:K(s.mimeType),size:s.size===void 0||s.size===null?void 0:D(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:C(s.matchOrigins).map(o=>p(o,"asset.matchOrigins"))}}),participants:C(e.participants).map(i=>{let s=E(i);return{id:p(s.id,"participant.id"),displayName:p(s.displayName,"participant.displayName"),relationships:C(s.relationships).map(o=>A(p(o,"relationship"),st)),lifecycle:A(p(s.lifecycle,"participant.lifecycle"),Xt)}}),revealPolicy:(()=>{let i=E(e.revealPolicy);return{masterKeyRelease:A(p(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:A(p(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=E(e.dms);return{subjectEmail:p(i.subjectEmail,"dms.subjectEmail"),countdownDays:D(i.countdownDays,"dms.countdownDays"),countdownHours:D(i.countdownHours,"dms.countdownHours"),countdownMinutes:D(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:A(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:A(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function X(r){let e=E(r);return{operationId:p(e.operationId,"operationId"),stage:A(p(e.stage,"stage"),be),outcome:A(p(e.outcome,"outcome"),er),planId:K(e.planId),lastErrorCode:K(e.lastErrorCode),participants:e.participants===void 0?void 0:C(e.participants).map(t=>{let n=E(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:C(n.relationships).map(a=>tr(p(a,"relationship"),st))}})}}function ct(r){let e=E(r),t=E(e.assetSummary),n=E(e.governance),a=E(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:K(e.description),status:A(p(e.status,"status"),jt),createdAt:p(e.createdAt,"createdAt"),configuredAt:K(e.configuredAt),assetSummary:{count:D(t.count,"assetSummary.count"),types:C(t.types).map(i=>A(p(i,"assetType"),me)),names:it(t.names).map(i=>p(i,"assetSummary.names"))},governance:{mode:A(p(n.mode,"governance.mode"),Yt),minimumApprovals:D(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:D(a.owners,"owners"),mergers:D(a.mergers,"mergers"),moderators:D(a.moderators,"moderators")},authentication:it(e.authentication).map(i=>{let s=E(i);return{id:A(p(s.id,"authentication.id"),Zt),status:A(p(s.status,"authentication.status"),Jt)}})}}function A(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function tr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function it(r){return r==null?[]:C(r)}function C(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function K(r){return r==null?void 0:p(r,"optional")}function D(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function rr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var B=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function pt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function nr(r,e){if(!e){if(r.length===0)throw new B("organization_required");if(r.length>1)throw new B("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new B("organization_access_denied");return e}function Le(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function Ge(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var q=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},F=class{constructor(e,t,n,a,i){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a;this.business=i?Object.freeze({...i}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(pt)}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 a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return ot(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return lt(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return dt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){N(e);let{idempotencyKey:t,...n}=e;return X(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return X(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return z(t),X(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return X(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){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}async cancelMasterKeyRelaySession(e){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}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){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}getRevealCustodianClaimable(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET")}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...i}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,i){this.requireBusinessSelection(e);let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&o.set("x-organization-id",this.business.organizationId),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[g,v]of Object.entries(i??{}))o.set(g,v);n&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,d),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),c=await ut(l);if(!l.ok)throw new q(l.status,Le(c),Ge(c));if(!c.ok||c.result===void 0)throw new q(l.status,Le(c),Ge(c));return c.result}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});n&&a.set("authorization",`Bearer ${n}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),t&&a.set("content-type","application/json");let i=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,i),{method:"POST",headers:a,body:t?JSON.stringify(t):void 0}),o=await ut(s);if(!s.ok||!o.ok)throw new q(s.status,Le(o),Ge(o))}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 ut(r){try{return await r.json()}catch{return{ok:!1}}}import{createNodeSsdpV2Processor as pr}from"@safetech/inheriti-core-sdk/node";async function ze(r,e){if(!e)throw new Error("master_key_required");let t=ar(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=ir(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return sr(new Uint8Array(o))}function ar(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function ir(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function sr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Z=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await mt("plan_key_unwrap_failed",()=>ze(e.planKey,t)),a=await crypto.subtle.importKey("raw",qe(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let d=await mt("plan_share_decryption_failed",()=>cr(o.data,a));lr(o.shareType)?s.push(d):i.push(d)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new fe("plan_share_reconstruction_failed",dr(o))}}},fe=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},or=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 dr(r){let e=r instanceof Error?r.message:void 0;if(e)return or.has(e)?e:void 0}async function mt(r,e){try{return await e()}catch{throw new fe(r)}}function lr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function cr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=qe(r.slice(0,t)),a=qe(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function qe(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let a=0;a<e.length;a+=1)n[a]=e.charCodeAt(a);return t}var J=class extends Z{constructor(e){super(()=>pr(e))}};var f={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 U=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},ee=class{constructor(e,t,n,a=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}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,n,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n},type:"BACKUP",privacyMode:a?"PUBLIC":"PRIVATE",audience:a})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",ht(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",ht(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(f.invalidMasterKeyContext);let a=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!a?.sessionId)throw new Error(f.relayFailed);return a}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(f.relayFailed);return n}async request(e,t,n,a){let i=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(f.reauthenticationRequired);i.set("authorization",`Bearer ${s}`),a!==void 0&&i.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:n,headers:i,body:a===void 0?void 0:JSON.stringify(a)}),c={};try{c=await l.json()}catch{}if(!l.ok||c.ok!==!0)throw new U(l.status,c.error);return c.result}};function ht(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var re=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){te(e.signal),mr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return te(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){te(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(te(e.signal),!a.custodianPair)throw new P("custodian_share_required");let i=Ve(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ve(a.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(Ve(a.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return te(e.signal),{protectionProtocol:a.protocol,validatorShares:Be(s.encryptedShares),dataShards:Be(o.encryptedShares),backupShards:Be(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:ur(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Fe(n.encryptedShares[0]),dataShard:Fe(n.encryptedShares[1])}}};function Ve(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Be(r){return r.map(Fe)}function Fe(r){return{id:r.id,data:r.encryptedData}}function ur(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new P("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function mr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new P("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new P("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new P("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let a=t.get(n.id);if(!a||a.type!==n.type)throw new P("plan_secrets_declaration_mismatch")}}function te(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function gt(r,e,t,n,a,i,s){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(f.invalidShares);let{asset:d,plan:l}=e;l.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let c=r.masterKeySource??new b({api:{startRelaySession:y=>a.startRelaySession(r.organizationId,t.masterKeyAcquisition,y),readRelaySession:y=>a.readRelaySession(r.organizationId,y)}}),g=new re(i,c);s?.("encrypting");let v=await g.encrypt({planId:r.planId,declaration:l,secrets:{assets:[d],totalShares:r.totalShares,threshold:o}});return s?.("generating_shares"),g.generateShares({planId:r.planId,declaration:l,encrypted:v})}import{PlanAssetDeclaration as hr}from"@safetech/inheriti-core-sdk/node";function ve(r){let e=hr.create([{type:r.asset.type,meta:r.asset.meta}]),t=r.asset.meta.isMedia===!0,n;if(t){let s="data"in r.asset.secret?r.asset.secret.data:void 0;if(s instanceof Blob&&(n=s.size),typeof s=="string")try{n=atob(s).length}catch{throw new m("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(n)||!n)throw new m("binary_asset_metadata_invalid")}let a=e.complete({[e.entries[0].id]:r.asset.secret})[0],i={idempotencyKey:r.planId,name:r.title,assets:[{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:t?[]:Object.keys(a.secret),isBinary:t,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:n}],participants:[]};return{asset:a,plan:i}}async function ft(r){let e=await Promise.all(Object.entries(r.asset.secret).sort(([t],[n])=>t.localeCompare(n)).map(async([t,n])=>[t,n instanceof Blob?await yt(new Uint8Array(await n.arrayBuffer())):n]));return yt(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,audience:r.audience??null,totalShares:r.totalShares,asset:{type:r.asset.type,meta:r.asset.meta,secret:e}})))}async function yt(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var ne=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!e.asset?.meta?.name?.trim())throw new Error(f.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(f.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(f.invalidShares);let n=await ft(e),a=this.flights.get(e.planId);if(a){if(a.fingerprint!==n)throw new Error(f.reconciliationRequired);return a.promise}let i=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:i});try{return await i}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let a=ve({planId:e.planId,title:e.title,asset:e.asset}),i=this.material.get(e.planId);if(i&&(i.fingerprint!==t||i.masterKeySource!==e.masterKeySource))throw new Error(f.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(Ie(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!i)throw new Error(f.reconciliationRequired);if(!s&&i)throw new Error(f.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(f.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(f.invalidMasterKeyContext);if(!s){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience)}catch(c){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw c}}s??=await this.port.status(e.organizationId,e.planId);let d=i?.encrypted??await gt(e,a,o,s,this.port,this.coreSdk,n);i||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(c){if(!Ie(await this.statusOrMissing(e.organizationId,e.planId)))throw c}n?.("verifying");let l=await this.port.status(e.organizationId,e.planId);return Ie(l)&&this.material.delete(e.planId),{planId:e.planId,status:Ie(l)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(f.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof U&&n.status===404)return;throw n}}};function Ie(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Pe=class{constructor(e,t,n,a=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}start(e,t,n,a){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},a)}async listEligibleCandidates(e,t,n){let a=new URLSearchParams({status:"PROTECTED"});t&&a.set("cursor",t),n&&a.set("namePrefix",n);let i=await this.request(e,`plans/editable?${a}`,"GET");if(!this.isCandidatePage(i))throw new Error("invalid_plan_edit_candidates");return i}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(f.invalidMasterKeyContext);let a=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!a?.sessionId)throw new Error(f.relayFailed);return a}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(f.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}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,n,a,i){let s=await this.getBearerToken();if(!s)throw new Error(f.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});a!==void 0&&o.set("content-type","application/json"),i&&o.set("idempotency-key",i);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:n,headers:o,body:a===void 0?void 0:JSON.stringify(a)}),g={};try{g=await c.json()}catch{}if(!c.ok||g.ok!==!0){let v=Array.isArray(g.validationErrors)?g.validationErrors.join("; "):void 0;throw new U(c.status,v||g.error)}return g.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(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(a=>typeof a=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(a=>typeof a=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.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 Re=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}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){let n=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 a=await this.assertEditSession(e),i=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!i)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=i.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;i.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?s.assets:await this.revealAssets(e,d,i.withCustodian,t);if(new Set(c.map(g=>g.id)).size!==c.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&a>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(a,l),assets:c,masterKey:d}),{plan:i,masterKey:d,assets:c}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED","EXPIRED"].includes(t.stage)||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new b({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,a){let i=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s,o=y=>{y!==s&&(s=y,a?.(y))},d=y=>{switch(y.status){case"PENDING_DMS":o("pending_dms");break;case"PENDING_APPROVALS":o("pending_approvals");break;case"PENDING_AUTH":o("pending_auth");break;case"PENDING_MODERATION":o("pending_moderation");break}},l=await i.resume(e.planId,{onViewUpdate:d});if(l?.processId!==e.editId)throw new Error("edit_merge_not_ready");d(l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await i.run(e.editId,{onViewUpdate:d,onApprovalsRequested:()=>o("pending_approvals")});let c=(await i.getView(e.editId))?.status;if(c!=="READY_TO_REVEAL"&&c!=="REVEALED")throw new Error("edit_merge_not_ready");o("revealing");let g=null,v={onRevealed:y=>{g=y},onViewUpdate:d,onRevealStepUpdate:(y,w)=>{if(w==="IN_PROCESS")switch(y){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":o("collecting_validators");break;case"COLLECTING_SHARES":o("collecting_shares");break;case"RECONSTRUCTING":o("reconstructing");break;case"OPENING_WINDOW":o("opening_window");break;case"PREPARING_VIEW":o("preparing_view");break}}};if(n&&(v.onCustodianShareRequired=async(y,w)=>{switch(w.mode){case"distribute":{this.assertNotAborted(e.signal),o("configuring_custodian_share");let S=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),S==="SK_MOBILE")return i.distributeCustodianShareViaMobile(w.planId);if(S!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let _=e.proDevice;try{this.assertNotAborted(e.signal);let se=await i.getCustodianShareData(y);this.assertShare(se,w.planId),o("connecting_safekey_pro");let{deviceId:Qe}=await _.write(se,e.signal);if(this.assertNotAborted(e.signal),!Qe?.trim())throw new Error("custodian_share_unavailable");await i.recordCustodianShareClaim(w.planId,se.id,Qe,"SK_PRO"),this.assertNotAborted(e.signal),await i.markCustodianShareAsCollected(y,se.id);return}finally{_.clearPin?.()}}case"awaiting-claim":o("claiming_custodian_share");return;case"awaiting-release":o("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let S=e.proDevice;try{if(this.assertNotAborted(e.signal),!w.shareId||!w.deviceId)throw new Error("custodian_share_unavailable");o("connecting_safekey_pro");let _=await S.read({shareId:w.shareId,planId:w.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(_,w.planId,w.shareId),_.deviceId!==w.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:_.shares}}finally{S.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),c==="REVEALED"?await i.resumeReveal(e.editId,v,t):await i.openRevealWindow(e.editId,{timeoutMinutes:10},v,t),!g)throw new Error("edit_assets_unavailable");return g}assertShare(e,t,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(a=>typeof a!="string"||!a))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Ee=class{constructor(e,t,n,a){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=a}async saveAssets(e,t,n,a,i,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,a);s?.("preparing");let l=await o.prepare(d),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(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,c),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:i,material:c}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,i,c,o,d,s)}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 n=await this.configurationRepository().findByPlanId(e.planId),a=n?.editDistribution??n?.preparedDistribution;if(!t&&(!a||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let i=t?.material??{mergeProcessId:e.editId,protectionProtocol:a.protectionProtocol,validatorShares:a.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:a.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:a.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:a.encryptedKey,assetsMetadata:a.assetsMetadata,custodianPair:a.custodianPair};try{if(await this.isCommitted(e,i))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,i),await this.port.commit(e.organizationId,e.planId,i),await this.isCommitted(e,i)?(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 n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.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 n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),a=await n.findByPlanId(e);if(t&&a&&a.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),a&&await n.delete(a.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,a){let i=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:a,reconfigureContext:{mergeProcessId:e.editId}};return{configure:i,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}async commit(e,t,n,a,i,s){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,s?.(c))};try{await a.execute(i,{onLocalProcessUpdated:d})}catch(l){try{if(s?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&s?.(o),l}try{if(s?.("verifying"),!await this.isCommitted(e,n))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 n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let a=[t.validatorShares,t.dataShards,t.backupShards].flat().map(s=>s.id);t.custodianPair&&a.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let i=n.shares.map(s=>s.id).sort();return a.sort(),!(a.length!==i.length||a.some((s,o)=>s!==i[o]))}};var Se=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new Re(e,t,n),this.reconfiguration=new Ee(e,t,n,a=>this.clearRevealedAssets(a))}assetAccess;reconfiguration;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,a){return this.port.start(e,t,n,a)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(a=>({id:a.id,type:a.type,name:a.meta.name,isMedia:this.isMedia(a)}))}async getAsset(e,t,n){let{assets:a}=await this.assetAccess.loadAssets(e,n),i=a.find(s=>s.id===t);if(!i)throw new Error("edit_asset_not_found");return i}async replaceAsset(e,t){if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:a,assets:i}=await this.assetAccess.loadAssets(e,t),s=i.findIndex(c=>c.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=i[s];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=i.map((c,g)=>g===s?d:c);return this.reconfiguration.saveAssets(e,l,n.withCustodian,a,o.id,t)}async addAsset(e,t){let{plan:n,masterKey:a,assets:i}=await this.assetAccess.loadAssets(e,t),s=ve({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(i.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,i.concat(s),n.withCustodian,a,s.id,t)}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.reconfiguration.recover(e)}discard(e){return this.reconfiguration.discard(e)}discardLocal(e){return this.reconfiguration.discardLocal(e)}};function vt({apiUrl:r,organizationId:e,planId:t,editId:n,environment:a,transport:i}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.toString()),l=new URL(r.endsWith("/")?r:`${r}/`);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 i(d,o)}if(c==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let g=gr(c,d.searchParams,t,n),v=new Headers(o?.headers);v.set("x-organization-id",e),v.set("x-elements-environment",a);let y=l.pathname.endsWith("/integrations/")?`v1/${g}`:`integrations/v1/${g}`;return i(new URL(y,l),Object.assign({},o,{headers:v}))}}function gr(r,e,t,n){if(r==="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 i=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(i){let o=i[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(i[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(i[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{DataAssetDefinitionService as Pa}from"@safetech/inheriti-core-sdk/node";import{PassphraseMasterKeySource as _a,RawMasterKeySource as Aa,deriveMasterKey as Ca,generateHexSeed as Ta,computePassphraseVerifier as Da}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as ba}from"@safetech/inheriti-core-sdk/node";function It(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var we=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),It(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return It(new Uint8Array(t))}},_e=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let i=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(i),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var ae=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},ie=class extends ae{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},h=class extends ae{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function He(r){if(r instanceof ae)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Pt=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:L(n,"issuer"),authorizationEndpoint:L(n,"authorization_endpoint"),tokenEndpoint:L(n,"token_endpoint"),deviceAuthorizationEndpoint:k(n,"device_authorization_endpoint"),endSessionEndpoint:k(n,"end_session_endpoint"),revocationEndpoint:k(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:L(t,"device_code"),userCode:L(t,"user_code"),verificationUri:L(t,"verification_uri"),verificationUriComplete:k(t,"verification_uri_complete"),expiresInSeconds:Rt(t,"expires_in"),intervalSeconds:$e(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:L(n,"access_token"),refreshToken:k(n,"refresh_token"),idToken:k(n,"id_token"),tokenType:L(n,"token_type"),expiresInSeconds:Rt(n,"expires_in"),refreshExpiresInSeconds:$e(n,"refresh_expires_in"),scope:k(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let i=k(a,"error")??`oauth_http_${n.status}`;throw new h(i,k(a,"error_description")??i)}return a}};function L(r,e){let t=k(r,e);if(!t)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function k(r,e){return typeof r[e]=="string"?r[e]:void 0}function Rt(r,e){let t=$e(r,e);if(t===void 0)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function $e(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var yr=600*1e3,Ae=5,fr=5,Et=class{constructor(e){this.options=e;this.crypto=e.crypto??new we,this.clock=e.clock??new _e}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),i=await this.crypto.sha256UrlSafe(a),s=this.clock.now()+yr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",i),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new h("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new h("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new h("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new h(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new h("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new h("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:n.codeVerifier,redirectUri:n.redirectUri}),c=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(c),c}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new h("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(Ae,t.intervalSeconds??Ae),a=this.clock.now(),i={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),i),i}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new h("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(Ae,a.intervalSeconds??Ae),o=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(o>=a.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:i.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let l=await this.acceptTokens(d);return await this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=He(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=fr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new h("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 ie;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new h("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=He(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new ie:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(V(e.issuer)!==V(this.options.configuration.issuer))throw new h("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${V(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new h("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new h("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new h("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(a.issuer))throw new h("issuer_mismatch");if(!i.includes(a.audience))throw new h("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new h("client_mismatch");if(e.environment!==a.environment)throw new h("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new h("required_claim_missing");if(n&&e.nonce!==t)throw new h("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(V(e.issuer)!==V(n.issuer))throw new h("issuer_mismatch");if(!a.includes(n.clientId))throw new h("client_mismatch");if(e.authorizedParty!==n.clientId)throw new h("client_mismatch");if(!e.subject||!e.sessionId)throw new h("required_claim_missing");if(e.nonce!==t)throw new h("nonce_mismatch")}};function V(r){return r.replace(/\/+$/u,"")}var St=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function ia(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(i,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(i,Object.assign({},s,{headers:o}))},n=r.business?void 0:We({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),a=new F(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new Y(n,{keyVault:r.keyVault,state:r.state,api:a,reconstructor:new J(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:vr})}function sa(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=We({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new ne(new ee(r.apiUrl,r.environment,r.getBearerToken,e),t)}function oa(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=We({apiUrl:t,getBearerToken:r.getBearerToken,transport:vt({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Se(new Pe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}export{B as BusinessOrganizationSelectionError,re as CorePlanMaterialBuilder,Pa as DataAssetDefinitionService,q as ElementsApiRequestFailed,Y as ElementsClient,j as GuidedCreateRecoveryError,Q as GuidedPlanCreator,F as HttpElementsApiPort,Pt as HttpOperatorAuthTransport,Pe as HttpPlanEditPort,ee as HttpQuickPlanPort,m as InvalidPlanDeclaration,P as InvalidPlanMaterial,le as MasterKeyRelayCancellationFailed,de as MasterKeyRelayExpired,oe as MasterKeyRelayTimedOut,O as MasterKeyRequired,W as MemoryGuidedCreateCheckpointStore,H as MemoryKeyVault,$ as MemoryStatePort,h as OAuthProtocolError,Et as OperatorAuthClient,ae as OperatorAuthError,ie as OperatorReauthenticationRequired,St as OperatorSessionController,be as PLAN_CREATION_SERVER_STAGES,_a as PassphraseMasterKeySource,ba as PlanAssetDeclaration,U as PlanRequestFailed,ne as QuickPlanCreator,Se as QuickPlanEditor,Aa as RawMasterKeySource,b as RelayMasterKeySource,Te as StaticMasterKeyResolver,_e as SystemOAuthClock,we as WebOAuthCrypto,Da as computePassphraseVerifier,ce as createMasterKeyResolver,ia as createNodeElementsClient,sa as createNodeQuickPlanCreator,oa as createNodeQuickPlanEditor,vr as decodeAssetContainer,Ca as deriveMasterKey,Ta as generateHexSeed,De as masterKeyRefFor,x as masterKeyRefKey,He as oauthErrorCode,nr as selectBusinessOrganization,ze as unwrapDekWithMasterKey,N as validatePlanCreationInput,z as validatePlanCreationMaterial};
|
|
1
|
+
import{createNodeSharedConfigurationSdk as Xe,decodeAssetContainer as Rr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Tt,generateRSAOAEPKeyPair as Dt}from"@safetech/inheriti-core-sdk/crypto";var pe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ue=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},me=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},O=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:a}=await Dt();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let i=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(h=>new Promise(f=>setTimeout(f,h))),l=!0,c=!1,m,v=()=>m??=Promise.resolve().then(()=>this.options.api.cancelRelaySession?.(i.sessionId)),_,Q=new Promise((h,f)=>{_=()=>{l&&v().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",_,{once:!0})});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),c=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let h=await Promise.race([this.options.api.readRelaySession(i.sessionId),Q]);if(h.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(h.status==="DELIVERED"&&h.sealedMasterKey){let f=(await Tt(h.sealedMasterKey,a)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(h.status==="EXPIRED")throw new ue(i.sessionId);await kt(d,s,e)}throw new pe(i.sessionId)}catch(h){if(l&&(!c||e?.aborted))try{await v()}catch(f){if(e?.aborted)throw new me(f)}throw h}finally{_&&e?.removeEventListener("abort",_)}}};async function kt(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,a)=>{let i=()=>a(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",i,{once:!0}),r(e).then(n,a).finally(()=>t.removeEventListener("abort",i))})}function he(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let a=await r.source?.resolve();return a||be(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(bt(e,r.applicationId)){let a=await r.source?.resolve();return a||be(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return be(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function bt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function be(r,e,t,n,a){if((await e()).relayAvailable)return new O({...r.relay,api:Ot(r.api,t)}).resolve(n,a)}function Ot(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t),cancelRelaySession:t=>r.cancelMasterKeyRelaySession(t)}}function M(r){return`${r.system}:${r.contextId}`}function xe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var x=class extends Error{constructor(t){super(`master_key_required:${M(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Oe=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(M(e),t),this}async resolve(e){return this.sources.get(M(e))?.resolve()}};var Y=class{keys=new Map;async store(e,t){this.keys.set(M(e),t.slice())}async load(e){return this.keys.get(M(e))?.slice()}async remove(e){this.keys.delete(M(e))}};var X=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 ge=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},u=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ye=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var fe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],xt={"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"]},Ne=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],g=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function z(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(Me(r.dataShards,"data_shards_invalid"),Me(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Me(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new E("material_operation_invalid")}function Me(r,e){if(!Array.isArray(r))throw new E(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function N(r){if(q(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Kt(r.idempotencyKey))throw new g("idempotency_key_invalid");if(!r.name?.trim())throw new g("plan_name_required");if(!r.assets.length)throw new g("assets_required");let e=new Set;for(let t of r.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 g("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!fe.includes(t.type))throw new g("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new g("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new g("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new g("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new g("asset_field_names_invalid");if(Mt(t.matchOrigins),!t.isBinary){let i=xt[t.type];if(!i||a.some(s=>!i.includes(s)))throw new g("asset_field_name_not_canonical")}}if(!r.participants.length)throw new g("participants_required");for(let t of r.participants){if(q(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!et(t.routingEmail))throw new g("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new g("participant_relationships_invalid")}Nt(r)}function Mt(r){if(r===void 0)return;if(!r.length)throw new g("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new g("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new g("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof g?n:new g("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new g("asset_match_origins_duplicated")}function Nt(r){let e=r.policy;if(e&&q(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new g("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){q(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new g("authentication_mode_invalid")}if(e.moderation){q(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new g("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.length))throw new g("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new g("approval_mode_invalid")}let t=e.dms;if(!t)return;q(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!et(t.subjectEmail))throw new g("dms_subject_invalid");if(!r.participants.some(i=>Je(i.routingEmail)===Je(t.subjectEmail)))throw new g("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new g("dms_countdown_invalid")}function Kt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function et(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Je(r){return r.normalize("NFC").trim().toLowerCase()}function q(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new g(t)}var Z=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)}},J=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),N(e),Ie(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,i={}){N(t);let s=await this.checkpoints.load(e);if(!s)throw new ee("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await tt(t))throw new ee("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.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;Ie(i.signal),i.onProgress?.("ENCRYPTING");let d=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});Ie(i.signal),i.onProgress?.("GENERATING_SHARES");let l=await a.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});Ie(i.signal),z(l);let c=await this.api.supplyPlanCreationMaterial(e,l);return i.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 tt(e),serverStage:t.stage})}},ee=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function tt(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Ie(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function rt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new ge(n.stage);return r.authorizeRevealAction(e,t)}function Ut(r){let e=r?.status;return e===400||e===401||e===403}async function nt(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!Ut(i))throw i}return r.releaseRevealMaterial(e,t)}function Lt(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?qt(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":Gt.has(r.stage)?"ENDED":"CONTINUING"}var Gt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function qt(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var Ke=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ot(r,e,t={}){if(t.signal?.aborted)throw R();let n=await r.getPlan(e),a=await r.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):at(a.id);if(t.signal?.aborted||(t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e,t.signal,t.onRelaySession),t.signal?.aborted))throw R();let i=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:i})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let l=await r.getActivePlanReveal(e);throw!l||l.planId!==e||l.mode!==(t.mode??"DIRECT")?d:at(l.id)}let o;try{if(t.signal?.aborted)throw R();let d=await Vt(r,s,t);if(t.signal?.aborted)throw R();K(t,"RELEASING_MATERIAL",d);let l=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted)throw R();d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id);let c;try{c=await $t(r,d,Wt(l),t)}finally{t.proDevice?.clearPin?.()}K(t,"RECONSTRUCTING",d);try{o=await r.reconstructPlanMaterial(c)}catch(v){throw await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Ht(v)}),v}let m=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});return K(t,"OPEN",m),new Le(r,m,n,o,t.signal)}catch(d){throw o?.fill(0),await jt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function at(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var zt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Vt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.signal?.aborted)throw R();if(t.onSession?.(n),t.onProgress?.({phase:Lt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(zt.has(n.stage))throw new Ue(n.stage);await qe(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var Ue=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function K(r,e,t){r.onProgress?.({phase:e,session:t})}function qe(r,e){return e?.aborted?Promise.reject(R()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(R())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var Le=class{constructor(e,t,n,a,i){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=i?()=>{this.close("CANCELED")}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new Ke;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=Bt(i),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new P("asset_not_found");if(d.isBinary)throw new P("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new P("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:s}}),a=[];try{for(let s of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let i=n.map(s=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new P("asset_value_invalid");return{selector:s.selector,value:Ft(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",it(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new P("asset_not_found");if(!n.isBinary)throw new P("action_not_allowed");let a=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),i;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new P("asset_value_invalid");i=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:i})}catch(s){throw await this.reportAction(a.id,"FAILED",it(s)),s}finally{i?.fill(0)}await this.reportAction(a.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!dt(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function Bt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new P("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new P("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Ft(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new P("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new P("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new P("asset_value_invalid")}return n[e]}function it(r){if(r instanceof P)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Ht(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function $t(r,e,t,n){let a=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(a){let d=await ve(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Pe;let l=await ve(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(st(l,a.id,e.planId),!l.shares.includes(a.data))throw new D;K(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:c}=await ve(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw R();if(!c?.trim())throw new D;if(await r.claimRevealCustodianShare(e.id,l.id,c),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw R();return{...t,shares:t.shares.filter(m=>m!==a).concat(l.shares.map((m,v)=>({id:`${l.id}:${v}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:m})))}}if(d!=="SK_MOBILE")throw new D;return await r.distributeRevealCustodianShare(e.id),K(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),K(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await qe(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new Pe;if(!i.shareId||!i.deviceId)throw new D;K(n,"CONNECTING_SAFEKEY_PRO",e);let d=await ve(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw R();if(st(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new D;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw R();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(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new D;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),K(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await Qt(r,e.id,n);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 st(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new D}async function ve(r,e){if(e?.aborted)throw R();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(R()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw R();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Qt(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let i=a;if(i.shares?.length)return i;throw new D}if(Date.now()>=n)throw new Ge;await qe(t.pollIntervalMs??1500,t.signal)}}var D=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Pe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ge=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Wt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function jt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!dt(n))throw n}}function dt(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function R(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var te=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 Y,this.state=t.state??new X,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Zt(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 u;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new u;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new u;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return N(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new u;return z(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new u;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new Z){if(this.requireApplication(),!this.api)throw new u;return new J(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new x({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let a=await this.keyVault.load(e);if(a)return Xt(a);let i=await this.masterKeys?.resolve(e,t,n);if(!i)throw new x(e);return await this.keyVault.store(e,Yt(i)),i}async prepareReveal(e,t,n){if(!this.api)throw new u;let a=await this.api.planKeyReference(e);if(!a.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(a,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new u;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ye;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new x({system:"INHERITI_BUSINESS",contextId:this.organizationId});let a=xe(e);if(!a)throw new x({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(a,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new u;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new u;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new u;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e){if(!this.api)throw new u;return this.api.getReveal(e)}openReveal(e,t){return ot(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let i=await n(a);return await a.close("COMPLETED"),i}catch(i){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new u;return nt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new u;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new u;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new u;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new u;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new u;return this.api.getRevealCustodianShare(e)}getRevealCustodianClaimable(e){if(!this.api)throw new u;return this.api.getRevealCustodianClaimable(e)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new u;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new u;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new u;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new u;return this.api.closeReveal(e,t)}abortPlanAccess(e,t){if(!this.api)throw new u;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e){if(!this.api)throw new u;return this.api.cancelMasterKeyRelaySession(e)}async authorizeRevealAction(e,t){if(!this.api)throw new u;return rt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new u;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new u;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new u;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new u;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new u;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new u;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=n.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=a.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=a.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:i.concat(s,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new u;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new ze;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new x({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ze=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Yt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Xt(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Zt(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return he({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return he({...e,organizationId:r.organizationId})}var Jt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],er=["DIRECT","GOVERNED"],ct=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],tr=["ACTIVE","REVOKED"],rr=["SK_MOBILE"],nr=["ACTIVE","INACTIVE"],ar=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function pt(r){let e=S(r);return{items:C(e.items).map(ht),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function ut(r){let e=S(r);return{total:k(e.total,"total"),items:C(e.items).map(t=>{let n=S(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:p(n.id,"log.id"),planId:p(n.planId,"log.planId"),tenantId:p(n.tenantId,"log.tenantId"),event:p(n.event,"log.event"),occurredOn:p(n.occurredOn,"log.occurredOn"),status:U(n.status),title:p(n.title,"log.title"),details:C(n.details).map(a=>{let i=S(a);return{label:p(i.label,"log.detail.label"),value:p(i.value,"log.detail.value")}})}})}}function mt(r){let e=S(r),t=ht(e),n=S(e.source),a=p(n.kind,"source.kind");return{...t,assets:C(e.assets).map(i=>{let s=S(i);return{id:p(s.id,"asset.id"),code:U(s.code),type:A(p(s.type,"asset.type"),fe),name:p(s.name,"asset.name"),isBinary:sr(s.isBinary,"asset.isBinary"),fieldNames:C(s.fieldNames).map(o=>p(o,"asset.fieldNames")),fileName:U(s.fileName),mimeType:U(s.mimeType),size:s.size===void 0||s.size===null?void 0:k(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:C(s.matchOrigins).map(o=>p(o,"asset.matchOrigins"))}}),participants:C(e.participants).map(i=>{let s=S(i);return{id:p(s.id,"participant.id"),displayName:p(s.displayName,"participant.displayName"),relationships:C(s.relationships).map(o=>A(p(o,"relationship"),ct)),lifecycle:A(p(s.lifecycle,"participant.lifecycle"),tr)}}),revealPolicy:(()=>{let i=S(e.revealPolicy);return{masterKeyRelease:A(p(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:A(p(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=S(e.dms);return{subjectEmail:p(i.subjectEmail,"dms.subjectEmail"),countdownDays:k(i.countdownDays,"dms.countdownDays"),countdownHours:k(i.countdownHours,"dms.countdownHours"),countdownMinutes:k(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:A(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:A(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function re(r){let e=S(r);return{operationId:p(e.operationId,"operationId"),stage:A(p(e.stage,"stage"),Ne),outcome:A(p(e.outcome,"outcome"),ar),planId:U(e.planId),lastErrorCode:U(e.lastErrorCode),participants:e.participants===void 0?void 0:C(e.participants).map(t=>{let n=S(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:C(n.relationships).map(a=>ir(p(a,"relationship"),ct))}})}}function ht(r){let e=S(r),t=S(e.assetSummary),n=S(e.governance),a=S(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:U(e.description),status:A(p(e.status,"status"),Jt),createdAt:p(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:k(t.count,"assetSummary.count"),types:C(t.types).map(i=>A(p(i,"assetType"),fe)),names:lt(t.names).map(i=>p(i,"assetSummary.names"))},governance:{mode:A(p(n.mode,"governance.mode"),er),minimumApprovals:k(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:k(a.owners,"owners"),mergers:k(a.mergers,"mergers"),moderators:k(a.moderators,"moderators")},authentication:lt(e.authentication).map(i=>{let s=S(i);return{id:A(p(s.id,"authentication.id"),rr),status:A(p(s.status,"authentication.status"),nr)}})}}function A(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function ir(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function S(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function lt(r){return r==null?[]:C(r)}function C(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function U(r){return r==null?void 0:p(r,"optional")}function k(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function sr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var H=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function gt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function or(r,e){if(!e){if(r.length===0)throw new H("organization_required");if(r.length>1)throw new H("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new H("organization_access_denied");return e}function Ve(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function Be(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var V=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},$=class{constructor(e,t,n,a,i){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a;this.business=i?Object.freeze({...i}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(gt)}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 a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return pt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return mt(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return ut(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){N(e);let{idempotencyKey:t,...n}=e;return re(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return z(t),re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return re(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}async cancelMasterKeyRelaySession(e){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}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){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}getRevealCustodianClaimable(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET")}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...i}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,i){this.requireBusinessSelection(e);let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&o.set("x-organization-id",this.business.organizationId),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[m,v]of Object.entries(i??{}))o.set(m,v);n&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,d),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),c=await yt(l);if(!l.ok)throw new V(l.status,Ve(c),Be(c));if(!c.ok||c.result===void 0)throw new V(l.status,Ve(c),Be(c));return c.result}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});n&&a.set("authorization",`Bearer ${n}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),t&&a.set("content-type","application/json");let i=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,i),{method:"POST",headers:a,body:t?JSON.stringify(t):void 0}),o=await yt(s);if(!s.ok||!o.ok)throw new V(s.status,Ve(o),Be(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new V(400,"organization_selection_required")}};async function yt(r){try{return await r.json()}catch{return{ok:!1}}}import{createNodeSsdpV2Processor as gr}from"@safetech/inheriti-core-sdk/node";async function Fe(r,e){if(!e)throw new Error("master_key_required");let t=dr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=lr(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return cr(new Uint8Array(o))}function dr(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function lr(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function cr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var ne=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await ft("plan_key_unwrap_failed",()=>Fe(e.planKey,t)),a=await crypto.subtle.importKey("raw",He(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let d=await ft("plan_share_decryption_failed",()=>hr(o.data,a));mr(o.shareType)?s.push(d):i.push(d)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new Ee("plan_share_reconstruction_failed",ur(o))}}},Ee=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},pr=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 ur(r){let e=r instanceof Error?r.message:void 0;if(e)return pr.has(e)?e:void 0}async function ft(r,e){try{return await e()}catch{throw new Ee(r)}}function mr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function hr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=He(r.slice(0,t)),a=He(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function He(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let a=0;a<e.length;a+=1)n[a]=e.charCodeAt(a);return t}var ae=class extends ne{constructor(e){super(()=>gr(e))}};var I={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 L=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},ie=class{constructor(e,t,n,a=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}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,n,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n},type:"BACKUP",privacyMode:a?"PUBLIC":"PRIVATE",audience:a})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",It(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",It(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(I.invalidMasterKeyContext);let a=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!a?.sessionId)throw new Error(I.relayFailed);return a}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(I.relayFailed);return n}async request(e,t,n,a){let i=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(I.reauthenticationRequired);i.set("authorization",`Bearer ${s}`),a!==void 0&&i.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:n,headers:i,body:a===void 0?void 0:JSON.stringify(a)}),c={};try{c=await l.json()}catch{}if(!l.ok||c.ok!==!0)throw new L(l.status,c.error);return c.result}};function It(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var oe=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){se(e.signal),fr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return se(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){se(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(se(e.signal),!a.custodianPair)throw new E("custodian_share_required");let i=$e(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares($e(a.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares($e(a.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return se(e.signal),{protectionProtocol:a.protocol,validatorShares:Qe(s.encryptedShares),dataShards:Qe(o.encryptedShares),backupShards:Qe(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:yr(e.encrypted.assets,e.declaration),custodianShard:l,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:We(n.encryptedShares[0]),dataShard:We(n.encryptedShares[1])}}};function $e(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Qe(r){return r.map(We)}function We(r){return{id:r.id,data:r.encryptedData}}function yr(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new E("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function fr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new E("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new E("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new E("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let a=t.get(n.id);if(!a||a.type!==n.type)throw new E("plan_secrets_declaration_mismatch")}}function se(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function vt(r,e,t,n,a,i,s){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(I.invalidShares);let{asset:d,plan:l}=e;l.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let c=r.masterKeySource??new O({api:{startRelaySession:_=>a.startRelaySession(r.organizationId,t.masterKeyAcquisition,_),readRelaySession:_=>a.readRelaySession(r.organizationId,_)}}),m=new oe(i,c);s?.("encrypting");let v=await m.encrypt({planId:r.planId,declaration:l,secrets:{assets:[d],totalShares:r.totalShares,threshold:o}});return s?.("generating_shares"),m.generateShares({planId:r.planId,declaration:l,encrypted:v})}import{PlanAssetDeclaration as Ir}from"@safetech/inheriti-core-sdk/node";function Re(r){let e=Ir.create([{type:r.asset.type,meta:r.asset.meta}]),t=r.asset.meta.isMedia===!0,n;if(t){let s="data"in r.asset.secret?r.asset.secret.data:void 0;if(s instanceof Blob&&(n=s.size),typeof s=="string")try{n=atob(s).length}catch{throw new g("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(n)||!n)throw new g("binary_asset_metadata_invalid")}let a=e.complete({[e.entries[0].id]:r.asset.secret})[0],i={idempotencyKey:r.planId,name:r.title,assets:[{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:t?[]:Object.keys(a.secret),isBinary:t,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:n}],participants:[]};return{asset:a,plan:i}}async function Et(r){let e=await Promise.all(Object.entries(r.asset.secret).sort(([t],[n])=>t.localeCompare(n)).map(async([t,n])=>[t,n instanceof Blob?await Pt(new Uint8Array(await n.arrayBuffer())):n]));return Pt(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,audience:r.audience??null,totalShares:r.totalShares,asset:{type:r.asset.type,meta:r.asset.meta,secret:e}})))}async function Pt(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var de=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!e.asset?.meta?.name?.trim())throw new Error(I.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(I.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(I.invalidShares);let n=await Et(e),a=this.flights.get(e.planId);if(a){if(a.fingerprint!==n)throw new Error(I.reconciliationRequired);return a.promise}let i=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:i});try{return await i}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let a=Re({planId:e.planId,title:e.title,asset:e.asset}),i=this.material.get(e.planId);if(i&&(i.fingerprint!==t||i.masterKeySource!==e.masterKeySource))throw new Error(I.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(Se(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!i)throw new Error(I.reconciliationRequired);if(!s&&i)throw new Error(I.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(I.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(I.invalidMasterKeyContext);if(!s){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience)}catch(c){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw c}}s??=await this.port.status(e.organizationId,e.planId);let d=i?.encrypted??await vt(e,a,o,s,this.port,this.coreSdk,n);i||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(c){if(!Se(await this.statusOrMissing(e.organizationId,e.planId)))throw c}n?.("verifying");let l=await this.port.status(e.organizationId,e.planId);return Se(l)&&this.material.delete(e.planId),{planId:e.planId,status:Se(l)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(I.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof L&&n.status===404)return;throw n}}};function Se(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var we=class{constructor(e,t,n,a=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}start(e,t,n,a){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},a)}async listEligibleCandidates(e,t,n){let a=new URLSearchParams({status:"PROTECTED"});t&&a.set("cursor",t),n&&a.set("namePrefix",n);let i=await this.request(e,`plans/editable?${a}`,"GET");if(!this.isCandidatePage(i))throw new Error("invalid_plan_edit_candidates");return i}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let a=n;if(a.id!==t||!Array.isArray(a.participants)||a.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let i=new Map;for(let s of a.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&i.set(s.id,s.displayName)}return i}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(I.invalidMasterKeyContext);let a=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!a?.sessionId)throw new Error(I.relayFailed);return a}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(I.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}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,n,a,i){let s=await this.getBearerToken();if(!s)throw new Error(I.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});a!==void 0&&o.set("content-type","application/json"),i&&o.set("idempotency-key",i);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:n,headers:o,body:a===void 0?void 0:JSON.stringify(a)}),m={};try{m=await c.json()}catch{}if(!c.ok||m.ok!==!0){let v=Array.isArray(m.validationErrors)?m.validationErrors.join("; "):void 0;throw new L(c.status,v||m.error)}return m.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(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(a=>typeof a=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(a=>typeof a=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.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 _e=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}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){let n=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 a=await this.assertEditSession(e),i=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!i)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=i.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;i.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?s.assets:await this.revealAssets(e,d,i.withCustodian,t);if(new Set(c.map(m=>m.id)).size!==c.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&a>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(a,l),assets:c,masterKey:d}),{plan:i,masterKey:d,assets:c}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=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"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new O({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,a){let i=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=a?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=h=>{h!==o&&(o=h,a?.(h))},l=h=>{if(h.processId!==e.editId||h.planId&&h.planId!==e.planId)return;switch(h.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 f=this.approvalError(h);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!h.moderatorParticipants||h.requiredModeratorApprovals===void 0||!h.approvalProcess)return;let T=h.moderatorParticipants.map(w=>w.memberId??w.userId);T.some(w=>typeof w!="string"||!w)||new Set(T).size!==T.length||a?.(o,{requiredApprovals:h.requiredModeratorApprovals,approvedModerators:h.approvalProcess.approvedModerators,moderators:h.moderatorParticipants.map((w,F)=>{let W=T[F],Ze=w.flows.filter(j=>j.status==="PENDING"&&j.expiresAt&&Number.isFinite(j.expiresAt.getTime())).map(j=>j.expiresAt.getTime());return{id:W,displayName:s.get(W)||"Moderator",status:w.status,expiresAt:Ze.length?new Date(Math.min(...Ze)).toISOString():void 0}})})},c=await i.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 i.run(e.editId,{onViewUpdate:l,onApprovalsRequested:()=>d("pending_approvals")});let m=await i.getView(e.editId);if(m?.processId!==e.editId||m.planId&&m.planId!==e.planId)throw new Error("edit_merge_not_ready");l(m),this.assertApprovalOutcome(e.planId,m);let v=m?.status;if(v!=="READY_TO_REVEAL"&&v!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let _=null,Q={onRevealed:h=>{_=h},onViewUpdate:l,onRevealStepUpdate:(h,f)=>{if(f==="IN_PROCESS")switch(h){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(n&&(Q.onCustodianShareRequired=async(h,f)=>{switch(f.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let T=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),T==="SK_MOBILE")return i.distributeCustodianShareViaMobile(f.planId);if(T!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let w=e.proDevice;try{this.assertNotAborted(e.signal);let F=await i.getCustodianShareData(h);this.assertShare(F,f.planId),d("connecting_safekey_pro");let{deviceId:W}=await w.write(F,e.signal);if(this.assertNotAborted(e.signal),!W?.trim())throw new Error("custodian_share_unavailable");await i.recordCustodianShareClaim(f.planId,F.id,W,"SK_PRO"),this.assertNotAborted(e.signal),await i.markCustodianShareAsCollected(h,F.id);return}finally{w.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 T=e.proDevice;try{if(this.assertNotAborted(e.signal),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let w=await T.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(w,f.planId,f.shareId),w.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:w.shares}}finally{T.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),v==="REVEALED"?await i.resumeReveal(e.editId,Q,t):await i.openRevealWindow(e.editId,{timeoutMinutes:10},Q,t),!_)throw new Error("edit_assets_unavailable");return _}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}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,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(a=>typeof a!="string"||!a))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Ae=class{constructor(e,t,n,a){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=a}async saveAssets(e,t,n,a,i,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,a);s?.("preparing");let l=await o.prepare(d),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(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,c),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:i,material:c}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,i,c,o,d,s)}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 n=await this.configurationRepository().findByPlanId(e.planId),a=n?.editDistribution??n?.preparedDistribution;if(!t&&(!a||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let i=t?.material??{mergeProcessId:e.editId,protectionProtocol:a.protectionProtocol,validatorShares:a.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:a.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:a.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:a.encryptedKey,assetsMetadata:a.assetsMetadata,custodianPair:a.custodianPair};try{if(await this.isCommitted(e,i))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,i),await this.port.commit(e.organizationId,e.planId,i),await this.isCommitted(e,i)?(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 n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.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 n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),a=await n.findByPlanId(e);if(t&&a&&a.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),a&&await n.delete(a.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,a){let i=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:a,reconfigureContext:{mergeProcessId:e.editId}};return{configure:i,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}async commit(e,t,n,a,i,s){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,s?.(c))};try{await a.execute(i,{onLocalProcessUpdated:d})}catch(l){try{if(s?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&s?.(o),l}try{if(s?.("verifying"),!await this.isCommitted(e,n))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 n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let a=[t.validatorShares,t.dataShards,t.backupShards].flat().map(s=>s.id);t.custodianPair&&a.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let i=n.shares.map(s=>s.id).sort();return a.sort(),!(a.length!==i.length||a.some((s,o)=>s!==i[o]))}};var Ce=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new _e(e,t,n),this.reconfiguration=new Ae(e,t,n,a=>this.clearRevealedAssets(a))}assetAccess;reconfiguration;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,a){return this.port.start(e,t,n,a)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(a=>({id:a.id,type:a.type,name:a.meta.name,isMedia:this.isMedia(a)}))}async getAsset(e,t,n){let{assets:a}=await this.assetAccess.loadAssets(e,n),i=a.find(s=>s.id===t);if(!i)throw new Error("edit_asset_not_found");return i}async replaceAsset(e,t){if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:a,assets:i}=await this.assetAccess.loadAssets(e,t),s=i.findIndex(c=>c.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=i[s];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=i.map((c,m)=>m===s?d:c);return this.reconfiguration.saveAssets(e,l,n.withCustodian,a,o.id,t)}async addAsset(e,t){let{plan:n,masterKey:a,assets:i}=await this.assetAccess.loadAssets(e,t),s=Re({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(i.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,i.concat(s),n.withCustodian,a,s.id,t)}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.reconfiguration.recover(e)}discard(e){return this.reconfiguration.discard(e)}discardLocal(e){return this.reconfiguration.discardLocal(e)}};function Rt({apiUrl:r,organizationId:e,planId:t,editId:n,environment:a,transport:i}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.toString()),l=new URL(r.endsWith("/")?r:`${r}/`);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 i(d,o)}if(c==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let m=vr(c,d.searchParams,t,n),v=new Headers(o?.headers);v.set("x-organization-id",e),v.set("x-elements-environment",a);let _=l.pathname.endsWith("/integrations/")?`v1/${m}`:`integrations/v1/${m}`;return i(new URL(_,l),Object.assign({},o,{headers:v}))}}function vr(r,e,t,n){if(r==="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 i=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(i){let o=i[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(i[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(i[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{DataAssetDefinitionService as wa}from"@safetech/inheriti-core-sdk/node";import{PassphraseMasterKeySource as Da,RawMasterKeySource as ka,deriveMasterKey as ba,generateHexSeed as Oa,computePassphraseVerifier as xa}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as Na}from"@safetech/inheriti-core-sdk/node";function St(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Te=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),St(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return St(new Uint8Array(t))}},De=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let i=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(i),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var le=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},ce=class extends le{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},y=class extends le{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function je(r){if(r instanceof le)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var wt=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:G(n,"issuer"),authorizationEndpoint:G(n,"authorization_endpoint"),tokenEndpoint:G(n,"token_endpoint"),deviceAuthorizationEndpoint:b(n,"device_authorization_endpoint"),endSessionEndpoint:b(n,"end_session_endpoint"),revocationEndpoint:b(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:G(t,"device_code"),userCode:G(t,"user_code"),verificationUri:G(t,"verification_uri"),verificationUriComplete:b(t,"verification_uri_complete"),expiresInSeconds:_t(t,"expires_in"),intervalSeconds:Ye(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:G(n,"access_token"),refreshToken:b(n,"refresh_token"),idToken:b(n,"id_token"),tokenType:G(n,"token_type"),expiresInSeconds:_t(n,"expires_in"),refreshExpiresInSeconds:Ye(n,"refresh_expires_in"),scope:b(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let i=b(a,"error")??`oauth_http_${n.status}`;throw new y(i,b(a,"error_description")??i)}return a}};function G(r,e){let t=b(r,e);if(!t)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function b(r,e){return typeof r[e]=="string"?r[e]:void 0}function _t(r,e){let t=Ye(r,e);if(t===void 0)throw new y("invalid_oauth_response",`Missing ${e}`);return t}function Ye(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Pr=600*1e3,ke=5,Er=5,At=class{constructor(e){this.options=e;this.crypto=e.crypto??new Te,this.clock=e.clock??new De}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),i=await this.crypto.sha256UrlSafe(a),s=this.clock.now()+Pr;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",i),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new y("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new y("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new y("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new y(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new y("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new y("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:n.codeVerifier,redirectUri:n.redirectUri}),c=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(c),c}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new y("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(ke,t.intervalSeconds??ke),a=this.clock.now(),i={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),i),i}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new y("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(ke,a.intervalSeconds??ke),o=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(o>=a.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:i.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let l=await this.acceptTokens(d);return await this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=je(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=Er,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new y("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 ce;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new y("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=je(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new ce:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(B(e.issuer)!==B(this.options.configuration.issuer))throw new y("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${B(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new y("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new y("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new y("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(B(e.issuer)!==B(a.issuer))throw new y("issuer_mismatch");if(!i.includes(a.audience))throw new y("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new y("client_mismatch");if(e.environment!==a.environment)throw new y("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new y("required_claim_missing");if(n&&e.nonce!==t)throw new y("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(B(e.issuer)!==B(n.issuer))throw new y("issuer_mismatch");if(!a.includes(n.clientId))throw new y("client_mismatch");if(e.authorizedParty!==n.clientId)throw new y("client_mismatch");if(!e.subject||!e.sessionId)throw new y("required_claim_missing");if(e.nonce!==t)throw new y("nonce_mismatch")}};function B(r){return r.replace(/\/+$/u,"")}var Ct=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function la(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(i,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(i,Object.assign({},s,{headers:o}))},n=r.business?void 0:Xe({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),a=new $(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new te(n,{keyVault:r.keyVault,state:r.state,api:a,reconstructor:new ae(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Rr})}function ca(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Xe({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new de(new ie(r.apiUrl,r.environment,r.getBearerToken,e),t)}function pa(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=Xe({apiUrl:t,getBearerToken:r.getBearerToken,transport:Rt({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ce(new we(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}export{H as BusinessOrganizationSelectionError,oe as CorePlanMaterialBuilder,wa as DataAssetDefinitionService,V as ElementsApiRequestFailed,te as ElementsClient,ee as GuidedCreateRecoveryError,J as GuidedPlanCreator,$ as HttpElementsApiPort,wt as HttpOperatorAuthTransport,we as HttpPlanEditPort,ie as HttpQuickPlanPort,g as InvalidPlanDeclaration,E as InvalidPlanMaterial,me as MasterKeyRelayCancellationFailed,ue as MasterKeyRelayExpired,pe as MasterKeyRelayTimedOut,x as MasterKeyRequired,Z as MemoryGuidedCreateCheckpointStore,Y as MemoryKeyVault,X as MemoryStatePort,y as OAuthProtocolError,At as OperatorAuthClient,le as OperatorAuthError,ce as OperatorReauthenticationRequired,Ct as OperatorSessionController,Ne as PLAN_CREATION_SERVER_STAGES,Da as PassphraseMasterKeySource,Na as PlanAssetDeclaration,L as PlanRequestFailed,de as QuickPlanCreator,Ce as QuickPlanEditor,ka as RawMasterKeySource,O as RelayMasterKeySource,Oe as StaticMasterKeyResolver,De as SystemOAuthClock,Te as WebOAuthCrypto,xa as computePassphraseVerifier,he as createMasterKeyResolver,la as createNodeElementsClient,ca as createNodeQuickPlanCreator,pa as createNodeQuickPlanEditor,Rr as decodeAssetContainer,ba as deriveMasterKey,Oa as generateHexSeed,xe as masterKeyRefFor,M as masterKeyRefKey,je as oauthErrorCode,or as selectBusinessOrganization,Fe as unwrapDekWithMasterKey,N as validatePlanCreationInput,z as validatePlanCreationMaterial};
|
|
@@ -75,6 +75,7 @@ export declare class HttpPlanEditPort {
|
|
|
75
75
|
start(organizationId: string, planId: string, mode: 'DIRECT' | 'GOVERNED', idempotencyKey: string): Promise<EditSession>;
|
|
76
76
|
listEligibleCandidates(organizationId: string, cursor?: string, namePrefix?: string): Promise<PlanEditCandidatePage>;
|
|
77
77
|
context(organizationId: string, planId: string): Promise<PlanEditContext>;
|
|
78
|
+
moderatorNames(organizationId: string, planId: string): Promise<ReadonlyMap<string, string>>;
|
|
78
79
|
startRelaySession(organizationId: string, context: PlanEditContext['masterKeyAcquisition'], clientPublicKey: string): Promise<{
|
|
79
80
|
sessionId: string;
|
|
80
81
|
expiresAt: string | Date;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SDKContainer, DataAsset } from '@safetech/inheriti-core-sdk/node';
|
|
2
2
|
import type { HttpPlanEditPort } from './http-plan-edit-port';
|
|
3
|
-
import type { EditRecoveryStore, PlanEditAssetReference,
|
|
3
|
+
import type { EditRecoveryStore, PlanEditAssetReference, QuickPlanEditProgress } from './quick-plan-editor';
|
|
4
4
|
type Plan = {
|
|
5
5
|
withCustodian: boolean;
|
|
6
6
|
masterKeyEncrypted: boolean;
|
|
@@ -14,7 +14,7 @@ export declare class PlanEditAssetAccess {
|
|
|
14
14
|
constructor(port: HttpPlanEditPort, coreSdk: SDKContainer, recoveryStore: EditRecoveryStore);
|
|
15
15
|
clearRevealedAssets(planId: string): void;
|
|
16
16
|
private configurationRepository;
|
|
17
|
-
loadAssets(input: PlanEditAssetReference, onProgress?:
|
|
17
|
+
loadAssets(input: PlanEditAssetReference, onProgress?: QuickPlanEditProgress): Promise<{
|
|
18
18
|
plan: Plan;
|
|
19
19
|
masterKey?: string;
|
|
20
20
|
assets: DataAsset[];
|
|
@@ -22,6 +22,8 @@ export declare class PlanEditAssetAccess {
|
|
|
22
22
|
private assertEditSession;
|
|
23
23
|
private resolveMasterKey;
|
|
24
24
|
private revealAssets;
|
|
25
|
+
private assertApprovalOutcome;
|
|
26
|
+
private approvalError;
|
|
25
27
|
private assertShare;
|
|
26
28
|
private assertNotAborted;
|
|
27
29
|
}
|
|
@@ -4,6 +4,17 @@ import { HttpPlanEditPort } from './http-plan-edit-port';
|
|
|
4
4
|
import type { ReconfigureMaterial } from './http-plan-edit-port';
|
|
5
5
|
import type { EditReference } from './plan-edit-reconfiguration';
|
|
6
6
|
export type QuickPlanEditPhase = 'checking_edit' | 'acquiring_key' | 'opening_plan' | 'revealing' | 'pending_dms' | 'pending_approvals' | 'pending_auth' | 'pending_moderation' | 'distributing_custodian_share' | 'configuring_custodian_share' | 'claiming_custodian_share' | 'releasing_custodian_share' | 'connecting_safekey_pro' | 'collecting_validators' | 'collecting_shares' | 'reconstructing' | 'opening_window' | 'preparing_view' | 'preparing' | 'preflighting' | 'distributing_validators' | 'distributing_data' | 'finalizing' | 'verifying';
|
|
7
|
+
export interface QuickPlanEditApprovalProgress {
|
|
8
|
+
requiredApprovals: number;
|
|
9
|
+
approvedModerators: number;
|
|
10
|
+
moderators: readonly {
|
|
11
|
+
id: string;
|
|
12
|
+
displayName: string;
|
|
13
|
+
status: 'IDLE' | 'PENDING' | 'APPROVED' | 'DENIED' | 'CANCELED';
|
|
14
|
+
expiresAt?: string;
|
|
15
|
+
}[];
|
|
16
|
+
}
|
|
17
|
+
export type QuickPlanEditProgress = (phase: QuickPlanEditPhase, approvals?: QuickPlanEditApprovalProgress) => void;
|
|
7
18
|
export interface AddPlanAssetInput {
|
|
8
19
|
organizationId: string;
|
|
9
20
|
planId: string;
|
|
@@ -62,13 +73,13 @@ export declare class QuickPlanEditor {
|
|
|
62
73
|
constructor(port: HttpPlanEditPort, coreSdk: SDKContainer, recoveryStore: EditRecoveryStore);
|
|
63
74
|
clearRevealedAssets(planId: string): void;
|
|
64
75
|
start(organizationId: string, planId: string, mode: 'DIRECT' | 'GOVERNED', idempotencyKey: string): Promise<EditSession>;
|
|
65
|
-
listAssets(input: PlanEditAssetReference, onProgress?:
|
|
66
|
-
getAsset(input: PlanEditAssetReference, assetId: string, onProgress?:
|
|
67
|
-
replaceAsset(input: ReplacePlanAssetInput, onProgress?:
|
|
76
|
+
listAssets(input: PlanEditAssetReference, onProgress?: QuickPlanEditProgress): Promise<PlanEditAssetSummary[]>;
|
|
77
|
+
getAsset(input: PlanEditAssetReference, assetId: string, onProgress?: QuickPlanEditProgress): Promise<DataAsset>;
|
|
78
|
+
replaceAsset(input: ReplacePlanAssetInput, onProgress?: QuickPlanEditProgress): Promise<{
|
|
68
79
|
status: 'UPDATED' | 'RECOVERY_REQUIRED';
|
|
69
80
|
assetId: string;
|
|
70
81
|
}>;
|
|
71
|
-
addAsset(input: AddPlanAssetInput, onProgress?:
|
|
82
|
+
addAsset(input: AddPlanAssetInput, onProgress?: QuickPlanEditProgress): Promise<{
|
|
72
83
|
status: 'UPDATED' | 'RECOVERY_REQUIRED';
|
|
73
84
|
assetId: string;
|
|
74
85
|
}>;
|
package/package.json
CHANGED