@safetech/inheriti-client-sdk 1.17.16 → 1.17.18

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 (32) hide show
  1. package/dist/automation.d.ts +5 -0
  2. package/dist/automation.js +1 -0
  3. package/dist/browser.d.ts +1 -0
  4. package/dist/browser.js +1 -1
  5. package/dist/inbox.d.ts +11 -0
  6. package/dist/inbox.js +1 -0
  7. package/dist/index.d.ts +3 -0
  8. package/dist/index.js +1 -1
  9. package/dist/inheriti-client-sdk.umd.js +41 -41
  10. package/dist/node-base.d.ts +88 -0
  11. package/dist/node-base.js +1 -0
  12. package/dist/node.d.ts +3 -84
  13. package/dist/node.js +1 -1
  14. package/dist/sdk-types.d.ts +390 -2
  15. package/dist/src/business/inbox/inbox-response-validator.d.ts +39 -0
  16. package/dist/src/business/inbox/node-inbox-file.d.ts +43 -0
  17. package/dist/src/business/inbox/node-inbox-normal.d.ts +50 -0
  18. package/dist/src/business/inbox/node-inbox-parent.d.ts +104 -0
  19. package/dist/src/business/inbox/node-inbox-text.d.ts +88 -0
  20. package/dist/src/business/inbox/types.d.ts +269 -0
  21. package/dist/src/business/quick-plan/build-material.d.ts +3 -3
  22. package/dist/src/business/quick-plan/contract.d.ts +5 -1
  23. package/dist/src/business/quick-plan/http-quick-plan-port.d.ts +1 -1
  24. package/dist/src/business/quick-plan/prepare-asset.d.ts +8 -0
  25. package/dist/src/business/quick-plan/quick-plan-creator.d.ts +5 -1
  26. package/dist/src/business/quick-plan/request-fingerprint.d.ts +2 -2
  27. package/dist/src/elements/automation-reveal-client.d.ts +13 -0
  28. package/dist/src/elements/elements-api-port.d.ts +39 -0
  29. package/dist/src/elements/http-automation-reveal-api-port.d.ts +30 -0
  30. package/dist/src/elements/http-elements-api-port.d.ts +64 -0
  31. package/dist/src/elements/index.d.ts +3 -0
  32. package/package.json +27 -2
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{SDKContainer as Sa}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as xt,useEffect as qe,createContext as Dt,useMemo as Ot}from"react";import{CoreProvider as Nt,HttpClientFactory as Mt,AuthModule as kt,AuthStateProvider as Kt,AuthSessionRestorer as Ut,useClient as Lt}from"@safetech/inheriti-core-sdk";function N(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 $ from"react";import Lr from"react-dom";function Pt(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 Gr=Array(12).fill(0);var It=1,St=100,Be=r=>{var e;return typeof r?.id=="number"||(r==null||(e=r.id)==null?void 0:e.length)>0?r.id:It++},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-St;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=Be(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],$.isValidElement(l))i=!1,this.create({id:n,type:"default",message:l});else if(_t(l)&&!l.ok){i=!1;let p=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,y=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,b=typeof p=="object"&&!$.isValidElement(p)?p:{message:p};this.create({id:n,type:"error",description:y,...b})}else if(l instanceof Error){i=!1;let p=typeof t.error=="function"?await t.error(l):t.error,y=typeof t.description=="function"?await t.description(l):t.description,b=typeof p=="object"&&!$.isValidElement(p)?p:{message:p};this.create({id:n,type:"error",description:y,...b})}else if(t.success!==void 0){i=!1;let p=typeof t.success=="function"?await t.success(l):t.success,y=typeof t.description=="function"?await t.description(l):t.description,b=typeof p=="object"&&!$.isValidElement(p)?p:{message:p};this.create({id:n,type:"success",description:y,...b})}}).catch(async l=>{if(s=["reject",l],t.error!==void 0){i=!1;let m=typeof t.error=="function"?await t.error(l):t.error,p=typeof t.description=="function"?await t.description(l):t.description,A=typeof m=="object"&&!$.isValidElement(m)?m:{message:m};this.create({id:n,type:"error",description:p,...A})}}).finally(()=>{i&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),d=()=>new Promise((l,m)=>o.then(()=>s[0]==="reject"?m(s[1]):l(s[1])).catch(m));return typeof n!="string"&&typeof n!="number"?{unwrap:d}:Object.assign(n,{unwrap:d})},this.custom=(e,t)=>{let n=Be(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}},I=new we,At=(r,e)=>I.message(r,e),_t=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",bt=At,Ct=()=>I.toasts,Tt=()=>I.getActiveToasts(),V=Object.assign(bt,{success:I.success,info:I.info,warning:I.warning,error:I.error,custom:I.custom,message:I.message,promise:I.promise,dismiss:I.dismiss,loading:I.loading},{getHistory:Ct,getToasts:Tt});Pt("[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 Ve={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{V.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{V.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{V.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{V.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{V.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as Bt,jsx as q}from"react/jsx-runtime";var Gt="inheriti_client_merging_process",Ee=Dt(null);function Fe({children:r,clientId:e,options:t}){let n=t?.env??"development",a={key:e??"",options:{env:n}},i=xt(Mt.create({apiUrl:N("",n),errorHandlingStrategy:Ve}));qe(()=>{i.current?.setApiUrl(N("",n))},[n]);let s=Ot(()=>({core:{httpClient:i.current},"protection-plan":{authTokens:{mergingProcessKey:Gt}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return q(Ee.Provider,{value:i.current,children:q(Kt,{children:q(Nt,{modules:{auth:kt},moduleConfigs:s,children:q(Ut,{children:q(zt,{client:a,children:r})})})})})}function zt({children:r,client:e}){let{connect:t,isConnected:n}=Lt();return qe(()=>{!e?.key||n||t(e)},[e.key]),q(Bt,{children:r})}import{useContext as Vt,useCallback as qt}from"react";import{useClient as Ft}from"@safetech/inheriti-core-sdk";function He(){let{connect:r,...e}=Ft(),t=Vt(Ee),n=qt(async a=>(a?.options?.env&&t?.setApiUrl(N("",a.options.env)),r(a)),[r,t]);return{...e,connect:n}}function Ht(){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=N("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:a}}import{decryptRSAOAEP as $t,generateRSAOAEPKeyPair as Wt}from"@safetech/inheriti-core-sdk/crypto";var ne=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ae=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ie=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},W=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 Wt();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??(P=>new Promise(_=>setTimeout(_,P))),l=!0,m=!1,p,y=()=>p??=(async()=>{let P=new AbortController,_,wt=new Promise((Mr,Et)=>{_=setTimeout(()=>{P.abort(),Et(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(i.sessionId,P.signal),wt])}finally{clearTimeout(_)}})(),A,b=new Promise((P,_)=>{A=()=>{l&&y().catch(()=>{}),_(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",A,{once:!0})});b.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(i),m=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let P=await Promise.race([this.options.api.readRelaySession(i.sessionId,e),b]);if(P.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(P.status==="DELIVERED"&&P.sealedMasterKey){let _=(await $t(P.sealedMasterKey,a)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(_))throw new Error("invalid_master_key_material");return _}if(P.status==="EXPIRED")throw new ae(i.sessionId);await jt(d,s,e)}throw new ne(i.sessionId)}catch(P){if(l&&(!m||e?.aborted))try{await y()}catch(_){if(e?.aborted)throw new ie(_)}throw P}finally{A&&e?.removeEventListener("abort",A)}}};async function jt(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 se(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||Pe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Yt(e,r.applicationId)){let a=await r.source?.resolve();return a||Pe(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Pe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Yt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Pe(r,e,t,n,a){if((await e()).relayAvailable)return new W({...r.relay,api:Xt(r.api,t)}).resolve(n,a)}function Xt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function M(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 D=class extends Error{constructor(t){super(`master_key_required:${M(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(M(e),t),this}async resolve(e){return this.sources.get(M(e))?.resolve()}};var j=class{keys=new Map;async store(e,t){let n=M(e),a=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,a)}async load(e){return this.keys.get(M(e))?.slice()}async remove(e){let t=M(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var Y=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 X=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 Q=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var oe=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],_e={"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"]},We=["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 F(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 G(r){if(L(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(L(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),!oe.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(Qt(t.matchOrigins),!t.isBinary){let i=_e[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(L(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!je(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")}Zt(r)}function Qt(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 Zt(r){let e=r.policy;if(e&&L(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"){L(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){L(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;L(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!je(t.subjectEmail))throw new f("dms_subject_invalid");if(!r.participants.some(i=>$e(i.routingEmail)===$e(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 je(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function $e(r){return r.normalize("NFC").trim().toLowerCase()}function L(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new f(t)}var de=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},ce=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),G(e),le(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={}){G(t);let s=await this.checkpoints.load(e);if(!s)throw new ue("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Ye(t))throw new ue("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;le(i.signal),i.onProgress?.("ENCRYPTING");let d=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});le(i.signal),i.onProgress?.("GENERATING_SHARES");let l=await a.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:i.signal});le(i.signal),F(l);let m=await this.api.supplyPlanCreationMaterial(e,l);return i.onProgress?.(m.stage),m.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,m),m}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Ye(e),serverStage:t.stage})}},ue=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Ye(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 le(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Xe(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new X(n.stage);return r.authorizeRevealAction(e,t)}function er(r){let e=r?.status;return e===400||e===401||e===403}async function Qe(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!er(i))throw i}return r.releaseRevealMaterial(e,t)}function tt(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"?rr(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":tr.has(r.stage)?"ENDED":"CONTINUING"}var tr=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function rr(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"}},v=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function rt(r,e,t={}){if(t.signal?.aborted)throw g();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"}):Ze(a.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw g();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:Ze(l.id)}let o;try{if(t.signal?.aborted)throw g();let d=await ar(r,s,t);if(t.signal?.aborted||(k(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw g();let l=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw g();let m;try{m=await or(r,d,dr(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(k(t,"RECONSTRUCTING",d),t.signal?.aborted))throw g();try{o=await r.reconstructPlanMaterial(m)}catch(y){throw t.signal?.aborted?g():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:sr(y)}),y)}if(t.signal?.aborted)throw g();let p=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(k(t,"OPEN",p),t.signal?.aborted))throw g();return new Ce(r,p,n,o,t.signal)}catch(d){throw o?.fill(0),await at(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Ze(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var nr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function ar(r,e,t){let n=await O(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw g();if(t.onSession?.(n),t.onProgress?.({phase:tt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(nr.has(n.stage))throw new be(n.stage);await xe(t.pollIntervalMs??1500,t.signal),n=await O(()=>r.getReveal(e.id,t.signal),t.signal)}}var be=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function k(r,e,t){r.onProgress?.({phase:e,session:t})}function xe(r,e){return e?.aborted?Promise.reject(g()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(g())};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").catch(()=>{})}: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 v("asset_selector_invalid");if(!this.client.assetDecoder)throw new v("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=nt(i),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new v("asset_not_found");if(d.isBinary)throw new v("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new v("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 v("asset_value_invalid");return{selector:s.selector,value:ir(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",Je(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new v("asset_selector_invalid");if(!this.client.assetDecoder)throw new v("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new v("asset_not_found");if(!n.isBinary)throw new v("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 v("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",Je(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=at(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function nt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new v("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new v("asset_selector_invalid");return{asset:r.asset,field:r.field}}function ir(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new v("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new v("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?_e[t]:void 0)?.includes(e))return"";throw new v("asset_value_invalid")}return n[e]}function Je(r){if(r instanceof v)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 sr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function or(r,e,t,n){let a=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(a){let d=await O(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new me;let l=await O(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(et(l,a.id,e.planId),!l.shares.includes(a.data))throw new C;k(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:m}=await O(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw g();if(!m?.trim())throw new C;if(await r.claimRevealCustodianShare(e.id,l.id,m),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw g();return{...t,shares:t.shares.filter(p=>p!==a).concat(l.shares.map((p,y)=>({id:`${l.id}:${y}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new C;if(n.signal?.aborted)throw g();return await r.distributeRevealCustodianShare(e.id),k(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await O(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),k(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await xe(n.pollIntervalMs??1500,n.signal),i=await O(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new me;if(!i.shareId||!i.deviceId)throw new C;k(n,"CONNECTING_SAFEKEY_PRO",e);let d=await O(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw g();if(et(d,i.shareId,e.planId),d.deviceId!==i.deviceId)throw new C;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw g();return{...t,shares:t.shares.concat(d.shares.map((l,m)=>({id:`${d.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new C;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(s),k(n,"WAITING_FOR_CUSTODIAN",s),n.signal?.aborted)throw g();await r.requestRevealCustodianRelease(e.id);let o=await lr(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 et(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new C}async function O(r,e){if(e?.aborted)throw g();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(g()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw g();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function lr(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await O(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(a&&a.status!=="PENDING"){let i=a;if(i.shares?.length)return i;throw new C}if(Date.now()>=n)throw new Te;await xe(t.pollIntervalMs??1500,t.signal)}}var C=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"}},Te=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function dr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function at(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(s){if(!cr(s))throw s}return}let n=new AbortController,a,i=new Promise((s,o)=>{a=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([r.closeReveal(e,t,n.signal),i]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(a)}}function cr(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function g(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var Z=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 j,this.state=t.state??new Y,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??hr(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 G(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 F(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new de){if(this.requireApplication(),!this.api)throw new c;return new ce(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new D({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let a=await this.keyVault.load(e);if(a)return mr(a);let i=await this.masterKeys?.resolve(e,t,n);if(!i)throw new D(e);return await this.keyVault.store(e,pr(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 Q;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new D({system:"INHERITI_BUSINESS",contextId:this.organizationId});let a=Se(e);if(!a)throw new D({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,t){if(!this.api)throw new c;return this.api.getReveal(e,t)}openReveal(e,t){return rt(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 Qe(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,t){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,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,n){if(!this.api)throw new c;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return Xe(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 De;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new D({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},De=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function ur(r){return new Z(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 pr(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 mr(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function hr(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 se({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return se({...e,organizationId:r.organizationId})}var fr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],gr=["DIRECT","GOVERNED"],st=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],yr=["ACTIVE","REVOKED"],vr=["SK_MOBILE"],Rr=["ACTIVE","INACTIVE"],wr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ot(r){let e=R(r);return{items:S(e.items).map(ct),nextCursor:e.nextCursor===null?null:u(e.nextCursor,"nextCursor")}}function lt(r){let e=R(r);return{total:T(e.total,"total"),items:S(e.items).map(t=>{let n=R(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:K(n.status),title:u(n.title,"log.title"),details:S(n.details).map(a=>{let i=R(a);return{label:u(i.label,"log.detail.label"),value:u(i.value,"log.detail.value")}})}})}}function dt(r){let e=R(r),t=ct(e),n=R(e.source),a=u(n.kind,"source.kind");return{...t,assets:S(e.assets).map(i=>{let s=R(i);return{id:u(s.id,"asset.id"),code:K(s.code),type:E(u(s.type,"asset.type"),oe),name:u(s.name,"asset.name"),isBinary:Pr(s.isBinary,"asset.isBinary"),fieldNames:S(s.fieldNames).map(o=>u(o,"asset.fieldNames")),fileName:K(s.fileName),mimeType:K(s.mimeType),size:s.size===void 0||s.size===null?void 0:T(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:S(s.matchOrigins).map(o=>u(o,"asset.matchOrigins"))}}),participants:S(e.participants).map(i=>{let s=R(i);return{id:u(s.id,"participant.id"),displayName:u(s.displayName,"participant.displayName"),relationships:S(s.relationships).map(o=>E(u(o,"relationship"),st)),lifecycle:E(u(s.lifecycle,"participant.lifecycle"),yr)}}),revealPolicy:(()=>{let i=R(e.revealPolicy);return{masterKeyRelease:E(u(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:E(u(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=R(e.dms);return{subjectEmail:u(i.subjectEmail,"dms.subjectEmail"),countdownDays:T(i.countdownDays,"dms.countdownDays"),countdownHours:T(i.countdownHours,"dms.countdownHours"),countdownMinutes:T(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:E(u(n.system,"source.system"),["INHERITI_BUSINESS"]),status:E(u(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function J(r){let e=R(r);return{operationId:u(e.operationId,"operationId"),stage:E(u(e.stage,"stage"),We),outcome:E(u(e.outcome,"outcome"),wr),planId:K(e.planId),lastErrorCode:K(e.lastErrorCode),participants:e.participants===void 0?void 0:S(e.participants).map(t=>{let n=R(t);return{clientParticipantRef:u(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:u(n.planParticipantId,"planParticipantId"),relationships:S(n.relationships).map(a=>Er(u(a,"relationship"),st))}})}}function ct(r){let e=R(r),t=R(e.assetSummary),n=R(e.governance),a=R(e.participantSummary);return{id:u(e.id,"id"),name:u(e.name,"name"),description:K(e.description),status:E(u(e.status,"status"),fr),createdAt:u(e.createdAt,"createdAt"),configuredAt:K(e.configuredAt),assetSummary:{count:T(t.count,"assetSummary.count"),types:S(t.types).map(i=>E(u(i,"assetType"),oe)),names:it(t.names).map(i=>u(i,"assetSummary.names"))},governance:{mode:E(u(n.mode,"governance.mode"),gr),minimumApprovals:T(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:T(a.owners,"owners"),mergers:T(a.mergers,"mergers"),moderators:T(a.moderators,"moderators")},authentication:it(e.authentication).map(i=>{let s=R(i);return{id:E(u(s.id,"authentication.id"),vr),status:E(u(s.status,"authentication.status"),Rr)}})}}function E(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Er(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function R(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function it(r){return r==null?[]:S(r)}function S(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 K(r){return r==null?void 0:u(r,"optional")}function T(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Pr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var H=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function ut(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 Ir(r,e){if(!e){if(r.length===0)throw new H("organization_required");if(r.length>1)throw new H("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new H("organization_access_denied");return e}function Oe(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 Ne(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var z=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(ut)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return ot(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return dt(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return lt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){G(e);let{idempotencyKey:t,...n}=e;return J(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return J(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return F(t),J(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return J(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...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,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...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,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),a?.requestId&&d.set("x-elements-step-up-request",a.requestId);for(let[A,b]of Object.entries(i??{}))d.set(A,b);n&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,m={method:t,headers:d,body:n?JSON.stringify(n):void 0};s&&(m.signal=s);let p=await this.transport(new URL(e,l),m);s?.throwIfAborted();let y=await pt(p,s);if(s?.throwIfAborted(),!p.ok)throw new z(p.status,Oe(y),Ne(y));if(!y.ok||y.result===void 0)throw new z(p.status,Oe(y),Ne(y));return y.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 pt(s);if(!s.ok||!o.ok)throw new z(s.status,Oe(o),Ne(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new z(400,"organization_selection_required")}};async function pt(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}async function mt(r,e){if(!e)throw new Error("master_key_required");let t=Sr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=Ar(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return _r(new Uint8Array(o))}function Sr(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 Ar(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 _r(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Me=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as br}from"@safetech/inheriti-core-sdk/shared-configuration";var Cr=new Set(["COMPLETED","ABORTED","EXPIRED"]),ke=class{constructor(e,t=new fe,n=new ge,a=Math.random){this.api=e;this.loop=new br(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=Tr(o);n!==void 0&&l!==n&&await t.onProcessUpdated?.(),a!==void 0&&d!==a&&await t.onApprovalUpdated?.(),n=l,a=d;let m=Cr.has(o.status);if(o.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),o.status==="ABORTED"&&await t.onForceAborted?.(e),m)return{transitionKey:l,shouldPoll:!1,terminal:!0};if(!i){let p=await this.api.getCustodianShare(e);"status"in p||(i=!0,await t.onCustodianShareReceived?.(e,p))}return{transitionKey:l,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,s)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function Tr(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 ht=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){ee(e.signal),Dr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return ee(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){ee(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(ee(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 ee(e.signal),{protectionProtocol:a.protocol,validatorShares:Ue(s.encryptedShares),dataShards:Ue(o.encryptedShares),backupShards:Ue(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:xr(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:Le(n.encryptedShares[0]),dataShard:Le(n.encryptedShares[1])}}};function Ke(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ue(r){return r.map(Le)}function Le(r){return{id:r.id,data:r.encryptedData}}function xr(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 Dr(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 ee(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function ft(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),ft(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return ft(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 te=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},re=class extends te{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},h=class extends te{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ge(r){if(r instanceof te)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var gt=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:U(n,"issuer"),authorizationEndpoint:U(n,"authorization_endpoint"),tokenEndpoint:U(n,"token_endpoint"),deviceAuthorizationEndpoint:x(n,"device_authorization_endpoint"),endSessionEndpoint:x(n,"end_session_endpoint"),revocationEndpoint:x(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:U(t,"device_code"),userCode:U(t,"user_code"),verificationUri:U(t,"verification_uri"),verificationUriComplete:x(t,"verification_uri_complete"),expiresInSeconds:yt(t,"expires_in"),intervalSeconds:ze(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:U(n,"access_token"),refreshToken:x(n,"refresh_token"),idToken:x(n,"id_token"),tokenType:U(n,"token_type"),expiresInSeconds:yt(n,"expires_in"),refreshExpiresInSeconds:ze(n,"refresh_expires_in"),scope:x(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=x(a,"error")??`oauth_http_${n.status}`;throw new h(i,x(a,"error_description")??i)}return a}};function U(r,e){let t=x(r,e);if(!t)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function x(r,e){return typeof r[e]=="string"?r[e]:void 0}function yt(r,e){let t=ze(r,e);if(t===void 0)throw new h("invalid_oauth_response",`Missing ${e}`);return t}function ze(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Or=600*1e3,Re=5,Nr=5,vt=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()+Or;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",i),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new h("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new h("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new h("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new h(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new h("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new h("authorization_code_missing");let d=await this.getDiscovery(),l=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),m=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(m),m}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new h("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(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 h("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=Ge(d);if(l==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(l==="slow_down"){s+=Nr,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new h("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new re;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new h("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=Ge(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new re:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(B(e.issuer)!==B(this.options.configuration.issuer))throw new h("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${B(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new h("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new h("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new h("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(B(e.issuer)!==B(a.issuer))throw new h("issuer_mismatch");if(!i.includes(a.audience))throw new h("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new h("client_mismatch");if(e.environment!==a.environment)throw new h("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new h("required_claim_missing");if(n&&e.nonce!==t)throw new h("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(B(e.issuer)!==B(n.issuer))throw new h("issuer_mismatch");if(!a.includes(n.clientId))throw new h("client_mismatch");if(e.authorizedParty!==n.clientId)throw new h("client_mismatch");if(!e.subject||!e.sessionId)throw new h("required_claim_missing");if(e.nonce!==t)throw new h("nonce_mismatch")}};function B(r){return r.replace(/\/+$/u,"")}var Rt=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{H as BusinessOrganizationSelectionError,oe as CANONICAL_PLAN_ASSET_TYPES,_e as CANONICAL_STRUCTURED_ASSET_FIELDS,ht as CorePlanMaterialBuilder,c as ElementsApiPortRequired,z as ElementsApiRequestFailed,Z as ElementsClient,ue as GuidedCreateRecoveryError,ce as GuidedPlanCreator,fe as HostProcessRuntimeEnvironment,he as HttpElementsApiPort,gt as HttpOperatorAuthTransport,Fe as InheritiClientProvider,f as InvalidPlanDeclaration,w as InvalidPlanMaterial,ge as LocalProcessReconciliationOwnership,ie as MasterKeyRelayCancellationFailed,ae as MasterKeyRelayExpired,ne as MasterKeyRelayTimedOut,D as MasterKeyRequired,de as MemoryGuidedCreateCheckpointStore,j as MemoryKeyVault,Y as MemoryStatePort,h as OAuthProtocolError,vt as OperatorAuthClient,te as OperatorAuthError,re as OperatorReauthenticationRequired,Rt as OperatorSessionController,We as PLAN_CREATION_SERVER_STAGES,Me as PlanMaterialReconstructionFailed,Q as PlanMaterialReconstructorRequired,ke as PollingSharedPlanEventListener,W as RelayMasterKeySource,X as RevealActionsNotOpen,v as RevealFieldAccessError,pe as RevealHandleClosed,Sa as SDKContainer,Ie as StaticMasterKeyResolver,ve as SystemOAuthClock,ye as WebOAuthCrypto,ur as createElementsClient,se as createMasterKeyResolver,Ht as getAvailableEnvs,Se as masterKeyRefFor,M as masterKeyRefKey,Ge as oauthErrorCode,nt as parseAssetFieldSelector,tt as revealPhaseOf,Ir as selectBusinessOrganization,mt as unwrapDekWithMasterKey,He as useClient,G as validatePlanCreationInput,F as validatePlanCreationMaterial};
1
+ import{SDKContainer as as}from"@safetech/inheriti-core-sdk/vanilla";export*from"@safetech/inheriti-core-sdk";import{useRef as Jt,useEffect as tt,createContext as en,useMemo as tn}from"react";import{CoreProvider as nn,HttpClientFactory as rn,AuthModule as sn,AuthStateProvider as an,AuthSessionRestorer as on,useClient as ln}from"@safetech/inheriti-core-sdk";function L(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 te from"react";import cr from"react-dom";function $t(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 ur=Array(12).fill(0);var Ht=1,Wt=100,Je=r=>{var e;return typeof r?.id=="number"||(r==null||(e=r.id)==null?void 0:e.length)>0?r.id:Ht++},Me=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-Wt;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,i=Je(e),s=this.pendingDismissals.get(i);s!==void 0&&(cancelAnimationFrame(s),this.pendingDismissals.delete(i),this.dismissedToasts.delete(i));let a=this.dismissedToasts.has(i),o=e.dismissible===void 0?!0:e.dismissible;return a&&(this.dismissedToasts.delete(i),this.toasts=this.toasts.filter(l=>l.id!==i)),(a?void 0:this.toasts.find(l=>l.id===i))?this.toasts=this.toasts.map(l=>l.id===i?(this.publish({...l,...e,id:i,title:t}),{...l,...e,id:i,dismissible:o,title:t}):l):this.addToast({title:t,...n,dismissible:o,id:i}),i},this.dismiss=e=>{if(e==null)return this.getActiveToasts().forEach(n=>{this.dismissedToasts.add(n.id),this.subscribers.forEach(i=>i({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 i=Promise.resolve(e instanceof Function?e():e),s=n!==void 0,a,o=i.then(async l=>{if(a=["resolve",l],te.isValidElement(l))s=!1,this.create({id:n,type:"default",message:l});else if(Yt(l)&&!l.ok){s=!1;let g=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,b=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description,_=typeof g=="object"&&!te.isValidElement(g)?g:{message:g};this.create({id:n,type:"error",description:b,..._})}else if(l instanceof Error){s=!1;let g=typeof t.error=="function"?await t.error(l):t.error,b=typeof t.description=="function"?await t.description(l):t.description,_=typeof g=="object"&&!te.isValidElement(g)?g:{message:g};this.create({id:n,type:"error",description:b,..._})}else if(t.success!==void 0){s=!1;let g=typeof t.success=="function"?await t.success(l):t.success,b=typeof t.description=="function"?await t.description(l):t.description,_=typeof g=="object"&&!te.isValidElement(g)?g:{message:g};this.create({id:n,type:"success",description:b,..._})}}).catch(async l=>{if(a=["reject",l],t.error!==void 0){s=!1;let u=typeof t.error=="function"?await t.error(l):t.error,g=typeof t.description=="function"?await t.description(l):t.description,x=typeof u=="object"&&!te.isValidElement(u)?u:{message:u};this.create({id:n,type:"error",description:g,...x})}}).finally(()=>{s&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),d=()=>new Promise((l,u)=>o.then(()=>a[0]==="reject"?u(a[1]):l(a[1])).catch(u));return typeof n!="string"&&typeof n!="number"?{unwrap:d}:Object.assign(n,{unwrap:d})},this.custom=(e,t)=>{let n=Je(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}},C=new Me,jt=(r,e)=>C.message(r,e),Yt=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",Xt=jt,Qt=()=>C.toasts,Zt=()=>C.getActiveToasts(),X=Object.assign(Xt,{success:C.success,info:C.info,warning:C.warning,error:C.error,custom:C.custom,message:C.message,promise:C.promise,dismiss:C.dismiss,loading:C.loading},{getHistory:Qt,getToasts:Zt});$t("[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 et={getErrorTitle:()=>"Inheriti\xAE Client SDK",shouldShowToast:(r,e)=>!0,handleNetworkError:r=>{X.error("Inheriti\xAE Client SDK",{description:"Can't connect to server",richColors:!0})},handleUnauthorizedError:r=>{X.error("Inheriti\xAE Client SDK",{description:"Your session has expired. Try reconnecting your client.",richColors:!0})},handleForbiddenError:r=>{X.error("Inheriti\xAE Client SDK",{description:"Your session has expired or the access was denied. Try reconnecting your client.",richColors:!0})},handleInvalidClientError:r=>{X.error("Inheriti\xAE Client SDK",{description:"The client ID provided is not valid",richColors:!0})},handleGenericError:(r,e)=>{X.error("Inheriti\xAE Client SDK",{description:`An error occurred: ${r.message}`,richColors:!0})}};import{Fragment as un,jsx as Q}from"react/jsx-runtime";var dn="inheriti_client_merging_process",Oe=en(null);function nt({children:r,clientId:e,options:t}){let n=t?.env??"development",i={key:e??"",options:{env:n}},s=Jt(rn.create({apiUrl:L("",n),errorHandlingStrategy:et}));tt(()=>{s.current?.setApiUrl(L("",n))},[n]);let a=tn(()=>({core:{httpClient:s.current},"protection-plan":{authTokens:{mergingProcessKey:dn}},auth:{routes:{login:"client/connect",logout:"client/disconnect",profile:"client/info"}}}),[]);return Q(Oe.Provider,{value:s.current,children:Q(an,{children:Q(nn,{modules:{auth:sn},moduleConfigs:a,children:Q(on,{children:Q(cn,{client:i,children:r})})})})})}function cn({children:r,client:e}){let{connect:t,isConnected:n}=ln();return tt(()=>{!e?.key||n||t(e)},[e.key]),Q(un,{children:r})}import{useContext as pn,useCallback as mn}from"react";import{useClient as gn}from"@safetech/inheriti-core-sdk";function rt(){let{connect:r,...e}=gn(),t=pn(Oe),n=mn(async i=>(i?.options?.env&&t?.setApiUrl(L("",i.options.env)),r(i)),[r,t]);return{...e,connect:n}}function hn(){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/",i=L("",t);return{availableEnvironments:e,defaultEnv:t,registerUrl:n,demoKeyApiUrl:i}}import{decryptRSAOAEP as fn,generateRSAOAEPKeyPair as yn}from"@safetech/inheriti-core-sdk/crypto";var ue=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},pe=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},me=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},B=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await yn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(S=>new Promise(w=>setTimeout(w,S))),l=!0,u=!1,g,b=()=>g??=(async()=>{let S=new AbortController,w,Bt=new Promise((ar,Vt)=>{w=setTimeout(()=>{S.abort(),Vt(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(s.sessionId,S.signal),Bt])}finally{clearTimeout(w)}})(),x,_=new Promise((S,w)=>{x=()=>{l&&b().catch(()=>{}),w(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",x,{once:!0})});_.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),u=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let S=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),_]);if(S.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(S.status==="DELIVERED"&&S.sealedMasterKey){let w=(await fn(S.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(w))throw new Error("invalid_master_key_material");return w}if(S.status==="EXPIRED")throw new pe(s.sessionId);await vn(d,a,e)}throw new ue(s.sessionId)}catch(S){if(l&&(!u||e?.aborted))try{await b()}catch(w){if(e?.aborted)throw new me(w)}throw S}finally{x&&e?.removeEventListener("abort",x)}}};async function vn(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function ge(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||ke(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(In(e,r.applicationId)){let i=await r.source?.resolve();return i||ke(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ke(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function In(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ke(r,e,t,n,i){if((await e()).relayAvailable)return new B({...r.relay,api:bn(r.api,t)}).resolve(n,i)}function bn(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function q(r){return`${r.system}:${r.contextId}`}function ne(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var K=class extends Error{constructor(t){super(`master_key_required:${q(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Ne=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(q(e),t),this}async resolve(e){return this.sources.get(q(e))?.resolve()}};var re=class{keys=new Map;async store(e,t){let n=q(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(q(e))?.slice()}async remove(e){let t=q(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ie=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 se=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var ae=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var he=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ue={"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"]},st=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],y=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function Z(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(Ke(r.dataShards,"data_shards_invalid"),Ke(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Ke(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new E("material_operation_invalid")}function Ke(r,e){if(!Array.isArray(r))throw new E(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function $(r){if(V(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Rn(r.idempotencyKey))throw new y("idempotency_key_invalid");if(!r.name?.trim())throw new y("plan_name_required");if(!r.assets.length)throw new y("assets_required");let e=new Set;for(let t of r.assets){if(V(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 y("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!he.includes(t.type))throw new y("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new y("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new y("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new y("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new y("asset_field_names_invalid");if(wn(t.matchOrigins),!t.isBinary){let s=Ue[t.type];if(!s||i.some(a=>!s.includes(a)))throw new y("asset_field_name_not_canonical")}}if(!r.participants.length)throw new y("participants_required");for(let t of r.participants){if(V(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!at(t.routingEmail))throw new y("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new y("participant_relationships_invalid")}Pn(r)}function wn(r){if(r===void 0)return;if(!r.length)throw new y("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new y("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new y("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof y?n:new y("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new y("asset_match_origins_duplicated")}function Pn(r){let e=r.policy;if(e&&V(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new y("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){V(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new y("authentication_mode_invalid")}if(e.moderation){V(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new y("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new y("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new y("approval_mode_invalid")}let t=e.dms;if(!t)return;V(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!at(t.subjectEmail))throw new y("dms_subject_invalid");if(!r.participants.some(s=>it(s.routingEmail)===it(t.subjectEmail)))throw new y("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new y("dms_countdown_invalid")}function Rn(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 at(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function it(r){return r.normalize("NFC").trim().toLowerCase()}function V(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new y(t)}var ye=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)}},ve=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),$(e),fe(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,s={}){$(t);let a=await this.checkpoints.load(e);if(!a)throw new Ie("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await ot(t))throw new Ie("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;fe(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});fe(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});fe(s.signal),Z(l);let u=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(u.stage),u.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,u),u}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 ot(e),serverStage:t.stage})}},Ie=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function ot(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function fe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function lt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new se(n.stage);return r.authorizeRevealAction(e,t)}function Sn(r){let e=r?.status;return e===400||e===401||e===403}async function dt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Sn(s))throw s}return r.releaseRevealMaterial(e,t)}function mt(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"?xn(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":En.has(r.stage)?"ENDED":"CONTINUING"}var En=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function xn(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 be=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function gt(r,e,t={}){if(t.signal?.aborted)throw I();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):ct(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw I();let s=t.idempotencyKey??crypto.randomUUID(),a;try{a=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}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:ct(l.id)}let o;try{if(t.signal?.aborted)throw I();let d=await _n(r,a,t);if(t.signal?.aborted||(G(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw I();let l=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw I();let u;try{u=await Dn(r,d,On(l),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(G(t,"RECONSTRUCTING",d),t.signal?.aborted))throw I();try{o=await r.reconstructPlanMaterial(u)}catch(b){throw t.signal?.aborted?I():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Tn(b)}),b)}if(t.signal?.aborted)throw I();let g=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(G(t,"OPEN",g),t.signal?.aborted))throw I();return new qe(r,g,n,o,t.signal)}catch(d){throw o?.fill(0),await ft(r,a.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function ct(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var An=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function _n(r,e,t){let n=await U(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw I();if(t.onSession?.(n),t.onProgress?.({phase:mt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(An.has(n.stage))throw new Le(n.stage);await ze(t.pollIntervalMs??1500,t.signal),n=await U(()=>r.getReveal(e.id,t.signal),t.signal)}}var Le=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function G(r,e,t){r.onProgress?.({phase:e,session:t})}function ze(r,e){return e?.aborted?Promise.reject(I()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(I())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var qe=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new be;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=ht(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new P("asset_not_found");if(d.isBinary)throw new P("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new P("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new P("asset_value_invalid");return{selector:a.selector,value:Cn(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",ut(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new P("asset_selector_invalid");if(!this.client.assetDecoder)throw new P("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new P("asset_not_found");if(!n.isBinary)throw new P("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new P("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",ut(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=ft(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function ht(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new P("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new P("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Cn(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new P("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new P("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Ue[t]:void 0)?.includes(e))return"";throw new P("asset_value_invalid")}return n[e]}function ut(r){if(r instanceof P)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Tn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Dn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await U(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new we;let l=await U(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(pt(l,i.id,e.planId),!l.shares.includes(i.data))throw new O;G(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:u}=await U(()=>n.proDevice.write(l,n.signal),n.signal);if(n.signal?.aborted)throw I();if(!u?.trim())throw new O;if(await r.claimRevealCustodianShare(e.id,l.id,u),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,l.id),n.signal?.aborted))throw I();return{...t,shares:t.shares.filter(g=>g!==i).concat(l.shares.map((g,b)=>({id:`${l.id}:${b}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:g})))}}if(d!=="SK_MOBILE")throw new O;if(n.signal?.aborted)throw I();return await r.distributeRevealCustodianShare(e.id),G(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await U(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),G(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ze(n.pollIntervalMs??1500,n.signal),s=await U(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new we;if(!s.shareId||!s.deviceId)throw new O;G(n,"CONNECTING_SAFEKEY_PRO",e);let d=await U(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw I();if(pt(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new O;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw I();return{...t,shares:t.shares.concat(d.shares.map((l,u)=>({id:`${d.id}:${u}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new O;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),G(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw I();await r.requestRevealCustodianRelease(e.id);let o=await Mn(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 pt(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 O}async function U(r,e){if(e?.aborted)throw I();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(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 Mn(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await U(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new O}if(Date.now()>=n)throw new Ge;await ze(t.pollIntervalMs??1500,t.signal)}}var O=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},we=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ge=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function On(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function ft(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!kn(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function kn(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 H=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 re,this.state=t.state??new ie,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Ln(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return $(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return Z(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new ye){if(this.requireApplication(),!this.api)throw new p;return new ve(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 K({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return Un(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new K(e);return await this.keyVault.store(e,Kn(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new ae;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 K({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=ne(e);if(!i)throw new K({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new p;return this.api.getReveal(e,t)}openReveal(e,t){return gt(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return dt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new p;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return lt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let s=n.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,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 p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new Fe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new K({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Fe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Nn(r){return new H(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 Kn(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 Un(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ln(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 ge({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ge({...e,organizationId:r.organizationId})}var qn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Gn=["DIRECT","GOVERNED"],vt=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],zn=["ACTIVE","REVOKED"],Fn=["SK_MOBILE"],Bn=["ACTIVE","INACTIVE"],Vn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function It(r){let e=R(r);return{items:T(e.items).map(wt),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function bt(r){let e=R(r);return{total:k(e.total,"total"),items:T(e.items).map(t=>{let n=R(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:m(n.id,"log.id"),planId:m(n.planId,"log.planId"),tenantId:m(n.tenantId,"log.tenantId"),event:m(n.event,"log.event"),occurredOn:m(n.occurredOn,"log.occurredOn"),status:z(n.status),title:m(n.title,"log.title"),details:T(n.details).map(i=>{let s=R(i);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function Pe(r){let e=R(r),t=wt(e),n=R(e.source),i=m(n.kind,"source.kind");return{...t,assets:T(e.assets).map(s=>{let a=R(s);return{id:m(a.id,"asset.id"),code:z(a.code),type:A(m(a.type,"asset.type"),he),name:m(a.name,"asset.name"),isBinary:Hn(a.isBinary,"asset.isBinary"),fieldNames:T(a.fieldNames).map(o=>m(o,"asset.fieldNames")),fileName:z(a.fileName),mimeType:z(a.mimeType),size:a.size===void 0||a.size===null?void 0:k(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:T(a.matchOrigins).map(o=>m(o,"asset.matchOrigins"))}}),participants:T(e.participants).map(s=>{let a=R(s);return{id:m(a.id,"participant.id"),displayName:m(a.displayName,"participant.displayName"),relationships:T(a.relationships).map(o=>A(m(o,"relationship"),vt)),lifecycle:A(m(a.lifecycle,"participant.lifecycle"),zn)}}),revealPolicy:(()=>{let s=R(e.revealPolicy);return{masterKeyRelease:A(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:A(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=R(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:k(s.countdownDays,"dms.countdownDays"),countdownHours:k(s.countdownHours,"dms.countdownHours"),countdownMinutes:k(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:A(m(n.system,"source.system"),["INHERITI_BUSINESS"]),status:A(m(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function oe(r){let e=R(r);return{operationId:m(e.operationId,"operationId"),stage:A(m(e.stage,"stage"),st),outcome:A(m(e.outcome,"outcome"),Vn),planId:z(e.planId),lastErrorCode:z(e.lastErrorCode),participants:e.participants===void 0?void 0:T(e.participants).map(t=>{let n=R(t);return{clientParticipantRef:m(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(n.planParticipantId,"planParticipantId"),relationships:T(n.relationships).map(i=>$n(m(i,"relationship"),vt))}})}}function wt(r){let e=R(r),t=R(e.assetSummary),n=R(e.governance),i=R(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:z(e.description),status:A(m(e.status,"status"),qn),createdAt:m(e.createdAt,"createdAt"),configuredAt:z(e.configuredAt),assetSummary:{count:k(t.count,"assetSummary.count"),types:T(t.types).map(s=>A(m(s,"assetType"),he)),names:yt(t.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:A(m(n.mode,"governance.mode"),Gn),minimumApprovals:k(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:k(i.owners,"owners"),mergers:k(i.mergers,"mergers"),moderators:k(i.moderators,"moderators")},authentication:yt(e.authentication).map(s=>{let a=R(s);return{id:A(m(a.id,"authentication.id"),Fn),status:A(m(a.status,"authentication.status"),Bn)}})}}function A(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function $n(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function R(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function yt(r){return r==null?[]:T(r)}function T(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function m(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function z(r){return r==null?void 0:m(r,"optional")}function k(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Hn(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var J=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Pt(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Wn(r,e){if(!e){if(r.length===0)throw new J("organization_required");if(r.length>1)throw new J("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new J("organization_access_denied");return e}function jn(r){let e=v(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),createdAt:D(e.createdAt)}}function Rt(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(jn),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function St(r){let e=v(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=v(t);return{unitId:c(n.unitId),position:h(n.position,0),commitment:c(n.commitment),status:c(n.status)}})}}function Be(r){let e=v(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:c(e.parentId),sequence:h(e.sequence,1),status:e.status}}function Et(r){let e=v(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),parentId:c(e.parentId),participantRevision:h(e.participantRevision,1),recipients:e.recipients.map(Ve)}}function xt(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=v(t);return{parentId:c(n.parentId),sequence:h(n.sequence,1),senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),participantRevision:h(n.participantRevision,1),createdAt:D(n.createdAt)}}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0),unreadCount:h(e.unreadCount,0),readThroughSequence:h(e.readThroughSequence,0)}}function At(r){return{readThroughSequence:h(v(r).readThroughSequence,0)}}function _t(r){return{clearedThroughSequence:h(v(r).clearedThroughSequence,0)}}function Ct(r){let e=v(r);return{parentId:c(e.parentId),sequence:h(e.sequence,1),senderMemberId:c(e.senderMemberId),senderDeviceId:c(e.senderDeviceId),participantRevision:h(e.participantRevision,1),canonicalManifest:c(e.canonicalManifest),frame:c(e.frame),signature:c(e.signature),wrappedContentKey:c(e.wrappedContentKey),senderSigningPublicKey:c(e.senderSigningPublicKey)}}function v(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function c(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function D(r){let e=c(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function h(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Ve(r){let e=v(r);return{memberId:c(e.memberId),deviceId:c(e.deviceId),deviceVersion:h(e.deviceVersion,1),encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint)}}function ee(r){let e=v(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:c(e.id),tenantId:c(e.tenantId),memberId:c(e.memberId),version:e.version,encryptionPublicKey:c(e.encryptionPublicKey),encryptionKeyFingerprint:c(e.encryptionKeyFingerprint),signingPublicKey:c(e.signingPublicKey),signingKeyFingerprint:c(e.signingKeyFingerprint),status:e.status,createdAt:D(e.createdAt),updatedAt:D(e.updatedAt)}}function Re(r){let e=v(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:c(e.id),tenantId:c(e.tenantId),creatorMemberId:c(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(c),participantRevision:e.participantRevision,status:e.status,createdAt:D(e.createdAt),updatedAt:D(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=v(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:c(n.senderMemberId),createdAt:D(n.createdAt)}}return t}function Tt(r){let e=v(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Re),total:e.total,limit:e.limit,offset:e.offset}}function Dt(r){let e=v(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Ve(t);return{memberId:n.memberId,name:c(v(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:h(e.limit,1),offset:h(e.offset,0),nextOffset:e.nextOffset===null?null:h(e.nextOffset,0)}}function Mt(r){let e=v(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:c(e.conversationId),messageId:c(e.messageId),participantRevision:h(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Ve),shareLayers:e.shareLayers.map(t=>{let n=v(t),i=c(n.id),s=c(n.dataShareId),a=c(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:c(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function Se(r){let e=v(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:c(e.messageId),status:e.status}}function Ot(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=v(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:c(n.id),status:n.status,senderMemberId:c(n.senderMemberId),senderDeviceId:c(n.senderDeviceId),createdAt:D(n.createdAt),updatedAt:D(n.updatedAt),expiresAt:D(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=v(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:c(a.memberId),status:a.status}})),i}),total:h(e.total,0),limit:h(e.limit,1),offset:h(e.offset,0)}}function kt(r){let e=v(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:D(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=v(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId),ciphertext:c(n.ciphertext)}})}}function Nt(r){let e=v(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:c(e.leaseId),leaseExpiresAt:D(e.leaseExpiresAt),senderSigningPublicKey:c(e.senderSigningPublicKey),senderSigningKeyFingerprint:c(e.senderSigningKeyFingerprint),senderDeviceVersion:h(e.senderDeviceVersion,1),canonicalManifest:c(e.canonicalManifest),signature:c(e.signature),tenantWrappedShareKey:c(e.tenantWrappedShareKey),wrappedContentKey:c(e.wrappedContentKey),shares:e.shares.map(t=>{let n=v(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:h(n.index,0),shareId:c(n.shareId),layerId:c(n.layerId)}})}}function W(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 j(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var M=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},xe=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ee(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:ee(n)}async registerInboxDevice(e){return ee(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ee(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ee(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Re(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Re(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Tt(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return Dt(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Et(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Se(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Rt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return St(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return _t(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return Ct(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return At(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Se(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await Ee(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new M(o.status,W(d),j(d))}async publishInboxFile(e,t,n){return Se(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return Nt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,l=await this.requestBinary(d,"GET",void 0,a);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let u=Number(l.headers.get("content-length"));if(Number.isFinite(u)&&u>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let g=l.body.getReader(),b=[],x=0;try{for(;;){a?.throwIfAborted();let w=await g.read();if(w.done)break;if(x+=w.value.length,x>14*1024*1024)throw new Error("invalid_inbox_share_size");b.push(w.value)}}catch(w){throw await g.cancel().catch(()=>{}),w}let _=new Uint8Array(x),S=0;for(let w of b)_.set(w,S),S+=w.length;return _}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return Ot(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return kt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Pt)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return It(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Pe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return bt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){$(e);let{idempotencyKey:t,...n}=e;return oe(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return oe(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return Z(t),oe(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return oe(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[x,_]of Object.entries(s??{}))d.set(x,_);n&&d.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(u.signal=a);let g=await this.transport(new URL(e,l),u);a?.throwIfAborted();let b=await Ee(g,a);if(a?.throwIfAborted(),!g.ok)throw new M(g.status,W(b),j(b));if(!b.ok||b.result===void 0)throw new M(g.status,W(b),j(b));return b.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let l=await Ee(d,i);throw new M(d.status,W(l),j(l))}return d}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,a=await this.transport(new URL(e,s),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await Ee(a);if(!a.ok||!o.ok)throw new M(a.status,W(o),j(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new M(400,"organization_selection_required")}};async function Ee(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}var $e=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Pe(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let u;try{u=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||u&&u.ok===!1||i&&u?.result===void 0)throw new M(l.status,u&&W(u),u&&j(u));return u?.result}};function Yn(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=ne(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new B({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}});return new H(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,l)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,l)}}}).openReveal(e,t)}}}async function Kt(r,e){if(!e)throw new Error("master_key_required");let t=Xn(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Qn(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return Zn(new Uint8Array(o))}function Xn(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 Qn(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 Zn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var He=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}};import{MergeProcessReconciliationLoop as Jn}from"@safetech/inheriti-core-sdk/shared-configuration";var er=new Set(["COMPLETED","ABORTED","EXPIRED"]),We=class{constructor(e,t=new Ae,n=new _e,i=Math.random){this.api=e;this.loop=new Jn(t,n,i)}subscriptions=new Map;loop;refreshConnection(){for(let e of this.subscriptions.values())e.wake()}subscribe(e,t){this.unsubscribe(e);let n,i,s=!1,a=this.loop.start(e,async()=>{let o=await this.api.getGovernedReveal(e),d=o.approvalProcess?.status??"",l=tr(o);n!==void 0&&l!==n&&await t.onProcessUpdated?.(),i!==void 0&&d!==i&&await t.onApprovalUpdated?.(),n=l,i=d;let u=er.has(o.status);if(o.status==="EXPIRED"&&await t.onRevealWindowExpired?.(e),o.status==="ABORTED"&&await t.onForceAborted?.(e),u)return{transitionKey:l,shouldPoll:!1,terminal:!0};if(!s){let g=await this.api.getCustodianShare(e);"status"in g||(s=!0,await t.onCustodianShareReceived?.(e,g))}return{transitionKey:l,shouldPoll:!0,terminal:!1}});this.subscriptions.set(e,a)}unsubscribe(e){this.subscriptions.get(e)?.stop(),this.subscriptions.delete(e)}};function tr(r){return`${r.status}:${r.approvalProcess?.status??""}`}var Ae=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)})}},_e=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){le(e.signal),rr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return le(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){le(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(le(e.signal),!i.custodianPair)throw new E("custodian_share_required");let s=je(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(je(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(je(i.backupShards),a.symmetricKeyBase64),l=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return le(e.signal),{protectionProtocol:i.protocol,validatorShares:Ye(a.encryptedShares),dataShards:Ye(o.encryptedShares),backupShards:Ye(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:nr(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:Xe(n.encryptedShares[0]),dataShard:Xe(n.encryptedShares[1])}}};function je(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ye(r){return r.map(Xe)}function Xe(r){return{id:r.id,data:r.encryptedData}}function nr(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new E("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function rr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new E("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new E("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new E("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new E("plan_secrets_declaration_mismatch")}}function le(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}function Lt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Ce=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Lt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Lt(new Uint8Array(t))}},Te=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var de=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},ce=class extends de{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},f=class extends de{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Qe(r){if(r instanceof de)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var qt=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:F(n,"issuer"),authorizationEndpoint:F(n,"authorization_endpoint"),tokenEndpoint:F(n,"token_endpoint"),deviceAuthorizationEndpoint:N(n,"device_authorization_endpoint"),endSessionEndpoint:N(n,"end_session_endpoint"),revocationEndpoint:N(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:F(t,"device_code"),userCode:F(t,"user_code"),verificationUri:F(t,"verification_uri"),verificationUriComplete:N(t,"verification_uri_complete"),expiresInSeconds:Gt(t,"expires_in"),intervalSeconds:Ze(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:F(n,"access_token"),refreshToken:N(n,"refresh_token"),idToken:N(n,"id_token"),tokenType:F(n,"token_type"),expiresInSeconds:Gt(n,"expires_in"),refreshExpiresInSeconds:Ze(n,"refresh_expires_in"),scope:N(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let s=N(i,"error")??`oauth_http_${n.status}`;throw new f(s,N(i,"error_description")??s)}return i}};function F(r,e){let t=N(r,e);if(!t)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function N(r,e){return typeof r[e]=="string"?r[e]:void 0}function Gt(r,e){let t=Ze(r,e);if(t===void 0)throw new f("invalid_oauth_response",`Missing ${e}`);return t}function Ze(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var ir=600*1e3,De=5,sr=5,zt=class{constructor(e){this.options=e;this.crypto=e.crypto??new Ce,this.clock=e.clock??new Te}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),s=await this.crypto.sha256UrlSafe(i),a=this.clock.now()+ir;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:a});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",s),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:a}}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 f("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new f("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new f("redirect_uri_mismatch");let a=i.searchParams.get("error");if(a)throw new f(a,i.searchParams.get("error_description")??a);if(i.searchParams.get("state")!==n.state)throw new f("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new f("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}),u=await this.acceptTokens(l,n.nonce);return await this.options.sessions.save(u),u}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new f("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(De,t.intervalSeconds??De),i=this.clock.now(),s={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new f("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(De,i.intervalSeconds??De),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let l=await this.acceptTokens(d);return await this.options.sessions.save(l),await this.options.transactions.remove(t),l}catch(d){let l=Qe(d);if(l==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(l==="slow_down"){a+=sr,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new f("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new ce;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new f("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=Qe(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new ce:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(Y(e.issuer)!==Y(this.options.configuration.issuer))throw new f("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${Y(t)}|${n}|${i}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new f("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 f("id_token_validation_required");let s=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(s,t),s.subject!==n.subject||s.sessionId!==n.sessionId)throw new f("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(Y(e.issuer)!==Y(i.issuer))throw new f("issuer_mismatch");if(!s.includes(i.audience))throw new f("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new f("client_mismatch");if(e.environment!==i.environment)throw new f("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new f("required_claim_missing");if(n&&e.nonce!==t)throw new f("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(Y(e.issuer)!==Y(n.issuer))throw new f("issuer_mismatch");if(!i.includes(n.clientId))throw new f("client_mismatch");if(e.authorizedParty!==n.clientId)throw new f("client_mismatch");if(!e.subject||!e.sessionId)throw new f("required_claim_missing");if(e.nonce!==t)throw new f("nonce_mismatch")}};function Y(r){return r.replace(/\/+$/u,"")}var Ft=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{J as BusinessOrganizationSelectionError,he as CANONICAL_PLAN_ASSET_TYPES,Ue as CANONICAL_STRUCTURED_ASSET_FIELDS,Ut as CorePlanMaterialBuilder,p as ElementsApiPortRequired,M as ElementsApiRequestFailed,H as ElementsClient,Ie as GuidedCreateRecoveryError,ve as GuidedPlanCreator,Ae as HostProcessRuntimeEnvironment,$e as HttpAutomationRevealApiPort,xe as HttpElementsApiPort,qt as HttpOperatorAuthTransport,nt as InheritiClientProvider,y as InvalidPlanDeclaration,E as InvalidPlanMaterial,_e as LocalProcessReconciliationOwnership,me as MasterKeyRelayCancellationFailed,pe as MasterKeyRelayExpired,ue as MasterKeyRelayTimedOut,K as MasterKeyRequired,ye as MemoryGuidedCreateCheckpointStore,re as MemoryKeyVault,ie as MemoryStatePort,f as OAuthProtocolError,zt as OperatorAuthClient,de as OperatorAuthError,ce as OperatorReauthenticationRequired,Ft as OperatorSessionController,st as PLAN_CREATION_SERVER_STAGES,He as PlanMaterialReconstructionFailed,ae as PlanMaterialReconstructorRequired,We as PollingSharedPlanEventListener,B as RelayMasterKeySource,se as RevealActionsNotOpen,P as RevealFieldAccessError,be as RevealHandleClosed,as as SDKContainer,Ne as StaticMasterKeyResolver,Te as SystemOAuthClock,Ce as WebOAuthCrypto,Yn as createAutomationRevealClient,Nn as createElementsClient,ge as createMasterKeyResolver,hn as getAvailableEnvs,ne as masterKeyRefFor,q as masterKeyRefKey,Qe as oauthErrorCode,ht as parseAssetFieldSelector,mt as revealPhaseOf,Wn as selectBusinessOrganization,Kt as unwrapDekWithMasterKey,rt as useClient,$ as validatePlanCreationInput,Z as validatePlanCreationMaterial};