@safetech/inheriti-client-sdk 1.17.11 → 1.17.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/browser.d.ts +1 -1
  2. package/dist/browser.js +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/inheriti-client-sdk.umd.js +30 -30
  5. package/dist/node.d.ts +25 -1
  6. package/dist/node.js +1 -1
  7. package/dist/sdk-types.d.ts +52 -8
  8. package/dist/src/business/plan-edit/core-edit-transport.d.ts +10 -0
  9. package/dist/src/business/plan-edit/http-plan-edit-port.d.ts +106 -0
  10. package/dist/src/business/plan-edit/plan-edit-asset-access.d.ts +28 -0
  11. package/dist/src/business/plan-edit/plan-edit-reconfiguration.d.ts +26 -0
  12. package/dist/src/business/plan-edit/quick-plan-editor.d.ts +82 -0
  13. package/dist/src/business/quick-plan/build-material.d.ts +6 -0
  14. package/dist/src/business/quick-plan/contract.d.ts +57 -0
  15. package/dist/src/business/quick-plan/http-quick-plan-port.d.ts +40 -0
  16. package/dist/src/business/quick-plan/messages.d.ts +9 -0
  17. package/dist/src/business/quick-plan/prepare-asset.d.ts +10 -0
  18. package/dist/src/business/quick-plan/quick-plan-creator.d.ts +17 -0
  19. package/dist/src/business/quick-plan/request-fingerprint.d.ts +2 -0
  20. package/dist/src/elements/elements-api-port.d.ts +5 -1
  21. package/dist/src/elements/elements-client.d.ts +19 -3
  22. package/dist/src/elements/http-elements-api-port.d.ts +5 -1
  23. package/dist/src/elements/index.d.ts +1 -1
  24. package/dist/src/elements/master-key.d.ts +4 -1
  25. package/dist/src/elements/plan-operations.d.ts +3 -0
  26. package/dist/src/elements/relay-master-key-source.d.ts +9 -1
  27. package/dist/src/elements/scoped-reveal.d.ts +6 -0
  28. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SDKContainer as fa}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as At,useEffect as ze,createContext as _t,useMemo as Ct}from"react";import{CoreProvider as Tt,HttpClientFactory as bt,AuthModule as xt,AuthStateProvider as Dt,AuthSessionRestorer as Ot,useClient as Nt}from"@safetech/inheriti-core-sdk";function b(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},n=t[e]??t.development;return r==""?n:`${n}/${r}`}import q from"react";import xr from"react-dom";function yt(r){if(!r||typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}var Dr=Array(12).fill(0);var vt=1,Rt=100,Le=r=>{var e;return typeof r?.id=="number"||(r==null||(e=r.id)==null?void 0:e.length)>0?r.id:vt++},ye=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),this.getActiveToasts().forEach(t=>e(t)),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e],this.trimHistory()},this.trimHistory=()=>{let e=this.toasts.length-Rt;e<=0||(this.toasts=this.toasts.filter(t=>e>0&&this.dismissedToasts.has(t.id)?(this.dismissedToasts.delete(t.id),e--,!1):!0))},this.create=e=>{let{message:t,...n}=e,a=Le(e),i=this.pendingDismissals.get(a);i!==void 0&&(cancelAnimationFrame(i),this.pendingDismissals.delete(a),this.dismissedToasts.delete(a));let s=this.dismissedToasts.has(a),o=e.dismissible===void 0?!0:e.dismissible;return s&&(this.dismissedToasts.delete(a),this.toasts=this.toasts.filter(l=>l.id!==a)),(s?void 0:this.toasts.find(l=>l.id===a))?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...e,id:a,title:t}),{...l,...e,id:a,dismissible:o,title:t}):l):this.addToast({title:t,...n,dismissible:o,id:a}),a},this.dismiss=e=>{if(e==null)return this.getActiveToasts().forEach(n=>{this.dismissedToasts.add(n.id),this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),e;this.dismissedToasts.add(e);let t=this.pendingDismissals.get(e);return t!==void 0&&cancelAnimationFrame(t),this.pendingDismissals.set(e,requestAnimationFrame(()=>{this.pendingDismissals.delete(e),this.subscribers.forEach(n=>n({id:e,dismiss:!0}))})),e},this.message=(e,t)=>this.create({...t,message:e,type:void 0}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let a=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,s,o=a.then(async l=>{if(s=["resolve",l],q.isValidElement(l))i=!1,this.create({id:n,type:"default",message:l});else if(Pt(l)&&!l.ok){i=!1;let h=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,R=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,V=typeof h=="object"&&!q.isValidElement(h)?h:{message:h};this.create({id:n,type:"error",description:R,...V})}else if(l instanceof Error){i=!1;let h=typeof t.error=="function"?await t.error(l):t.error,R=typeof t.description=="function"?await t.description(l):t.description,V=typeof h=="object"&&!q.isValidElement(h)?h:{message:h};this.create({id:n,type:"error",description:R,...V})}else if(t.success!==void 0){i=!1;let h=typeof t.success=="function"?await t.success(l):t.success,R=typeof t.description=="function"?await t.description(l):t.description,V=typeof h=="object"&&!q.isValidElement(h)?h:{message:h};this.create({id:n,type:"success",description:R,...V})}}).catch(async l=>{if(s=["reject",l],t.error!==void 0){i=!1;let p=typeof t.error=="function"?await t.error(l):t.error,h=typeof t.description=="function"?await t.description(l):t.description,T=typeof p=="object"&&!q.isValidElement(p)?p:{message:p};this.create({id:n,type:"error",description:h,...T})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),d=()=>new Promise((l,p)=>o.then(()=>s[0]==="reject"?p(s[1]):l(s[1])).catch(p));return typeof n!="string"&&typeof n!="number"?{unwrap:d}:Object.assign(n,{unwrap:d})},this.custom=(e,t)=>{let n=Le(t);return this.create({...t,jsx:e(n),id:n,type:void 0}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set,this.pendingDismissals=new Map}},P=new ye,wt=(r,e)=>P.message(r,e),Pt=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",Et=wt,It=()=>P.toasts,St=()=>P.getActiveToasts(),L=Object.assign(Et,{success:P.success,info:P.info,warning:P.warning,error:P.error,custom:P.custom,message:P.message,promise:P.promise,dismiss:P.dismiss,loading:P.loading},{getHistory:It,getToasts:St});yt("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--normal-text);background:var(--normal-bg);border:1px solid var(--normal-border);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{-webkit-user-select:none;user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");var Ge={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{L.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{L.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{L.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{L.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{L.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as Kt,jsx as G}from"react/jsx-runtime";var kt="inheriti_client_merging_process",ve=_t(null);function Be({children:r,clientId:e,options:t}){let n=t?.env??"development",a={key:e??"",options:{env:n}},i=At(bt.create({apiUrl:b("",n),errorHandlingStrategy:Ge}));ze(()=>{i.current?.setApiUrl(b("",n))},[n]);let s=Ct(()=>({core:{httpClient:i.current},"protection-plan":{authTokens:{mergingProcessKey:kt}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return G(ve.Provider,{value:i.current,children:G(Dt,{children:G(Tt,{modules:{auth:xt},moduleConfigs:s,children:G(Ot,{children:G(Mt,{client:a,children:r})})})})})}function Mt({children:r,client:e}){let{connect:t,isConnected:n}=Nt();return ze(()=>{!e?.key||n||t(e)},[e.key]),G(Kt,{children:r})}import{useContext as Ut,useCallback as Lt}from"react";import{useClient as Gt}from"@safetech/inheriti-core-sdk";function Ve(){let{connect:r,...e}=Gt(),t=Ut(ve),n=Lt(async a=>(a?.options?.env&&t?.setApiUrl(b("",a.options.env)),r(a)),[r,t]);return{...e,connect:n}}function zt(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",n=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",a=b("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:a}}import{decryptRSAOAEP as Bt,generateRSAOAEPKeyPair as Vt}from"@safetech/inheriti-core-sdk/crypto";var te=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},re=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},F=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await Vt(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,i=Date.now()+(this.options.timeoutMs??600*1e3),s=this.options.sleep??(o=>new Promise(d=>setTimeout(d,o)));for(;Date.now()<i;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let d=(await Bt(o.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(d))throw new Error("invalid_master_key_material");return d}if(o.status==="EXPIRED")throw new re(n.sessionId);await s(a)}throw new te(n.sessionId)}};function ne(r){return{resolve:async e=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let t=await r.source?.resolve();return t||Re(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}if(qt(e,r.applicationId)){let t=await r.source?.resolve();return t||Re(r,()=>r.api.masterKeyAcquisition())}return Re(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}}}function qt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Re(r,e,t){if((await e()).relayAvailable)return new F({...r.relay,api:Ft(r.api,t)}).resolve()}function Ft(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t)}}function x(r){return`${r.system}:${r.contextId}`}function Pe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var C=class extends Error{constructor(t){super(`master_key_required:${x(t)}`);this.ref=t;this.name="MasterKeyRequired"}},we=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 W=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 j=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var ae=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ht={"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"]},Fe=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],f=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},v=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 v("plan_material_field_unknown");if(Ee(r.dataShards,"data_shards_invalid"),Ee(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Ee(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new v("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new v("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new v("material_operation_invalid")}function Ee(r,e){if(!Array.isArray(r))throw new v(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new v(e);if(t.data!==void 0&&typeof t.data!="string")throw new v(e)}}function M(r){if(k(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!jt(r.idempotencyKey))throw new f("idempotency_key_invalid");if(!r.name?.trim())throw new f("plan_name_required");if(!r.assets.length)throw new f("assets_required");let e=new Set;for(let t of r.assets){if(k(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new f("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!ae.includes(t.type))throw new f("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new f("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new f("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new f("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new f("asset_field_names_invalid");if($t(t.matchOrigins),!t.isBinary){let i=Ht[t.type];if(!i||a.some(s=>!i.includes(s)))throw new f("asset_field_name_not_canonical")}}if(!r.participants.length)throw new f("participants_required");for(let t of r.participants){if(k(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!He(t.routingEmail))throw new f("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new f("participant_relationships_invalid")}Wt(r)}function $t(r){if(r===void 0)return;if(!r.length)throw new f("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new f("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new f("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof f?n:new f("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new f("asset_match_origins_duplicated")}function Wt(r){let e=r.policy;if(e&&k(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new f("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){k(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new f("authentication_mode_invalid")}if(e.moderation){k(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new f("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.length))throw new f("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new f("approval_mode_invalid")}let t=e.dms;if(!t)return;k(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!He(t.subjectEmail))throw new f("dms_subject_invalid");if(!r.participants.some(i=>qe(i.routingEmail)===qe(t.subjectEmail)))throw new f("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 f("dms_countdown_invalid")}function jt(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 He(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function qe(r){return r.normalize("NFC").trim().toLowerCase()}function k(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new f(t)}var se=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)}},oe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),M(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={}){M(t);let s=await this.checkpoints.load(e);if(!s)throw new le("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await $e(t))throw new le("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 p=await this.api.supplyPlanCreationMaterial(e,l);return i.onProgress?.(p.stage),p.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,p),p}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 $e(e),serverStage:t.stage})}},le=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function $e(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 We(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new W(n.stage);return r.authorizeRevealAction(e,t)}function Yt(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(!Yt(i))throw i}return r.releaseRevealMaterial(e,t)}function Xe(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":Xt.has(r.stage)?"ENDED":"CONTINUING"}var Xt=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 de=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},g=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Qe(r,e,t={}){if(t.signal?.aborted)throw I();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let a=t.idempotencyKey??crypto.randomUUID(),i=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),s;try{let o=await Jt(r,i,t);D(t,"RELEASING_MATERIAL",o);let d=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let l=await rr(r,o,ar(d),t);D(t,"RECONSTRUCTING",o);try{s=await r.reconstructPlanMaterial(l)}catch(h){throw await r.reportRevealReconstruction(o.id,{status:"FAILED",errorCode:tr(h)}),h}let p=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return D(t,"OPEN",p),new Ae(r,p,n,s,t.signal)}catch(o){throw s?.fill(0),await ir(r,i.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var Zt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Jt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:Xe(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Zt.has(n.stage))throw new Se(n.stage);await Ce(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var Se=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function D(r,e,t){r.onProgress?.({phase:e,session:t})}function Ce(r,e){return e?.aborted?Promise.reject(I()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(I())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var Ae=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 de;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new g("asset_selector_invalid");if(!this.client.assetDecoder)throw new g("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=Ze(i),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new g("asset_not_found");if(d.isBinary)throw new g("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new g("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 g("asset_value_invalid");return{selector:s.selector,value:er(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",Ye(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new g("asset_selector_invalid");if(!this.client.assetDecoder)throw new g("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new g("asset_not_found");if(!n.isBinary)throw new g("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 g("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",Ye(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(!Je(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 Ze(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new g("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new g("asset_selector_invalid");return{asset:r.asset,field:r.field}}function er(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new g("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new g("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new g("asset_value_invalid")}return n[e]}function Ye(r){if(r instanceof g)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function tr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function rr(r,e,t,n){let a=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(a){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new ce;let l=await Y(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(Ie(l,a.id,e.planId),!l.shares.includes(a.data))throw new E;D(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:p}=await Y(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw I();if(!p?.trim())throw new E;let h=await Y(()=>n.proDevice.read({shareId:l.id,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(Ie(h,l.id,e.planId),h.deviceId!==p)throw new E;if(h.shares.length!==l.shares.length||h.shares.some((R,T)=>R!==l.shares[T]))throw new E;if(await r.claimRevealCustodianShare(e.id,l.id,p),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw I();return{...t,shares:t.shares.filter(R=>R!==a).concat(h.shares.map((R,T)=>({id:`${h.id}:${T}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:R})))}}if(d!=="SK_MOBILE")throw new E;return await r.distributeRevealCustodianShare(e.id),D(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),D(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Ce(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new ce;if(!i.shareId||!i.deviceId)throw new E;D(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(Ie(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new E;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw I();return{...t,shares:t.shares.concat(d.shares.map((l,p)=>({id:`${d.id}:${p}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new E;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),D(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await nr(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 Ie(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 E}async function Y(r,e){if(e?.aborted)throw I();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(I()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw I();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function nr(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 E}if(Date.now()>=n)throw new _e;await Ce(t.pollIntervalMs??1500,t.signal)}}var E=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ce=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},_e=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function ar(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function ir(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!Je(n))throw n}}function Je(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function I(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var X=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??or(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new 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 M(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 se){if(this.requireApplication(),!this.api)throw new u;return new oe(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()},n=await this.keyVault.load(t);if(n)return tt(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new C(t);return await this.keyVault.store(t,et(a)),a}async prepareReveal(e){if(!this.api)throw new u;let t=await this.api.planKeyReference(e);if(!t.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new u;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new j;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e){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 C({system:"INHERITI_BUSINESS",contextId:this.organizationId});let t=Pe(e);if(!t)throw new C({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return tt(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new C(t);return await this.keyVault.store(t,et(a)),a}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)}getReveal(e){if(!this.api)throw new u;return this.api.getReveal(e)}openReveal(e,t){return Qe(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){if(!this.api)throw new u;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new u;return We(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 Te;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new C({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Te=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function sr(r){return new X(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:r.assetDecoder})}function et(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 tt(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function or(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 ne({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ne({...e,organizationId:r.organizationId})}var lr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],dr=["DIRECT","GOVERNED"],nt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],cr=["ACTIVE","REVOKED"],ur=["SK_MOBILE"],pr=["ACTIVE","INACTIVE"],mr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function at(r){let e=y(r);return{items:S(e.items).map(ot),nextCursor:e.nextCursor===null?null:c(e.nextCursor,"nextCursor")}}function it(r){let e=y(r);return{total:A(e.total,"total"),items:S(e.items).map(t=>{let n=y(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:c(n.id,"log.id"),planId:c(n.planId,"log.planId"),tenantId:c(n.tenantId,"log.tenantId"),event:c(n.event,"log.event"),occurredOn:c(n.occurredOn,"log.occurredOn"),status:O(n.status),title:c(n.title,"log.title"),details:S(n.details).map(a=>{let i=y(a);return{label:c(i.label,"log.detail.label"),value:c(i.value,"log.detail.value")}})}})}}function st(r){let e=y(r),t=ot(e),n=y(e.source),a=c(n.kind,"source.kind");return{...t,assets:S(e.assets).map(i=>{let s=y(i);return{id:c(s.id,"asset.id"),code:O(s.code),type:w(c(s.type,"asset.type"),ae),name:c(s.name,"asset.name"),isBinary:fr(s.isBinary,"asset.isBinary"),fieldNames:S(s.fieldNames).map(o=>c(o,"asset.fieldNames")),fileName:O(s.fileName),mimeType:O(s.mimeType),size:s.size===void 0||s.size===null?void 0:A(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:S(s.matchOrigins).map(o=>c(o,"asset.matchOrigins"))}}),participants:S(e.participants).map(i=>{let s=y(i);return{id:c(s.id,"participant.id"),displayName:c(s.displayName,"participant.displayName"),relationships:S(s.relationships).map(o=>w(c(o,"relationship"),nt)),lifecycle:w(c(s.lifecycle,"participant.lifecycle"),cr)}}),revealPolicy:(()=>{let i=y(e.revealPolicy);return{masterKeyRelease:w(c(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:w(c(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=y(e.dms);return{subjectEmail:c(i.subjectEmail,"dms.subjectEmail"),countdownDays:A(i.countdownDays,"dms.countdownDays"),countdownHours:A(i.countdownHours,"dms.countdownHours"),countdownMinutes:A(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:w(c(n.system,"source.system"),["INHERITI_BUSINESS"]),status:w(c(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function Q(r){let e=y(r);return{operationId:c(e.operationId,"operationId"),stage:w(c(e.stage,"stage"),Fe),outcome:w(c(e.outcome,"outcome"),mr),planId:O(e.planId),lastErrorCode:O(e.lastErrorCode),participants:e.participants===void 0?void 0:S(e.participants).map(t=>{let n=y(t);return{clientParticipantRef:c(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:c(n.planParticipantId,"planParticipantId"),relationships:S(n.relationships).map(a=>hr(c(a,"relationship"),nt))}})}}function ot(r){let e=y(r),t=y(e.assetSummary),n=y(e.governance),a=y(e.participantSummary);return{id:c(e.id,"id"),name:c(e.name,"name"),description:O(e.description),status:w(c(e.status,"status"),lr),createdAt:c(e.createdAt,"createdAt"),configuredAt:O(e.configuredAt),assetSummary:{count:A(t.count,"assetSummary.count"),types:S(t.types).map(i=>w(c(i,"assetType"),ae)),names:rt(t.names).map(i=>c(i,"assetSummary.names"))},governance:{mode:w(c(n.mode,"governance.mode"),dr),minimumApprovals:A(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:A(a.owners,"owners"),mergers:A(a.mergers,"mergers"),moderators:A(a.moderators,"moderators")},authentication:rt(e.authentication).map(i=>{let s=y(i);return{id:w(c(s.id,"authentication.id"),ur),status:w(c(s.status,"authentication.status"),pr)}})}}function w(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function hr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function y(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function rt(r){return r==null?[]:S(r)}function S(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function c(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function O(r){return r==null?void 0:c(r,"optional")}function A(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function fr(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 lt(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 gr(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 be(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function xe(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var K=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ue=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(lt)}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 at(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return st(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 it(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){M(e);let{idempotencyKey:t,...n}=e;return Q(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return z(t),Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,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")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}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){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...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[h,R]of Object.entries(i??{}))o.set(h,R);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}),p=await dt(l);if(!l.ok)throw new K(l.status,be(p),xe(p));if(!p.ok||p.result===void 0)throw new K(l.status,be(p),xe(p));return p.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 dt(s);if(!s.ok||!o.ok)throw new K(s.status,be(o),xe(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new K(400,"organization_selection_required")}};async function dt(r){try{return await r.json()}catch{return{ok:!1}}}async function ct(r,e){if(!e)throw new Error("master_key_required");let t=yr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=vr(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return Rr(new Uint8Array(o))}function yr(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 vr(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 Rr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var De=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as wr}from"@safetech/inheriti-core-sdk/shared-configuration";var Pr=new Set(["COMPLETED","ABORTED","EXPIRED"]),Oe=class{constructor(e,t=new pe,n=new me,a=Math.random){this.api=e;this.loop=new wr(t,n,a)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,a,i=!1,s=this.loop.start(e,async()=>{let o=await this.api.getGovernedReveal(e),d=o.approvalProcess?.status??"",l=Er(o);n!==void 0&&l!==n&&await t.onProcessUpdated?.(),a!==void 0&&d!==a&&await t.onApprovalUpdated?.(),n=l,a=d;let p=Pr.has(o.status);if(o.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),o.status==="ABORTED"&&await t.onForceAborted?.(e),p)return{transitionKey:l,shouldPoll:!1,terminal:!0};if(!i){let h=await this.api.getCustodianShare(e);"status"in h||(i=!0,await t.onCustodianShareReceived?.(e,h))}return{transitionKey:l,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,s)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function Er(r){return`${r.status}:${r.approvalProcess?.status??""}`}var pe=class{visibility(){return typeof document<"u"&&document.visibilityState==="hidden"?"hidden":"visible"}isOnline(){return typeof navigator>"u"||navigator.onLine!==!1}now(){return Date.now()}schedule(e,t){let n=setTimeout(e,t);return()=>clearTimeout(n)}onRecovery(e){return typeof globalThis.addEventListener!="function"?()=>{}:(globalThis.addEventListener("online",e),globalThis.addEventListener("visibilitychange",e),()=>{globalThis.removeEventListener("online",e),globalThis.removeEventListener("visibilitychange",e)})}},me=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var ut=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Z(e.signal),Sr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Z(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Z(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(Z(e.signal),!a.custodianPair)throw new v("custodian_share_required");let i=Ne(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ne(a.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(Ne(a.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return Z(e.signal),{protectionProtocol:a.protocol,validatorShares:ke(s.encryptedShares),dataShards:ke(o.encryptedShares),backupShards:ke(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Ir(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:Me(n.encryptedShares[0]),dataShard:Me(n.encryptedShares[1])}}};function Ne(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function ke(r){return r.map(Me)}function Me(r){return{id:r.id,data:r.encryptedData}}function Ir(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new v("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function Sr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new v("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new v("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new v("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 v("plan_secrets_declaration_mismatch")}}function Z(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function pt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var he=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),pt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return pt(new Uint8Array(t))}},fe=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 J=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},ee=class extends J{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},m=class extends J{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ke(r){if(r instanceof J)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var mt=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:N(n,"issuer"),authorizationEndpoint:N(n,"authorization_endpoint"),tokenEndpoint:N(n,"token_endpoint"),deviceAuthorizationEndpoint:_(n,"device_authorization_endpoint"),endSessionEndpoint:_(n,"end_session_endpoint"),revocationEndpoint:_(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:N(t,"device_code"),userCode:N(t,"user_code"),verificationUri:N(t,"verification_uri"),verificationUriComplete:_(t,"verification_uri_complete"),expiresInSeconds:ht(t,"expires_in"),intervalSeconds:Ue(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:N(n,"access_token"),refreshToken:_(n,"refresh_token"),idToken:_(n,"id_token"),tokenType:N(n,"token_type"),expiresInSeconds:ht(n,"expires_in"),refreshExpiresInSeconds:Ue(n,"refresh_expires_in"),scope:_(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=_(a,"error")??`oauth_http_${n.status}`;throw new m(i,_(a,"error_description")??i)}return a}};function N(r,e){let t=_(r,e);if(!t)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function _(r,e){return typeof r[e]=="string"?r[e]:void 0}function ht(r,e){let t=Ue(r,e);if(t===void 0)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function Ue(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ar=600*1e3,ge=5,_r=5,ft=class{constructor(e){this.options=e;this.crypto=e.crypto??new he,this.clock=e.clock??new fe}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()+Ar;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 m("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new m("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new m("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new m(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new m("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new m("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}),p=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(p),p}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new m("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(ge,t.intervalSeconds??ge),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 m("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(ge,a.intervalSeconds??ge),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=Ke(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=_r,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new m("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 ee;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 m("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=Ke(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new ee:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(U(e.issuer)!==U(this.options.configuration.issuer))throw new m("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}|${U(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new m("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 m("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 m("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(U(e.issuer)!==U(a.issuer))throw new m("issuer_mismatch");if(!i.includes(a.audience))throw new m("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new m("client_mismatch");if(e.environment!==a.environment)throw new m("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new m("required_claim_missing");if(n&&e.nonce!==t)throw new m("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(U(e.issuer)!==U(n.issuer))throw new m("issuer_mismatch");if(!a.includes(n.clientId))throw new m("client_mismatch");if(e.authorizedParty!==n.clientId)throw new m("client_mismatch");if(!e.subject||!e.sessionId)throw new m("required_claim_missing");if(e.nonce!==t)throw new m("nonce_mismatch")}};function U(r){return r.replace(/\/+$/u,"")}var gt=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};export{B as BusinessOrganizationSelectionError,ae as CANONICAL_PLAN_ASSET_TYPES,Ht as CANONICAL_STRUCTURED_ASSET_FIELDS,ut as CorePlanMaterialBuilder,u as ElementsApiPortRequired,K as ElementsApiRequestFailed,X as ElementsClient,le as GuidedCreateRecoveryError,oe as GuidedPlanCreator,pe as HostProcessRuntimeEnvironment,ue as HttpElementsApiPort,mt as HttpOperatorAuthTransport,Be as InheritiClientProvider,f as InvalidPlanDeclaration,v as InvalidPlanMaterial,me as LocalProcessReconciliationOwnership,re as MasterKeyRelayExpired,te as MasterKeyRelayTimedOut,C as MasterKeyRequired,se as MemoryGuidedCreateCheckpointStore,H as MemoryKeyVault,$ as MemoryStatePort,m as OAuthProtocolError,ft as OperatorAuthClient,J as OperatorAuthError,ee as OperatorReauthenticationRequired,gt as OperatorSessionController,Fe as PLAN_CREATION_SERVER_STAGES,De as PlanMaterialReconstructionFailed,j as PlanMaterialReconstructorRequired,Oe as PollingSharedPlanEventListener,F as RelayMasterKeySource,W as RevealActionsNotOpen,g as RevealFieldAccessError,de as RevealHandleClosed,fa as SDKContainer,we as StaticMasterKeyResolver,fe as SystemOAuthClock,he as WebOAuthCrypto,sr as createElementsClient,ne as createMasterKeyResolver,zt as getAvailableEnvs,Pe as masterKeyRefFor,x as masterKeyRefKey,Ke as oauthErrorCode,Ze as parseAssetFieldSelector,Xe as revealPhaseOf,gr as selectBusinessOrganization,ct as unwrapDekWithMasterKey,Ve as useClient,M as validatePlanCreationInput,z as validatePlanCreationMaterial};
1
+ import{SDKContainer as wa}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as Ct,useEffect as Ve,createContext as bt,useMemo as Tt}from"react";import{CoreProvider as xt,HttpClientFactory as Dt,AuthModule as Ot,AuthStateProvider as Nt,AuthSessionRestorer as Mt,useClient as kt}from"@safetech/inheriti-core-sdk";function D(r,e="local"){let t={local:"http://localhost:3000",development:"https://api-dev.inheriti.com",staging:"https://api-stg.inheriti.com",production:"https://api.inheriti.com"},n=t[e]??t.development;return r==""?n:`${n}/${r}`}import H from"react";import kr from"react-dom";function Rt(r){if(!r||typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}var Kr=Array(12).fill(0);var wt=1,Pt=100,ze=r=>{var e;return typeof r?.id=="number"||(r==null||(e=r.id)==null?void 0:e.length)>0?r.id:wt++},we=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),this.getActiveToasts().forEach(t=>e(t)),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e],this.trimHistory()},this.trimHistory=()=>{let e=this.toasts.length-Pt;e<=0||(this.toasts=this.toasts.filter(t=>e>0&&this.dismissedToasts.has(t.id)?(this.dismissedToasts.delete(t.id),e--,!1):!0))},this.create=e=>{let{message:t,...n}=e,a=ze(e),i=this.pendingDismissals.get(a);i!==void 0&&(cancelAnimationFrame(i),this.pendingDismissals.delete(a),this.dismissedToasts.delete(a));let s=this.dismissedToasts.has(a),o=e.dismissible===void 0?!0:e.dismissible;return s&&(this.dismissedToasts.delete(a),this.toasts=this.toasts.filter(l=>l.id!==a)),(s?void 0:this.toasts.find(l=>l.id===a))?this.toasts=this.toasts.map(l=>l.id===a?(this.publish({...l,...e,id:a,title:t}),{...l,...e,id:a,dismissible:o,title:t}):l):this.addToast({title:t,...n,dismissible:o,id:a}),a},this.dismiss=e=>{if(e==null)return this.getActiveToasts().forEach(n=>{this.dismissedToasts.add(n.id),this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),e;this.dismissedToasts.add(e);let t=this.pendingDismissals.get(e);return t!==void 0&&cancelAnimationFrame(t),this.pendingDismissals.set(e,requestAnimationFrame(()=>{this.pendingDismissals.delete(e),this.subscribers.forEach(n=>n({id:e,dismiss:!0}))})),e},this.message=(e,t)=>this.create({...t,message:e,type:void 0}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let a=Promise.resolve(e instanceof Function?e():e),i=n!==void 0,s,o=a.then(async l=>{if(s=["resolve",l],H.isValidElement(l))i=!1,this.create({id:n,type:"default",message:l});else if(It(l)&&!l.ok){i=!1;let h=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,R=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,K=typeof h=="object"&&!H.isValidElement(h)?h:{message:h};this.create({id:n,type:"error",description:R,...K})}else if(l instanceof Error){i=!1;let h=typeof t.error=="function"?await t.error(l):t.error,R=typeof t.description=="function"?await t.description(l):t.description,K=typeof h=="object"&&!H.isValidElement(h)?h:{message:h};this.create({id:n,type:"error",description:R,...K})}else if(t.success!==void 0){i=!1;let h=typeof t.success=="function"?await t.success(l):t.success,R=typeof t.description=="function"?await t.description(l):t.description,K=typeof h=="object"&&!H.isValidElement(h)?h:{message:h};this.create({id:n,type:"success",description:R,...K})}}).catch(async l=>{if(s=["reject",l],t.error!==void 0){i=!1;let p=typeof t.error=="function"?await t.error(l):t.error,h=typeof t.description=="function"?await t.description(l):t.description,b=typeof p=="object"&&!H.isValidElement(p)?p:{message:p};this.create({id:n,type:"error",description:h,...b})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),d=()=>new Promise((l,p)=>o.then(()=>s[0]==="reject"?p(s[1]):l(s[1])).catch(p));return typeof n!="string"&&typeof n!="number"?{unwrap:d}:Object.assign(n,{unwrap:d})},this.custom=(e,t)=>{let n=ze(t);return this.create({...t,jsx:e(n),id:n,type:void 0}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set,this.pendingDismissals=new Map}},E=new we,Et=(r,e)=>E.message(r,e),It=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",St=Et,At=()=>E.toasts,_t=()=>E.getActiveToasts(),B=Object.assign(St,{success:E.success,info:E.info,warning:E.warning,error:E.error,custom:E.custom,message:E.message,promise:E.promise,dismiss:E.dismiss,loading:E.loading},{getHistory:At,getToasts:_t});Rt("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--normal-text);background:var(--normal-bg);border:1px solid var(--normal-border);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{-webkit-user-select:none;user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");var Be={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{B.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{B.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{B.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{B.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{B.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as Lt,jsx as V}from"react/jsx-runtime";var Kt="inheriti_client_merging_process",Pe=bt(null);function qe({children:r,clientId:e,options:t}){let n=t?.env??"development",a={key:e??"",options:{env:n}},i=Ct(Dt.create({apiUrl:D("",n),errorHandlingStrategy:Be}));Ve(()=>{i.current?.setApiUrl(D("",n))},[n]);let s=Tt(()=>({core:{httpClient:i.current},"protection-plan":{authTokens:{mergingProcessKey:Kt}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return V(Pe.Provider,{value:i.current,children:V(Nt,{children:V(xt,{modules:{auth:Ot},moduleConfigs:s,children:V(Mt,{children:V(Ut,{client:a,children:r})})})})})}function Ut({children:r,client:e}){let{connect:t,isConnected:n}=kt();return Ve(()=>{!e?.key||n||t(e)},[e.key]),V(Lt,{children:r})}import{useContext as Gt,useCallback as zt}from"react";import{useClient as Bt}from"@safetech/inheriti-core-sdk";function Fe(){let{connect:r,...e}=Bt(),t=Gt(Pe),n=zt(async a=>(a?.options?.env&&t?.setApiUrl(D("",a.options.env)),r(a)),[r,t]);return{...e,connect:n}}function Vt(){let r=typeof window<"u"?window.location.hostname:"",e=r.includes("localhost")?["local","development","staging","production"]:r.includes("elements-dev.inheriti.com")?["development","staging","production"]:["staging","production"],t=r.includes("localhost")?"local":r.includes("elements-dev.inheriti.com")?"development":"staging",n=r.includes("localhost")?"http://localhost:8081":r.includes("elements-dev.inheriti.com")?"https://app-dev.inheriti.com/":"https://app-stg.inheriti.com/",a=D("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:a}}import{decryptRSAOAEP as qt,generateRSAOAEPKeyPair as Ft}from"@safetech/inheriti-core-sdk/crypto";var re=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ne=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ae=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},$=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 Ft();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(x=>setTimeout(x,S))),l=!0,p=!1,h,R=()=>h??=Promise.resolve().then(()=>this.options.api.cancelRelaySession?.(i.sessionId)),b,K=new Promise((S,x)=>{b=()=>{l&&R().catch(()=>{}),x(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",b,{once:!0})});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),p=!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),K]);if(S.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(S.status==="DELIVERED"&&S.sealedMasterKey){let x=(await qt(S.sealedMasterKey,a)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(x))throw new Error("invalid_master_key_material");return x}if(S.status==="EXPIRED")throw new ne(i.sessionId);await Ht(d,s,e)}throw new re(i.sessionId)}catch(S){if(l&&(!p||e?.aborted))try{await R()}catch(x){if(e?.aborted)throw new ae(x)}throw S}finally{b&&e?.removeEventListener("abort",b)}}};async function Ht(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 ie(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||Ee(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if($t(e,r.applicationId)){let a=await r.source?.resolve();return a||Ee(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Ee(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function $t(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ee(r,e,t,n,a){if((await e()).relayAvailable)return new $({...r.relay,api:Wt(r.api,t)}).resolve(n,a)}function Wt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t),cancelRelaySession:t=>r.cancelMasterKeyRelaySession(t)}}function O(r){return`${r.system}:${r.contextId}`}function Se(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var T=class extends Error{constructor(t){super(`master_key_required:${O(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Ie=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(O(e),t),this}async resolve(e){return this.sources.get(O(e))?.resolve()}};var W=class{keys=new Map;async store(e,t){this.keys.set(O(e),t.slice())}async load(e){return this.keys.get(O(e))?.slice()}async remove(e){this.keys.delete(O(e))}};var j=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 Y=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},c=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var X=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var se=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],jt={"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"]},$e=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],f=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},w=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function q(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new w("plan_material_field_unknown");if(Ae(r.dataShards,"data_shards_invalid"),Ae(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Ae(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new w("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new w("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new w("material_operation_invalid")}function Ae(r,e){if(!Array.isArray(r))throw new w(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new w(e);if(t.data!==void 0&&typeof t.data!="string")throw new w(e)}}function L(r){if(U(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Qt(r.idempotencyKey))throw new f("idempotency_key_invalid");if(!r.name?.trim())throw new f("plan_name_required");if(!r.assets.length)throw new f("assets_required");let e=new Set;for(let t of r.assets){if(U(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new f("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!se.includes(t.type))throw new f("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new f("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new f("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new f("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new f("asset_field_names_invalid");if(Yt(t.matchOrigins),!t.isBinary){let i=jt[t.type];if(!i||a.some(s=>!i.includes(s)))throw new f("asset_field_name_not_canonical")}}if(!r.participants.length)throw new f("participants_required");for(let t of r.participants){if(U(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!We(t.routingEmail))throw new f("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new f("participant_relationships_invalid")}Xt(r)}function Yt(r){if(r===void 0)return;if(!r.length)throw new f("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new f("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new f("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof f?n:new f("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new f("asset_match_origins_duplicated")}function Xt(r){let e=r.policy;if(e&&U(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new f("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){U(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new f("authentication_mode_invalid")}if(e.moderation){U(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(i.length===0)throw new f("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.length))throw new f("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new f("approval_mode_invalid")}let t=e.dms;if(!t)return;U(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!We(t.subjectEmail))throw new f("dms_subject_invalid");if(!r.participants.some(i=>He(i.routingEmail)===He(t.subjectEmail)))throw new f("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 f("dms_countdown_invalid")}function Qt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function We(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function He(r){return r.normalize("NFC").trim().toLowerCase()}function U(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new f(t)}var le=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},de=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),L(e),oe(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={}){L(t);let s=await this.checkpoints.load(e);if(!s)throw new ce("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await je(t))throw new ce("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;oe(i.signal),i.onProgress?.("ENCRYPTING");let d=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});oe(i.signal),i.onProgress?.("GENERATING_SHARES");let l=await a.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});oe(i.signal),q(l);let p=await this.api.supplyPlanCreationMaterial(e,l);return i.onProgress?.(p.stage),p.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,p),p}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await je(e),serverStage:t.stage})}},ce=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function je(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,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 oe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ye(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Y(n.stage);return r.authorizeRevealAction(e,t)}function Zt(r){let e=r?.status;return e===400||e===401||e===403}async function Xe(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!Zt(i))throw i}return r.releaseRevealMaterial(e,t)}function et(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?er(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":Jt.has(r.stage)?"ENDED":"CONTINUING"}var Jt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function er(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 pe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},g=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function tt(r,e,t={}){if(t.signal?.aborted)throw y();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"}):Qe(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 y();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:Qe(l.id)}let o;try{if(t.signal?.aborted)throw y();let d=await rr(r,s,t);if(t.signal?.aborted)throw y();N(t,"RELEASING_MATERIAL",d);let l=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted)throw y();d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id);let p;try{p=await ir(r,d,or(l),t)}finally{t.proDevice?.clearPin?.()}N(t,"RECONSTRUCTING",d);try{o=await r.reconstructPlanMaterial(p)}catch(R){throw await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:ar(R)}),R}let h=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});return N(t,"OPEN",h),new Ce(r,h,n,o,t.signal)}catch(d){throw o?.fill(0),await lr(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Qe(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var tr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function rr(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.signal?.aborted)throw y();if(t.onSession?.(n),t.onProgress?.({phase:et(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(tr.has(n.stage))throw new _e(n.stage);await Te(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var _e=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function N(r,e,t){r.onProgress?.({phase:e,session:t})}function Te(r,e){return e?.aborted?Promise.reject(y()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(y())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var Ce=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 pe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new g("asset_selector_invalid");if(!this.client.assetDecoder)throw new g("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=rt(i),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new g("asset_not_found");if(d.isBinary)throw new g("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new g("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 g("asset_value_invalid");return{selector:s.selector,value:nr(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",Ze(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new g("asset_selector_invalid");if(!this.client.assetDecoder)throw new g("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new g("asset_not_found");if(!n.isBinary)throw new g("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 g("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",Ze(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(!nt(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 rt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new g("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new g("asset_selector_invalid");return{asset:r.asset,field:r.field}}function nr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new g("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new g("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new g("asset_value_invalid")}return n[e]}function Ze(r){if(r instanceof g)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function ar(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function ir(r,e,t,n){let a=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(a){let d=await ue(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new me;let l=await ue(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(Je(l,a.id,e.planId),!l.shares.includes(a.data))throw new A;N(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:p}=await ue(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw y();if(!p?.trim())throw new A;if(await r.claimRevealCustodianShare(e.id,l.id,p),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw y();return{...t,shares:t.shares.filter(h=>h!==a).concat(l.shares.map((h,R)=>({id:`${l.id}:${R}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:h})))}}if(d!=="SK_MOBILE")throw new A;return await r.distributeRevealCustodianShare(e.id),N(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),N(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Te(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new me;if(!i.shareId||!i.deviceId)throw new A;N(n,"CONNECTING_SAFEKEY_PRO",e);let d=await ue(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw y();if(Je(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new A;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw y();return{...t,shares:t.shares.concat(d.shares.map((l,p)=>({id:`${d.id}:${p}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new A;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),N(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await sr(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 Je(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new A}async function ue(r,e){if(e?.aborted)throw y();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(y()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw y();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function sr(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 A}if(Date.now()>=n)throw new be;await Te(t.pollIntervalMs??1500,t.signal)}}var A=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},me=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},be=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function or(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function lr(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!nt(n))throw n}}function nt(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function y(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var Q=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 W,this.state=t.state??new j,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??pr(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new c;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new c;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new c;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return L(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new c;return q(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new le){if(this.requireApplication(),!this.api)throw new c;return new de(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 T({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 ur(a);let i=await this.masterKeys?.resolve(e,t,n);if(!i)throw new T(e);return await this.keyVault.store(e,cr(i)),i}async prepareReveal(e,t,n){if(!this.api)throw new c;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 c;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new X;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 T({system:"INHERITI_BUSINESS",contextId:this.organizationId});let a=Se(e);if(!a)throw new T({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(a,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new c;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new c;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e){if(!this.api)throw new c;return this.api.getReveal(e)}openReveal(e,t){return tt(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 c;return Xe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new c;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new c;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new c;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e)}getRevealCustodianClaimable(e){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new c;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new c;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new c;return this.api.closeReveal(e,t)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return Ye(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new c;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new c;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new c;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new c;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new c;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new c;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let 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 c;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 xe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new T({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},xe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function dr(r){return new Q(r.coreSdk,{keyVault:r.keyVault,state:r.state,api:r.api,reconstructor:r.reconstructor,masterKeys:r.masterKeys,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:r.assetDecoder})}function cr(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 ur(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function pr(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 ie({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ie({...e,organizationId:r.organizationId})}var mr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],hr=["DIRECT","GOVERNED"],it=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],fr=["ACTIVE","REVOKED"],gr=["SK_MOBILE"],yr=["ACTIVE","INACTIVE"],vr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function st(r){let e=v(r);return{items:I(e.items).map(dt),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function ot(r){let e=v(r);return{total:_(e.total,"total"),items:I(e.items).map(t=>{let n=v(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:u(n.id,"log.id"),planId:u(n.planId,"log.planId"),tenantId:u(n.tenantId,"log.tenantId"),event:u(n.event,"log.event"),occurredOn:u(n.occurredOn,"log.occurredOn"),status:M(n.status),title:u(n.title,"log.title"),details:I(n.details).map(a=>{let i=v(a);return{label:u(i.label,"log.detail.label"),value:u(i.value,"log.detail.value")}})}})}}function lt(r){let e=v(r),t=dt(e),n=v(e.source),a=u(n.kind,"source.kind");return{...t,assets:I(e.assets).map(i=>{let s=v(i);return{id:u(s.id,"asset.id"),code:M(s.code),type:P(u(s.type,"asset.type"),se),name:u(s.name,"asset.name"),isBinary:wr(s.isBinary,"asset.isBinary"),fieldNames:I(s.fieldNames).map(o=>u(o,"asset.fieldNames")),fileName:M(s.fileName),mimeType:M(s.mimeType),size:s.size===void 0||s.size===null?void 0:_(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:I(s.matchOrigins).map(o=>u(o,"asset.matchOrigins"))}}),participants:I(e.participants).map(i=>{let s=v(i);return{id:u(s.id,"participant.id"),displayName:u(s.displayName,"participant.displayName"),relationships:I(s.relationships).map(o=>P(u(o,"relationship"),it)),lifecycle:P(u(s.lifecycle,"participant.lifecycle"),fr)}}),revealPolicy:(()=>{let i=v(e.revealPolicy);return{masterKeyRelease:P(u(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:P(u(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=v(e.dms);return{subjectEmail:u(i.subjectEmail,"dms.subjectEmail"),countdownDays:_(i.countdownDays,"dms.countdownDays"),countdownHours:_(i.countdownHours,"dms.countdownHours"),countdownMinutes:_(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:P(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:P(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function Z(r){let e=v(r);return{operationId:u(e.operationId,"operationId"),stage:P(u(e.stage,"stage"),$e),outcome:P(u(e.outcome,"outcome"),vr),planId:M(e.planId),lastErrorCode:M(e.lastErrorCode),participants:e.participants===void 0?void 0:I(e.participants).map(t=>{let n=v(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:I(n.relationships).map(a=>Rr(u(a,"relationship"),it))}})}}function dt(r){let e=v(r),t=v(e.assetSummary),n=v(e.governance),a=v(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:M(e.description),status:P(u(e.status,"status"),mr),createdAt:u(e.createdAt,"createdAt"),configuredAt:M(e.configuredAt),assetSummary:{count:_(t.count,"assetSummary.count"),types:I(t.types).map(i=>P(u(i,"assetType"),se)),names:at(t.names).map(i=>u(i,"assetSummary.names"))},governance:{mode:P(u(n.mode,"governance.mode"),hr),minimumApprovals:_(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:_(a.owners,"owners"),mergers:_(a.mergers,"mergers"),moderators:_(a.moderators,"moderators")},authentication:at(e.authentication).map(i=>{let s=v(i);return{id:P(u(s.id,"authentication.id"),gr),status:P(u(s.status,"authentication.status"),yr)}})}}function P(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Rr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function v(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function at(r){return r==null?[]:I(r)}function I(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function u(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function M(r){return r==null?void 0:u(r,"optional")}function _(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function wr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var F=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function ct(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Pr(r,e){if(!e){if(r.length===0)throw new F("organization_required");if(r.length>1)throw new F("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new F("organization_access_denied");return e}function De(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 Oe(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var G=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}},he=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(ct)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let 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 st(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 ot(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){L(e);let{idempotencyKey:t,...n}=e;return Z(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return Z(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return q(t),Z(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return Z(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[h,R]of Object.entries(i??{}))o.set(h,R);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}),p=await ut(l);if(!l.ok)throw new G(l.status,De(p),Oe(p));if(!p.ok||p.result===void 0)throw new G(l.status,De(p),Oe(p));return p.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 G(s.status,De(o),Oe(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new G(400,"organization_selection_required")}};async function ut(r){try{return await r.json()}catch{return{ok:!1}}}async function pt(r,e){if(!e)throw new Error("master_key_required");let t=Er(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 Er(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 Ne=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as Ar}from"@safetech/inheriti-core-sdk/shared-configuration";var _r=new Set(["COMPLETED","ABORTED","EXPIRED"]),Me=class{constructor(e,t=new fe,n=new ge,a=Math.random){this.api=e;this.loop=new Ar(t,n,a)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,a,i=!1,s=this.loop.start(e,async()=>{let o=await this.api.getGovernedReveal(e),d=o.approvalProcess?.status??"",l=Cr(o);n!==void 0&&l!==n&&await t.onProcessUpdated?.(),a!==void 0&&d!==a&&await t.onApprovalUpdated?.(),n=l,a=d;let p=_r.has(o.status);if(o.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),o.status==="ABORTED"&&await t.onForceAborted?.(e),p)return{transitionKey:l,shouldPoll:!1,terminal:!0};if(!i){let h=await this.api.getCustodianShare(e);"status"in h||(i=!0,await t.onCustodianShareReceived?.(e,h))}return{transitionKey:l,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,s)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function Cr(r){return`${r.status}:${r.approvalProcess?.status??""}`}var fe=class{visibility(){return typeof document<"u"&&document.visibilityState==="hidden"?"hidden":"visible"}isOnline(){return typeof navigator>"u"||navigator.onLine!==!1}now(){return Date.now()}schedule(e,t){let n=setTimeout(e,t);return()=>clearTimeout(n)}onRecovery(e){return typeof globalThis.addEventListener!="function"?()=>{}:(globalThis.addEventListener("online",e),globalThis.addEventListener("visibilitychange",e),()=>{globalThis.removeEventListener("online",e),globalThis.removeEventListener("visibilitychange",e)})}},ge=class{join(e,t){let n=!0;return{isOwner:()=>n,requestReconciliation:()=>{n&&t.onReconciliationRequested()},publishReconciled:()=>{},leave:()=>{n=!1}}}};var mt=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){J(e.signal),Tr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return J(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){J(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(J(e.signal),!a.custodianPair)throw new w("custodian_share_required");let i=ke(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(ke(a.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(ke(a.backupShards),s.symmetricKeyBase64),l=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return J(e.signal),{protectionProtocol:a.protocol,validatorShares:Ke(s.encryptedShares),dataShards:Ke(o.encryptedShares),backupShards:Ke(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:br(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:Ue(n.encryptedShares[0]),dataShard:Ue(n.encryptedShares[1])}}};function ke(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ke(r){return r.map(Ue)}function Ue(r){return{id:r.id,data:r.encryptedData}}function br(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new w("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 Tr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new w("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new w("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new w("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 w("plan_secrets_declaration_mismatch")}}function J(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function ht(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var ye=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),ht(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return ht(new Uint8Array(t))}},ve=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 ee=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},te=class extends ee{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},m=class extends ee{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Le(r){if(r instanceof ee)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var ft=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:k(n,"issuer"),authorizationEndpoint:k(n,"authorization_endpoint"),tokenEndpoint:k(n,"token_endpoint"),deviceAuthorizationEndpoint:C(n,"device_authorization_endpoint"),endSessionEndpoint:C(n,"end_session_endpoint"),revocationEndpoint:C(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:k(t,"device_code"),userCode:k(t,"user_code"),verificationUri:k(t,"verification_uri"),verificationUriComplete:C(t,"verification_uri_complete"),expiresInSeconds:gt(t,"expires_in"),intervalSeconds:Ge(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:k(n,"access_token"),refreshToken:C(n,"refresh_token"),idToken:C(n,"id_token"),tokenType:k(n,"token_type"),expiresInSeconds:gt(n,"expires_in"),refreshExpiresInSeconds:Ge(n,"refresh_expires_in"),scope:C(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=C(a,"error")??`oauth_http_${n.status}`;throw new m(i,C(a,"error_description")??i)}return a}};function k(r,e){let t=C(r,e);if(!t)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function C(r,e){return typeof r[e]=="string"?r[e]:void 0}function gt(r,e){let t=Ge(r,e);if(t===void 0)throw new m("invalid_oauth_response",`Missing ${e}`);return t}function Ge(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var xr=600*1e3,Re=5,Dr=5,yt=class{constructor(e){this.options=e;this.crypto=e.crypto??new ye,this.clock=e.clock??new ve}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()+xr;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 m("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new m("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new m("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new m(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new m("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new m("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}),p=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(p),p}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new m("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(Re,t.intervalSeconds??Re),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 m("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(Re,a.intervalSeconds??Re),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=Le(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=Dr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new m("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 te;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 m("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=Le(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new te:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(z(e.issuer)!==z(this.options.configuration.issuer))throw new m("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}|${z(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new m("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 m("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 m("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(z(e.issuer)!==z(a.issuer))throw new m("issuer_mismatch");if(!i.includes(a.audience))throw new m("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new m("client_mismatch");if(e.environment!==a.environment)throw new m("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new m("required_claim_missing");if(n&&e.nonce!==t)throw new m("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(z(e.issuer)!==z(n.issuer))throw new m("issuer_mismatch");if(!a.includes(n.clientId))throw new m("client_mismatch");if(e.authorizedParty!==n.clientId)throw new m("client_mismatch");if(!e.subject||!e.sessionId)throw new m("required_claim_missing");if(e.nonce!==t)throw new m("nonce_mismatch")}};function z(r){return r.replace(/\/+$/u,"")}var vt=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};export{F as BusinessOrganizationSelectionError,se as CANONICAL_PLAN_ASSET_TYPES,jt as CANONICAL_STRUCTURED_ASSET_FIELDS,mt as CorePlanMaterialBuilder,c as ElementsApiPortRequired,G as ElementsApiRequestFailed,Q as ElementsClient,ce as GuidedCreateRecoveryError,de as GuidedPlanCreator,fe as HostProcessRuntimeEnvironment,he as HttpElementsApiPort,ft as HttpOperatorAuthTransport,qe as InheritiClientProvider,f as InvalidPlanDeclaration,w as InvalidPlanMaterial,ge as LocalProcessReconciliationOwnership,ae as MasterKeyRelayCancellationFailed,ne as MasterKeyRelayExpired,re as MasterKeyRelayTimedOut,T as MasterKeyRequired,le as MemoryGuidedCreateCheckpointStore,W as MemoryKeyVault,j as MemoryStatePort,m as OAuthProtocolError,yt as OperatorAuthClient,ee as OperatorAuthError,te as OperatorReauthenticationRequired,vt as OperatorSessionController,$e as PLAN_CREATION_SERVER_STAGES,Ne as PlanMaterialReconstructionFailed,X as PlanMaterialReconstructorRequired,Me as PollingSharedPlanEventListener,$ as RelayMasterKeySource,Y as RevealActionsNotOpen,g as RevealFieldAccessError,pe as RevealHandleClosed,wa as SDKContainer,Ie as StaticMasterKeyResolver,ve as SystemOAuthClock,ye as WebOAuthCrypto,dr as createElementsClient,ie as createMasterKeyResolver,Vt as getAvailableEnvs,Se as masterKeyRefFor,O as masterKeyRefKey,Le as oauthErrorCode,rt as parseAssetFieldSelector,et as revealPhaseOf,Pr as selectBusinessOrganization,pt as unwrapDekWithMasterKey,Fe as useClient,L as validatePlanCreationInput,q as validatePlanCreationMaterial};