@copio/sdk 0.1.5 → 0.1.6

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 (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q3AWHANC.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-TK5N67RB.js +2 -0
  45. package/dist/chunk-V2D55DVU.js +1 -0
  46. package/dist/chunk-VPSUKD6F.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2316 -135
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +10 -3
  92. package/sdk/core.js +219 -12
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +297 -17
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FQRADJY6.js +0 -2
  105. package/dist/chunk-G5EUMLYT.js +0 -4
  106. package/dist/chunk-K4NR6OAC.js +0 -2
  107. package/dist/chunk-L4OVZN23.js +0 -2
  108. package/dist/chunk-MEE2NNYB.js +0 -2
  109. package/dist/chunk-O7IV7A6O.js +0 -2
  110. package/dist/chunk-Q7XPZMZA.js +0 -1395
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
@@ -0,0 +1,2 @@
1
+ var d=Object.defineProperty;var e=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var f=(a,b)=>{for(var c in b)d(a,c,{get:b[c],enumerable:!0})};export{e as a,f as b};
2
+ //# sourceMappingURL=chunk-25WAHT3G.js.map
@@ -0,0 +1,175 @@
1
+ import{h as y,i as p,n as h,o as x}from"./chunk-VPSUKD6F.js";import{a,b as m}from"./chunk-HCCNUPKB.js";import{i as b}from"./chunk-ZT72PD2C.js";var g=`:host{all:initial;display:block;position:relative;width:100%;height:100%;min-height:280px;box-sizing:border-box;container-type:inline-size;container-name:copio-handoff;overflow-y:auto;overflow-x:hidden;text-align:left;direction:ltr;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--copio-font-family:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;--copio-font-mono:'JetBrains Mono','SFMono-Regular',Consolas,'Liberation Mono',monospace;--copio-color-bg:#0b0f17;--copio-color-surface:#131b26;--copio-color-surface-elevated:#1c2736;--copio-color-surface-overlay:rgba(15,22,32,0.88);--copio-color-text:#f1f5f9;--copio-color-text-muted:#94a3b8;--copio-color-text-inverse:#090d14;--copio-color-primary:#38bdf8;--copio-color-primary-hover:#7dd3fc;--copio-color-primary-contrast:#06131f;--copio-color-success:#22c55e;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(148,163,184,0.18);--copio-color-border-strong:rgba(148,163,184,0.34);--copio-focus-ring:0 0 2px #0b0f17,0 0 0 4px #38bdf8;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-radius-pill:9999px;--copio-spacing-xs:4px;--copio-spacing-sm:8px;--copio-spacing-md:12px;--copio-spacing-lg:16px;--copio-spacing-xl:24px;--copio-touch-target-min:44px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.55);--copio-transition-fast:150ms cubic-bezier(0.22,1,0.36,1);--copio-transition-normal:240ms cubic-bezier(0.22,1,0.36,1);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;color:var(--copio-color-text);background-color:var(--copio-color-bg);color-scheme:dark}:host([theme="light"]),:host(.copio-theme-light),:host-context([data-theme="light"]),:host-context(.sl-theme-light),:host-context(.theme-light){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-text:#0f172a;--copio-color-text-muted:#64748b;--copio-color-text-inverse:#ffffff;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.24);--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.12);color-scheme:light}*,*::before,*::after{box-sizing:border-box}.copio-handoff-root{display:flex;flex-direction:column;align-items:center;justify-content:center;width:100%;min-height:100%;padding:var(--copio-spacing-xl);background-color:var(--copio-color-bg);color:var(--copio-color-text);text-align:center}.copio-handoff-card{display:flex;flex-direction:column;align-items:center;width:100%;max-width:440px;background-color:var(--copio-color-surface);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-lg);padding:var(--copio-spacing-xl);box-shadow:var(--copio-shadow-elevated);transition:transform var(--copio-transition-fast),border-color var(--copio-transition-fast)}.copio-handoff-title{font-size:18px;font-weight:600;margin:0 var(--copio-spacing-xs);color:var(--copio-color-text)}.copio-handoff-desc{font-size:13px;color:var(--copio-color-text-muted);margin:0 var(--copio-spacing-lg);max-width:320px;line-height:1.4}.copio-handoff-qr-box{display:flex;align-items:center;justify-content:center;width:220px;height:220px;background-color:#ffffff;border-radius:var(--copio-radius-md);padding:var(--copio-spacing-md);margin-bottom:var(--copio-spacing-md);box-shadow:0 4px 12px rgba(0,0,0,0.15);position:relative;overflow:hidden}.copio-handoff-qr-box svg{width:100%;height:100%;display:block}.copio-handoff-qr-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);color:#64748b;font-size:12px}.copio-handoff-meta-row{display:flex;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);margin-bottom:var(--copio-spacing-lg);font-size:12px;color:var(--copio-color-text-muted)}.copio-handoff-timer-badge{display:inline-flex;align-items:center;gap:5px;background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);padding:4px 10px;border-radius:var(--copio-radius-pill);font-family:var(--copio-font-mono);font-weight:500}.copio-handoff-icon-btn{background:transparent;border:none;color:var(--copio-color-text-muted);cursor:pointer;padding:6px;border-radius:var(--copio-radius-pill);display:inline-flex;align-items:center;justify-content:center;transition:color var(--copio-transition-fast),background-color var(--copio-transition-fast)}.copio-handoff-icon-btn:hover{color:var(--copio-color-primary);background-color:var(--copio-color-surface-elevated)}.copio-handoff-divider{display:flex;align-items:center;width:100%;margin:var(--copio-spacing-sm) 0 var(--copio-spacing-md);color:var(--copio-color-text-muted);font-size:11px;text-transform:uppercase;letter-spacing:0.05em}.copio-handoff-divider::before,.copio-handoff-divider::after{content:'';flex:1;height:1px;background-color:var(--copio-color-border)}.copio-handoff-divider span{padding:0 var(--copio-spacing-sm)}.copio-handoff-btn{display:inline-flex;align-items:center;justify-content:center;gap:var(--copio-spacing-sm);width:100%;min-height:var(--copio-touch-target-min);padding:10px 16px;font-size:13px;font-weight:500;border-radius:var(--copio-radius-md);cursor:pointer;border:1px solid transparent;transition:background-color var(--copio-transition-fast),border-color var(--copio-transition-fast),color var(--copio-transition-fast)}.copio-handoff-btn-secondary{background-color:var(--copio-color-surface-elevated);border-color:var(--copio-color-border);color:var(--copio-color-text)}.copio-handoff-btn-secondary:hover{border-color:var(--copio-color-border-strong);color:var(--copio-color-primary);background-color:var(--copio-color-surface)}.copio-handoff-btn-primary{background-color:var(--copio-color-primary);color:var(--copio-color-primary-contrast);font-weight:600}.copio-handoff-btn-primary:hover{background-color:var(--copio-color-primary-hover)}.copio-handoff-status-pill{display:inline-flex;align-items:center;gap:8px;padding:6px 14px;border-radius:var(--copio-radius-pill);font-size:13px;font-weight:500;margin-bottom:var(--copio-spacing-md);border:1px solid var(--copio-color-border);background-color:var(--copio-color-surface-elevated)}.copio-handoff-pulse-dot{width:8px;height:8px;border-radius:50%;background-color:var(--copio-color-success);box-shadow:0 rgba(34,197,94,0.7);animation:copio-handoff-pulse 2s infinite}@keyframes copio-handoff-pulse{0%{box-shadow:0 rgba(34,197,94,0.7)}70%{box-shadow:0 0 8px rgba(34,197,94,0)}100%{box-shadow:0 rgba(34,197,94,0)}}.copio-handoff-badge{display:inline-flex;align-items:center;justify-content:center;padding:4px 10px;border-radius:var(--copio-radius-pill);background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);font-size:12px;color:var(--copio-color-text-muted);font-weight:500;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-progress-wrap{width:100%;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-progress-bar{width:100%;height:8px;background-color:var(--copio-color-surface-elevated);border-radius:var(--copio-radius-pill);overflow:hidden;border:1px solid var(--copio-color-border)}.copio-handoff-progress-fill{height:100%;background:linear-gradient(90deg,var(--copio-color-primary) 0%,#38bdf8 100%);border-radius:var(--copio-radius-pill);transition:width 150ms ease-out}.copio-handoff-progress-label{display:flex;justify-content:space-between;font-size:12px;color:var(--copio-color-text-muted);margin-top:6px}.copio-handoff-thumbnails{display:grid;grid-template-columns:repeat(auto-fill,minmax(80px,1fr));gap:var(--copio-spacing-sm);width:100%;max-height:240px;overflow-y:auto;padding:4px;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-thumb-card{position:relative;aspect-ratio:3 / 4;background-color:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);overflow:hidden;display:flex;align-items:center;justify-content:center}.copio-handoff-thumb-img{width:100%;height:100%;object-fit:cover;display:block}.copio-handoff-thumb-label{position:absolute;bottom:4px;right:4px;background-color:rgba(0,0,0,0.7);color:#ffffff;font-size:10px;padding:2px 5px;border-radius:4px;font-family:var(--copio-font-mono)}.copio-handoff-thumb-shimmer{width:100%;height:100%;background:linear-gradient(90deg,var(--copio-color-surface-elevated) 0%,rgba(56,189,248,0.15) 50%,var(--copio-color-surface-elevated) 100%);background-size:200% 100%;animation:copio-shimmer 1.5s infinite;display:flex;align-items:center;justify-content:center;color:var(--copio-color-primary)}@keyframes copio-shimmer{0%{background-position:-200% 0}100%{background-position:200% 0}}.copio-handoff-success-icon{width:48px;height:48px;border-radius:50%;background-color:rgba(34,197,94,0.15);color:var(--copio-color-success);display:flex;align-items:center;justify-content:center;margin-bottom:var(--copio-spacing-md)}.copio-handoff-alert{display:flex;flex-direction:column;align-items:center;width:100%;margin-bottom:var(--copio-spacing-lg)}.copio-handoff-alert-icon{width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:var(--copio-spacing-md)}.copio-handoff-alert-icon.warning{background-color:rgba(245,158,11,0.15);color:var(--copio-color-warning)}.copio-handoff-alert-icon.danger{background-color:rgba(239,68,68,0.15);color:var(--copio-color-danger)}.copio-handoff-spinner{width:24px;height:24px;border:2px solid rgba(148,163,184,0.2);border-top-color:var(--copio-color-primary);border-radius:50%;animation:copio-spin 0.8s linear infinite}@keyframes copio-spin{to{transform:rotate(360deg)}}@container copio-handoff (max-width:400px){.copio-handoff-root{padding:var(--copio-spacing-md)}.copio-handoff-card{padding:var(--copio-spacing-md)}.copio-handoff-qr-box{width:170px;height:170px}.copio-handoff-title{font-size:16px}.copio-handoff-desc{font-size:12px}}@container copio-handoff (min-width:600px){.copio-handoff-card{max-width:520px}.copio-handoff-qr-box{width:240px;height:240px}}`,f=null;function v(){if(typeof CSSStyleSheet>"u")return null;if(!f)try{f=new CSSStyleSheet,f.replaceSync(g)}catch{f=null}return f}function w(s){if(!s)return;let t=v();if(t&&"adoptedStyleSheets"in s){let o=s.adoptedStyleSheets||[];o.includes(t)||(s.adoptedStyleSheets=[...o,t])}else if(!s.querySelector("style[data-copio-handoff-styles]")){let o=document.createElement("style");o.setAttribute("data-copio-handoff-styles",""),o.textContent=g,s.appendChild(o)}}var S=typeof HTMLElement<"u"?HTMLElement:class{};async function k(s){try{let t=await b();if(t){let o=t(0,"M");return o.addData(s),o.make(),o.createSvgTag({scalable:!0,margin:4})}}catch(t){console.warn("[CopioHandoff] loadQrCode failed, using SVG fallback:",t)}return`<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
2
+ <rect width="100" height="100" fill="#ffffff" />
3
+ <rect x="8" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
4
+ <rect x="13" y="13" width="18" height="18" fill="#ffffff" rx="2" />
5
+ <rect x="17" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
6
+ <rect x="64" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
7
+ <rect x="69" y="13" width="18" height="18" fill="#ffffff" rx="2" />
8
+ <rect x="73" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
9
+ <rect x="8" y="64" width="28" height="28" fill="#0b0f17" rx="3" />
10
+ <rect x="13" y="69" width="18" height="18" fill="#ffffff" rx="2" />
11
+ <rect x="17" y="73" width="10" height="10" fill="#0b0f17" rx="1" />
12
+ <rect x="42" y="12" width="6" height="6" fill="#0284c7" />
13
+ <rect x="52" y="20" width="6" height="6" fill="#0284c7" />
14
+ <rect x="42" y="42" width="16" height="16" fill="#0284c7" rx="2" />
15
+ <rect x="68" y="48" width="6" height="6" fill="#0b0f17" />
16
+ <rect x="78" y="58" width="6" height="6" fill="#0b0f17" />
17
+ <rect x="48" y="68" width="6" height="6" fill="#0b0f17" />
18
+ <rect x="64" y="74" width="12" height="6" fill="#0b0f17" />
19
+ </svg>`}var u=class extends S{#o=null;#e="waiting";#r=null;#v="";#c=null;#t=[];#i=null;#l="";#p=600;#d=null;#u=null;#b=[];#R=!0;#w="";#S="";#s=null;#m="all";#h=null;#f=null;static get observedAttributes(){return["state","receiver-url","doc-id","theme","ttl","mode","aspect","relay-url","ice-servers","signaling-url","ice-transport-policy","transport"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"})}get#g(){return this.docId?this.docId:(this.#u||(this.#u=p("doc_")),this.#u)}connectedCallback(){this.shadowRoot&&(w(this.shadowRoot),this.#n()),this.#R&&!this.#o&&this.start().catch(t=>{this.#A(t)})}disconnectedCallback(){this.#a(),this.#y()}attributeChangedCallback(t,o,e){o!==e&&(t==="state"&&e&&e!==this.#e?(this.#e=e,this.#n()):t==="theme"&&this.shadowRoot&&this.#n())}get state(){return this.#e}set state(t){this.#e!==t&&(this.#e=t,typeof this.setAttribute=="function"&&this.setAttribute("state",t),this.#n())}get session(){return this.#o}set session(t){t&&this.attachSession(t)}get receiverUrl(){return typeof this.getAttribute=="function"&&this.getAttribute("receiver-url")||""}set receiverUrl(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("receiver-url",t):this.removeAttribute("receiver-url"))}get docId(){return typeof this.getAttribute=="function"&&this.getAttribute("doc-id")||null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get ttlMs(){let t=typeof this.getAttribute=="function"?this.getAttribute("ttl"):null;return t?parseInt(t,10):y}set ttlMs(t){typeof this.setAttribute=="function"&&this.setAttribute("ttl",String(t))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"batch"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get pages(){return[...this.#t]}get token(){return this.#r}get url(){return this.#v}get relayUrl(){return this.#w||typeof this.getAttribute=="function"&&this.getAttribute("relay-url")||""}set relayUrl(t){this.#w=t||"",typeof this.setAttribute=="function"&&(t?this.setAttribute("relay-url",t):this.removeAttribute("relay-url"))}get signalingUrl(){return this.#S||typeof this.getAttribute=="function"&&this.getAttribute("signaling-url")||""}set signalingUrl(t){this.#S=t||"",typeof this.setAttribute=="function"&&(t?this.setAttribute("signaling-url",t):this.removeAttribute("signaling-url"))}get iceServers(){if(this.#s)return this.#s;let t=typeof this.getAttribute=="function"?this.getAttribute("ice-servers"):null;if(t)try{let o=JSON.parse(t);if(Array.isArray(o))return o}catch{return t.split(",").map(o=>({urls:o.trim()}))}return null}set iceServers(t){if(Array.isArray(t))this.#s=t;else if(typeof t=="string")try{this.#s=JSON.parse(t)}catch{this.#s=t?[{urls:t}]:null}else this.#s=null;typeof this.setAttribute=="function"&&(Array.isArray(t)?this.setAttribute("ice-servers",JSON.stringify(t)):t?this.setAttribute("ice-servers",String(t)):this.removeAttribute("ice-servers"))}get iceTransportPolicy(){return typeof this.getAttribute=="function"?this.getAttribute("ice-transport-policy")||this.#m||"all":this.#m||"all"}set iceTransportPolicy(t){this.#m=t||"all",typeof this.setAttribute=="function"&&(t?this.setAttribute("ice-transport-policy",t):this.removeAttribute("ice-transport-policy"))}get transport(){return this.#h?this.#h:typeof this.getAttribute=="function"&&this.getAttribute("transport")||"auto"}set transport(t){typeof t=="string"?typeof this.setAttribute=="function"&&this.setAttribute("transport",t):this.#h=t}get connectionInfo(){return this.#f||{transport:this.iceTransportPolicy==="relay"?"turn":"direct",rttMs:0}}async getConnectionInfo(){if(this.#o&&typeof this.#o.getConnectionInfo=="function"){let t=await this.#o.getConnectionInfo();return this.#f=t,t}return this.connectionInfo}async start(t={}){this.#y(),this.#t=[],this.#i=null,this.#l="";let o=t.transport||this.#h;if(!o){let n=!!t.peer||this.getAttribute("transport")==="peer"||!!this.relayUrl||!!this.signalingUrl||!!this.iceServers,d=t.peerId||(n?p("copio-hnd-"):p("peer_"));if(t.peerId=d,n)try{let{HandoffPeerTransport:l}=await import("./handoff-transport-7YFK4RYL.js");o=new l({role:"host",peerId:d,relayUrl:this.relayUrl,signalingUrl:this.signalingUrl,iceServers:this.iceServers,iceTransportPolicy:this.iceTransportPolicy})}catch(l){console.warn("[CopioHandoff] Failed to initialize HandoffPeerTransport, falling back to loopback:",l),o=new h}else{let l=new h;this.iceTransportPolicy==="relay"&&(l.forceRelay=!0,l.iceTransportPolicy="relay"),o=l}}let e=new x({role:"host",ttlMs:this.ttlMs,transport:o});this.#o=e,this.#k(e);let r=t.baseUrl||this.receiverUrl||this.#U(),{token:i,url:c}=await e.startHost({baseUrl:r,peerId:t.peerId,relayUrl:this.relayUrl,signalingUrl:this.signalingUrl,iceServers:this.iceServers});o instanceof h&&i?.peerId&&h.register(i.peerId,o),this.#r=i,this.#v=c,this.#p=Math.max(0,Math.ceil((i.expiresAt-Date.now())/1e3)),this.#C(i.expiresAt),this.state="waiting",this.#c=null,this.#n();try{this.#c=await k(c),this.#e==="waiting"&&this.#n()}catch(n){console.warn("[CopioHandoff] QR code generation error:",n)}return{token:i,url:c}}attachSession(t,o=null){t&&(this.#y(),this.#o=t,this.#r=o||t.token,this.#r?.expiresAt&&(this.#p=Math.max(0,Math.ceil((this.#r.expiresAt-Date.now())/1e3)),this.#C(this.#r.expiresAt)),this.#k(t),this.state=t.state==="idle"?"waiting":t.state)}async refresh(){return this.start()}async clear(){return this.#t=[],this.#i=null,this.start()}getPages(){return[...this.#t]}dispatch(t,o={}){return m(this,t,o)}#U(){return typeof location<"u"&&location.href?`${location.origin}${location.pathname}`:"https://copio.netlify.app/scan"}#k(t){this.#b.push(t.on("stateChange",o=>{o!=="closed"&&(this.state=o,o==="connected"&&(this.dispatch(a.HANDOFF_CONNECTED,{sessionId:this.#r?.sessionId||"",peerId:this.#r?.peerId||""}),t.getConnectionInfo().then(e=>{this.#f=e,this.dispatch(a.CONNECTION_INFO,e)}).catch(()=>{})))}),t.on("connectionInfo",o=>{this.#f=o,this.dispatch(a.CONNECTION_INFO,o)}),t.on("progress",o=>{this.#i=o,this.#e!=="receiving"?this.state="receiving":this.#L()}),t.on("page",o=>{this.#T(o)}),t.on("complete",o=>{this.#P(o)}),t.on("error",o=>{this.#A(o)}))}#T(t){let o="";if(t.blob&&typeof URL<"u"&&typeof URL.createObjectURL=="function")try{o=URL.createObjectURL(t.blob)}catch{o=""}let e=typeof t.pageIndex=="number"?t.pageIndex:this.#t.length,r=this.#t.length+1,i={id:t.id||p("page_"),pageIndex:e,pageNumber:r,label:`Page ${r}`,mimeType:t.mimeType||"image/jpeg",blob:t.blob,src:o,originalSrc:o,originalPreserved:!0,dimensions:t.metadata?.width?{width:t.metadata.width,height:t.metadata.height}:{width:0,height:0},edits:{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:null};this.#t.push(i),this.#i=null,this.dispatch(a.PAGE_ADDED,{page:i,pageNumber:i.pageNumber,docId:this.docId||this.#g,source:"handoff"}),this.#e==="receiving"?this.state="connected":this.#n()}#P(t={}){this.#a(),this.state="complete";let o={mode:this.mode,aspect:this.aspect,docId:this.docId||t.docId||this.#g,pageCount:this.#t.length,pages:[...this.#t],summary:t.summary||{}};this.dispatch(a.SCAN_COMPLETE,o)}#A(t){this.#a(),this.#l=t?.message||String(t),this.state="error",this.dispatch(a.ERROR,{code:"HANDOFF_ERROR",message:this.#l,error:t})}#C(t){this.#a(),this.#d=setInterval(()=>{let o=Math.max(0,Math.ceil((t-Date.now())/1e3));if(this.#p=o,o<=0)this.#a(),this.state="expired";else{let e=this.shadowRoot?.querySelector(".copio-handoff-countdown");e&&(e.textContent=this.#I(o))}},1e3)}#a(){this.#d&&(clearInterval(this.#d),this.#d=null)}#y(){for(let t of this.#b)try{t()}catch{}if(this.#b=[],this.#o){try{this.#o.close()}catch{}this.#o=null}}#I(t){let o=Math.floor(t/60),e=t%60;return`${o.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}async#$(t){if(!t||t.length===0)return;for(let e=0;e<t.length;e++){let r=t[e],i="";if(typeof URL<"u"&&typeof URL.createObjectURL=="function")try{i=URL.createObjectURL(r)}catch{i=""}let c=this.#t.length,n=c+1,d={id:p("page_"),pageIndex:c,pageNumber:n,label:r.name||`Page ${n}`,mimeType:r.type||"image/jpeg",blob:r,src:i,originalSrc:i,originalPreserved:!0,dimensions:{width:0,height:0},edits:{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:null};this.#t.push(d),this.dispatch(a.PAGE_ADDED,{page:d,pageNumber:n,docId:this.docId||this.#g,source:"file"})}this.state="complete";let o={mode:this.mode,aspect:this.aspect,docId:this.docId||this.#g,pageCount:this.#t.length,pages:[...this.#t],source:"file",summary:{source:"local_upload",count:t.length}};this.dispatch(a.SCAN_COMPLETE,o)}#L(){if(!this.shadowRoot)return;let t=this.shadowRoot.querySelector(".copio-handoff-progress-fill"),o=this.shadowRoot.querySelector(".copio-handoff-progress-pct");t&&this.#i&&(t.style.width=`${this.#i.percent||0}%`),o&&this.#i&&(o.textContent=`${this.#i.percent||0}%`)}#n(){if(!this.shadowRoot)return;let t="";switch(this.#e){case"waiting":t=this.#E();break;case"connected":t=this.#M();break;case"receiving":t=this.#N();break;case"complete":t=this.#O();break;case"expired":t=this.#B();break;case"error":t=this.#q();break;default:t=this.#E()}this.shadowRoot.innerHTML=`
20
+ <div class="copio-handoff-root">
21
+ <div class="copio-handoff-card">
22
+ ${t}
23
+ </div>
24
+ </div>
25
+ `,this.#z()}#E(){let t=this.#I(this.#p);return`
26
+ <h2 class="copio-handoff-title">Scan with your phone camera</h2>
27
+ <p class="copio-handoff-desc">Point your smartphone camera at the code below to snap document pages with zero app install.</p>
28
+
29
+ <div class="copio-handoff-qr-box" data-testid="qr-container">
30
+ ${this.#c?this.#c:`
31
+ <div class="copio-handoff-qr-loading">
32
+ <div class="copio-handoff-spinner"></div>
33
+ <span>Generating QR code\u2026</span>
34
+ </div>
35
+ `}
36
+ </div>
37
+
38
+ <div class="copio-handoff-meta-row">
39
+ <span class="copio-handoff-timer-badge" title="Session time remaining">
40
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
41
+ <circle cx="12" cy="12" r="10"></circle>
42
+ <polyline points="12 6 12 12 16 14"></polyline>
43
+ </svg>
44
+ Expires in <span class="copio-handoff-countdown">${t}</span>
45
+ </span>
46
+ <button class="copio-handoff-icon-btn copio-handoff-refresh-btn" type="button" title="Refresh QR code">
47
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
48
+ <polyline points="23 4 23 10 17 10"></polyline>
49
+ <polyline points="1 20 1 14 7 14"></polyline>
50
+ <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
51
+ </svg>
52
+ </button>
53
+ </div>
54
+
55
+ <div class="copio-handoff-divider">
56
+ <span>OR</span>
57
+ </div>
58
+
59
+ <button class="copio-handoff-btn copio-handoff-btn-secondary copio-handoff-upload-btn" type="button">
60
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
61
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
62
+ <polyline points="17 8 12 3 7 8"></polyline>
63
+ <line x1="12" y1="3" x2="12" y2="15"></line>
64
+ </svg>
65
+ Or upload file on this computer
66
+ </button>
67
+ <input type="file" class="copio-handoff-file-input" accept="image/*,application/pdf" multiple style="display:none">
68
+ `}#M(){let t=this.#t.length;return`
69
+ <div class="copio-handoff-status-pill">
70
+ <span class="copio-handoff-pulse-dot"></span>
71
+ <span>Phone connected \u2014 scanning in progress\u2026</span>
72
+ </div>
73
+
74
+ <h2 class="copio-handoff-title">Ready for Captures</h2>
75
+ <p class="copio-handoff-desc">Snap pages or receipts on your phone. They will transfer securely with end-to-end encryption.</p>
76
+
77
+ <div class="copio-handoff-badge" data-testid="page-count-badge">${t===1?"1 page snapped":`${t} pages snapped`}</div>
78
+
79
+ ${this.#x(!1)}
80
+ `}#N(){let t=this.#i||{percent:0,pageIndex:this.#t.length},o=(t.pageIndex||this.#t.length)+1,e=t.percent||0;return`
81
+ <div class="copio-handoff-status-pill">
82
+ <div class="copio-handoff-spinner" style="width:12px;height:12px;border-width:2px;margin-right:4px;"></div>
83
+ <span>Receiving page ${o}\u2026</span>
84
+ </div>
85
+
86
+ <h2 class="copio-handoff-title">Streaming Page ${o}</h2>
87
+ <p class="copio-handoff-desc">Decrypting 64 KB binary chunks directly in memory.</p>
88
+
89
+ <div class="copio-handoff-progress-wrap">
90
+ <div class="copio-handoff-progress-bar">
91
+ <div class="copio-handoff-progress-fill" style="width: ${e}%;"></div>
92
+ </div>
93
+ <div class="copio-handoff-progress-label">
94
+ <span>Receiving page ${o}</span>
95
+ <span class="copio-handoff-progress-pct">${e}%</span>
96
+ </div>
97
+ </div>
98
+
99
+ ${this.#x(!0)}
100
+ `}#O(){let t=this.#t.length;return`
101
+ <div class="copio-handoff-success-icon">
102
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
103
+ <polyline points="20 6 9 17 4 12"></polyline>
104
+ </svg>
105
+ </div>
106
+
107
+ <h2 class="copio-handoff-title">Scan Complete</h2>
108
+ <p class="copio-handoff-desc">${t===1?"1 page received":`${t} pages received`} successfully transferred to this computer.</p>
109
+
110
+ ${this.#x(!1)}
111
+
112
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-reset-btn" type="button">
113
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
114
+ <line x1="12" y1="5" x2="12" y2="19"></line>
115
+ <line x1="5" y1="12" x2="19" y2="12"></line>
116
+ </svg>
117
+ New Scan
118
+ </button>
119
+ `}#B(){return`
120
+ <div class="copio-handoff-alert">
121
+ <div class="copio-handoff-alert-icon warning">
122
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
123
+ <circle cx="12" cy="12" r="10"></circle>
124
+ <polyline points="12 6 12 12 16 14"></polyline>
125
+ </svg>
126
+ </div>
127
+ <h2 class="copio-handoff-title">QR Code Expired</h2>
128
+ <p class="copio-handoff-desc">For security, handoff QR codes are single-use and expire after 10 minutes.</p>
129
+ </div>
130
+
131
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
132
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
133
+ <polyline points="23 4 23 10 17 10"></polyline>
134
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
135
+ </svg>
136
+ Generate new QR code
137
+ </button>
138
+ `}#q(){return`
139
+ <div class="copio-handoff-alert">
140
+ <div class="copio-handoff-alert-icon danger">
141
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
142
+ <circle cx="12" cy="12" r="10"></circle>
143
+ <line x1="12" y1="8" x2="12" y2="12"></line>
144
+ <line x1="12" y1="16" x2="12.01" y2="16"></line>
145
+ </svg>
146
+ </div>
147
+ <h2 class="copio-handoff-title">Connection Error</h2>
148
+ <p class="copio-handoff-desc">${this.#l||"Unable to establish secure peer connection."}</p>
149
+ </div>
150
+
151
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
152
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
153
+ <polyline points="23 4 23 10 17 10"></polyline>
154
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
155
+ </svg>
156
+ Generate new QR code
157
+ </button>
158
+ `}#x(t=!1){return this.#t.length===0&&!t?"":`
159
+ <div class="copio-handoff-thumbnails" data-testid="thumbnail-grid">
160
+ ${this.#t.map((r,i)=>`
161
+ <div class="copio-handoff-thumb-card" data-page-id="${r.id}">
162
+ ${r.src?`<img class="copio-handoff-thumb-img" src="${r.src}" alt="${r.label||`Page ${i+1}`}">`:""}
163
+ <span class="copio-handoff-thumb-label">P${i+1}</span>
164
+ </div>
165
+ `).join("")}
166
+ ${t?`
167
+ <div class="copio-handoff-thumb-card">
168
+ <div class="copio-handoff-thumb-shimmer">
169
+ <div class="copio-handoff-spinner" style="width:14px;height:14px;border-width:2px;"></div>
170
+ </div>
171
+ </div>
172
+ `:""}
173
+ </div>
174
+ `}#z(){if(!this.shadowRoot)return;let t=this.shadowRoot.querySelector(".copio-handoff-refresh-btn");t&&t.addEventListener("click",()=>{this.refresh()});let o=this.shadowRoot.querySelector(".copio-handoff-retry-btn");o&&o.addEventListener("click",()=>{this.refresh()});let e=this.shadowRoot.querySelector(".copio-handoff-reset-btn");e&&e.addEventListener("click",()=>{this.clear()});let r=this.shadowRoot.querySelector(".copio-handoff-upload-btn"),i=this.shadowRoot.querySelector(".copio-handoff-file-input");r&&i&&(r.addEventListener("click",()=>{i.click()}),i.addEventListener("change",c=>{let n=c.target;n.files&&n.files.length>0&&this.#$(Array.from(n.files))}))}};typeof customElements<"u"&&!customElements.get("copio-handoff")&&customElements.define("copio-handoff",u);export{g as a,v as b,w as c,u as d};
175
+ //# sourceMappingURL=chunk-2VH2NPXW.js.map
@@ -1,2 +1,2 @@
1
- var a=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(e){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(e,t){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(e,t){let r=await this.getDoc(e);if(!r)throw new Error(`Document "${e}" not found`);r.name=t,await this.saveDoc(e,r)}async deleteDoc(e){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(e,t,r){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(e,t){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(e,t){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(e){return()=>{}}};export{a};
2
- //# sourceMappingURL=chunk-DIU5BGU5.js.map
1
+ var a=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(e){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(e,t){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(e,t){let r=await this.getDoc(e);if(!r)throw new Error(`Document "${e}" not found`);r.name=t,await this.saveDoc(e,r)}async deleteDoc(e){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(e,t,r){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(e,t){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(e,t){throw new Error("StoragePort.deletePage() must be implemented by adapter")}async getSchemaVersion(){return this._schemaVersion??null}async setSchemaVersion(e){this._schemaVersion=typeof e=="number"?e:null}subscribe(e){return()=>{}}};export{a};
2
+ //# sourceMappingURL=chunk-4D6GC55I.js.map
@@ -0,0 +1,2 @@
1
+ import{a as U}from"./chunk-NNSM2I5L.js";import{a as L,b as S,d as m}from"./chunk-JIPKWRBK.js";import{a as D}from"./chunk-4D6GC55I.js";async function $(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let l=await navigator.storage.getDirectory();if(!l)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,i=await l.getFileHandle(t,{create:!0}),r=await i.createWritable();if(await r.write(new Uint8Array([1,2,3,4])),await r.close(),(await i.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await l.removeEntry(t),!0}catch{return!1}}function j(l,t,i="store.json"){let r=0,s=null,n=Promise.resolve(),a=0,o=()=>typeof t=="function"?t():t,e=async()=>{await n;let f=o();if(f){r=1;try{let u=await(await(await f.getFileHandle(i)).getFile()).text();u&&u.trim().length>0&&l.setJson(u)}catch{}finally{r=0}}},c=()=>{let f=o();return f?(a++,r=2,n=n.catch(()=>{}).then(async()=>{try{let w=l.getJson(),u=await(await f.getFileHandle(i,{create:!0})).createWritable();await u.write(w),await u.close()}catch(w){console.warn("[OpfsPersister] Failed to save store.json:",w)}finally{a--,a<=0&&(a=0,r=0)}}),n):Promise.resolve()};return{load:e,save:c,startAutoSave:()=>{s||(s=l.addDidFinishTransactionListener(()=>{c()}))},stopAutoSave:()=>{s&&(l.delListener(s),s=null)},getStatus:()=>r,getStore:()=>l}}async function O(l){let t=[];try{if(typeof l.entries=="function")for await(let i of l.entries())t.push(i);else if(typeof l.values=="function")for await(let i of l.values())t.push([i.name,i])}catch(i){console.warn("[OpfsAdapter] Error reading directory entries:",i)}return t}var v=class extends D{#p;#d="copio";#b=null;#u=null;#r=null;#e=null;#c=null;#i=!1;#t=null;#l=new Set;#h=new Map;#s=new Map;#a=new Map;#n=new Map;#w=null;constructor(t={}){super(),this.#p=t,this.#d=t.dirName||"copio",t.store?this.#e=t.store:(this.#e=L(),this.#e.setTable("docs",{})),this.#c=t.persister||j(this.#e,()=>this.#u,"store.json")}get store(){return this.#i?this.#t?.store:this.#e}get persister(){return this.#i?this.#t?.persister:this.#c}get isFallback(){return this.#i}get fallbackAdapter(){return this.#t}async#o(){if(this.#i)return!1;if(this.#r&&this.#u)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#b=await navigator.storage.getDirectory(),this.#u=await this.#b.getDirectoryHandle(this.#d,{create:!0}),this.#r=await this.#u.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#f(),!1}else return await this.#f(),!1}#y(t,i){return typeof i=="string"&&i.startsWith("blob:")&&(this.#l.add(i),this.#h.has(t)||this.#h.set(t,[]),this.#h.get(t).push(i)),i}revokeDocUrls(t){if(this.#i){this.#t?.revokeDocUrls(t);return}let i=this.#h.get(t);if(i){for(let r of i){try{URL.revokeObjectURL(r)}catch{}this.#l.delete(r)}this.#h.delete(t)}for(let[r,s]of this.#s.entries())if(r.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#s.delete(r)}for(let[r,s]of this.#a.entries())if(r.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#a.delete(r)}this.#n.delete(t)}revokeAllUrls(){if(this.#i){this.#t?.revokeAllUrls();return}for(let t of this.#l)try{URL.revokeObjectURL(t)}catch{}this.#l.clear(),this.#h.clear(),this.#s.clear(),this.#a.clear(),this.#n.clear()}async init(){return this.#w?this.#w:(this.#w=(async()=>{if(this.#p.forceFallback)return this.#f();if(!await $())return this.#f();try{await this.#o(),await this.#c.load(),this.#c.startAutoSave(),await this.sweepOrphans();let i=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{i=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:i}}catch(i){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",i),this.#f()}})(),this.#w)}async#f(){return this.#i=!0,this.#t=new m(this.#p),{kind:"indexeddb",persistent:(await this.#t.init()).persistent}}async sweepOrphans(){if(this.#i)return this.#t?.sweepOrphans();if(await this.#o(),!this.#r)return 0;let t=0,i=this.#e.getTable("docs")||{},r=new Set(Object.keys(i)),s=new Map;for(let[a,o]of Object.entries(i)){let e=this.#g(o.pages);s.set(a,new Set(e.map(c=>c.id)))}let n=await O(this.#r);for(let[a,o]of n)if(o.kind==="directory")if(r.has(a)){let e=s.get(a)||new Set,c=o,g=await O(c);for(let[y]of g){let f=y.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!e.has(f))try{await c.removeEntry(y),t++}catch{}}}else try{await this.#r.removeEntry(a,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#i)return this.#t?.listDocsSync();let t=this.#e.getTable("docs");return Object.entries(t||{}).map(([i,r])=>({id:i,name:r.name||"",pages:this.#g(r.pages)}))}async listDocs(){return this.#i?this.#t?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#i)return this.#t?.getDocSync(t);if(this.#n.has(t))return this.#n.get(t);if(!this.#e.hasRow("docs",t))return null;let i=this.#e.getRow("docs",t);return{id:t,name:i.name||"",pages:this.#g(i.pages)}}async getDoc(t){if(this.#i)return this.#t?.getDoc(t);if(await this.#o(),!this.#e.hasRow("docs",t))return null;let i=this.#e.getRow("docs",t),r=this.#g(i.pages),s=null;if(this.#r)try{s=await this.#r.getDirectoryHandle(t)}catch{}let n=await Promise.all(r.map(async o=>{if(!o||!s)return o;let e={...o},c=`${t}:${o.id}`;try{let f=await(await s.getFileHandle(`${o.id}.bin`)).getFile();e.blob=f,this.#s.has(c)?e.src=this.#s.get(c):(e.src=this.#y(t,URL.createObjectURL(f)),this.#s.set(c,e.src))}catch{}let g=`${t}:${o.id}:orig`;try{let f=await(await s.getFileHandle(`${o.id}-original.bin`)).getFile();e.originalBlob=f,this.#a.has(g)?e.originalSrc=this.#a.get(g):(e.originalSrc=this.#y(t,URL.createObjectURL(f)),this.#a.set(g,e.originalSrc))}catch{e.blob&&(e.originalBlob=e.blob,e.originalSrc=e.src)}return e})),a={id:t,name:i.name||"",pages:n};return this.#n.set(t,a),a}async saveDoc(t,i){if(this.#i)return this.#t?.saveDoc(t,i);if(!t)throw new Error("Cannot save document without an ID");let r=Array.isArray(i.pages)?i.pages:this.#g(i.pages),s=[],n=[],a=[];for(let e of r){if(!e)continue;let c=S(e.src)||(e.src instanceof Blob?e.src:null)||(e.blob instanceof Blob?e.blob:null),g=c?.type||"image/jpeg",y={id:e.id,name:e.name||"",type:e.type||"image",hasBlob:!0,mimeType:g,edits:e.edits,exif:e.exif,content:e.content,ocrText:e.ocrText??null,ocrConfidence:e.ocrConfidence??null,ocrWords:Array.isArray(e.ocrWords)?e.ocrWords:null,ocrWidth:e.ocrWidth??null,ocrHeight:e.ocrHeight??null};s.push(y);let f=`${t}:${e.id}`,w=`${t}:${e.id}:orig`,h={...e},u=this.#s.get(f),k=typeof e.src=="string"&&e.src.startsWith("data:")||e.src instanceof Blob||e.src&&u&&e.src!==u;if(c)if(h.blob=c,k||!u){if(u){try{URL.revokeObjectURL(u)}catch{}this.#l.delete(u)}let b=this.#y(t,URL.createObjectURL(c));this.#s.set(f,b),h.src=b}else h.src=u;let d=S(e.originalSrc)||(e.originalSrc instanceof Blob?e.originalSrc:null)||(e.originalBlob instanceof Blob?e.originalBlob:null),p=this.#a.get(w),R=!p&&!d&&(!e.originalSrc||e.originalSrc===e.src);R&&c&&(d=c);let H=typeof e.originalSrc=="string"&&e.originalSrc.startsWith("data:")||e.originalSrc instanceof Blob||R&&!!d;if(d)if(h.originalBlob=d,H||!p){if(p&&H){try{URL.revokeObjectURL(p)}catch{}this.#l.delete(p)}let b=this.#y(t,URL.createObjectURL(d));this.#a.set(w,b),h.originalSrc=b}else h.originalSrc=p;else p?h.originalSrc=p:e.originalSrc?h.originalSrc=e.originalSrc:(h.originalSrc=h.src,h.blob&&(h.originalBlob=h.blob));n.push(h),a.push({pageId:e.id,page:e,srcBlob:c,origBlob:d})}if(this.#e.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(s)}),this.#n.set(t,{id:t,name:i.name||"",pages:n}),await this.#o(),this.#i)return this.#t?.saveDoc(t,i);let o=null;if(this.#r)try{o=await this.#r.getDirectoryHandle(t,{create:!0})}catch(e){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,e)}if(o)for(let e of a){let{pageId:c,page:g,srcBlob:y,origBlob:f}=e;if(!y&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{y=await(await fetch(g.src)).blob()}catch{}if(y)try{let h=await(await o.getFileHandle(`${c}.bin`,{create:!0})).createWritable();await h.write(y),await h.close()}catch(w){console.warn(`[OpfsAdapter] Failed writing page file "${c}.bin":`,w)}if(!f&&typeof g.originalSrc=="string"&&g.originalSrc.startsWith("blob:"))try{f=await(await fetch(g.originalSrc)).blob()}catch{}if(f)try{let h=await(await o.getFileHandle(`${c}-original.bin`,{create:!0})).createWritable();await h.write(f),await h.close()}catch{}}}async deleteDoc(t){if(this.#i)return this.#t?.deleteDoc(t);if(this.#e.delRow("docs",t),this.#n.delete(t),this.revokeDocUrls(t),await this.#o(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,i){if(this.#i)return this.#t?.renameDoc(t,i);if(!this.#e.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#e.setCell("docs",t,"name",i),this.#n.has(t)&&(this.#n.get(t).name=i)}async savePage(t,i,r){if(this.#i)return this.#t?.savePage(t,i,r);await this.#o();let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let n=s.pages.findIndex(e=>e.id===i),a;if(n>=0)typeof r=="object"&&r!==null&&!(r instanceof Blob)?s.pages[n]={...s.pages[n],...r}:s.pages[n]={...s.pages[n],src:r,blob:r instanceof Blob?r:void 0},a=s.pages[n];else{let e=typeof r=="object"&&r!==null&&!(r instanceof Blob)?{id:i,...r}:{id:i,src:r,blob:r instanceof Blob?r:void 0};s.pages.push(e),a=e}let o=S(a.src)||(a.src instanceof Blob?a.src:null)||(a.blob instanceof Blob?a.blob:null);if(!o&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{o=await(await fetch(a.src)).blob()}catch{}if(o&&this.#r)try{let g=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${i}.bin`,{create:!0})).createWritable();await g.write(o),await g.close()}catch(e){console.warn(`[OpfsAdapter] Failed writing page file "${i}.bin":`,e)}await this.saveDoc(t,s)}async getPage(t,i){if(this.#i)return this.#t?.getPage(t,i);if(await this.#o(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${i}.bin`)).getFile()}catch{}let r=this.getDocSync(t);if(!r)return null;let s=r.pages.find(n=>n.id===i);return s?s.content??s.src??s:null}async deletePage(t,i){if(this.#i)return this.#t?.deletePage(t,i);await this.#o();let r=this.getDocSync(t);if(!r)return;if(r.pages=r.pages.filter(a=>a.id!==i),this.#e.setRow("docs",t,{name:r.name||"",pages:JSON.stringify(r.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${i}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${i}-original.bin`)}catch{}}let s=`${t}:${i}`;if(this.#s.has(s)){try{URL.revokeObjectURL(this.#s.get(s))}catch{}this.#s.delete(s)}let n=`${t}:${i}:orig`;if(this.#a.has(n)){try{URL.revokeObjectURL(this.#a.get(n))}catch{}this.#a.delete(n)}this.#n.delete(t)}async getSchemaVersion(){if(this.#i&&this.#t)return this.#t.getSchemaVersion();if(this.#e&&this.#e.hasValue("schemaVersion")){let t=this.#e.getValue("schemaVersion");return typeof t=="number"?t:null}return null}async setSchemaVersion(t){if(this.#i&&this.#t)return this.#t.setSchemaVersion(t);this.#e&&(this.#e.setValue("schemaVersion",typeof t=="number"?t:null),this.#c&&typeof this.#c.save=="function"&&await this.#c.save())}subscribe(t){if(this.#i)return this.#t?.subscribe(t);let i=this.#e.addTableListener("docs",t);return()=>{this.#e.delListener(i)}}#g(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function V(l={}){return l.forceMemory?new U:l.forceIndexedDb?new m(l):l.forceOpfs?new v(l):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new v(l):typeof indexedDB<"u"?new m(l):new U}export{$ as a,v as b,V as c};
2
+ //# sourceMappingURL=chunk-6QK7337A.js.map
@@ -0,0 +1,2 @@
1
+ import{a as C,b as u,d as R}from"./chunk-ZILTJGT2.js";import{a as E,c as x}from"./chunk-ZT72PD2C.js";function W(t,e,n){return{topLeft:{x:t.topLeft.x*e,y:t.topLeft.y*n},topRight:{x:t.topRight.x*e,y:t.topRight.y*n},bottomRight:{x:t.bottomRight.x*e,y:t.bottomRight.y*n},bottomLeft:{x:t.bottomLeft.x*e,y:t.bottomLeft.y*n}}}function h(t){return Number.isFinite(t)?t<=0?0:t>=1?1:t:0}function M(t){let e=[{x:h(t.topLeft.x),y:h(t.topLeft.y)},{x:h(t.topRight.x),y:h(t.topRight.y)},{x:h(t.bottomRight.x),y:h(t.bottomRight.y)},{x:h(t.bottomLeft.x),y:h(t.bottomLeft.y)}],n=(e[0].x+e[1].x+e[2].x+e[3].x)/4,i=(e[0].y+e[1].y+e[2].y+e[3].y)/4;e.sort((o,a)=>Math.atan2(o.y-i,o.x-n)-Math.atan2(a.y-i,a.x-n));let s=0,r=1/0;for(let o=0;o<4;o++){let a=e[o].x+e[o].y;a<r&&(r=a,s=o)}return{topLeft:e[s],topRight:e[(s+1)%4],bottomRight:e[(s+2)%4],bottomLeft:e[(s+3)%4]}}var f=null,y=null;async function A(t){if(!t)throw new Error("ScanicWasmEdgeAdapter.detect(): No image source provided");if(typeof t.width=="number"&&typeof t.height=="number"&&t.data&&(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array)){if(!(t.width>0&&t.height>0))throw new Error("ScanicWasmEdgeAdapter.detect(): Image has invalid dimensions");return{data:t.data,width:t.width,height:t.height}}let e=t;if(typeof t=="string"){if(typeof Image>"u")throw new Error("ScanicWasmEdgeAdapter.detect(): Cannot decode image URL without browser Image API");let r=new Image;r.crossOrigin="anonymous",await new Promise((o,a)=>{r.onload=()=>o(null),r.onerror=()=>a(new Error("Failed to load image for edge detection")),r.src=t}),e=r}else if(typeof Blob<"u"&&t instanceof Blob)if(typeof createImageBitmap=="function")e=await createImageBitmap(t);else if(typeof Image<"u"&&typeof URL<"u"){let r=URL.createObjectURL(t);try{let o=new Image;await new Promise((a,l)=>{o.onload=()=>a(null),o.onerror=()=>l(new Error("Failed to decode Blob for edge detection")),o.src=r}),e=o}finally{URL.revokeObjectURL(r)}}else throw new Error("ScanicWasmEdgeAdapter.detect(): Cannot decode Blob in this environment");if(typeof e.getContext=="function"&&e.width>0&&e.height>0){let r=e.getContext("2d",{willReadFrequently:!0});if(r&&typeof r.getImageData=="function")return{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}let n=e.naturalWidth||e.videoWidth||e.displayWidth||e.width||0,i=e.naturalHeight||e.videoHeight||e.displayHeight||e.height||0;if(!(n>0&&i>0))throw new Error("ScanicWasmEdgeAdapter.detect(): Source image has zero width or height");if(!f){if(typeof OffscreenCanvas<"u")f=new OffscreenCanvas(n,i);else if(typeof document<"u"&&typeof document.createElement=="function")f=document.createElement("canvas");else throw new Error("ScanicWasmEdgeAdapter.detect(): No Canvas implementation available");y=f.getContext("2d",{willReadFrequently:!0})}f.width!==n||f.height!==i?(f.width=n,f.height=i):y.clearRect(0,0,n,i),y.drawImage(e,0,0,n,i);let s=y.getImageData(0,0,n,i);return typeof ImageBitmap<"u"&&e instanceof ImageBitmap&&e!==t&&e.close?.(),{data:s.data,width:n,height:i}}var L=class extends R{#t;#e=null;#i=null;#o=null;#s=1;#n=new Map;constructor(e={}){super();let n=typeof window>"u"&&typeof Worker>"u";this.#t={maxProcessingDimension:800,enableDetectionCascade:!0,minConfidence:.55,fallbackOnLowConfidence:!1,useWorker:!0,detector:n?"classical":"ml",...e}}get detector(){return this.#t.detector||"classical"}set detector(e){this.#t.detector=e==="ml"?"ml":"classical"}async preloadMl(e={}){let n=await this.getEdgeWorker();if(n&&!("isInlineFallback"in n)){let i=await this.#r({type:"init",preloadMl:!0,mlOptions:e});if(i&&i.mlReady===!1&&i.mlError)throw new Error(i.mlError)}else await(await import("./scanic-mlDetector-BCSVQYFV.js")).initializeMl(e)}#c(){if(this.#t.workerPath)return x(this.#t.workerPath);let e=E(),n=x("js/lib/scanic-detector.js");return e==="."&&typeof location<"u"&&location.pathname&&location.pathname!=="/"&&!location.pathname.endsWith("/index.html")&&!n.startsWith("/")&&!/^(https?:|blob:|data:)/i.test(n)?`/${n}`:n}async#a(){if(this.#o)return this.#o;let n=await import("../../lib/scanic-detector.js");return await n.initialize(),this.#o=n,n}#r(e,n=[]){return new Promise((i,s)=>{if(!this.#e||this.#e.isInlineFallback){s(new Error("Web Worker is not active"));return}let r=this.#s++;this.#n.set(r,{resolve:i,reject:s});try{this.#e.postMessage({...e,id:r},n)}catch(o){this.#n.delete(r),s(o)}})}async getEdgeWorker(){if(this.#e)return this.#e;if(this.#i)return this.#i;this.#i=(async()=>{if(this.#t.useWorker!==!1&&typeof Worker=="function")try{let n=this.#c(),i=new Worker(n,{type:"module"});return i.addEventListener("message",s=>{let r=s?.data;if(!r||typeof r.id!="number")return;let o=this.#n.get(r.id);o&&(this.#n.delete(r.id),r.ok?o.resolve(r):o.reject(new Error(r.error||"Edge detector worker error")))}),i.addEventListener("error",s=>{let r=new Error(s?.message||"Edge detector Web Worker error");for(let[,o]of this.#n)o.reject(r);this.#n.clear()}),this.#e=i,await this.#r({type:"init"}),this.#e}catch{if(this.#e&&typeof this.#e.terminate=="function")try{this.#e.terminate()}catch{}this.#e=null}return await this.#a(),this.#e={isInlineFallback:!0,terminate:()=>{}},this.#e})();try{return await this.#i}finally{this.#i=null}}async detect(e,n={}){let i={...this.#t,...n},s=typeof i.minConfidence=="number"?i.minConfidence:.55,r=!!i.fallbackOnLowConfidence,{data:o,width:a,height:l}=await A(e),k=await this.getEdgeWorker(),I=i.detector||this.#t.detector||"classical",m={maxProcessingDimension:i.maxProcessingDimension??800,enableDetectionCascade:i.enableDetectionCascade??!0,lowThreshold:i.lowThreshold,highThreshold:i.highThreshold,dilationKernelSize:i.dilationKernelSize,applyDilation:i.applyDilation,detector:I,ml:i.ml},d;if(k&&!("isInlineFallback"in k)){let c=new Uint8ClampedArray(o);d=(await this.#r({type:"detect",buffer:c.buffer,width:a,height:l,options:m},[c.buffer])).result}else{let c=await this.#a();if(m.detector==="ml")try{let p=await import("./scanic-mlDetector-BCSVQYFV.js"),D=typeof ImageData<"u"?new ImageData(o instanceof Uint8ClampedArray?o:new Uint8ClampedArray(o),a,l):{data:o,width:a,height:l},g=await p.detectDocumentMl(D,m.ml||m),w=g.success&&g.corners?g.corners:null,U=w?c.normalizeCornerQuad(w,a,l):null;d={success:!!(g.success&&w),corners:w,normalizedCorners:U,confidence:g.confidence??g.score??0,width:a,height:l,detector:"ml",durationMs:0}}catch{d=await c.detectEdgesFromRgba(o,a,l,m)}else d=await c.detectEdgesFromRgba(o,a,l,m)}let b=typeof d?.confidence=="number"?d.confidence:0;if(d?.success&&d?.normalizedCorners&&b>=s){let c=M(d.normalizedCorners),p=W(c,a,l);return{quad:c,normalizedCorners:u(c),corners:u(c),pixelCorners:p,confidence:b,width:a,height:l,isFallback:!1,durationMs:d.durationMs}}if(r){let c=u(C);return{quad:c,normalizedCorners:u(c),corners:u(c),pixelCorners:W(c,a,l),confidence:b,width:a,height:l,isFallback:!0,durationMs:d?.durationMs??0}}return null}async terminateEdgeWorker(){this.#i=null;for(let[,e]of this.#n)e.reject(new Error("Edge detector worker terminated"));if(this.#n.clear(),this.#e){try{this.#e.terminate?.()}catch{}this.#e=null}}};export{L as a};
2
+ //# sourceMappingURL=chunk-GLY5CGCY.js.map
@@ -0,0 +1,4 @@
1
+ import{a as ae}from"./chunk-ULTSZWZO.js";function c(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var Kt=typeof self<"u"?self:global,ot=typeof navigator<"u",ze=ot&&typeof HTMLImageElement>"u",oe=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Yt=Kt.Buffer,St=Kt.BigInt,Jt=!!Yt,kt=s=>we(s)?void 0:s,je=s=>s!==void 0;function we(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(je).length===0)}function y(s){let t=new Error(s);throw delete t.stack,t}function xe(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function he(s){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(s);return s.jfif.enabled&&(t+=50),s.xmp.enabled&&(t+=2e4),s.iptc.enabled&&(t+=14e3),s.icc.enabled&&(t+=6e3),t}var Vt=s=>String.fromCharCode.apply(null,s),le=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Se(s){return le?le.decode(s):Jt?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(Vt(s)))}var B=class s{static from(t,e){return t instanceof this&&t.le===e?t:new s(t,void 0,void 0,e)}constructor(t,e=0,i,n){if(typeof n=="boolean"&&(this.le=n),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let r=new DataView(t,e,i);this._swapDataView(r)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof s){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&y("Creating view outside of available memory in ArrayBuffer");let r=new DataView(t.buffer,e,i);this._swapDataView(r)}else if(typeof t=="number"){let r=new DataView(new ArrayBuffer(t));this._swapDataView(r)}else y("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=s){return t instanceof DataView||t instanceof s?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||y("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new s(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return Se(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Vt(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let n=0;n<e&&t+n<this.byteLength;n+=2)i.push(this.getUint16(t+n));return Vt(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function zt(s,t){y(`${s} '${t}' was not loaded, try using full build of exifr.`)}var ht=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||zt(this.kind,t),e&&(t in e||(function(i,n){y(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||zt(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},_=new ht("file parser"),M=new ht("segment parser"),X=new ht("file reader"),ke=Kt.fetch;function fe(s,t){return(e=s).startsWith("data:")||e.length>1e4?Ht(s,t,"base64"):oe&&s.includes("://")?jt(s,t,"url",Z):oe?Ht(s,t,"fs"):ot?jt(s,t,"url",Z):void y("Invalid input argument");var e}async function jt(s,t,e,i){return X.has(e)?Ht(s,t,e):i?(async function(n,r){let a=await r(n);return new B(a)})(s,i):void y(`Parser ${e} is not loaded`)}async function Ht(s,t,e){let i=new(X.get(e))(s,t);return await i.read(),i}var Z=s=>ke(s).then((t=>t.arrayBuffer())),Q=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),Wt=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function A(s,t,e){let i=new Wt;for(let[n,r]of e)i.set(n,r);if(Array.isArray(t))for(let n of t)s.set(n,i);else s.set(t,i);return i}function Zt(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var U=new Map,et=new Map,$=new Map,j=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],lt=["jfif","xmp","icc","iptc","ihdr"],tt=["tiff",...lt],p=["ifd0","ifd1","exif","gps","interop"],H=[...tt,...p],W=["makerNote","userComment"],ft=["translateKeys","translateValues","reviveValues","multiSegment"],G=[...ft,"sanitize","mergeOutput","silentErrors"],vt=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},z=class extends vt{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,n){if(super(),c(this,"enabled",!1),c(this,"skip",new Set),c(this,"pick",new Set),c(this,"deps",new Set),c(this,"translateKeys",!1),c(this,"translateValues",!1),c(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=p.includes(t),this.canBeFiltered&&(this.dict=U.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:r,skip:a}=i;r&&r.length>0&&this.translateTagSet(r,this.pick),a&&a.length>0&&this.translateTagSet(a,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:y(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of ft)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:r,tagValues:a}=this.dict;for(i of t)typeof i=="string"?(n=a.indexOf(i),n===-1&&(n=r.indexOf(Number(i))),n!==-1&&e.add(Number(r[n]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,Mt(this.pick,this.deps)):this.enabled&&this.pick.size>0&&Mt(this.pick,this.deps)}},v={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},ue=new Map,N=class extends vt{static useCached(t){let e=ue.get(t);return e!==void 0||(e=new this(t),ue.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):y(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=ot?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of j)this[t]=v[t];for(t of G)this[t]=v[t];for(t of W)this[t]=v[t];for(t of H)this[t]=new z(t,v[t],void 0,this)}setupFromTrue(){let t;for(t of j)this[t]=v[t];for(t of G)this[t]=v[t];for(t of W)this[t]=!0;for(t of H)this[t]=new z(t,!0,void 0,this)}setupFromArray(t){let e;for(e of j)this[e]=v[e];for(e of G)this[e]=v[e];for(e of W)this[e]=v[e];for(e of H)this[e]=new z(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,p)}setupFromObject(t){let e;for(e of(p.ifd0=p.ifd0||p.image,p.ifd1=p.ifd1||p.thumbnail,Object.assign(this,t),j))this[e]=Dt(t[e],v[e]);for(e of G)this[e]=Dt(t[e],v[e]);for(e of W)this[e]=Dt(t[e],v[e]);for(e of tt)this[e]=new z(e,v[e],t[e],this);for(e of p)this[e]=new z(e,v[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,p,H),t.tiff===!0?this.batchEnableWithBool(p,!0):t.tiff===!1?this.batchEnableWithUserValue(p,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,p):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,p)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let n=e[i];this[i].enabled=n!==!1&&n!==void 0}}setupGlobalFilters(t,e,i,n=i){if(t&&t.length){for(let a of n)this[a].enabled=!1;let r=ce(t,i);for(let[a,o]of r)Mt(this[a].pick,o),this[a].enabled=!0}else if(e&&e.length){let r=ce(e,i);for(let[a,o]of r)Mt(this[a].skip,o)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:n,icc:r}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),n.enabled||t.skip.add(33723),r.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:n}=this;n.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=p.some((r=>this[r].enabled===!0))||this.makerNote||this.userComment;for(let r of p)this[r].finalizeFilters()}get onlyTiff(){return!lt.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of tt)this[t].enabled&&!M.has(t)&&zt("segment parser",t)}};function ce(s,t){let e,i,n,r,a=[];for(n of t){for(r of(e=U.get(n),i=[],e))(s.includes(r[0])||s.includes(r[1]))&&i.push(r[0]);i.length&&a.push([n,i])}return a}function Dt(s,t){return s!==void 0?s:t!==void 0?t:void 0}function Mt(s,t){for(let e of t)s.add(e)}c(N,"default",v);var R=class{constructor(t){c(this,"parsers",{}),c(this,"output",{}),c(this,"errors",[]),c(this,"pushToErrors",(e=>this.errors.push(e))),this.options=N.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?fe(e,i):ot&&!ze&&e instanceof HTMLImageElement?fe(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new B(e):ot&&e instanceof Blob?jt(e,i,"blob",Q):void y("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,n]of _)if(n.canHandle(t,e))return this.fileParser=new n(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),y("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),kt(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let n=await i.parse();i.assignToOutput(t,n)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=M.get("tiff",t);var n;if(e.tiff?n={start:0,type:"tiff"}:e.jpeg&&(n=await this.fileParser.getOrFindSegment("tiff")),n===void 0)return;let r=await this.fileParser.ensureSegmentChunk(n),a=this.parsers.tiff=new i(r,t,e),o=await a.extractThumbnail();return e.close&&e.close(),o}};async function Qt(s,t){let e=new R(t);return await e.read(s),e.parse()}var He=Object.freeze({__proto__:null,parse:Qt,Exifr:R,fileParsers:_,segmentParsers:M,fileReaders:X,tagKeys:U,tagValues:et,tagRevivers:$,createDictionary:A,extendDictionary:Zt,fetchUrlAsArrayBuffer:Z,readBlobAsArrayBuffer:Q,chunkedProps:j,otherSegments:lt,segments:tt,tiffBlocks:p,segmentsAndBlocks:H,tiffExtractables:W,inheritables:ft,allFormatters:G,Options:N}),Ct=class{constructor(t,e,i){c(this,"errors",[]),c(this,"ensureSegmentChunk",(async n=>{let r=n.start,a=n.size||65536;if(this.file.chunked)if(this.file.available(r,a))n.chunk=this.file.subarray(r,a);else try{n.chunk=await this.file.readChunk(r,a)}catch(o){y(`Couldn't read segment: ${JSON.stringify(n)}. ${o.message}`)}else this.file.byteLength>r+a?n.chunk=this.file.subarray(r,a):n.size===void 0?n.chunk=this.file.subarray(r):y("Segment unreachable: "+JSON.stringify(n));return n.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(M.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:n}=e,r=this.options[i];if(r&&r.enabled){let a=this.parsers[i];a&&a.append||a||this.createParser(i,n)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},L=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,n=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,r=e+n,a=i-n;return{offset:e,length:i,headerLength:n,start:r,size:a,end:r+a}}static parse(t,e={}){return new this(t,new N({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof B?t:new B(t)}constructor(t,e={},i){c(this,"errors",[]),c(this,"raw",new Map),c(this,"handleError",(n=>{if(!this.options.silentErrors)throw n;this.errors.push(n.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=$.get(e),n=et.get(e),r=U.get(e),a=this.options[e],o=a.reviveValues&&!!i,h=a.translateValues&&!!n,l=a.translateKeys&&!!r,f={};for(let[g,u]of t)o&&i.has(g)?u=i.get(g)(u):h&&n.has(g)&&(u=this.translateValue(u,n.get(g))),l&&r.has(g)&&(g=r.get(g)||g),f[g]=u;return f}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};c(L,"headerLength",4),c(L,"type",void 0),c(L,"multiSegment",!1),c(L,"canHandle",(()=>!1));function We(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function Ge(s){return s>=224&&s<=239}function $e(s,t,e){for(let[i,n]of M)if(n.canHandle(s,t,e))return i}var Ot=class extends Ct{constructor(...t){super(...t),c(this,"appSegments",[]),c(this,"jpegSegments",[]),c(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(M.keyList())):(t=t===void 0?M.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&M.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:n,wanted:r,remaining:a}=this;if(!n&&this.file.chunked&&(n=Array.from(r).some((o=>{let h=M.get(o),l=this.options[o];return h.multiSegment&&l.multiSegment})),n&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let o=!1;for(;a.size>0&&!o&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:h}=i,l=this.appSegments.some((f=>!this.file.available(f.offset||f.start,f.length||f.size)));if(o=t>h&&!l?!await i.readNextChunk(t):!await i.readNextChunk(h),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,r,a,o,h,{file:l,findAll:f,wanted:g,remaining:u,options:m}=this;for(;t<e;t++)if(l.getUint8(t)===255){if(i=l.getUint8(t+1),Ge(i)){if(n=l.getUint16(t+2),r=$e(l,t,n),r&&g.has(r)&&(a=M.get(r),o=a.findPosition(l,t),h=m[r],o.type=r,this.appSegments.push(o),!f&&(a.multiSegment&&h.multiSegment?(this.unfinishedMultiSegment=o.chunkNumber<o.chunkCount,this.unfinishedMultiSegment||u.delete(r)):u.delete(r),u.size===0)))break;m.recordUnknownSegments&&(o=L.findPosition(l,t),o.marker=i,this.unknownSegments.push(o)),t+=n+1}else if(We(i)){if(n=l.getUint16(t+2),i===218&&m.stopAfterSos!==!1)return;m.recordJpegSegments&&this.jpegSegments.push({offset:t,length:n,marker:i}),t+=n+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let n,r,a,o=new Map;for(let h=0;h<e.length;h++)n=e[h],r=n[i],o.has(r)?a=o.get(r):o.set(r,a=[]),a.push(n);return Array.from(o)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let n=M.get(e,this.options);return n.handleMultiSegments?{type:e,chunk:n.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};c(Ot,"type","jpeg"),_.set("jpeg",Ot);var _e=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],Gt=class extends L{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:n,skip:r}=this.options[e];n=new Set(n);let a=n.size>0,o=r.size===0,h=this.chunk.getUint16(t);t+=2;for(let l=0;l<h;l++){let f=this.chunk.getUint16(t);if(a){if(n.has(f)&&(i.set(f,this.parseTag(t,f,e)),n.delete(f),n.size===0))break}else!o&&r.has(f)||i.set(f,this.parseTag(t,f,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,r=n.getUint16(t+2),a=n.getUint32(t+4),o=_e[r];if(o*a<=4?t+=8:t=n.getUint32(t+8),(r<1||r>13)&&y(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${r}, offset ${t}`),t>n.byteLength&&y(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${r}, offset ${t} is outside of chunk size ${n.byteLength}`),r===1)return n.getUint8Array(t,a);if(r===2)return xe(n.getString(t,a));if(r===7)return n.getUint8Array(t,a);if(a===1)return this.parseTagValue(r,t);{let h=new((function(f){switch(f){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(r))(a),l=o;for(let f=0;f<a;f++)h[f]=this.parseTagValue(r,t),t+=l;return h}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:y(`Invalid tiff type ${t}`)}}},nt=class extends Gt{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&y("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&y(`IFD0 offset points to outside of file.
2
+ this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,he(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,he(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",de(...t.get(2),t.get(1))),t.set("longitude",de(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,n={};for(e of p)if(t=this[e],!we(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(n,i)}else n[e]=i;return this.makerNote&&(n.makerNote=this.makerNote),this.userComment&&(n.userComment=this.userComment),n}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,n]of Object.entries(e))this.assignObjectToOutput(t,i,n)}};function de(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}c(nt,"type","tiff"),c(nt,"headerLength",10),M.set("tiff",nt);var Xe=Object.freeze({__proto__:null,default:He,Exifr:R,fileParsers:_,segmentParsers:M,fileReaders:X,tagKeys:U,tagValues:et,tagRevivers:$,createDictionary:A,extendDictionary:Zt,fetchUrlAsArrayBuffer:Z,readBlobAsArrayBuffer:Q,chunkedProps:j,otherSegments:lt,segments:tt,tiffBlocks:p,segmentsAndBlocks:H,tiffExtractables:W,inheritables:ft,allFormatters:G,Options:N,parse:Qt}),te={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},ve=Object.assign({},te,{firstChunkSize:4e4,gps:[1,2,3,4]});async function qe(s){let t=new R(ve);await t.read(s);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:n}=e.gps;return{latitude:i,longitude:n}}}var Me=Object.assign({},te,{tiff:!1,ifd1:!0,mergeOutput:!1});async function Ke(s){let t=new R(Me);await t.read(s);let e=await t.extractThumbnail();return e&&Jt?Yt.from(e):e}async function Ye(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var Ce=Object.assign({},te,{firstChunkSize:4e4,ifd0:[274]});async function Oe(s){let t=new R(Ce);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var Ae=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),Y=!0,J=!0;if(typeof navigator=="object"){let s=navigator.userAgent;if(s.includes("iPad")||s.includes("iPhone")){let t=s.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;Y=Number(e)+.1*Number(i)<13.4,J=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);Y=J=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);Y=J=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);Y=J=Number(t)<77}}async function Je(s){let t=await Oe(s);return Object.assign({canvas:Y,css:J},Ae[t])}var $t=class extends B{constructor(...t){super(...t),c(this,"ranges",new _t),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let n=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(n)}else{let n=t+e;if(n>this.byteLength){let{dataView:r}=this._extend(n);this._swapDataView(r)}}}_extend(t){let e;e=Jt?Yt.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let n=super.set(t,e);return this.ranges.add(e,n.byteLength),n}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},_t=class{constructor(){c(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,r=this.list.filter((a=>ge(t,a.offset,n)||ge(t,a.end,n)));if(r.length>0){t=Math.min(t,...r.map((o=>o.offset))),n=Math.max(n,...r.map((o=>o.end))),e=n-t;let a=r.shift();a.offset=t,a.length=e,a.end=n,this.list=this.list.filter((o=>!r.includes(o)))}else this.list.push({offset:t,length:e,end:n})}available(t,e){let i=t+e;return this.list.some((n=>n.offset<=t&&i<=n.end))}};function ge(s,t,e){return s<=t&&t<=e}var At=class extends $t{constructor(t,e){super(0),c(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};X.set("blob",class extends At{async readWhole(){this.chunked=!1;let s=await Q(this.input);this._swapArrayBuffer(s)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(s,t){let e=t?s+t:void 0,i=this.input.slice(s,e),n=await Q(i);return this.set(n,s,!0)}});var Ze=Object.freeze({__proto__:null,default:Xe,Exifr:R,fileParsers:_,segmentParsers:M,fileReaders:X,tagKeys:U,tagValues:et,tagRevivers:$,createDictionary:A,extendDictionary:Zt,fetchUrlAsArrayBuffer:Z,readBlobAsArrayBuffer:Q,chunkedProps:j,otherSegments:lt,segments:tt,tiffBlocks:p,segmentsAndBlocks:H,tiffExtractables:W,inheritables:ft,allFormatters:G,Options:N,parse:Qt,gpsOnlyOptions:ve,gps:qe,thumbnailOnlyOptions:Me,thumbnail:Ke,thumbnailUrl:Ye,orientationOnlyOptions:Ce,orientation:Oe,rotations:Ae,get rotateCanvas(){return Y},get rotateCss(){return J},rotation:Je});X.set("url",class extends At{async readWhole(){this.chunked=!1;let s=await Z(this.input);s instanceof ArrayBuffer?this._swapArrayBuffer(s):s instanceof Uint8Array&&this._swapBuffer(s)}async _readChunk(s,t){let e=t?s+t-1:void 0,i=this.options.httpHeaders||{};(s||e)&&(i.range=`bytes=${[s,e].join("-")}`);let n=await ke(this.input,{headers:i}),r=await n.arrayBuffer(),a=r.byteLength;if(n.status!==416)return a!==t&&(this.size=s+a),this.set(r,s,!0)}});B.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof St!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),St(t)<<St(32)|St(e)):void y("Trying to read 64b value but JS can only handle 53b numbers.")};var Xt=class extends Ct{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),n=t+8;return e===1&&(e=this.file.getUint64(t+8),n+=8),{offset:t,length:e,kind:i,start:n}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},Pt=class extends Xt{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let n=16,r=[];for(;n<i;)r.push(t.getString(n,4)),n+=4;return r.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let n=this.file.subarray(e,i);this.createParser(t,n)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let n=this.findBox(i,"colr");n!==void 0&&await this.registerSegment("icc",n.offset+12,n.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let n=this.findExifLocIdInIinf(e),r=this.findExtentInIloc(i,n);if(r===void 0)return;let[a,o]=r;await this.file.ensureChunk(a,o);let h=4+this.file.getUint32(a);a+=h,o-=h,await this.registerSegment("tiff",a,o)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,r,a=t.start,o=this.file.getUint16(a);for(a+=2;o--;){if(e=this.parseBoxHead(a),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(n=e.version===3?4:2,r=this.file.getString(i+n+2,4),r==="Exif"))return this.file.getUintBytes(i,n);a+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[n,r]=this.get8bits(i++),[a,o]=this.get8bits(i++),h=t.version===2?4:2,l=t.version===1||t.version===2?2:0,f=o+n+r,g=t.version===2?4:2,u=this.file.getUintBytes(i,g);for(i+=g;u--;){let m=this.file.getUintBytes(i,h);i+=h+l+2+a;let b=this.file.getUint16(i);if(i+=2,m===e)return b>1&&console.warn(`ILOC box has more than one extent but we're only processing one
3
+ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+o,n),this.file.getUintBytes(i+o+n,r)];i+=b*f}}},It=class extends Pt{};c(It,"type","heic");var Lt=class extends Pt{};c(Lt,"type","avif"),_.set("heic",It),_.set("avif",Lt),A(U,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),A(U,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),A(U,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),A(et,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var rt=A(et,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),pe={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};rt.set(37392,pe),rt.set(41488,pe);var Nt={0:"Normal",1:"Low",2:"High"};function me(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function ye(s){let t=Array.from(s).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Et(s){if(typeof s=="string"){var[t,e,i,n,r,a]=s.trim().split(/[-: ]/g).map(Number),o=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(a)||(o.setHours(n),o.setMinutes(r),o.setSeconds(a)),Number.isNaN(+o)?s:o}}function st(s){if(typeof s=="string")return s;let t=[];if(s[1]===0&&s[s.length-1]===0)for(let e=0;e<s.length;e+=2)t.push(be(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(be(s[e],s[e+1]));return xe(String.fromCodePoint(...t))}function be(s,t){return s<<8|t}rt.set(41992,Nt),rt.set(41993,Nt),rt.set(41994,Nt),A($,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Se(s):s}],[306,Et],[40091,st],[40092,st],[40093,st],[40094,st],[40095,st]]),A($,"exif",[[40960,ye],[36864,ye],[36867,Et],[36868,Et],[40962,me],[40963,me]]),A($,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var at=class extends L{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:B.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(r){let a={},o={};for(let h of Ue)a[h]=[],o[h]=0;return r.replace(ii,((h,l,f)=>{if(l==="<"){let g=++o[f];return a[f].push(g),`${h}#${g}`}return`${h}#${a[f].pop()}`}))})(t);let e=Ut.findAll(t,"rdf","Description");e.length===0&&e.push(new Ut("rdf","Description",void 0,t));let i,n={};for(let r of e)for(let a of r.properties)i=ei(a.ns,n),Pe(a,i);return(function(r){let a;for(let o in r)a=r[o]=kt(r[o]),a===void 0&&delete r[o];return kt(r)})(n)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,n]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",n);break;case"exif":this.assignObjectToOutput(t,"exif",n);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,n)}else t.xmp=e}};c(at,"type","xmp"),c(at,"multiSegment",!0),M.set("xmp",at);var qt=class s{static findAll(t){return Ie(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[3].slice(1,-1);return n=Le(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Ut=class s{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var n=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else n=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return Ie(t,n).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[4],r=t[8];return new s(e,i,n,r)}constructor(t,e,i,n){this.ns=t,this.name=e,this.attrString=i,this.innerXml=n,this.attrs=qt.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?Le(n):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return ti(this.children.map(Qe));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Pe(e,t);return this.value!==void 0&&(t.value=this.value),kt(t)}};function Pe(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var Qe=s=>s.serialize(),ti=s=>s.length===1?s[0]:s,ei=(s,t)=>t[s]?t[s]:t[s]={};function Ie(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function Le(s){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(s))return;let t=Number(s);if(!Number.isNaN(t))return t;let e=s.toLowerCase();return e==="true"||e!=="false"&&s.trim()}var Ue=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],ii=new RegExp(`(<|\\/)(${Ue.join("|")})`,"g"),Be=Ze;var d=s=>Math.round(s*1e6)/1e6,E=s=>Math.max(0,Math.min(1,Number(s)||0));function ut(s){if(!s||typeof s!="object")return null;let t=["topLeft","topRight","bottomRight","bottomLeft"],e={};for(let i of t){let n=s[i];if(!n||typeof n!="object"||!Number.isFinite(Number(n.x))||!Number.isFinite(Number(n.y)))return null;e[i]={x:d(E(n.x)),y:d(E(n.y))}}return e}function di(s){if(!s||typeof s!="object")return null;let t=E(s.x),e=E(s.y),i=E(t+(Number(s.w)||0)),n=E(e+(Number(s.h)||0));return{topLeft:{x:d(t),y:d(e)},topRight:{x:d(i),y:d(e)},bottomRight:{x:d(i),y:d(n)},bottomLeft:{x:d(t),y:d(n)}}}function si(s={}){let t=s&&s.crop&&typeof s.crop=="object"?{x:Math.max(0,Math.min(1,Number(s.crop.x)||0)),y:Math.max(0,Math.min(1,Number(s.crop.y)||0)),w:Math.max(0,Math.min(1,Number(s.crop.w)||1)),h:Math.max(0,Math.min(1,Number(s.crop.h)||1))}:null,e=ut(s?.quad),i=0,n=s?.rotate!==void 0?s.rotate:s?.rotation;if(n!==void 0){let a=(Math.round(Number(n)/90)*90%360+360)%360;(a===90||a===180||a===270)&&(i=a)}let r=s&&s.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotate:i,filter:r}}function ni(s){if(!s)return!1;let t=s.rotate!==void 0?s.rotate:s.rotation;return!!(s.crop||ut(s.quad)||t&&t!==0||s.filter&&s.filter!=="none")}function Fe(s,t=0){if(!s)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:n,w:r,h:a}=s;return e===90?{x:d(Math.max(0,Math.min(1,1-n-a))),y:d(Math.max(0,Math.min(1,i))),w:d(Math.max(.01,Math.min(1,a))),h:d(Math.max(.01,Math.min(1,r)))}:e===180?{x:d(Math.max(0,Math.min(1,1-i-r))),y:d(Math.max(0,Math.min(1,1-n-a))),w:d(Math.max(.01,Math.min(1,r))),h:d(Math.max(.01,Math.min(1,a)))}:e===270?{x:d(Math.max(0,Math.min(1,n))),y:d(Math.max(0,Math.min(1,1-i-r))),w:d(Math.max(.01,Math.min(1,a))),h:d(Math.max(.01,Math.min(1,r)))}:{x:d(Math.max(0,Math.min(1,i))),y:d(Math.max(0,Math.min(1,n))),w:d(Math.max(.01,Math.min(1,r))),h:d(Math.max(.01,Math.min(1,a)))}}function gi(s,t=0){return Fe(s,t)}function pi(s,t=0){return Fe(s,-t)}function C(s,t){let e=E(s.x),i=E(s.y);return t===90?{x:d(1-i),y:d(e)}:t===180?{x:d(1-e),y:d(1-i)}:t===270?{x:d(i),y:d(1-e)}:{x:d(e),y:d(i)}}function De(s,t=0){let e=ut(s);if(!e)return null;let i=(Math.round(Number(t)/90)*90%360+360)%360;return i===90?{topLeft:C(e.bottomLeft,90),topRight:C(e.topLeft,90),bottomRight:C(e.topRight,90),bottomLeft:C(e.bottomRight,90)}:i===180?{topLeft:C(e.bottomRight,180),topRight:C(e.bottomLeft,180),bottomRight:C(e.topLeft,180),bottomLeft:C(e.topRight,180)}:i===270?{topLeft:C(e.topRight,270),topRight:C(e.bottomRight,270),bottomRight:C(e.bottomLeft,270),bottomLeft:C(e.topLeft,270)}:e}function mi(s,t=0){return De(s,t)}function yi(s,t=0){return De(s,-t)}var Bt=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=si(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return ni(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Re=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof Bt?e:new Bt(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},Te=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};function ri(s){let{topLeft:t,topRight:e,bottomRight:i,bottomLeft:n}=s,r=Math.hypot(e.x-t.x,e.y-t.y),a=Math.hypot(i.x-n.x,i.y-n.y),o=Math.hypot(n.x-t.x,n.y-t.y),h=Math.hypot(i.x-e.x,i.y-e.y);return{width:Math.max(1,Math.round(Math.max(r,a))),height:Math.max(1,Math.round(Math.max(o,h)))}}function ai(s){let t=s.topLeft.x,e=s.topLeft.y,i=s.topRight.x,n=s.topRight.y,r=s.bottomRight.x,a=s.bottomRight.y,o=s.bottomLeft.x,h=s.bottomLeft.y,l=i-r,f=o-r,g=t-i+r-o,u=n-a,m=h-a,b=e-n+a-h,k=l*m-f*u,S=0,w=0;return Math.abs(k)>1e-12&&(S=(g*m-f*b)/k,w=(l*b-g*u)/k),{a:i-t+S*i,b:o-t+w*o,c:t,d:n-e+S*n,e:h-e+w*h,f:e,g:S,h:w}}function oi(s,t,e,i,n,r){let a=new Uint8ClampedArray(n*r*4),{a:o,b:h,c:l,d:f,e:g,f:u,g:m,h:b}=ai(i),k=t-1,S=e-1;for(let w=0;w<r;w++){let x=(w+.5)/r,O=h*x+l,P=g*x+u,Rt=b*x+1;for(let q=0;q<n;q++){let V=(q+.5)/n,it=m*V+Rt;if(Math.abs(it)<1e-12)continue;let T=(o*V+O)/it-.5,F=(f*V+P)/it-.5;T<0?T=0:T>k&&(T=k),F<0?F=0:F>S&&(F=S);let D=T|0,I=F|0,K=D<k?D+1:k,se=I<S?I+1:S,Tt=T-D,Ft=F-I,ne=1-Tt,re=1-Ft,ct=ne*re,dt=Tt*re,gt=ne*Ft,pt=Tt*Ft,mt=(I*t+D)*4,yt=(I*t+K)*4,bt=(se*t+D)*4,wt=(se*t+K)*4,xt=(w*n+q)*4;a[xt]=Math.round(s[mt]*ct+s[yt]*dt+s[bt]*gt+s[wt]*pt),a[xt+1]=Math.round(s[mt+1]*ct+s[yt+1]*dt+s[bt+1]*gt+s[wt+1]*pt),a[xt+2]=Math.round(s[mt+2]*ct+s[yt+2]*dt+s[bt+2]*gt+s[wt+2]*pt),a[xt+3]=Math.round(s[mt+3]*ct+s[yt+3]*dt+s[bt+3]*gt+s[wt+3]*pt)}}return a}function Ne(s,t){let e=s.naturalWidth||s.width||0,i=s.naturalHeight||s.height||0;if(e<=0||i<=0){let b=document.createElement("canvas");return b.width=1,b.height=1,b}let n;typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement?n=s:(n=document.createElement("canvas"),n.width=e,n.height=i,n.getContext("2d").drawImage(s,0,0,e,i));let a=n.getContext("2d").getImageData(0,0,e,i),o={topLeft:{x:t.topLeft.x*e,y:t.topLeft.y*i},topRight:{x:t.topRight.x*e,y:t.topRight.y*i},bottomRight:{x:t.bottomRight.x*e,y:t.bottomRight.y*i},bottomLeft:{x:t.bottomLeft.x*e,y:t.bottomLeft.y*i}},{width:h,height:l}=ri(o),f=oi(a.data,e,i,o,h,l),g=document.createElement("canvas");g.width=h,g.height=l;let u=g.getContext("2d"),m=u.createImageData(h,l);return m.data.set(f),u.putImageData(m,0,0),g}async function vi(s){try{return await Be.parse(s)||null}catch{return null}}function Mi(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function Ci(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let o=await s.arrayBuffer(),h=globalThis.Buffer,l=typeof h<"u"?h.from(o).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(o)));return`data:${s.type||"image/png"};base64,${l}`}if(typeof s=="string")return s}let t=await createImageBitmap(s),n=Math.min(1,1654/t.width,2339/t.height);if(n===1&&(s.type==="image/jpeg"||s.type==="image/jpg"||s.type==="image/png"||s.type==="image/webp"))return t.close(),new Promise((o,h)=>{let l=new FileReader;l.onload=()=>o(l.result),l.onerror=h,l.readAsDataURL(s)});let r=document.createElement("canvas");r.width=Math.round(t.width*n),r.height=Math.round(t.height*n),r.getContext("2d").drawImage(t,0,0,r.width,r.height),t.close();let a=s.type==="image/png"?"image/png":"image/jpeg";return r.toDataURL(a,a==="image/png"?void 0:.82)}function Ee(s,t=21,e=.2,i=128){let{data:n,width:r,height:a}=s,o=r+1,h=new Float64Array((r+1)*(a+1)),l=new Float64Array((r+1)*(a+1)),f=new Uint8Array(r*a);for(let u=0;u<a;u++){let m=0,b=0,k=u*r,S=(u+1)*o,w=u*o;for(let x=0;x<r;x++){let O=(k+x)*4,P=n[O]*77+n[O+1]*150+n[O+2]*29>>8;f[k+x]=P,m+=P,b+=P*P,h[S+x+1]=h[w+x+1]+m,l[S+x+1]=l[w+x+1]+b}}let g=Math.floor(t/2);for(let u=0;u<a;u++){let m=Math.max(0,u-g),b=Math.min(a-1,u+g),k=m*o,S=(b+1)*o;for(let w=0;w<r;w++){let x=Math.max(0,w-g),O=Math.min(r-1,w+g),P=(O-x+1)*(b-m+1),Rt=h[S+O+1]-h[k+O+1]-h[S+x]+h[k+x],q=l[S+O+1]-l[k+O+1]-l[S+x]+l[k+x],V=Rt/P,it=Math.max(0,q/P-V*V),T=Math.sqrt(it),F=V*(1+e*(T/i-1)),D=u*r+w,I=f[D]<F?0:255,K=D*4;n[K]=I,n[K+1]=I,n[K+2]=I}}return s}function Oi(s,t=21,e=.2,i=128){return new Promise(n=>{let r=new Image;r.onload=()=>{let a=document.createElement("canvas");a.width=r.width,a.height=r.height;let o=a.getContext("2d");o.drawImage(r,0,0);let h=o.getImageData(0,0,a.width,a.height);Ee(h,t,e,i),o.putImageData(h,0,0);let l=s.startsWith("data:image/png"),f=l?"image/png":"image/jpeg";n(a.toDataURL(f,l?void 0:.82))},r.src=s})}function Ai(s){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let n=i.getContext("2d");n.translate(i.width/2,i.height/2),n.rotate(Math.PI/2),n.drawImage(e,-e.width/2,-e.height/2);let r=s.startsWith("data:image/png"),a=r?"image/png":"image/jpeg";t(i.toDataURL(a,r?void 0:.82))},e.src=s})}function Pi(s,t=""){if(!s)return"";let e=s.getCroppedCanvas(),i=t.startsWith("data:image/png"),n=i?"image/png":"image/jpeg";return e.toDataURL(n,i?void 0:.82)}function ee(s){if(!s||typeof s!="object")return{crop:null,quad:null,rotation:0,filter:"none"};let t=null;s.crop&&typeof s.crop=="object"&&(s.crop.width>0&&s.crop.height>0?t={x:Math.round(s.crop.x||0),y:Math.round(s.crop.y||0),width:Math.round(s.crop.width),height:Math.round(s.crop.height)}:s.crop.w>0&&s.crop.h>0&&(t={x:Number(s.crop.x)||0,y:Number(s.crop.y)||0,w:Number(s.crop.w)||1,h:Number(s.crop.h)||1}));let e=ut(s.quad),i=s.rotation!==void 0?s.rotation:s.rotate,n=(Math.round(Number(i)||0)%360+360)%360,r=s.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotation:n,filter:r}}function hi(s){if(!s)return!1;let t=ee(s);return!!(t.crop||t.quad||t.rotation!==0||t.filter!=="none")}function ie(s,t){let e=ee(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,r;if(e.quad)r=Ne(s,e.quad);else{r=document.createElement("canvas");let o=i,h=n,l=0,f=0;if(e.crop){let u=e.crop;"w"in u&&!("width"in u)?(l=Math.max(0,Math.min(Math.round(u.x*i),i)),f=Math.max(0,Math.min(Math.round(u.y*n),n)),o=Math.max(1,Math.min(Math.round(u.w*i),i-l)),h=Math.max(1,Math.min(Math.round(u.h*n),n-f))):(l=Math.max(0,Math.min(u.x,i)),f=Math.max(0,Math.min(u.y,n)),o=Math.max(1,Math.min(u.width,i-l)),h=Math.max(1,Math.min(u.height,n-f)))}r.width=o,r.height=h,r.getContext("2d").drawImage(s,l,f,o,h,0,0,o,h)}let a=r;if(e.rotation!==0){let o=e.rotation,h=document.createElement("canvas");o===90||o===270?(h.width=a.height,h.height=a.width):(h.width=a.width,h.height=a.height);let l=h.getContext("2d");l.translate(h.width/2,h.height/2),l.rotate(o*Math.PI/180),l.drawImage(a,-a.width/2,-a.height/2),a=h}if(e.filter==="bw"){let o=a.getContext("2d"),h=o.getImageData(0,0,a.width,a.height);Ee(h),o.putImageData(h,0,0)}return a}function Ii(s,t){if(!s)return Promise.resolve("");let e=ee(t);return hi(e)?new Promise((i,n)=>{let r=new Image;r.onload=()=>{try{let a=s.startsWith("data:image/png"),o=a?"image/png":"image/jpeg",h=ie(r,e);i(h.toDataURL(o,a?void 0:.82))}catch(a){n(a)}},r.onerror=n,r.src=s}):Promise.resolve(s)}function li(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var Ve=class extends ae{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await li(t),n={...e};return e?.crop&&"w"in e.crop&&(n.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(n.rotation=e.rotate),ie(i,n).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};export{ut as a,di as b,si as c,ni as d,Fe as e,gi as f,pi as g,De as h,mi as i,yi as j,Bt as k,Re as l,Te as m,vi as n,Mi as o,Ci as p,Ee as q,Oi as r,Ai as s,Pi as t,ee as u,ie as v,Ii as w,Ve as x};
4
+ //# sourceMappingURL=chunk-GU6OQMYK.js.map
@@ -0,0 +1,2 @@
1
+ var p={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",HANDOFF_CONNECTED:"copio:handoff-connected",CONNECTION_INFO:"copio:connection-info",EDGE_DETECTED:"copio:edge-detected",MIGRATION:"copio:migration",ERROR:"copio:error"};function n(o,c,E={}){let e=new CustomEvent(c,{bubbles:!0,composed:!0,cancelable:!0,detail:E});return o&&typeof o.dispatchEvent=="function"&&o.dispatchEvent(e),e}export{p as a,n as b};
2
+ //# sourceMappingURL=chunk-HCCNUPKB.js.map
@@ -0,0 +1,2 @@
1
+ import{a as xr}from"./chunk-4D6GC55I.js";var Ft=t=>typeof t;var Er=Ft(""),gn=Ft(!0),Hr=Ft(0),fn=Ft(Ft),Fe="type",Qt="default",vs="Listener",Vr="Result",Cs="add",zt="Has",Re="Ids",Jt="Table",Mr=Jt+"s",bn=Jt+Re,ae="Row",Ar=ae+"Count",Or=ae+Re,pn="Sorted"+ae+Re,Se="Cell",ze=Se+Re,_e="Value",jr=_e+"s",wn=_e+Re,at=t=>""+t;var yn=(t,e="",r)=>t.split(e,r),Ts=globalThis,ts=Math,ws=ts.max,ys=ts.min,Sn=ts.floor,Wr=isFinite,B=t=>t==null,it=(t,e,r)=>B(t)?r?.():e(t),Nr=t=>t==Er||t==gn,Ln=t=>Ft(t)==Er,Mt=t=>Ft(t)==fn,ie=t=>Array.isArray(t),Is=(t,e,r)=>t.slice(e,r),xt=t=>t.length,Jr=()=>{};var Ss=async(t,e,r)=>{try{return await t()}catch(o){e?.(o)}},ks=(t,e)=>t.includes(e),Ge=(t,e)=>t.every(e),Fr=(t,e)=>xt(t)===xt(e)&&Ge(t,((r,o)=>e[o]===r)),Dr=(t,e)=>Ge(t,((r,o)=>o==0||e(t[o-1],r)<=0)),xs=(t,e)=>t.sort(e),Tt=(t,e)=>t.forEach(e),Yt=(t,e)=>t.map(e),$r=t=>Kr(t,((e,r)=>e+r),0),Le=t=>xt(t)==0,Kr=(t,e,r)=>t.reduce(e,r),Ct=(t,...e)=>t.push(...e),Ur=t=>t.pop(),qr=t=>t.shift(),ne=t=>{let e=Ft(t);return Nr(e)||e==Hr&&Wr(t)?e:void 0};var Ye=(t,e,r,o,c)=>B(c)?t.delCell(e,r,o,!0):t.setCell(e,r,o,c),Vs=(t,e,r)=>B(r)?t.delValue(e):t.setValue(e,r),$s=t=>e=>Kr(ce(e),((r,o)=>r+t(o)),0),le=t=>t?.size??0,Xt=$s(le),Bt=$s(Xt),Ls=$s(Bt),dt=(t,e)=>t?.has(e)??!1,$=t=>B(t)||le(t)==0,ce=t=>[...t?.values()??[]],oe=t=>t.clear(),D=(t,e)=>t?.forEach(e),Dt=(t,e)=>t?.delete(e),Kt=Object,Pr=t=>Kt.getPrototypeOf(t),mn=Kt.isFrozen,Qr=Kt.entries,Xe=t=>!B(t)&&it(Pr(t),(e=>e==Kt.prototype||B(Pr(e))),(()=>!0)),Rn=Kt.keys,de=Kt.freeze,vn=(t=[])=>Kt.fromEntries(t),ye=(t,e)=>e in t,zr=(t,e)=>(delete t[e],t),Cn=(t,e)=>Tt(Qr(t),(([r,o])=>e(o,r))),Pt=(t,e)=>vn(((r,o)=>Yt(Qr(r),(([c,l])=>o(l,c))))(t,((r,o)=>[o,e(r,o)]))),jt=t=>Xe(t)&&(e=>xt(Rn(e)))(t)==0;var Wt=(t,e,r,o=0)=>B(t)||!Xe(t)||!o&&jt(t)||mn(t)?(r?.(),!1):(Cn(t,((c,l)=>{e(c,l)||zr(t,l)})),!!o||!jt(t)),p=t=>new Map(t),Gt=t=>[...t?.keys()??[]],g=(t,e)=>t?.get(e),pt=(t,e)=>D(t,((r,o)=>e(o,r))),k=(t,e,r)=>B(r)?(Dt(t,e),t):t?.set(e,r),lt=(t,e,r,o)=>(dt(t,e)?o?.(g(t,e)):k(t,e,r()),g(t,e)),_t=(t,e,r,o=k)=>(Pt(e,((c,l)=>r(t,l,c))),pt(t,(c=>ye(e,c)?0:o(t,c))),t),vt=(t,e,r,o)=>{let c={};return D(t,((l,u)=>{if(!r?.(l,u)){let i=e?e(l,u):l;o?.(i)||(c[u]=i)}})),c},Ms=(t,e,r)=>vt(t,(o=>vt(o,e,r)),$,jt),Ke=(t,e,r)=>vt(t,(o=>Ms(o,e,r)),$,jt),Nt=(t,e)=>{let r=p();return D(t,((o,c)=>r.set(c,e?.(o)??o))),r},js=t=>Nt(t,Nt),ms=t=>Nt(t,js),me=(t,e,r,o,c=0)=>it((r?lt:g)(t,e[c],c>xt(e)-2?r:p),(l=>{if(c>xt(e)-2)return o?.(l)&&k(t,e[c]),l;let u=me(l,e,r,o,c+1);return $(l)&&k(t,e[c]),u})),wt=t=>new Set(ie(t)||B(t)?t:[t]),ut=(t,e)=>t?.add(e),es=(t,e,r,o,c)=>{let l=t.hasRow,u=p(),i=p(),w=p(),S=p(),R=p(),b=p(),E=(L,x,..._)=>{let I=lt(b,L,wt);return Tt(_,(A=>ut(I,A)&&x&&t.callListener(A))),_},T=(L,...x)=>it(g(b,L),(_=>{Tt(Le(x)?ce(_):x,(I=>{t.delListener(I),Dt(_,I)})),$(_)&&k(b,L)})),F=(L,x)=>{k(u,L,x),dt(i,L)||(k(i,L,e()),k(S,L,p()),k(R,L,p()),c(w))},Z=L=>{k(u,L),k(i,L),k(S,L),k(R,L),T(L),c(w)};return[()=>t,()=>Gt(u),L=>pt(i,L),L=>dt(i,L),L=>g(u,L),L=>g(i,L),(L,x)=>k(i,L,x),F,(L,x,_,I,A)=>{F(L,x);let st=p(),y=p(),h=g(S,L),C=g(R,L),W=P=>{let q=ct=>t.getCell(x,P,ct),nt=g(h,P),ot=l(x,P)?r(I(q,P)):void 0;if(nt===ot||ie(nt)&&ie(ot)&&Fr(nt,ot)||k(st,P,[nt,ot]),!B(A)){let ct=g(C,P),N=l(x,P)?A(q,P):void 0;ct!=N&&k(y,P,N)}},K=P=>{_((()=>{D(st,(([,q],nt)=>k(h,nt,q))),D(y,((q,nt)=>k(C,nt,q)))}),st,y,h,C,P),oe(st),oe(y)};pt(h,W),t.hasTable(x)&&Tt(t.getRowIds(x),(P=>{dt(h,P)||W(P)})),K(!0),T(L),E(L,0,t.addRowListener(x,null,((P,q,nt)=>W(nt))),t.addTableListener(x,(()=>K())))},Z,L=>o(L,w),()=>pt(b,Z),E,T]},Ze=(t,e)=>Ln(t)?r=>r(t):t??(()=>e??""),ve=(t,e)=>{let r=new WeakMap;return o=>{r.has(o)||r.set(o,t(o));let c=r.get(o);return e?.(c),c}},Tn=/^\d+$/,_r=()=>{let t=[],e=0;return[r=>(r?qr(t):null)??""+e++,r=>{Tn.test(r)&&xt(t)<1e3&&Ct(t,r)}]},Ce=t=>{let e,[r,o]=_r(),c=p();return[(l,u,i,w=[],S=()=>[])=>{e??=t();let R=r(1);return k(c,R,[l,u,i,w,S]),ut(me(u,i??[""],wt),R),R},(l,u,...i)=>Tt(((w,S=[""])=>{let R=[],b=(E,T)=>T==xt(S)?Ct(R,E):S[T]===null?D(E,(F=>b(F,T+1))):Tt([S[T],null],(F=>b(g(E,F),T+1)));return b(w,0),R})(l,u),(w=>D(w,(S=>g(c,S)[0](e,...u??[],...i))))),l=>it(g(c,l),(([,u,i])=>(me(u,i??[""],void 0,(w=>(Dt(w,l),$(w)?1:0))),k(c,l),o(l),i))),l=>it(g(c,l),(([u,,i=[],w,S])=>{let R=(...b)=>{let E=xt(b);E==xt(i)?u(e,...b,...S(b)):B(i[E])?Tt(w[E]?.(...b)??[],(T=>R(...b,T))):R(...b,i[E])};R()}))]},to=ve((t=>{let e,r,o,c=100,l=p(),u=p(),i=1,w=p(),S=p(),[R,b,E]=Ce((()=>N)),T=p(),F=p(),Z=[],L=[],x=(m,j)=>{i=0,t.transaction((()=>{let[et,G]=g(T,j);D(et,((M,H)=>D(M,((J,Y)=>D(J,((O,Q)=>Ye(t,H,Y,Q,O[m]))))))),D(G,((M,H)=>Vs(t,H,M[m])))})),i=1},_=m=>{k(T,m),k(F,m),b(S,[m])},I=(m,j)=>Tt(((et,G)=>et.splice(0,G))(m,j??xt(m)),_),A=()=>I(Z,xt(Z)-c),st=()=>it(e,(()=>{Ct(Z,e),A(),I(L),e=void 0,o=1})),y=()=>{e=Ur(Z),o=1},h,C,W=(m="")=>(B(e)&&(e=""+r++,k(T,e,[l,u]),ot(e,m),l=p(),u=p(),o=1),e),K=()=>{Le(Z)||(((m,...j)=>{m.unshift(...j)})(L,W()),x(0,e),e=Ur(Z),o=1)},P=()=>{Le(L)||(Ct(Z,e),e=qr(L),x(1,e),o=1)},q=()=>{o&&(b(w),o=0)},nt=m=>{let j=W(m);return q(),j},ot=(m,j)=>(ct(m)&&g(F,m)!==j&&(k(F,m,j),b(S,[m])),N),ct=m=>dt(T,m),N={setSize:m=>(c=m,A(),N),addCheckpoint:nt,setCheckpoint:ot,getStore:()=>t,getCheckpointIds:()=>[[...Z],e,[...L]],forEachCheckpoint:m=>pt(F,m),hasCheckpoint:ct,getCheckpoint:m=>g(F,m),goBackward:()=>(K(),q(),N),goForward:()=>(P(),q(),N),goTo:m=>{let j=ks(Z,m)?K:ks(L,m)?P:null;for(;!B(j)&&m!=e;)j();return q(),N},addCheckpointIdsListener:m=>R(m,w),addCheckpointListener:(m,j)=>R(j,S,[m]),delListener:m=>(E(m),N),clear:()=>(I(Z),I(L),B(e)||_(e),e=void 0,r=0,nt(),N),clearForward:()=>(Le(L)||(I(L),b(w)),N),destroy:()=>{t.delListener(h),t.delListener(C)},getListenerStats:()=>({checkpointIds:Xt(w),checkpoint:Xt(S)}),_registerListeners:()=>{h=t.addCellListener(null,null,null,((m,j,et,G,M,H)=>{if(i){st();let J=lt(l,j,p),Y=lt(J,et,p),O=lt(Y,G,(()=>[H,void 0]));O[1]=M,O[0]===M&&$(k(Y,G))&&$(k(J,et))&&$(k(l,j))&&y(),q()}})),C=t.addValueListener(null,((m,j,et,G)=>{if(i){st();let M=lt(u,j,(()=>[G,void 0]));M[1]=et,M[0]===et&&$(k(u,j))&&y(),q()}}))}};return de(N.clear())}),(t=>t._registerListeners())),In=yn("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),eo=p(Yt(In,((t,e)=>[t,e])));var so=Ts.crypto?t=>Ts.crypto.getRandomValues(t):t=>Yt(t,(()=>Sn(256*ts.random())));var kn=JSON.stringify,Rs=JSON.parse,re=t=>kn(t,((e,r)=>{return o=Map,r instanceof o?Kt.fromEntries([...r]):r;var o})),ro=new Ts.TextEncoder;var no=2**36,oo=2**30,ao=2**24,io=2**18;var Gr=(t,e)=>(t??0)<(e??0)?-1:1,co=ve((t=>{let e=p(),r=p(),[o,c,l]=Ce((()=>_)),[u,i,w,S,R,b,E,,T,F,Z,L]=es(t,p,(I=>B(I)?"":ie(I)?Yt(I,at):at(I)),o,c),x=(I,A,st)=>{let y=R(I);D(st,((h,C)=>A(C,(W=>D(h,(K=>W(K,(P=>t.forEachCell(y,K,P)))))))))},_={setIndexDefinition:(I,A,st,y,h,C=Gr)=>{let W=B(h)?void 0:([K],[P])=>h(K,P);return T(I,A,((K,P,q,nt,ot,ct)=>{let N=0,m=wt(),j=wt(),et=b(I);if(D(P,(([G,M],H)=>{let J=wt(G),Y=wt(M);D(J,(O=>Dt(Y,O)?Dt(J,O):0)),D(J,(O=>{ut(m,O),it(g(et,O),(Q=>{Dt(Q,H),$(Q)&&(k(et,O),N=1)}))})),D(Y,(O=>{ut(m,O),dt(et,O)||(k(et,O,wt()),N=1),ut(g(et,O),H),B(y)||ut(j,O)}))})),K(),$(ot)||(ct?pt(et,(G=>ut(j,G))):pt(q,(G=>it(g(nt,G),(M=>Tt(ie(M)?M:[M],(H=>ut(j,H))))))),D(j,(G=>{let M=(J,Y)=>C(g(ot,J),g(ot,Y),G),H=[...g(et,G)];Dr(H,M)||(k(et,G,wt(xs(H,M))),ut(m,G))}))),(N||ct)&&!B(W)){let G=[...et];Dr(G,W)||(E(I,p(xs(G,W))),N=1)}N&&c(e,[I]),D(m,(G=>c(r,[I,G])))}),Ze(st),it(y,Ze)),_},delIndexDefinition:I=>(F(I),_),getStore:u,getIndexIds:i,forEachIndex:I=>w(((A,st)=>I(A,(y=>x(A,y,st))))),forEachSlice:(I,A)=>x(I,A,b(I)),hasIndex:S,hasSlice:(I,A)=>dt(b(I),A),getTableId:R,getSliceIds:I=>Gt(b(I)),getSliceRowIds:(I,A)=>ce(g(b(I),A)),addIndexIdsListener:Z,addSliceIdsListener:(I,A)=>o(A,e,[I]),addSliceRowIdsListener:(I,A,st)=>o(st,r,[I,A]),delListener:I=>(l(I),_),destroy:L,getListenerStats:()=>({sliceIds:Xt(e),sliceRowIds:Bt(r)})};return de(_)}));var qe=t=>[t,t],ft=(t,e=Xt)=>e(t[0])+e(t[1]),bt=()=>[p(),p()],Br=t=>[...t],Qe=([t,e])=>t===e,we=(t,e,r)=>k(t,e,g(t,e)==-r?void 0:r),Us=()=>{let t,e,r=!1,o=!1,c=0,l=[],u=p(),i=p(),w=p(),S=p(),R=p(),b=p(),E=p(),T=p(),F=p(),Z=p(),L=p(),x=p(),_=p(),I=p(),A=wt(),st=p(),y=p(),h=p(),C=p(),W=bt(),K=bt(),P=bt(),q=bt(),nt=bt(),ot=bt(),ct=bt(),N=bt(),m=bt(),j=bt(),et=bt(),G=bt(),M=bt(),H=bt(),J=bt(),Y=bt(),O=bt(),Q=bt(),V=bt(),rt=bt(),ht=bt(),Rt=bt(),St=p(),Lt=bt(),[yt,tt,It,Et]=Ce((()=>mt)),Ht=s=>{if(!Wt(s,((a,d)=>ks([Fe,Qt],d))))return!1;let n=s[Fe];return!(!Nr(n)&&n!=Hr)&&(ne(s[Qt])!=n&&zr(s,Qt),!0)},ls=ie,ke=(s,n)=>(!t||dt(L,n)||At(n))&&Wt(s,((a,d)=>qt(n,d,a)),(()=>At(n))),qt=(s,n,a,d)=>Wt(d?a:Ns(a,s,n),((f,v)=>it(xe(s,n,v,f),(U=>(a[v]=U,!0)),(()=>!1))),(()=>At(s,n))),xe=(s,n,a,d)=>t?it(g(g(L,s),a),(f=>ne(d)!=f[Fe]?At(s,n,a,d,f[Qt]):d),(()=>At(s,n,a,d))):B(ne(d))?At(s,n,a,d):d,ue=(s,n)=>Wt(n?s:hn(s),((a,d)=>it(Ws(d,a),(f=>(s[d]=f,!0)),(()=>!1))),(()=>fe())),Ws=(s,n)=>e?it(g(_,s),(a=>ne(n)!=a[Fe]?fe(s,n,a[Qt]):n),(()=>fe(s,n))):B(ne(n))?fe(s,n):n,Ns=(s,n,a)=>(it(g(x,n),(([d,f])=>{D(d,((v,U)=>{ye(s,U)||(s[U]=v)})),D(f,(v=>{ye(s,v)||At(n,a,v)}))})),s),hn=s=>(e&&(D(I,((n,a)=>{ye(s,a)||(s[a]=n)})),D(A,(n=>{ye(s,n)||fe(n)}))),s),Js=s=>_t(L,s,((n,a,d)=>{let f=p(),v=wt();_t(lt(L,a,p),d,((U,z,X)=>{k(U,z,X),it(X[Qt],(Ut=>k(f,z,Ut)),(()=>ut(v,z)))})),k(x,a,[f,v])}),((n,a)=>{k(L,a),k(x,a)})),Fs=s=>_t(_,s,((n,a,d)=>{k(_,a,d),it(d[Qt],(f=>k(I,a,f)),(()=>ut(A,a)))}),((n,a)=>{k(_,a),k(I,a),Dt(A,a)})),Ks=s=>jt(s)?Oe():He(s),qs=s=>_t(h,s,((n,a,d)=>Ve(a,d)),((n,a)=>Gs(a))),Ve=(s,n)=>_t(lt(h,s,(()=>(tr(s,1),k(st,s,_r()),k(y,s,p()),p()))),n,((a,d,f)=>ge(s,a,d,f)),((a,d)=>Ys(s,a,d))),ge=(s,n,a,d,f)=>_t(lt(n,a,(()=>(er(s,a,1),p()))),d,((v,U,z)=>ds(s,a,v,U,z)),((v,U)=>Xs(s,n,a,v,U,f))),ds=(s,n,a,d,f)=>{dt(a,d)||sr(s,n,d,1);let v=g(a,d);f!==v&&(rr(s,n,d,v,f),k(a,d,f))},Qs=(s,n,a,d,f)=>it(g(n,a),(v=>ds(s,a,v,d,f)),(()=>ge(s,n,a,Ns({[d]:f},s,a)))),zs=s=>jt(s)?We():Ae(s),_s=s=>_t(C,s,((n,a,d)=>Me(a,d)),((n,a)=>Zs(a))),Me=(s,n)=>{dt(C,s)||nr(s,1);let a=g(C,s);n!==a&&(or(s,a,n),k(C,s,n))},je=s=>g(h,s)??Ve(s,{}),Gs=s=>Ve(s,{}),Ys=(s,n,a)=>{let[,d]=g(st,s);d(a),ge(s,n,a,{},!0)},Xs=(s,n,a,d,f,v)=>{let U=g(g(x,s)?.[0],f);if(!B(U)&&!v)return ds(s,a,d,f,U);let z=X=>{rr(s,a,X,g(d,X)),sr(s,a,X,-1),k(d,X)};B(U)?z(f):pt(d,z),$(d)&&(er(s,a,-1),$(k(n,a))&&(tr(s,-1),k(h,s),k(st,s),k(y,s)))},Zs=s=>{let n=g(I,s);if(!B(n))return Me(s,n);or(s,g(C,s)),nr(s,-1),k(C,s)},tr=(s,n)=>we(u,s,n),er=(s,n,a)=>we(lt(S,s,p),n,a)&&k(w,s,lt(w,s,(()=>0))+a),sr=(s,n,a,d)=>{let f=g(y,s),v=g(f,a)??0;(v==0&&d==1||v==1&&d==-1)&&we(lt(i,s,p),a,d),k(f,a,v!=-d?v+d:null),we(lt(lt(R,s,p),n,p),a,d)},rr=(s,n,a,d,f)=>{lt(lt(lt(b,s,p),n,p),a,(()=>[d,0]))[1]=f,l[3]?.(s,n,a,f)},nr=(s,n)=>we(E,s,n),or=(s,n,a)=>{lt(T,s,(()=>[n,0]))[1]=a,l[4]?.(s,a)},At=(s,n,a,d,f)=>(Ct(lt(lt(lt(F,s,p),n,p),a,(()=>[])),d),f),fe=(s,n,a)=>(Ct(lt(Z,s,(()=>[])),n),a),De=(s,n,a)=>it(g(g(g(b,s),n),a),(([d,f])=>[!0,d,f]),(()=>[!1,...qe(Ue(s,n,a))])),ar=s=>it(g(T,s),(([n,a])=>[!0,n,a]),(()=>[!1,...qe(Pe(s))])),ir=s=>$(F)||$(Y[s])?0:D(s?ms(F):F,((n,a)=>D(n,((d,f)=>D(d,((v,U)=>tt(Y[s],[a,f,U],v))))))),cr=s=>$(Z)||$(O[s])?0:D(s?Nt(Z):Z,((n,a)=>tt(O[s],[a],n))),be=(s,n,a,d)=>{if(!$(s))return tt(n,d,(()=>vt(s))),pt(s,((f,v)=>tt(a,[...d??[],f],v==1))),1},lr=s=>{let n=Be();n!=r&&tt(W[s],void 0,n);let a=$(j[s]),d=$(M[s])&&$(H[s])&&$(m[s])&&$(et[s])&&$(ot[s])&&$(ct[s])&&$(N[s])&&a&&$(P[s])&&$(q[s]),f=$(J[s])&&$(G[s])&&$(nt[s])&&$(K[s]);if(!d||!f){let v=s?[Nt(u),js(i),Nt(w),js(S),ms(R),ms(b)]:[u,i,w,S,R,b];if(!d){be(v[0],P[s],q[s]),D(v[1],((z,X)=>be(z,ot[s],ct[s],[X]))),D(v[2],((z,X)=>{z!=0&&tt(N[s],[X],gr(X))}));let U=wt();D(v[3],((z,X)=>{be(z,m[s],et[s],[X])&&!a&&(tt(j[s],[X,null]),ut(U,X))})),a||D(v[5],((z,X)=>{if(!dt(U,X)){let Ut=wt();D(z,(Ot=>D(Ot,(([Ne,Je],pe)=>Je!==Ne?ut(Ut,pe):Dt(Ot,pe))))),D(Ut,(Ot=>tt(j[s],[X,Ot])))}})),D(v[4],((z,X)=>D(z,((Ut,Ot)=>be(Ut,M[s],H[s],[X,Ot])))))}if(!f){let U;D(v[5],((z,X)=>{let Ut;D(z,((Ot,Ne)=>{let Je;D(Ot,(([pe,kr],un)=>{kr!==pe&&(tt(J[s],[X,Ne,un],kr,pe,De),U=Ut=Je=1)})),Je&&tt(G[s],[X,Ne],De)})),Ut&&tt(nt[s],[X],De)})),U&&tt(K[s],void 0,De)}}},dr=s=>{let n=Ee();n!=o&&tt(Q[s],void 0,n);let a=$(rt[s])&&$(ht[s]),d=$(Rt[s])&&$(V[s]);if(!a||!d){let f=s?[Nt(E),Nt(T)]:[E,T];if(a||be(f[0],rt[s],ht[s]),!d){let v;D(f[1],(([U,z],X)=>{z!==U&&(tt(Rt[s],[X],z,U,ar),v=1)})),v&&tt(V[s],void 0,ar)}}},gt=(s,...n)=>(ps((()=>s(...Yt(n,at)))),mt),hr=(s,n,a,d,f)=>{let v=$e(s,n,...a);return yt((()=>{let U=$e(s,n,...a);Fr(U,v)||(v=U,d(mt,s,n,...a,v))}),j[f?1:0],[s,n],[kt])},hs=()=>Ke(h),kt=()=>Gt(h),ur=s=>Gt(g(y,at(s))),gr=s=>le(g(h,at(s))),se=s=>Gt(g(h,at(s))),$e=(s,n,a,d=0,f)=>{return Xe(s)?$e(s.tableId,s.cellId,s.descending,s.offset,s.limit):Yt(Is(xs((v=g(h,at(s)),U=(z,X)=>[B(n)?X:g(z,at(n)),X],Yt([...v?.entries()??[]],(([z,X])=>U(X,z)))),(([z],[X])=>Gr(z,X)*(a?-1:1))),d,B(f)?f:d+f),(([,z])=>z));var v,U},us=(s,n)=>Gt(g(g(h,at(s)),at(n))),Ue=(s,n,a)=>g(g(g(h,at(s)),at(n)),at(a)),gs=()=>vt(C),fs=()=>Gt(C),Pe=s=>g(C,at(s)),Be=()=>!$(h),fr=s=>dt(h,at(s)),br=(s,n)=>dt(g(y,at(s)),at(n)),pr=(s,n)=>dt(g(h,at(s)),at(n)),wr=(s,n,a)=>dt(g(g(h,at(s)),at(n)),at(a)),Ee=()=>!$(C),yr=s=>dt(C,at(s)),He=s=>gt((()=>(n=>Wt(n,ke,At))(s)?qs(s):0)),Ae=s=>gt((()=>ue(s)?_s(s):0)),Sr=s=>(Ss((()=>Ks(Rs(s)))),mt),Lr=s=>gt((()=>{if((t=Wt(s,(n=>Wt(n,Ht))))&&(Js(s),!$(h))){let n=hs();Oe(),He(n)}})),mr=s=>gt((()=>{if(e=(n=>Wt(n,Ht))(s)){let n=gs();bs(),We(),e=!0,Fs(s),Ae(n)}})),Oe=()=>gt((()=>qs({}))),Rr=s=>gt((n=>dt(h,n)?Gs(n):0),s),vr=(s,n)=>gt(((a,d)=>it(g(h,a),(f=>dt(f,d)?Ys(a,f,d):0))),s,n),We=()=>gt((()=>_s({}))),Cr=()=>gt((()=>{Js({}),t=!1})),bs=()=>gt((()=>{Fs({}),e=!1})),ps=(s,n)=>{if(c!=-1){Tr();let a=s();return Ir(n),a}},Tr=()=>(c!=-1&&c++,c==1&&(l[0]?.(),tt(St)),mt),Ir=s=>(c>0&&(c--,c==0&&(c=1,ir(1),$(b)||lr(1),cr(1),$(T)||dr(1),s?.(mt)&&(D(b,((n,a)=>D(n,((d,f)=>D(d,(([v],U)=>Ye(mt,a,f,U,v))))))),oe(b),D(T,(([n],a)=>Vs(mt,a,n))),oe(T)),tt(Lt[0],void 0),c=-1,ir(0),$(b)||lr(0),cr(0),$(T)||dr(0),l[1]?.(),tt(Lt[1],void 0),l[2]?.(),c=0,r=Be(),o=Ee(),Tt([u,i,w,S,R,b,F,E,T,Z],oe))),mt),mt={getContent:()=>[hs(),gs()],getTables:hs,getTableIds:kt,getTable:s=>Ms(g(h,at(s))),getTableCellIds:ur,getRowCount:gr,getRowIds:se,getSortedRowIds:$e,getRow:(s,n)=>vt(g(g(h,at(s)),at(n))),getCellIds:us,getCell:Ue,getValues:gs,getValueIds:fs,getValue:Pe,hasTables:Be,hasTable:fr,hasTableCell:br,hasRow:pr,hasCell:wr,hasValues:Ee,hasValue:yr,getTablesJson:()=>re(h),getValuesJson:()=>re(C),getJson:()=>re([h,C]),getTablesSchemaJson:()=>re(L),getValuesSchemaJson:()=>re(_),getSchemaJson:()=>re([L,_]),hasTablesSchema:()=>t,hasValuesSchema:()=>e,setContent:s=>gt((()=>{let n=Mt(s)?s():s;ls(n)&&(([a,d])=>{(jt(a)?Oe:He)(a),(jt(d)?We:Ae)(d)})(n)})),setTables:He,setTable:(s,n)=>gt((a=>ke(n,a)?Ve(a,n):0),s),setRow:(s,n,a)=>gt(((d,f)=>qt(d,f,a)?ge(d,je(d),f,a):0),s,n),addRow:(s,n,a=!0)=>ps((()=>{let d;return qt(s,d,n)&&(s=at(s),ge(s,je(s),d=((f,v)=>{let[U]=g(st,f),z;do z=U(v);while(dt(g(h,f),z));return z})(s,a?1:0),n)),d})),setPartialRow:(s,n,a)=>gt(((d,f)=>{if(qt(d,f,a,1)){let v=je(d);Pt(a,((U,z)=>Qs(d,v,f,z,U)))}}),s,n),setCell:(s,n,a,d)=>gt(((f,v,U)=>it(xe(f,v,U,Mt(d)?d(Ue(f,v,U)):d),(z=>Qs(f,je(f),v,U,z)))),s,n,a),setValues:Ae,setPartialValues:s=>gt((()=>ue(s,1)?Pt(s,((n,a)=>Me(a,n))):0)),setValue:(s,n)=>gt((a=>it(Ws(a,Mt(n)?n(Pe(a)):n),(d=>Me(a,d)))),s),applyChanges:s=>gt((()=>{Pt(s[0],((n,a)=>B(n)?Rr(a):Pt(n,((d,f)=>B(d)?vr(a,f):Pt(d,((v,U)=>Ye(mt,a,f,U,v))))))),Pt(s[1],((n,a)=>Vs(mt,a,n)))})),setTablesJson:Sr,setValuesJson:s=>(Ss((()=>zs(Rs(s)))),mt),setJson:s=>gt((()=>Ss((()=>{let[n,a]=Rs(s);Ks(n),zs(a)}),(()=>Sr(s))))),setTablesSchema:Lr,setValuesSchema:mr,setSchema:(s,n)=>gt((()=>{Lr(s),mr(n)})),delTables:Oe,delTable:Rr,delRow:vr,delCell:(s,n,a,d)=>gt(((f,v,U)=>it(g(h,f),(z=>it(g(z,v),(X=>dt(X,U)?Xs(f,z,v,X,U,d):0))))),s,n,a),delValues:We,delValue:s=>gt((n=>dt(C,n)?Zs(n):0),s),delTablesSchema:Cr,delValuesSchema:bs,delSchema:()=>gt((()=>{Cr(),bs()})),transaction:ps,startTransaction:Tr,getTransactionChanges:()=>[vt(b,((s,n)=>g(u,n)===-1?void 0:vt(s,((a,d)=>g(g(S,n),d)===-1?void 0:vt(a,(([,f])=>f),(f=>Qe(f)))),$,jt)),$,jt),vt(T,(([,s])=>s),(s=>Qe(s))),1],getTransactionLog:()=>[!$(b),!$(T),Ke(b,Br,Qe),Ke(F),vt(T,Br,Qe),vt(Z),vt(u),Ms(S),Ke(R),vt(E)],finishTransaction:Ir,forEachTable:s=>D(h,((n,a)=>s(a,(d=>D(n,((f,v)=>d(v,(U=>pt(f,U))))))))),forEachTableCell:(s,n)=>pt(g(y,at(s)),n),forEachRow:(s,n)=>D(g(h,at(s)),((a,d)=>n(d,(f=>pt(a,f))))),forEachCell:(s,n,a)=>pt(g(g(h,at(s)),at(n)),a),forEachValue:s=>pt(C,s),addSortedRowIdsListener:(s,n,a,d,f,v,U)=>Xe(s)?hr(s.tableId,s.cellId,[s.descending??!1,s.offset??0,s.limit],n,a):hr(s,n,[a,d,f],v,U),addStartTransactionListener:s=>yt(s,St),addWillFinishTransactionListener:s=>yt(s,Lt[0]),addDidFinishTransactionListener:s=>yt(s,Lt[1]),callListener:s=>(Et(s),mt),delListener:s=>(It(s),mt),getListenerStats:()=>({hasTables:ft(W),tables:ft(K),tableIds:ft(P),hasTable:ft(q),table:ft(nt),tableCellIds:ft(ot),hasTableCell:ft(ct,Bt),rowCount:ft(N),rowIds:ft(m),sortedRowIds:ft(j),hasRow:ft(et,Bt),row:ft(G,Bt),cellIds:ft(M,Bt),hasCell:ft(H,Ls),cell:ft(J,Ls),invalidCell:ft(Y,Ls),hasValues:ft(Q),values:ft(V),valueIds:ft(rt),hasValue:ft(ht),value:ft(Rt),invalidValue:ft(O),transaction:Xt(St)+ft(Lt)}),isMergeable:()=>!1,createStore:Us,addListener:yt,callListeners:tt,setInternalListeners:(s,n,a,d,f)=>l=[s,n,a,d,f]};return Pt({[zt+Mr]:[0,W,[],()=>[Be()]],[Mr]:[0,K],[bn]:[0,P],[zt+Jt]:[1,q,[kt],s=>[fr(...s)]],[Jt]:[1,nt,[kt]],[Jt+ze]:[1,ot,[kt]],[zt+Jt+Se]:[2,ct,[kt,ur],s=>[br(...s)]],[Ar]:[1,N,[kt]],[Or]:[1,m,[kt]],[zt+ae]:[2,et,[kt,se],s=>[pr(...s)]],[ae]:[2,G,[kt,se]],[ze]:[2,M,[kt,se]],[zt+Se]:[3,H,[kt,se,us],s=>[wr(...s)]],[Se]:[3,J,[kt,se,us],s=>qe(Ue(...s))],InvalidCell:[3,Y],[zt+jr]:[0,Q,[],()=>[Ee()]],[jr]:[0,V],[wn]:[0,rt],[zt+_e]:[1,ht,[fs],s=>[yr(...s)]],[_e]:[1,Rt,[fs],s=>qe(Pe(s[0]))],InvalidValue:[1,O]},(([s,n,a,d],f)=>{mt[Cs+f+vs]=(...v)=>yt(v[s],n[v[s+1]?1:0],s>0?Is(v,0,s):void 0,a,d)})),de(mt)};var Ds=p([["avg",[(t,e)=>$r(t)/e,(t,e,r)=>t+(e-t)/(r+1),(t,e,r)=>t+(t-e)/(r-1),(t,e,r,o)=>t+(e-r)/o]],["max",[t=>ws(...t),(t,e)=>ws(e,t),(t,e)=>e==t?void 0:t,(t,e,r)=>r==t?void 0:ws(e,t)]],["min",[t=>ys(...t),(t,e)=>ys(e,t),(t,e)=>e==t?void 0:t,(t,e,r)=>r==t?void 0:ys(e,t)]],["sum",[t=>$r(t),(t,e)=>t+e,(t,e)=>t-e,(t,e,r)=>t-r+e]]]),Yr=(t,e,r,o,c,l=!1)=>{if($(r))return;let[u,i,w,S]=c;return l||=B(t),D(o,(([R,b])=>{l||(t=B(R)?i?.(t,b,e++):B(b)?w?.(t,R,e--):S?.(t,b,R,e),l||=B(t))})),l?u(ce(r),le(r)):t},lo=ve((t=>{let e=p(),[r,o,c]=Ce((()=>L)),[l,u,i,w,S,R,b,,E,T,F,Z]=es(t,Jr,(x=>isNaN(x)||B(x)||x===!0||x===!1||x===""?void 0:1*x),r,o),L={setMetricDefinition:(x,_,I,A,st,y,h)=>{let C=Mt(I)?[I,st,y,h]:g(Ds,I)??g(Ds,"sum");return E(x,_,((W,K,P,q,nt,ot)=>{let ct=R(x),N=le(q);ot||=B(ct),W();let m=Yr(ct,N,q,K,C,ot);Wr(m)||(m=void 0),m!=ct&&(b(x,m),o(e,[x],m,ct))}),Ze(A,1)),L},delMetricDefinition:x=>(T(x),L),getStore:l,getMetricIds:u,forEachMetric:i,hasMetric:w,getTableId:S,getMetric:R,addMetricIdsListener:F,addMetricListener:(x,_)=>r(_,e,[x]),delListener:x=>(c(x),L),destroy:Z,getListenerStats:()=>({metric:Xt(e)})};return de(L)})),ho=ve((t=>{let e=t.createStore,r=e(),o=e(),c=p(),{addListener:l,callListeners:u,delListener:i}=o,[w,S,R,b,E,,,T,,F,Z,L,x,_]=es(t,(()=>!0),Jr,l,u),I=(h,C,...W)=>Tt(W,(K=>ut(lt(lt(c,C,p),h,wt),K))),A=h=>{it(g(c,h),(C=>{pt(C,((W,K)=>D(K,(P=>W.delListener(P))))),oe(C)})),Tt([o,r],(C=>C.delTable(h)))},st=(h,C,W)=>I(C,h,C.addStartTransactionListener(W.startTransaction),C.addDidFinishTransactionListener((()=>W.finishTransaction()))),y={setQueryDefinition:(h,C,W)=>{T(h,C),A(h);let K=[],P=[[null,[C,null,null,[],p()]]],q=[],nt=[],ot=[];W({select:(M,H)=>{let J=Mt(M)?[xt(K)+"",M]:[B(H)?M:H,Y=>Y(M,H)];return Ct(K,J),{as:Y=>J[0]=Y}},join:(M,H,J)=>{let Y=B(J)||Mt(H)?null:H,O=B(Y)?H:J,Q=[M,[M,Y,Mt(O)?O:V=>V(O),[],p()]];return Ct(P,Q),{as:V=>Q[0]=V}},where:(M,H,J)=>Ct(q,Mt(M)?M:B(J)?Y=>Y(M)===H:Y=>Y(M,H)===J),group:(M,H,J,Y,O)=>{let Q=[M,[M,Mt(H)?[H,J,Y,O]:g(Ds,H)??[(V,rt)=>rt]]];return Ct(nt,Q),{as:V=>Q[0]=V}},having:(M,H)=>Ct(ot,Mt(M)?M:J=>J(M)===H)});let ct=p(K);if($(ct))return y;let N=p(P);pt(N,((M,[,H])=>it(g(N,H),(({3:J})=>B(M)?0:Ct(J,M)))));let m=p(nt),j=r;if($(m)&&Le(ot))j=o;else{st(h,j,o);let M=p();pt(m,((O,[Q,V])=>ut(lt(M,Q,wt),[O,V])));let H=wt();pt(ct,(O=>dt(M,O)?0:ut(H,O)));let J=p(),Y=(O,Q,V,rt)=>it(O,(([ht,Rt,St,Lt])=>{pt(Q,((yt,[tt])=>{let It=lt(ht,yt,p),Et=g(It,V),Ht=rt?void 0:tt;if(Et!==Ht){let ls=wt([[Et,Ht]]),ke=le(It);k(It,V,Ht),D(g(M,yt),(([qt,xe])=>{let ue=Yr(Lt[qt],ke,It,ls,xe);Lt[qt]=B(ne(ue))?null:ue}))}})),$(Rt)||!Ge(ot,(yt=>yt((tt=>Lt[tt]))))?o.delRow(h,St):B(St)?O[2]=o.addRow(h,Lt):o.setRow(h,St,Lt)}));I(j,h,j.addRowListener(h,null,((O,Q,V,rt)=>{let ht=[],Rt=[],St=p(),Lt=j.hasRow(h,V),yt=!Lt;D(H,(tt=>{let[It,Et,Ht]=rt(h,V,tt);Ct(ht,Et),Ct(Rt,Ht),yt||=It})),pt(M,(tt=>{let[It,,Et]=rt(h,V,tt);(yt||It)&&k(St,tt,[Et])})),yt&&Y(me(J,ht,void 0,(([,tt])=>(Dt(tt,V),$(tt)))),St,V,1),Lt&&Y(me(J,Rt,(()=>{let tt={};return D(H,(It=>tt[It]=j.getCell(h,V,It))),[p(),wt(),void 0,tt]}),(([,tt])=>{ut(tt,V)})),St,V)})))}st(h,t,j);let et=(M,H,J,Y)=>{let O=Q=>t.getCell(H,J,Q);Tt(Y,(Q=>{let[V,,rt,ht,Rt]=g(N,Q),St=rt?.(O,M),[Lt,yt]=g(Rt,M)??[];St!=Lt&&(B(yt)||_(h,yt),k(Rt,M,B(St)?null:[St,...x(h,1,t.addRowListener(V,St,(()=>et(M,V,St,ht))))]))})),(Q=>{let V=(rt,ht)=>t.getCell(...B(ht)?[C,Q,rt]:rt===C?[C,Q,ht]:[g(N,rt)?.[0],g(g(N,rt)?.[4],Q)?.[0],ht]);j.transaction((()=>Ge(q,(rt=>rt(V)))?pt(ct,((rt,ht)=>Ye(j,h,Q,rt,ht(V,Q)))):j.delRow(h,Q)))})(M)},{3:G}=g(N,null);return j.transaction((()=>x(h,1,t.addRowListener(C,null,((M,H,J)=>{t.hasRow(C,J)?et(J,C,J,G):(j.delRow(h,J),D(N,(({4:Y})=>it(g(Y,J),(([,O])=>{_(h,O),k(Y,J)})))))}))))),y},delQueryDefinition:h=>(A(h),F(h),y),getStore:w,getQueryIds:S,forEachQuery:R,hasQuery:b,getTableId:E,addQueryIdsListener:h=>Z((()=>h(y))),delListener:h=>(i(h),y),destroy:L,getListenerStats:()=>{let{tables:h,tableIds:C,transaction:W,...K}=o.getListenerStats();return K}};return Pt({[Jt]:[1,1],[Jt+ze]:[0,1],[Ar]:[0,1],[Or]:[0,1],[pn]:[0,5],[ae]:[1,2],[ze]:[0,2],[Se]:[1,3]},(([h,C],W)=>{Tt(h?["get","has","forEach"]:["get"],(K=>y[K+Vr+W]=(...P)=>o[K+W](...P))),y[Cs+Vr+W+vs]=(...K)=>o[Cs+W+vs](...Is(K,0,C),((P,...q)=>K[C](y,...q)),!0)})),de(y)})),uo=ve((t=>{let e=p(),r=p(),o=p(),c=p(),[l,u,i]=Ce((()=>st)),[w,S,R,b,E,T,,,F,Z,L,x]=es(t,(()=>[p(),p(),p(),p()]),(y=>B(y)?void 0:y+""),l,u),_=(y,h,C)=>it(T(y),(([W,,K])=>{if(!dt(K,h)){let P=wt();if(E(y)!=A(y))ut(P,h);else{let q=h;for(;!B(q)&&!dt(P,q);)ut(P,q),q=g(W,q)}if(C)return P;k(K,h,P)}return g(K,h)})),I=(y,h)=>it(T(y),(([,,C])=>k(C,h))),A=y=>g(e,y),st={setRelationshipDefinition:(y,h,C,W)=>(k(e,y,C),F(y,h,((K,P)=>{let q=wt(),nt=wt(),ot=wt(),[ct,N]=T(y);D(P,(([m,j],et)=>{B(m)||(ut(nt,m),it(g(N,m),(G=>{Dt(G,et),$(G)&&k(N,m)}))),B(j)||(ut(nt,j),dt(N,j)||k(N,j,wt()),ut(g(N,j),et)),ut(q,et),k(ct,et,j),pt(g(c,y),(G=>{dt(_(y,G),et)&&ut(ot,G)}))})),K(),D(q,(m=>u(r,[y,m]))),D(nt,(m=>u(o,[y,m]))),D(ot,(m=>{I(y,m),u(c,[y,m])}))}),Ze(W)),st),delRelationshipDefinition:y=>(k(e,y),Z(y),st),getStore:w,getRelationshipIds:S,forEachRelationship:y=>R((h=>y(h,(C=>t.forEachRow(E(h),C))))),hasRelationship:b,getLocalTableId:E,getRemoteTableId:A,getRemoteRowId:(y,h)=>g(T(y)?.[0],h),getLocalRowIds:(y,h)=>ce(g(T(y)?.[1],h)),getLinkedRowIds:(y,h)=>B(T(y))?[h]:ce(_(y,h,!0)),addRelationshipIdsListener:L,addRemoteRowIdListener:(y,h,C)=>l(C,r,[y,h]),addLocalRowIdsListener:(y,h,C)=>l(C,o,[y,h]),addLinkedRowIdsListener:(y,h,C)=>(_(y,h),l(C,c,[y,h])),delListener:y=>(I(...i(y)??[]),st),destroy:x,getListenerStats:()=>({remoteRowId:Bt(r),localRowIds:Bt(o),linkedRowIds:Bt(c)})};return de(st)}));var tn=Promise,xn=globalThis,Xr=xn.window,Vn=1e3,Mn=(t,e,r)=>setInterval(t,e*Vn),jn=clearInterval,$t=t=>t==null,as=(t,e,r)=>$t(t)?r?.():e(t),Bs=t=>Array.isArray(t),te=t=>t.length,Dn=(t,e)=>t.test(e),en=t=>new tn(t),sn=async t=>tn.all(t),rn=t=>{throw new Error(t)},Zt=async(t,e,r)=>{try{return await t()}catch(o){e?.(o)}},Es=(t,e)=>t.forEach(e),Te=(t,e)=>t.map(e),$n=(t,e)=>t.splice(0,e),is=(t,...e)=>t.push(...e),nn=t=>t.shift(),he=Object,Zr=t=>he.getPrototypeOf(t),Un=he.entries,Pn=t=>!$t(t)&&as(Zr(t),e=>e==he.prototype||$t(Zr(e)),()=>!0),Bn=he.keys,En=he.freeze,Hn=(t=[])=>he.fromEntries(t),An=(t,e)=>e in t,On=(t,e)=>Te(Un(t),([r,o])=>e(o,r)),Wn=t=>te(Bn(t)),ss=t=>Pn(t)&&Wn(t)==0,Nn=t=>t?.size??0,Jn=(t,e)=>t?.has(e)??!1,on=t=>$t(t)||Nn(t)==0,an=(t,e)=>t?.forEach(e),cn=(t,e)=>t?.delete(e),Ie=t=>new Map(t),Vt=(t,e)=>t?.get(e),ee=(t,e,r)=>$t(r)?(cn(t,e),t):t?.set(e,r),Hs=(t,e,r,o)=>(Jn(t,e)?o?.(Vt(t,e)):ee(t,e,r()),Vt(t,e)),As=(t,e,r,o,c=0)=>as((r?Hs:Vt)(t,e[c],c>te(e)-2?r:Ie),l=>{if(c>te(e)-2)return o?.(l)&&ee(t,e[c]),l;let u=As(l,e,r,o,c+1);return on(l)&&ee(t,e[c]),u}),Fn=/^\d+$/,Kn=()=>{let t=[],e=0;return[r=>(r?nn(t):null)??""+e++,r=>{Dn(Fn,r)&&te(t)<1e3&&is(t,r)}]},qn=t=>new Set(Bs(t)||$t(t)?t:[t]),Qn=(t,e)=>t?.add(e),zn=(t,e=[""])=>{let r=[],o=(c,l)=>l==te(e)?is(r,c):e[l]===null?an(c,u=>o(u,l+1)):Es([e[l],null],u=>o(Vt(c,u),l+1));return o(t,0),r},_n=t=>{let e,[r,o]=Kn(),c=Ie();return[(l,u,i,w=[],S=()=>[])=>{e??=t();let R=r(1);return ee(c,R,[l,u,i,w,S]),Qn(As(u,i??[""],qn),R),R},(l,u,...i)=>Es(zn(l,u),w=>an(w,S=>Vt(c,S)[0](e,...u??[],...i))),l=>as(Vt(c,l),([,u,i])=>(As(u,i??[""],void 0,w=>(cn(w,l),on(w)?1:0)),ee(c,l),o(l),i)),l=>as(Vt(c,l),([u,,i=[],w,S])=>{let R=(...b)=>{let E=te(b);E==te(i)?u(e,...b,...S(b)):$t(i[E])?Es(w[E]?.(...b)??[],T=>R(...b,T)):R(...b,i[E])};R()})]},rs=Ie(),ns=Ie(),Gn=(t=1,e,r)=>t!=1&&e.isMergeable()?[1,e.getMergeableContent,()=>e.getTransactionMergeableChanges(!r),([[o],[c]])=>!ss(o)||!ss(c),e.setDefaultContent]:t!=2?[0,e.getContent,e.getTransactionChanges,([o,c])=>!ss(o)||!ss(c),e.setContent]:rn("Store type not supported by this Persister"),Yn=(t,e,r,o,c,l,u,i={},w=0,S=[])=>{let R=0,b=0,E=0,T,F,Z;Hs(rs,S,()=>0),Hs(ns,S,()=>[]);let L=Ie(),[x,_,I,A,st]=Gn(u,t,w),[y,h,C]=_n(()=>Q),W=V=>{V!=R&&(R=V,h(L,void 0,R))},K=async()=>{if(!Vt(rs,S)){for(ee(rs,S,1);!$t(T=nn(Vt(ns,S)));)await Zt(T,l);ee(rs,S,0)}},P=V=>{(x&&Bs(V?.[0])?V?.[2]===1?t.applyMergeableChanges:t.setMergeableContent:V?.[2]===1?t.applyChanges:t.setContent)(V)},q=async V=>(R!=2&&(W(1),b++,await O(async()=>{await Zt(async()=>{let rt=await e();Bs(rt)?P(rt):V?st(V):rn(`Content is not an array: ${rt}`)},()=>{V&&st(V)}),W(0)})),Q),nt=async V=>(ot(),await q(V),await Zt(async()=>F=await o(async(rt,ht)=>{ht||rt?R!=2&&(W(1),b++,P(ht??rt),W(0)):await q()}),l),Q),ot=async()=>(F&&(await Zt(()=>c(F),l),F=void 0),Q),ct=()=>!$t(F),N=async V=>(R!=1&&(W(2),E++,await O(async()=>{await Zt(()=>r(_,V),l),W(0)})),Q),m=async()=>(j(),await N(),Z=t.addDidFinishTransactionListener(()=>{let V=I();A(V)&&N(V)}),Q),j=async()=>(Z&&(t.delListener(Z),Z=void 0),Q),et=()=>!$t(Z),G=async(V,rt=!1)=>{let[ht,Rt]=rt?[m,nt]:[nt,m];return await ht(V),await Rt(V),Q},M=async(V=!1)=>{let[rt,ht]=V?[j,ot]:[ot,j];return await rt(),await ht(),Q},H=()=>R,J=V=>y(V,L),Y=V=>(C(V),t),O=async(...V)=>(is(Vt(ns,S),...V),await K(),Q),Q={load:q,startAutoLoad:nt,stopAutoLoad:ot,isAutoLoading:ct,save:N,startAutoSave:m,stopAutoSave:j,isAutoSaving:et,startAutoPersisting:G,stopAutoPersisting:M,getStatus:H,addStatusListener:J,delListener:Y,schedule:O,getStore:()=>t,destroy:()=>($n(Vt(ns,S)),M()),getStats:()=>({loads:b,saves:E}),...i};return En(Q)},Ps=["t","v"],Xn={keyPath:"k"},Zn=async(t,e)=>{let r=On(e,(o,c)=>os(t,"put",{k:c,v:o}));Te(await os(t,"getAllKeys"),o=>An(e,o)?0:is(r,os(t,"delete",o))),await sn(r)},os=async(t,e,r)=>en((o,c)=>{let l=t[e](r);l.onsuccess=()=>o(l.result),l.onerror=()=>c(`objectStore.${e} error`)}),ln=(t,e,r=1,o)=>{let c=async(l,u=[],i=0)=>en((w,S)=>{let R=(Xr?Xr.indexedDB:indexedDB).open(e,i?2:void 0);R.onupgradeneeded=()=>i&&Te(Ps,b=>Zt(()=>R.result.createObjectStore(b,Xn))),R.onsuccess=()=>Zt(async()=>{let b=R.result.transaction(Ps,"readwrite"),E=await sn(Te(Ps,(T,F)=>l(b.objectStore(T),u[F])));R.result.close(),w(E)},b=>{R.result.close(),S(b)}),R.onerror=()=>S("indexedDB.open error")});return Yn(t,async()=>await c(async l=>Hn(Te(await os(l,"getAll"),({k:u,v:i})=>[u,i]))),l=>c((u,i)=>Zn(u,i),l(),1),l=>Mn(l,r),l=>jn(l),o,1,{getDbName:()=>e})};var cs=class{#t;#e="blobs";#s=null;constructor(e="copio-blobs"){this.#t=e}async#a(){return this.#s?this.#s:(this.#s=new Promise((e,r)=>{if(typeof indexedDB>"u"){r(new Error("IndexedDB is not available"));return}let o=indexedDB.open(this.#t,1);o.onupgradeneeded=()=>{let c=o.result;c.objectStoreNames.contains(this.#e)||c.createObjectStore(this.#e)},o.onsuccess=()=>e(o.result),o.onerror=()=>r(o.error||new Error("Failed to open blob db"))}),this.#s)}async put(e,r){let o=await this.#a();return new Promise((c,l)=>{let w=o.transaction(this.#e,"readwrite").objectStore(this.#e).put(r,e);w.onsuccess=()=>c(),w.onerror=()=>l(w.error)})}async get(e){let r=await this.#a();return new Promise((o,c)=>{let i=r.transaction(this.#e,"readonly").objectStore(this.#e).get(e);i.onsuccess=()=>o(i.result||null),i.onerror=()=>c(i.error)})}async delete(e){let r=await this.#a();return new Promise((o,c)=>{let i=r.transaction(this.#e,"readwrite").objectStore(this.#e).delete(e);i.onsuccess=()=>o(),i.onerror=()=>c(i.error)})}async deleteByPrefix(e){let r=await this.#a();return new Promise((o,c)=>{let u=r.transaction(this.#e,"readwrite").objectStore(this.#e),i=u.openKeyCursor();i.onsuccess=w=>{let S=w.target.result;S?(typeof S.key=="string"&&S.key.startsWith(e)&&u.delete(S.key),S.continue()):o()},i.onerror=()=>c(i.error)})}async sweepOrphans(e){let r=new Set(e),o=await this.#a(),c=0;return new Promise((l,u)=>{let w=o.transaction(this.#e,"readwrite").objectStore(this.#e),S=w.openKeyCursor();S.onsuccess=R=>{let b=R.target.result;if(b){if(typeof b.key=="string"){let E=b.key.split(":")[0];r.has(E)||(w.delete(b.key),c++)}b.continue()}else l(c)},S.onerror=()=>u(S.error)})}async close(){if(this.#s){try{(await this.#s).close()}catch{}this.#s=null}}};function Os(t,e="image/jpeg"){if(t instanceof Blob)return t;if(typeof t!="string"||!t.startsWith("data:"))return null;let r=t.match(/^data:([^;]+);base64,(.*)$/),o=r?r[1]:e,c=r?r[2]:t.split(",")[1],l=atob(c),u=new Uint8Array(l.length);for(let i=0;i<l.length;i++)u[i]=l.charCodeAt(i);return new Blob([u],{type:o})}async function Lo(t){return new Promise((e,r)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=r,o.readAsDataURL(t)})}var dn=class extends xr{#t=null;#e=null;#s=null;#a="copio-db";#i=new Set;#c=new Map;#r=new Map;#n=new Map;#o=new Map;#l=null;constructor(e={}){super(),this.#a=e.dbName||"copio-db",this.#t=e.store||Us(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#e=e.persister||ln(this.#t,this.#a),this.#s=new cs(`${this.#a}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#s}#d(e,r){return typeof r=="string"&&r.startsWith("blob:")&&(this.#i.add(r),this.#c.has(e)||this.#c.set(e,[]),this.#c.get(e).push(r)),r}revokeDocUrls(e){let r=this.#c.get(e);if(r){for(let o of r){try{URL.revokeObjectURL(o)}catch{}this.#i.delete(o)}this.#c.delete(e)}for(let[o,c]of this.#r.entries())if(o.startsWith(`${e}:`)){try{URL.revokeObjectURL(c)}catch{}this.#r.delete(o)}for(let[o,c]of this.#n.entries())if(o.startsWith(`${e}:`)){try{URL.revokeObjectURL(c)}catch{}this.#n.delete(o)}this.#o.delete(e)}revokeAllUrls(){for(let e of this.#i)try{URL.revokeObjectURL(e)}catch{}this.#i.clear(),this.#c.clear(),this.#r.clear(),this.#n.clear(),this.#o.clear()}async init(){return this.#l?this.#l:(this.#l=(async()=>{await this.#e.load(),typeof this.#e.startAutoLoad=="function"&&this.#e.startAutoLoad(),typeof this.#e.startAutoSave=="function"&&this.#e.startAutoSave(),await this.sweepOrphans();let e=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:e}})(),this.#l)}async sweepOrphans(){let e=Object.keys(this.#t.getTable("docs")||{});return this.#s.sweepOrphans(e)}listDocsSync(){let e=this.#t.getTable("docs");return Object.entries(e||{}).map(([r,o])=>({id:r,name:o.name||"",pages:this.#h(o.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(e){if(this.#o.has(e))return this.#o.get(e);if(!this.#t.hasRow("docs",e))return null;let r=this.#t.getRow("docs",e);return{id:e,name:r.name||"",pages:this.#h(r.pages)}}async getDoc(e){if(!this.#t.hasRow("docs",e))return null;let r=this.#t.getRow("docs",e),o=this.#h(r.pages),c=await Promise.all(o.map(async u=>{if(!u)return u;let i={...u},w=`${e}:${u.id}`,S=await this.#s.get(`${e}:${u.id}`);S&&(i.blob=S,this.#r.has(w)?i.src=this.#r.get(w):(i.src=this.#d(e,URL.createObjectURL(S)),this.#r.set(w,i.src)));let R=`${e}:${u.id}:orig`,b=await this.#s.get(`${e}:${u.id}:original`);return b?(i.originalBlob=b,this.#n.has(R)?i.originalSrc=this.#n.get(R):(i.originalSrc=this.#d(e,URL.createObjectURL(b)),this.#n.set(R,i.originalSrc))):i.blob&&(i.originalBlob=i.blob,i.originalSrc=i.src),i})),l={id:e,name:r.name||"",pages:c};return this.#o.set(e,l),l}async saveDoc(e,r){if(!e)throw new Error("Cannot save document without an ID");let o=Array.isArray(r.pages)?r.pages:this.#h(r.pages),c=[],l=[],u=[];for(let i of o){if(!i)continue;let w=Os(i.src)||(i.src instanceof Blob?i.src:null)||(i.blob instanceof Blob?i.blob:null),S=w?.type||"image/jpeg",R={id:i.id,name:i.name||"",type:i.type||"image",hasBlob:!0,mimeType:S,edits:i.edits,exif:i.exif,content:i.content,ocrText:i.ocrText??null,ocrConfidence:i.ocrConfidence??null,ocrWords:Array.isArray(i.ocrWords)?i.ocrWords:null,ocrWidth:i.ocrWidth??null,ocrHeight:i.ocrHeight??null};c.push(R);let b=`${e}:${i.id}`,E=`${e}:${i.id}:orig`,T={...i},F=this.#r.get(b),Z=typeof i.src=="string"&&i.src.startsWith("data:")||i.src instanceof Blob||i.src&&F&&i.src!==F;if(w)if(T.blob=w,Z||!F){if(F){try{URL.revokeObjectURL(F)}catch{}this.#i.delete(F)}let A=this.#d(e,URL.createObjectURL(w));this.#r.set(b,A),T.src=A}else T.src=F;let L=Os(i.originalSrc)||(i.originalSrc instanceof Blob?i.originalSrc:null)||(i.originalBlob instanceof Blob?i.originalBlob:null),x=this.#n.get(E),_=!x&&!L&&(!i.originalSrc||i.originalSrc===i.src);_&&w&&(L=w);let I=typeof i.originalSrc=="string"&&i.originalSrc.startsWith("data:")||i.originalSrc instanceof Blob||_&&!!L;if(L)if(T.originalBlob=L,I||!x){if(x&&I){try{URL.revokeObjectURL(x)}catch{}this.#i.delete(x)}let A=this.#d(e,URL.createObjectURL(L));this.#n.set(E,A),T.originalSrc=A}else T.originalSrc=x;else x?T.originalSrc=x:i.originalSrc?T.originalSrc=i.originalSrc:(T.originalSrc=T.src,T.blob&&(T.originalBlob=T.blob));l.push(T),u.push({pageId:i.id,page:i,srcBlob:w,origBlob:L})}this.#t.setRow("docs",e,{name:r.name||"",pages:JSON.stringify(c)}),this.#o.set(e,{id:e,name:r.name||"",pages:l});for(let i of u){let{pageId:w,page:S,srcBlob:R,origBlob:b}=i;if(!R&&typeof S.src=="string"&&S.src.startsWith("blob:"))try{R=await(await fetch(S.src)).blob()}catch{}if(R&&await this.#s.put(`${e}:${w}`,R),!b&&typeof S.originalSrc=="string"&&S.originalSrc.startsWith("blob:"))try{b=await(await fetch(S.originalSrc)).blob()}catch{}b&&await this.#s.put(`${e}:${w}:original`,b)}}async deleteDoc(e){this.#t.delRow("docs",e),await this.#s.deleteByPrefix(`${e}:`),this.revokeDocUrls(e),this.#o.delete(e)}async renameDoc(e,r){if(!this.#t.hasRow("docs",e))throw new Error(`Document "${e}" not found`);this.#t.setCell("docs",e,"name",r),this.#o.has(e)&&(this.#o.get(e).name=r)}async savePage(e,r,o){let c=await this.getDoc(e);if(!c)throw new Error(`Document ${e} not found`);let l=c.pages.findIndex(w=>w.id===r),u;if(l>=0)typeof o=="object"&&o!==null&&!(o instanceof Blob)?c.pages[l]={...c.pages[l],...o}:c.pages[l]={...c.pages[l],src:o,blob:o instanceof Blob?o:void 0},u=c.pages[l];else{let w=typeof o=="object"&&o!==null&&!(o instanceof Blob)?{id:r,...o}:{id:r,src:o,blob:o instanceof Blob?o:void 0};c.pages.push(w),u=w}let i=Os(u.src)||(u.src instanceof Blob?u.src:null)||(u.blob instanceof Blob?u.blob:null);if(!i&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{i=await(await fetch(u.src)).blob()}catch{}i&&await this.#s.put(`${e}:${r}`,i),await this.saveDoc(e,c)}async getPage(e,r){let o=await this.#s.get(`${e}:${r}`);if(o)return o;let c=this.getDocSync(e);if(!c)return null;let l=c.pages.find(u=>u.id===r);return l?l.content??l.src??l:null}async deletePage(e,r){let o=this.getDocSync(e);if(!o)return;o.pages=o.pages.filter(u=>u.id!==r),this.#t.setRow("docs",e,{name:o.name||"",pages:JSON.stringify(o.pages)}),await this.#s.delete(`${e}:${r}`),await this.#s.delete(`${e}:${r}:original`);let c=`${e}:${r}`;if(this.#r.has(c)){try{URL.revokeObjectURL(this.#r.get(c))}catch{}this.#r.delete(c)}let l=`${e}:${r}:orig`;if(this.#n.has(l)){try{URL.revokeObjectURL(this.#n.get(l))}catch{}this.#n.delete(l)}this.#o.delete(e)}async getSchemaVersion(){if(this.#t&&this.#t.hasValue("schemaVersion")){let e=this.#t.getValue("schemaVersion");return typeof e=="number"?e:null}return null}async setSchemaVersion(e){this.#t&&(this.#t.setValue("schemaVersion",typeof e=="number"?e:null),this.#e&&typeof this.#e.save=="function"&&await this.#e.save())}subscribe(e){let r=this.#t.addTableListener("docs",e);return()=>{this.#t.delListener(r)}}#h(e){if(Array.isArray(e))return e;if(typeof e=="string")try{return JSON.parse(e)}catch{return[]}return[]}};export{Us as a,Os as b,Lo as c,dn as d};
2
+ //# sourceMappingURL=chunk-JIPKWRBK.js.map