@inkandswitch/patchwork-pkg-base 0.0.65 → 0.0.67

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 (60) hide show
  1. package/module-settings-url +1 -0
  2. package/package.json +2 -1
  3. package/packages/codemirror-markdown/example.js +1 -2
  4. package/packages/drafts/dist/assets/{DraftOverlayProvider-VYKlzOy1.js → DraftOverlayProvider-D2vIz7hy.js} +2 -3
  5. package/packages/drafts/dist/assets/{DraftOverlayProvider-VYKlzOy1.js.map → DraftOverlayProvider-D2vIz7hy.js.map} +1 -1
  6. package/packages/drafts/dist/assets/{DraftStateProvider-DX8b_RgQ.js → DraftStateProvider-Bhz0S4c1.js} +212 -87
  7. package/packages/drafts/dist/assets/DraftStateProvider-Bhz0S4c1.js.map +1 -0
  8. package/packages/drafts/dist/assets/{draft-docs-Bi8K1y3a.js → draft-docs-DyJ2l14d.js} +108 -99
  9. package/packages/drafts/dist/assets/draft-docs-DyJ2l14d.js.map +1 -0
  10. package/packages/drafts/dist/assets/{main-EEciTwbZ.js → main-CG9HOCai.js} +14 -10
  11. package/packages/drafts/dist/assets/main-CG9HOCai.js.map +1 -0
  12. package/packages/drafts/dist/index.js +9 -9
  13. package/packages/drafts/package.json +5 -5
  14. package/packages/sideboard/dist/{chunk-KHS2XJKP.js → chunk-6POQCUBB.js} +3 -3
  15. package/packages/sideboard/dist/{chunk-TXFTRSLY.js → chunk-DS3QVJZT.js} +3 -3
  16. package/packages/sideboard/dist/chunk-DS3QVJZT.js.map +7 -0
  17. package/packages/sideboard/dist/{create-new-menu-EU5KJJ3R.js → create-new-menu-VA4ELRJ6.js} +2 -2
  18. package/packages/sideboard/dist/document-list-panel-GHYN6JR5.js +2 -0
  19. package/packages/sideboard/dist/index.js +1 -1
  20. package/packages/sideboard/dist/sideboard/sideboard.js +1 -1
  21. package/packages/tldraw4/dist/{chunk-IKZWERSR.js → chunk-G3PMV62Z.js} +1 -3
  22. package/packages/tldraw4/dist/{chunk-7CJQMVDI.js → chunk-PMHAL5YM.js} +4 -4
  23. package/packages/tldraw4/dist/datatype.js +2 -2
  24. package/packages/tldraw4/dist/main.js +1 -1
  25. package/packages/tldraw4/dist/{sanitizeSvg-OOYBXUQ2.js → sanitizeSvg-NCGPTJ3E.js} +2 -2
  26. package/packages/tldraw4/dist/tool.js +450 -5675
  27. package/packages/tldraw4/dist/tool.js.map +4 -4
  28. package/packages/tldraw4/package.json +0 -1
  29. package/packages/tldraw5/dist/{chunk-GKLJTYCF.js → chunk-DO47QRII.js} +1 -3
  30. package/packages/tldraw5/dist/{chunk-4JN3PIR7.js → chunk-FTKY6DDS.js} +3 -3
  31. package/packages/tldraw5/dist/{chunk-JDHJ334K.js → chunk-SZI4VCOI.js} +4 -4
  32. package/packages/tldraw5/dist/datatype.js +3 -3
  33. package/packages/tldraw5/dist/main.js +1 -1
  34. package/packages/tldraw5/dist/{sanitizeSvg-3EKLLIYO.js → sanitizeSvg-J7F3MQGT.js} +2 -2
  35. package/packages/tldraw5/dist/{script-VW3AAU5T.js → script-4RKE5JKT.js} +3 -3
  36. package/packages/tldraw5/dist/script-4RKE5JKT.js.map +7 -0
  37. package/packages/tldraw5/dist/{tldr-archive-WERHN3T4.js → tldr-archive-5X7EMHWZ.js} +3 -3
  38. package/packages/tldraw5/dist/tool.js +293 -1543
  39. package/packages/tldraw5/dist/tool.js.map +4 -4
  40. package/packages/tldraw5/package.json +0 -1
  41. package/plugin-registry-url +1 -0
  42. package/packages/drafts/dist/assets/DraftStateProvider-DX8b_RgQ.js.map +0 -1
  43. package/packages/drafts/dist/assets/draft-docs-Bi8K1y3a.js.map +0 -1
  44. package/packages/drafts/dist/assets/index-FKZtof6Z.js +0 -67
  45. package/packages/drafts/dist/assets/index-FKZtof6Z.js.map +0 -1
  46. package/packages/drafts/dist/assets/main-EEciTwbZ.js.map +0 -1
  47. package/packages/sideboard/dist/chunk-TXFTRSLY.js.map +0 -7
  48. package/packages/sideboard/dist/document-list-panel-WDIVYTZU.js +0 -2
  49. package/packages/tldraw5/dist/script-VW3AAU5T.js.map +0 -7
  50. /package/packages/sideboard/dist/{chunk-KHS2XJKP.js.map → chunk-6POQCUBB.js.map} +0 -0
  51. /package/packages/sideboard/dist/{create-new-menu-EU5KJJ3R.js.map → create-new-menu-VA4ELRJ6.js.map} +0 -0
  52. /package/packages/sideboard/dist/{document-list-panel-WDIVYTZU.js.map → document-list-panel-GHYN6JR5.js.map} +0 -0
  53. /package/packages/tldraw4/dist/{chunk-IKZWERSR.js.map → chunk-G3PMV62Z.js.map} +0 -0
  54. /package/packages/tldraw4/dist/{chunk-7CJQMVDI.js.map → chunk-PMHAL5YM.js.map} +0 -0
  55. /package/packages/tldraw4/dist/{sanitizeSvg-OOYBXUQ2.js.map → sanitizeSvg-NCGPTJ3E.js.map} +0 -0
  56. /package/packages/tldraw5/dist/{chunk-GKLJTYCF.js.map → chunk-DO47QRII.js.map} +0 -0
  57. /package/packages/tldraw5/dist/{chunk-4JN3PIR7.js.map → chunk-FTKY6DDS.js.map} +0 -0
  58. /package/packages/tldraw5/dist/{chunk-JDHJ334K.js.map → chunk-SZI4VCOI.js.map} +0 -0
  59. /package/packages/tldraw5/dist/{sanitizeSvg-3EKLLIYO.js.map → sanitizeSvg-J7F3MQGT.js.map} +0 -0
  60. /package/packages/tldraw5/dist/{tldr-archive-WERHN3T4.js.map → tldr-archive-5X7EMHWZ.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/tool.tsx", "../node_modules/.pnpm/@automerge+react@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1__react@18.3.1_supports-color@7.2.0/node_modules/@automerge/react/dist/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/wrapPromise.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useRepo.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/regex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/validate.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/uuid@9.0.1/node_modules/uuid/dist/esm-browser/parse.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/crypto.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/utils.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/_md.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/_u64.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/sha2.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/sha256.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/base-x@4.0.1/node_modules/base-x/src/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/bs58@5.0.0/node_modules/bs58/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/bs58check@3.0.1/node_modules/bs58check/base.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/bs58check@3.0.1/node_modules/bs58check/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/helpers/bufferFromHex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/AutomergeUrl.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandle.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useDocument.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/helpers/useSet.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandles.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useDocuments.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/react-usestateref@1.0.9_react@18.3.1/node_modules/react-usestateref/dist/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/eventemitter3@5.0.1/node_modules/eventemitter3/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useRemoteAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/useLocalAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@automerge+automerge@3.2.5/node_modules/@automerge/automerge/dist/mjs/proxies.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@automerge+automerge@3.2.5/node_modules/@automerge/automerge/dist/mjs/wasm_bindgen_output/web/automerge_wasm.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/@automerge+automerge@3.2.5/node_modules/@automerge/automerge/dist/mjs/implementation.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/cbor-x@1.6.0/node_modules/cbor-x/decode.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/cbor-x@1.6.0/node_modules/cbor-x/encode.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/refs/ref.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/debug@4.4.1/node_modules/debug/src/common.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/debug@4.4.1/node_modules/debug/src/browser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/subduction/network.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/fast-sha256@1.3.0/node_modules/fast-sha256/sha256.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/synchronizer/CollectionSynchronizer.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/node_modules/.pnpm/isomorphic-ws@5.0.0_ws@8.20.0/node_modules/isomorphic-ws/browser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/subduction/websocket-transport.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/presence/constants.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/helpers/array.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/presence/PeerStateView.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/presence/PeerPresenceInfo.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo/dist/presence/Presence.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1_48b6189f99a8df5d317c0b85d2ec6291/node_modules/@automerge/automerge-repo-react-hooks/src/usePresence.ts", "../node_modules/.pnpm/@automerge+react@2.6.0-subduction.12_react-dom@18.3.1_react@18.3.1__react@18.3.1_supports-color@7.2.0/node_modules/@automerge/react/dist/default-exports.js", "../src/lith/useAutomergeStore.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/wrapPromise.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useRepo.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/regex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/validate.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/parse.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/base-x@5.0.1/node_modules/base-x/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58@6.0.0/node_modules/bs58/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/base.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/helpers/bufferFromHex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/subdoc-handles/types.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/subdoc-handles/parser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/Logger.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/AutomergeUrl.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandle.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocument.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/helpers/useSet.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandles.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocuments.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useStateRef.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useRemoteAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useLocalAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/usePresence.ts", "../src/lith/AutomergeToTLStore.ts", "../node_modules/.pnpm/@inkandswitch+patchwork-providers-react@0.2.6_@automerge+automerge-repo-react-hooks@2.6_80ffcbcf3e158b4c39ecf6aef28824ac/node_modules/@inkandswitch/patchwork-providers-react/dist/index.js", "../src/diff.ts", "../src/DiffShapeWrapper.tsx", "../src/PatchworkDocShape.tsx", "../src/NewDocTool.tsx", "../src/dnd.ts", "../src/CollaboratorCursor.tsx"],
4
- "sourcesContent": ["import type { AutomergeUrl, DocHandle } from \"@automerge/automerge-repo/slim\";\nimport { decodeHeads, type UrlHeads } from \"@automerge/automerge-repo/slim\";\nimport {\n RepoContext,\n useDocHandle,\n useDocument,\n useRepo,\n} from \"@automerge/react\";\nimport {\n Tldraw,\n useEditor,\n getMediaAssetInfoPartial,\n atom,\n createShapeId,\n type VecLike,\n type TLContent,\n type TLAssetId,\n type TLAsset,\n type TLComponents,\n type TLRecord,\n type TLShapeId,\n type TLStoreWithStatus,\n} from \"@tldraw/tldraw\";\nimport {\n useAutomergeStore,\n useAutomergePresence,\n useClearHistoryOnScopeSwap,\n useIsHandleReadOnly,\n} from \"./lith/useAutomergeStore.ts\";\nimport type { TLDrawDoc } from \"./datatype.ts\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { UnixFileEntry } from \"@inkandswitch/patchwork-filesystem\";\nimport { automergeUrlToServiceWorkerUrl } from \"@inkandswitch/patchwork-filesystem\";\nimport { useSubscribe } from \"@inkandswitch/patchwork-providers-react\";\nimport { createRoot } from \"react-dom/client\";\nimport { diffStore, type ShapeDiff } from \"./diff.ts\";\nimport {\n DiffShapeWrapper,\n DiffStatusContext,\n type DiffStatus,\n type DiffStatusAtom,\n} from \"./DiffShapeWrapper.tsx\";\nimport {\n PatchworkDocShapeUtil,\n PATCHWORK_DOC_SHAPE_TYPE,\n getDefaultToolId,\n} from \"./PatchworkDocShape.tsx\";\nimport {\n NewDocShapeTool,\n NewDocToolbar,\n newDocUiOverrides,\n setNewDocToolContext,\n} from \"./NewDocTool.tsx\";\nimport { isPatchworkDrag, parseDroppedDocs } from \"./dnd.ts\";\nimport { ContactCollaboratorCursor } from \"./CollaboratorCursor.tsx\";\n\nexport { splitPresenceUserId } from \"./CollaboratorCursor.tsx\";\n\n// Custom shapes / tools that let a tldraw canvas embed other Patchwork\n// documents. These must be registered both on the Automerge-backed store (so\n// the shape type persists) and on the <Tldraw> component (so it renders).\nconst customShapeUtils = [PatchworkDocShapeUtil];\nconst customTools = [NewDocShapeTool];\n\n// Diff baseline (fork-point heads) served by the draft overlay\n// (`draft:baseline`). `heads` is `null` when there is no baseline and no\n// diff is rendered (e.g. on \"main\"). It is `null` rather than optional so the\n// value is a valid structured-cloneable `JSONValue` crossing the provider\n// channel.\ntype Baseline = { heads: UrlHeads | null };\n\nconst MIME_TO_EXT: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"image/bmp\": \"bmp\",\n \"image/tiff\": \"tiff\",\n \"image/avif\": \"avif\",\n \"video/mp4\": \"mp4\",\n \"video/webm\": \"webm\",\n \"video/quicktime\": \"mov\",\n};\n\nfunction extensionForMimeType(mimeType: string): string {\n return MIME_TO_EXT[mimeType] || mimeType.split(\"/\")[1] || \"bin\";\n}\n\ninterface ContactDoc {\n type: string;\n name?: string;\n color?: string;\n}\n\nfunction useContactInfo() {\n const repo = useRepo();\n const [contactUrl, setContactUrl] = useState<AutomergeUrl | undefined>();\n\n useEffect(() => {\n const accountDocHandle = (window as any).accountDocHandle as\n | DocHandle<{ contactUrl: AutomergeUrl }>\n | undefined;\n if (!accountDocHandle) return;\n const doc = accountDocHandle.doc();\n if (doc?.contactUrl) {\n setContactUrl(doc.contactUrl);\n }\n }, []);\n\n const [contactDoc] = useDocument<ContactDoc>(contactUrl);\n\n return {\n // Compose userId as `${contactUrl}-${repo.peerId}` to uniquely identify a session;\n // this prevents tldraw from hiding local cursors across multiple sessions under the same account.\n userId: contactUrl ? `${contactUrl}-${repo.peerId}` : repo.peerId,\n name: contactDoc?.name ?? \"Anonymous\",\n // The color chosen in the account picker; it rides along in our presence\n // record, so the cursor arrow always matches the contact-cursor token.\n color: contactDoc?.color,\n };\n}\n\nexport function TldrawTool({\n docUrl,\n element,\n}: {\n docUrl: AutomergeUrl;\n element: HTMLElement;\n}) {\n const handle = useDocHandle<TLDrawDoc>(docUrl, { suspense: true });\n // A history-pinned handle is at fixed heads and rejects writes, so the whole\n // tool renders read-only. Tracked live: it flips in place when the handle's\n // backing is swapped.\n const readOnly = useIsHandleReadOnly(handle);\n const contactInfo = useContactInfo();\n const store = useAutomergeStore({\n handle,\n userId: contactInfo.userId,\n readOnly,\n shapeUtils: customShapeUtils,\n });\n\n useAutomergePresence({\n handle: handle as DocHandle<any>,\n store,\n userMetadata: contactInfo,\n element,\n });\n\n const baseline = useSubscribe<Baseline>(\n element,\n { type: \"draft:baseline\", url: docUrl },\n { heads: null }\n );\n const diff = useShapeDiff(handle, baseline.heads ?? undefined);\n\n // Per-tool atom feeding `DiffShapeWrapper` (read via `useValue`). Created once\n // per mount so multiple tldraw tools don't share styling state.\n const [statusAtom] = useState<DiffStatusAtom>(() =>\n atom(\"diff status\", new Map<TLShapeId, DiffStatus>())\n );\n useEffect(() => {\n statusAtom.set(buildStatusMap(diff));\n }, [diff, statusAtom]);\n\n // Deleted shapes are gone from the live store, so re-insert them as locked\n // ghosts (styled `tl-diff-deleted`). They never reach Automerge \u2014 see\n // `useDeletedGhosts`.\n useDeletedGhosts(store, handle, diff);\n\n const components = useMemo<TLComponents>(\n () => ({\n ShapeWrapper: DiffShapeWrapper,\n Toolbar: NewDocToolbar,\n CollaboratorCursor: ContactCollaboratorCursor,\n }),\n []\n );\n\n return (\n <DiffStatusContext.Provider value={statusAtom}>\n <Tldraw\n inferDarkMode\n autoFocus\n store={store}\n shapeUtils={customShapeUtils}\n tools={customTools}\n overrides={newDocUiOverrides}\n components={components}\n >\n <TldrawInner docUrl={docUrl} element={element} readOnly={readOnly} />\n </Tldraw>\n </DiffStatusContext.Provider>\n );\n}\n\n// Recomputes the diff against `heads` on every doc change. `baseline.heads`\n// only moves when the draft is forked (copy-on-write), so without listening to\n// the handle the diff would freeze after the first computation. The bump is\n// deferred to a microtask so we never recompute synchronously from inside the\n// sync layer's own `handle.change` callback.\nfunction useShapeDiff(\n handle: DocHandle<TLDrawDoc>,\n heads: UrlHeads | undefined\n): ShapeDiff | null {\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n let scheduled = false;\n const onChange = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n setTick((t) => t + 1);\n });\n };\n handle.on(\"change\", onChange);\n return () => {\n handle.off(\"change\", onChange);\n };\n }, [handle]);\n\n return useMemo(() => {\n if (!heads) return null;\n const doc = handle.doc();\n if (!doc) return null;\n try {\n return diffStore(doc, decodeHeads(heads));\n } catch (error) {\n console.warn(\"[tldraw4/diff] failed to compute diff\", error);\n return null;\n }\n // `tick` is intentionally a dependency: it forces recompute on doc change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [handle, heads, tick]);\n}\n\nfunction buildStatusMap(diff: ShapeDiff | null): Map<TLShapeId, DiffStatus> {\n const map = new Map<TLShapeId, DiffStatus>();\n if (!diff) return map;\n for (const id of diff.added) map.set(id, \"added\");\n for (const id of diff.changed) map.set(id, \"changed\");\n for (const record of diff.deleted) map.set(record.id as TLShapeId, \"deleted\");\n return map;\n}\n\n// Renders deleted shapes by putting their baseline records back into the\n// *tldraw* store as locked ghosts. These are applied via `mergeRemoteChanges`\n// (source: \"remote\"), and the only TLStore->Automerge sync path listens for\n// source: \"user\" \u2014 so ghosts never sync back to the doc. `diffStore` reads the\n// Automerge doc (not the tldraw store), so ghosts also never re-enter the diff.\nfunction useDeletedGhosts(\n store: TLStoreWithStatus,\n handle: DocHandle<TLDrawDoc>,\n diff: ShapeDiff | null\n) {\n const ghostIds = useRef<Set<TLShapeId>>(new Set());\n\n useEffect(() => {\n const inner = store.store;\n if (!inner) return;\n\n const desired = new Map<TLShapeId, TLRecord>();\n if (diff) {\n for (const record of diff.deleted) {\n desired.set(record.id as TLShapeId, record);\n }\n }\n\n // A ghost is only safe to remove if it isn't currently a real record in the\n // doc: if a deleted shape was re-added upstream, the sync layer puts the\n // real record back at the same id, and removing it then would drop the real\n // shape from the view.\n const liveStore = (handle.doc()?.store ?? {}) as Record<string, unknown>;\n const toRemove = [...ghostIds.current].filter(\n (id) => !desired.has(id) && !(id in liveStore)\n );\n const toAdd: TLRecord[] = [];\n for (const [id, record] of desired) {\n if (!ghostIds.current.has(id)) {\n // Fade the ghost via tldraw's first-class `opacity` prop. tldraw writes\n // `opacity` as an inline style on the shape element (Shape.tsx), so a CSS\n // class (`.tl-diff-deleted`) can't override it \u2014 the fade has to live on\n // the record itself. The red \"removed\" glow stays in CSS as a `filter`.\n toAdd.push({ ...record, isLocked: true, opacity: 0.1 } as TLRecord);\n }\n }\n\n if (toRemove.length === 0 && toAdd.length === 0) return;\n\n inner.mergeRemoteChanges(() => {\n if (toRemove.length) inner.remove(toRemove);\n if (toAdd.length) inner.put(toAdd);\n });\n\n for (const id of toRemove) ghostIds.current.delete(id);\n for (const record of toAdd) ghostIds.current.add(record.id as TLShapeId);\n }, [store, handle, diff]);\n}\n\nfunction TldrawInner(props: {\n docUrl: AutomergeUrl;\n element: HTMLElement;\n readOnly: boolean;\n}) {\n const key = useMemo(() => `${props.docUrl}-camera`, [props.docUrl]);\n\n const editor = useEditor();\n const repo = useRepo();\n const handle = useDocHandle<TLDrawDoc>(props.docUrl, { suspense: true });\n\n usePatchworkDrop(props.element);\n useClearHistoryOnScopeSwap(handle);\n\n const onChange = useCallback(() => {\n if (!editor) return;\n const camstate = editor.getCameraState();\n if (camstate == \"moving\") {\n // todo debounce?\n localStorage.setItem(key, JSON.stringify(editor.getCamera()));\n }\n }, []);\n\n useEffect(() => {\n if (!editor) return;\n\n // History-pinned views block all canvas editing (the store write-back is\n // also disabled in useAutomergeStore).\n editor.updateInstanceState({ isReadonly: props.readOnly });\n\n // Give the NewDocTool the repo it needs to create embedded documents.\n setNewDocToolContext(repo, editor);\n\n // Handle pasted/dropped files (images, videos) by storing them as\n // UnixFileEntry automerge docs and referencing them via service-worker URLs.\n editor.registerExternalAssetHandler(\"file\", async ({ file, assetId }) => {\n const isImage = file.type.startsWith(\"image/\");\n const isVideo = file.type.startsWith(\"video/\");\n\n // Create a stable asset ID if one wasn't provided\n const id = assetId ?? (`asset:${crypto.randomUUID()}` as TLAssetId);\n\n // Read the file bytes\n const bytes = new Uint8Array(await file.arrayBuffer());\n\n // Determine extension and name\n const ext = extensionForMimeType(file.type);\n const name =\n file.name && file.name !== \"image.png\"\n ? file.name\n : `Pasted image on ${new Date().toLocaleDateString()}.${ext}`;\n\n // Create an automerge doc for the file\n const fileHandle = repo.create<UnixFileEntry>();\n fileHandle.change((doc) => {\n doc.content = bytes;\n doc.extension = ext;\n doc.mimeType = file.type;\n doc.name = name;\n });\n\n // Build the asset using tldraw's helper to get dimensions etc.\n const asset = await getMediaAssetInfoPartial(file, id, isImage, isVideo);\n\n // Point the asset's src at the service-worker URL for this doc\n asset.props.src = automergeUrlToServiceWorkerUrl(fileHandle.url);\n\n return asset as TLAsset;\n });\n\n // Override the tldraw paste handler to avoid \"could not migrate content\"\n // errors when pasting from newer tldraw versions (e.g. tldraw.com may\n // run a canary build whose schema sequence versions are ahead of ours).\n editor.registerExternalContentHandler(\n \"tldraw\",\n ({ point, content }: { point?: VecLike; content: TLContent }) => {\n editor.run(() => {\n const selectionBoundsBefore = editor.getSelectionPageBounds();\n editor.markHistoryStoppingPoint(\"paste\");\n\n for (const shape of content.shapes) {\n if (content.rootShapeIds.includes(shape.id)) {\n shape.isLocked = false;\n }\n }\n\n // Replace the pasted content's schema with ours so that\n // migrateStoreSnapshot sees matching versions and skips migration\n // rather than failing on unknown future sequence versions.\n content.schema = editor.store.schema.serialize();\n\n editor.putContentOntoCurrentPage(content, {\n point,\n select: true,\n });\n\n const selectedBoundsAfter = editor.getSelectionPageBounds();\n if (\n selectionBoundsBefore &&\n selectedBoundsAfter &&\n selectionBoundsBefore.collides(selectedBoundsAfter)\n ) {\n editor.updateInstanceState({ isChangingStyle: true });\n }\n });\n }\n );\n\n const existing = localStorage.getItem(key);\n if (existing) {\n try {\n const cam = JSON.parse(existing);\n editor.setCamera(cam);\n } catch {\n localStorage.removeItem(key);\n }\n }\n editor.on(\"change\", onChange);\n return () => void editor.off(\"change\", onChange);\n }, [editor, props.readOnly]);\n return null;\n}\n\n// Accept documents dragged in from the folder-tree-view / sideboard and other\n// Patchwork tools, embedding each as a `patchwork-doc` shape at the drop point.\nfunction usePatchworkDrop(element: HTMLElement) {\n const editor = useEditor();\n const repo = useRepo();\n\n useEffect(() => {\n if (!editor || !element) return;\n\n // If the drop lands inside an already-embedded <patchwork-view>, let that\n // inner tool handle it instead of creating a nested embed. The outer\n // <patchwork-view> hosting this canvas appears at/after `element` in the\n // path, so we stop the walk once we reach `element`.\n const isInsideEmbeddedPatchworkView = (e: DragEvent) => {\n for (const el of e.composedPath()) {\n if (el === element) break;\n if ((el as Element).tagName?.toLowerCase() === \"patchwork-view\")\n return true;\n }\n return false;\n };\n\n const allowDrop = (e: DragEvent) => {\n if (e.dataTransfer && isPatchworkDrag(e.dataTransfer.types)) {\n e.preventDefault();\n // Dropping embeds a *reference* to the same automerge doc, not a copy.\n e.dataTransfer.dropEffect = \"link\";\n }\n };\n\n const handleDrop = (e: DragEvent) => {\n if (!e.dataTransfer || !isPatchworkDrag(e.dataTransfer.types)) return;\n e.preventDefault();\n if (isInsideEmbeddedPatchworkView(e)) return;\n e.stopImmediatePropagation();\n\n const docs = parseDroppedDocs(e.dataTransfer);\n if (docs.length === 0) return;\n\n const dropPoint = editor.screenToPage({ x: e.clientX, y: e.clientY });\n const STAGGER = 24;\n const createdIds: TLShapeId[] = [];\n\n docs.forEach((item, i) => {\n // Random id (not derived from the doc url) so the same document can be\n // embedded on the canvas any number of times.\n const shapeId = createShapeId();\n createdIds.push(shapeId);\n\n const knownType = item.type ?? \"\";\n editor.createShape({\n id: shapeId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: dropPoint.x + i * STAGGER,\n y: dropPoint.y + i * STAGGER,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: 640,\n h: 480,\n docUrl: item.url,\n docName: item.name ?? \"Loading\\u2026\",\n docType: knownType,\n toolId: getDefaultToolId(knownType),\n },\n });\n\n // Resolve datatype/name from the doc when the drag payload didn't\n // include them (e.g. bare-URL drags).\n if (!item.type || !item.name) {\n void (async () => {\n try {\n const handle = await repo.find<{\n \"@patchwork\"?: { type?: string };\n }>(item.url);\n const doc = handle.doc();\n const datatypeId = doc?.[\"@patchwork\"]?.type ?? knownType;\n if (!editor.getShape(shapeId)) return;\n editor.updateShape({\n id: shapeId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: {\n docName: item.name ?? datatypeId ?? item.url,\n docType: datatypeId,\n toolId: getDefaultToolId(datatypeId),\n },\n });\n } catch (err) {\n console.error(\"[tldraw4] failed to resolve dropped doc\", err);\n }\n })();\n }\n });\n\n editor.setSelectedShapes(createdIds);\n };\n\n element.addEventListener(\"dragenter\", allowDrop, { capture: true });\n element.addEventListener(\"dragover\", allowDrop, { capture: true });\n element.addEventListener(\"drop\", handleDrop, { capture: true });\n return () => {\n element.removeEventListener(\"dragenter\", allowDrop, { capture: true });\n element.removeEventListener(\"dragover\", allowDrop, { capture: true });\n element.removeEventListener(\"drop\", handleDrop, { capture: true });\n };\n }, [editor, repo, element]);\n}\n\nexport function render(handle: any, element: any) {\n const root = createRoot(element);\n root.render(\n <RepoContext.Provider value={element.repo}>\n <TldrawTool docUrl={handle.url} element={element} />\n </RepoContext.Provider>\n );\n return () => root.unmount();\n}\n", "export * from \"@automerge/automerge-repo\";\nexport * from \"./default-exports.js\";\n", "type Status = \"pending\" | \"success\" | \"error\"\n\nexport type PromiseWrapper<T> = {\n promise: Promise<T>\n read(): T\n}\n\nexport function wrapPromise<T>(promise: Promise<T>): PromiseWrapper<T> {\n let status: Status = \"pending\"\n let result: T\n let error: Error\n\n const suspender = promise.then(\n data => {\n status = \"success\"\n result = data\n },\n err => {\n status = \"error\"\n error = err\n }\n )\n\n return {\n promise,\n read(): T {\n switch (status) {\n case \"pending\":\n throw suspender\n case \"error\":\n throw error\n case \"success\":\n return result\n }\n },\n }\n}\n", "import { Repo } from \"@automerge/automerge-repo/slim\"\nimport { createContext, useContext } from \"react\"\n\n/** A [React context](https://react.dev/learn/passing-data-deeply-with-context) which provides access to an Automerge repo. */\nexport const RepoContext = createContext<Repo | null>(null)\n\n/** A [React hook](https://reactjs.org/docs/hooks-intro.html) which returns the Automerge repo from {@link RepoContext}. */\nexport function useRepo(): Repo {\n const repo = useContext(RepoContext)\n if (!repo) throw new Error(\"Repo was not found on RepoContext.\")\n return repo\n}\n", "export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;", "import REGEX from './regex.js';\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\n\nexport default validate;", "import validate from './validate.js';\n\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nexport default parse;", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.crypto = void 0;\nexports.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map", "\"use strict\";\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;\nexports.isBytes = isBytes;\nexports.anumber = anumber;\nexports.abytes = abytes;\nexports.ahash = ahash;\nexports.aexists = aexists;\nexports.aoutput = aoutput;\nexports.u8 = u8;\nexports.u32 = u32;\nexports.clean = clean;\nexports.createView = createView;\nexports.rotr = rotr;\nexports.rotl = rotl;\nexports.byteSwap = byteSwap;\nexports.byteSwap32 = byteSwap32;\nexports.bytesToHex = bytesToHex;\nexports.hexToBytes = hexToBytes;\nexports.asyncLoop = asyncLoop;\nexports.utf8ToBytes = utf8ToBytes;\nexports.bytesToUtf8 = bytesToUtf8;\nexports.toBytes = toBytes;\nexports.kdfInputToBytes = kdfInputToBytes;\nexports.concatBytes = concatBytes;\nexports.checkOpts = checkOpts;\nexports.createHasher = createHasher;\nexports.createOptHasher = createOptHasher;\nexports.createXOFer = createXOFer;\nexports.randomBytes = randomBytes;\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nconst crypto_1 = require(\"@noble/hashes/crypto\");\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nfunction anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nfunction u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nfunction u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nfunction clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nfunction createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nfunction rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nfunction rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nfunction byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexports.swap8IfBE = exports.isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexports.byteSwapIfBE = exports.swap8IfBE;\n/** In place byte swap for Uint32Array */\nfunction byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexports.swap32IfBE = exports.isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nconst nextTick = async () => { };\nexports.nextTick = nextTick;\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await (0, exports.nextTick)();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nfunction bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nfunction kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nclass Hash {\n}\nexports.Hash = Hash;\n/** Wraps hash function, creating an interface on top of it */\nfunction createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nfunction createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nfunction createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexports.wrapConstructor = createHasher;\nexports.wrapConstructorWithOpts = createOptHasher;\nexports.wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nfunction randomBytes(bytesLength = 32) {\n if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {\n return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SHA512_IV = exports.SHA384_IV = exports.SHA224_IV = exports.SHA256_IV = exports.HashMD = void 0;\nexports.setBigUint64 = setBigUint64;\nexports.Chi = Chi;\nexports.Maj = Maj;\n/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nconst utils_ts_1 = require(\"./utils.js\");\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nfunction Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nfunction Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nclass HashMD extends utils_ts_1.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0, utils_ts_1.createView)(this.buffer);\n }\n update(data) {\n (0, utils_ts_1.aexists)(this);\n data = (0, utils_ts_1.toBytes)(data);\n (0, utils_ts_1.abytes)(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0, utils_ts_1.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0, utils_ts_1.aexists)(this);\n (0, utils_ts_1.aoutput)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n (0, utils_ts_1.clean)(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0, utils_ts_1.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\nexports.HashMD = HashMD;\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexports.SHA256_IV = Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexports.SHA224_IV = Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexports.SHA384_IV = Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexports.SHA512_IV = Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toBig = exports.shrSL = exports.shrSH = exports.rotrSL = exports.rotrSH = exports.rotrBL = exports.rotrBH = exports.rotr32L = exports.rotr32H = exports.rotlSL = exports.rotlSH = exports.rotlBL = exports.rotlBH = exports.add5L = exports.add5H = exports.add4L = exports.add4H = exports.add3L = exports.add3H = void 0;\nexports.add = add;\nexports.fromBig = fromBig;\nexports.split = split;\n/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\nexports.toBig = toBig;\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nexports.shrSH = shrSH;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\nexports.shrSL = shrSL;\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nexports.rotrSH = rotrSH;\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\nexports.rotrSL = rotrSL;\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nexports.rotrBH = rotrBH;\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\nexports.rotrBL = rotrBL;\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nexports.rotr32H = rotr32H;\nconst rotr32L = (h, _l) => h;\nexports.rotr32L = rotr32L;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nexports.rotlSH = rotlSH;\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nexports.rotlSL = rotlSL;\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nexports.rotlBH = rotlBH;\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nexports.rotlBL = rotlBL;\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nexports.add3L = add3L;\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nexports.add3H = add3H;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nexports.add4L = add4L;\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nexports.add4H = add4H;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nexports.add5L = add5L;\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\nexports.add5H = add5H;\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexports.default = u64;\n//# sourceMappingURL=_u64.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.sha512_224 = exports.sha512_256 = exports.sha384 = exports.sha512 = exports.sha224 = exports.sha256 = exports.SHA512_256 = exports.SHA512_224 = exports.SHA384 = exports.SHA512 = exports.SHA224 = exports.SHA256 = void 0;\n/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nconst _md_ts_1 = require(\"./_md.js\");\nconst u64 = require(\"./_u64.js\");\nconst utils_ts_1 = require(\"./utils.js\");\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _md_ts_1.HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = _md_ts_1.SHA256_IV[0] | 0;\n this.B = _md_ts_1.SHA256_IV[1] | 0;\n this.C = _md_ts_1.SHA256_IV[2] | 0;\n this.D = _md_ts_1.SHA256_IV[3] | 0;\n this.E = _md_ts_1.SHA256_IV[4] | 0;\n this.F = _md_ts_1.SHA256_IV[5] | 0;\n this.G = _md_ts_1.SHA256_IV[6] | 0;\n this.H = _md_ts_1.SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0, utils_ts_1.rotr)(W15, 7) ^ (0, utils_ts_1.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0, utils_ts_1.rotr)(W2, 17) ^ (0, utils_ts_1.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0, utils_ts_1.rotr)(E, 6) ^ (0, utils_ts_1.rotr)(E, 11) ^ (0, utils_ts_1.rotr)(E, 25);\n const T1 = (H + sigma1 + (0, _md_ts_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0, utils_ts_1.rotr)(A, 2) ^ (0, utils_ts_1.rotr)(A, 13) ^ (0, utils_ts_1.rotr)(A, 22);\n const T2 = (sigma0 + (0, _md_ts_1.Maj)(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n (0, utils_ts_1.clean)(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n (0, utils_ts_1.clean)(this.buffer);\n }\n}\nexports.SHA256 = SHA256;\nclass SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = _md_ts_1.SHA224_IV[0] | 0;\n this.B = _md_ts_1.SHA224_IV[1] | 0;\n this.C = _md_ts_1.SHA224_IV[2] | 0;\n this.D = _md_ts_1.SHA224_IV[3] | 0;\n this.E = _md_ts_1.SHA224_IV[4] | 0;\n this.F = _md_ts_1.SHA224_IV[5] | 0;\n this.G = _md_ts_1.SHA224_IV[6] | 0;\n this.H = _md_ts_1.SHA224_IV[7] | 0;\n }\n}\nexports.SHA224 = SHA224;\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nclass SHA512 extends _md_ts_1.HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = _md_ts_1.SHA512_IV[0] | 0;\n this.Al = _md_ts_1.SHA512_IV[1] | 0;\n this.Bh = _md_ts_1.SHA512_IV[2] | 0;\n this.Bl = _md_ts_1.SHA512_IV[3] | 0;\n this.Ch = _md_ts_1.SHA512_IV[4] | 0;\n this.Cl = _md_ts_1.SHA512_IV[5] | 0;\n this.Dh = _md_ts_1.SHA512_IV[6] | 0;\n this.Dl = _md_ts_1.SHA512_IV[7] | 0;\n this.Eh = _md_ts_1.SHA512_IV[8] | 0;\n this.El = _md_ts_1.SHA512_IV[9] | 0;\n this.Fh = _md_ts_1.SHA512_IV[10] | 0;\n this.Fl = _md_ts_1.SHA512_IV[11] | 0;\n this.Gh = _md_ts_1.SHA512_IV[12] | 0;\n this.Gl = _md_ts_1.SHA512_IV[13] | 0;\n this.Hh = _md_ts_1.SHA512_IV[14] | 0;\n this.Hl = _md_ts_1.SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n (0, utils_ts_1.clean)(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n (0, utils_ts_1.clean)(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexports.SHA512 = SHA512;\nclass SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = _md_ts_1.SHA384_IV[0] | 0;\n this.Al = _md_ts_1.SHA384_IV[1] | 0;\n this.Bh = _md_ts_1.SHA384_IV[2] | 0;\n this.Bl = _md_ts_1.SHA384_IV[3] | 0;\n this.Ch = _md_ts_1.SHA384_IV[4] | 0;\n this.Cl = _md_ts_1.SHA384_IV[5] | 0;\n this.Dh = _md_ts_1.SHA384_IV[6] | 0;\n this.Dl = _md_ts_1.SHA384_IV[7] | 0;\n this.Eh = _md_ts_1.SHA384_IV[8] | 0;\n this.El = _md_ts_1.SHA384_IV[9] | 0;\n this.Fh = _md_ts_1.SHA384_IV[10] | 0;\n this.Fl = _md_ts_1.SHA384_IV[11] | 0;\n this.Gh = _md_ts_1.SHA384_IV[12] | 0;\n this.Gl = _md_ts_1.SHA384_IV[13] | 0;\n this.Hh = _md_ts_1.SHA384_IV[14] | 0;\n this.Hl = _md_ts_1.SHA384_IV[15] | 0;\n }\n}\nexports.SHA384 = SHA384;\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nclass SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexports.SHA512_224 = SHA512_224;\nclass SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\nexports.SHA512_256 = SHA512_256;\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexports.sha256 = (0, utils_ts_1.createHasher)(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexports.sha224 = (0, utils_ts_1.createHasher)(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexports.sha512 = (0, utils_ts_1.createHasher)(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexports.sha384 = (0, utils_ts_1.createHasher)(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexports.sha512_256 = (0, utils_ts_1.createHasher)(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexports.sha512_224 = (0, utils_ts_1.createHasher)(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.sha224 = exports.SHA224 = exports.sha256 = exports.SHA256 = void 0;\n/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nconst sha2_ts_1 = require(\"./sha2.js\");\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexports.SHA256 = sha2_ts_1.SHA256;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexports.sha256 = sha2_ts_1.sha256;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexports.SHA224 = sha2_ts_1.SHA224;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexports.sha224 = sha2_ts_1.sha224;\n//# sourceMappingURL=sha256.js.map", "'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (source instanceof Uint8Array) {\n } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Find code of next character\n var charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n var carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = new Uint8Array(zeroes + (size - it4))\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n", "const basex = require('base-x')\nconst ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n", "'use strict'\n\nvar base58 = require('bs58')\n\nmodule.exports = function (checksumFn) {\n // Encode a buffer as a base58-check encoded string\n function encode (payload) {\n var payloadU8 = Uint8Array.from(payload)\n var checksum = checksumFn(payloadU8)\n var length = payloadU8.length + 4\n var both = new Uint8Array(length)\n both.set(payloadU8, 0)\n both.set(checksum.subarray(0, 4), payloadU8.length)\n return base58.encode(both, length)\n }\n\n function decodeRaw (buffer) {\n var payload = buffer.slice(0, -4)\n var checksum = buffer.slice(-4)\n var newChecksum = checksumFn(payload)\n\n if (checksum[0] ^ newChecksum[0] |\n checksum[1] ^ newChecksum[1] |\n checksum[2] ^ newChecksum[2] |\n checksum[3] ^ newChecksum[3]) return\n\n return payload\n }\n\n // Decode a base58-check encoded string to a buffer, no result if checksum is wrong\n function decodeUnsafe (string) {\n var buffer = base58.decodeUnsafe(string)\n if (!buffer) return\n\n return decodeRaw(buffer)\n }\n\n function decode (string) {\n var buffer = base58.decode(string)\n var payload = decodeRaw(buffer, checksumFn)\n if (!payload) throw new Error('Invalid checksum')\n return payload\n }\n\n return {\n encode: encode,\n decode: decode,\n decodeUnsafe: decodeUnsafe\n }\n}\n", "'use strict'\n\nvar { sha256 } = require('@noble/hashes/sha256')\nvar bs58checkBase = require('./base')\n\n// SHA256(SHA256(buffer))\nfunction sha256x2 (buffer) {\n return sha256(sha256(buffer))\n}\n\nmodule.exports = bs58checkBase(sha256x2)\n", "export const uint8ArrayFromHexString = (hexString) => {\n if (hexString.length % 2 !== 0) {\n throw new Error(\"Hex string must have an even length\");\n }\n const bytes = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n bytes[i >> 1] = parseInt(hexString.slice(i, i + 2), 16);\n }\n return bytes;\n};\nexport const uint8ArrayToHexString = (data) => {\n return Array.from(data, byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n};\n", "import * as Uuid from \"uuid\";\nimport bs58check from \"bs58check\";\nimport { uint8ArrayFromHexString, uint8ArrayToHexString, } from \"./helpers/bufferFromHex.js\";\nexport const urlPrefix = \"automerge:\";\n/** Given an Automerge URL, returns the DocumentId in both base58check-encoded form and binary form */\nexport const parseAutomergeUrl = (url) => {\n const [baseUrl, headsSection, ...rest] = url.split(\"#\");\n if (rest.length > 0) {\n throw new Error(\"Invalid URL: contains multiple heads sections\");\n }\n const regex = new RegExp(`^${urlPrefix}(\\\\w+)$`);\n const [, docMatch] = baseUrl.match(regex) || [];\n const documentId = docMatch;\n const binaryDocumentId = documentIdToBinary(documentId);\n if (!binaryDocumentId)\n throw new Error(\"Invalid document URL: \" + url);\n if (headsSection === undefined)\n return { binaryDocumentId, documentId };\n const heads = (headsSection === \"\" ? [] : headsSection.split(\"|\"));\n const hexHeads = heads.map(head => {\n try {\n return uint8ArrayToHexString(bs58check.decode(head));\n }\n catch (e) {\n throw new Error(`Invalid head in URL: ${head}`);\n }\n });\n return { binaryDocumentId, hexHeads, documentId, heads };\n};\n/**\n * Given a documentId in either binary or base58check-encoded form, returns an Automerge URL.\n * Throws on invalid input.\n */\nexport const stringifyAutomergeUrl = (arg) => {\n if (arg instanceof Uint8Array || typeof arg === \"string\") {\n return (urlPrefix +\n (arg instanceof Uint8Array\n ? binaryToDocumentId(arg)\n : arg));\n }\n const { documentId, heads = undefined } = arg;\n if (documentId === undefined)\n throw new Error(\"Invalid documentId: \" + documentId);\n const encodedDocumentId = documentId instanceof Uint8Array\n ? binaryToDocumentId(documentId)\n : documentId;\n let url = `${urlPrefix}${encodedDocumentId}`;\n if (heads !== undefined) {\n heads.forEach(head => {\n try {\n bs58check.decode(head);\n }\n catch (e) {\n throw new Error(`Invalid head: ${head}`);\n }\n });\n url += \"#\" + heads.join(\"|\");\n }\n return url;\n};\n/** Helper to extract just the heads from a URL if they exist */\nexport const getHeadsFromUrl = (url) => {\n const { heads } = parseAutomergeUrl(url);\n return heads;\n};\nexport const anyDocumentIdToAutomergeUrl = (id) => isValidAutomergeUrl(id)\n ? id\n : isValidDocumentId(id)\n ? stringifyAutomergeUrl({ documentId: id })\n : isValidUuid(id)\n ? parseLegacyUUID(id)\n : undefined;\n/**\n * Given a string, returns true if it is a valid Automerge URL. This function also acts as a type\n * discriminator in Typescript.\n */\nexport const isValidAutomergeUrl = (str) => {\n if (typeof str !== \"string\" || !str || !str.startsWith(urlPrefix))\n return false;\n try {\n const { documentId, heads } = parseAutomergeUrl(str);\n if (!isValidDocumentId(documentId))\n return false;\n if (heads &&\n !heads.every(head => {\n try {\n bs58check.decode(head);\n return true;\n }\n catch {\n return false;\n }\n }))\n return false;\n return true;\n }\n catch {\n return false;\n }\n};\nexport const isValidDocumentId = (str) => {\n if (typeof str !== \"string\")\n return false;\n // try to decode from base58\n const binaryDocumentID = documentIdToBinary(str);\n return binaryDocumentID !== undefined;\n};\nexport const isValidUuid = (str) => typeof str === \"string\" && Uuid.validate(str);\n/**\n * Returns a new Automerge URL with a random UUID documentId. Called by Repo.create(), and also used by tests.\n */\nexport const generateAutomergeUrl = () => {\n const documentId = Uuid.v4(null, new Uint8Array(16));\n return stringifyAutomergeUrl({ documentId });\n};\nexport const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId);\nexport const binaryToDocumentId = (docId) => bs58check.encode(docId);\nexport const encodeHeads = (heads) => heads.map(h => bs58check.encode(uint8ArrayFromHexString(h)));\nexport const decodeHeads = (heads) => heads.map(h => uint8ArrayToHexString(bs58check.decode(h)));\nexport const parseLegacyUUID = (str) => {\n if (!Uuid.validate(str))\n return undefined;\n const documentId = Uuid.parse(str);\n return stringifyAutomergeUrl({ documentId });\n};\n/**\n * Given any valid expression of a document ID, returns a DocumentId in base58check-encoded form.\n *\n * Currently supports:\n * - base58check-encoded DocumentId\n * - Automerge URL\n * - legacy UUID\n * - binary DocumentId\n *\n * Throws on invalid input.\n */\nexport const interpretAsDocumentId = (id) => {\n // binary\n if (id instanceof Uint8Array)\n return binaryToDocumentId(id);\n // url\n if (isValidAutomergeUrl(id))\n return parseAutomergeUrl(id).documentId;\n // base58check\n if (isValidDocumentId(id))\n return id;\n // legacy UUID\n if (isValidUuid(id)) {\n console.warn(\"Future versions will not support UUIDs as document IDs; use Automerge URLs instead.\");\n const binaryDocumentID = Uuid.parse(id);\n return binaryToDocumentId(binaryDocumentID);\n }\n // none of the above\n throw new Error(`Invalid AutomergeUrl: '${id}'`);\n};\n", "import { AnyDocumentId, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { useRepo } from \"./useRepo.js\"\nimport { useEffect, useRef, useState } from \"react\"\nimport { anyDocumentIdToAutomergeUrl } from \"../../automerge-repo/dist/AutomergeUrl.js\"\n\n// Shared with useDocHandles\nexport const wrapperCache = new Map<\n AnyDocumentId,\n PromiseWrapper<DocHandle<unknown>>\n>()\n// NB: this is a global cache that isn't keyed on the Repo\n// so if your app uses the same documents in two Repos\n// this could cause problems. please let me know if you do.\n\ninterface UseDocHandleSuspendingParams {\n suspense: true\n}\ninterface UseDocHandleSynchronousParams {\n suspense: false\n}\n\ntype UseDocHandleParams =\n | UseDocHandleSuspendingParams\n | UseDocHandleSynchronousParams\n\nexport function useDocHandle<T>(\n id: AnyDocumentId,\n params: UseDocHandleSuspendingParams\n): DocHandle<T>\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocHandleSynchronousParams\n): DocHandle<T> | undefined\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n { suspense }: UseDocHandleParams = { suspense: false }\n): DocHandle<T> | undefined {\n const repo = useRepo()\n const controllerRef = useRef<AbortController>()\n const [handle, setHandle] = useState<DocHandle<T> | undefined>()\n\n let currentHandle: DocHandle<T> | undefined =\n // make sure the handle matches the id\n id && handle && handle.url === anyDocumentIdToAutomergeUrl(id)\n ? handle\n : undefined\n\n if (id && !currentHandle) {\n // if we haven't saved a handle yet, check if one is immediately available\n const progress = repo.findWithProgress<T>(id)\n const state = progress.peek()\n if (state.state === \"ready\") {\n currentHandle = state.handle\n }\n }\n\n let wrapper = id ? wrapperCache.get(id) : undefined\n if (!wrapper && id) {\n controllerRef.current?.abort()\n controllerRef.current = new AbortController()\n\n const promise = repo.find<T>(id, { signal: controllerRef.current.signal })\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n }\n\n /* From here we split into two paths: suspense and not.\n * In the suspense path, we return the wrapper directly.\n * In the non-suspense path, we wait for the promise to resolve\n * and then set the handle via setState. Suspense relies on\n * re-running this function until it succeeds, whereas the synchronous\n * form uses a setState to track the value. */\n useEffect(() => {\n if (currentHandle || suspense || !wrapper) {\n return\n }\n wrapper.promise\n .then(handle => {\n setHandle(handle as DocHandle<T>)\n })\n .catch(() => {\n setHandle(undefined)\n })\n }, [currentHandle, suspense, wrapper])\n\n if (currentHandle || !suspense || !wrapper) {\n return currentHandle\n }\n\n return wrapper.read() as DocHandle<T>\n}\n", "import { AnyDocumentId } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandle } from \"./useDocHandle.js\"\n\n/**\n * A hook which returns a document and a function to change it.\n * Uses React Suspense for loading states, returning a tuple matching useState pattern.\n *\n * @example\n * ```tsx\n * function Counter() {\n * const [doc, changeDoc] = useDocument<{ count: number }>(docUrl)\n * return (\n * <button onClick={() => changeDoc(d => d.count++)}>\n * Count: {doc.count}\n * </button>\n * )\n * }\n *\n * // Must be wrapped in Suspense boundary\n * <Suspense fallback={<Loading />}>\n * <Counter />\n * </Suspense>\n * ```\n */\n\ninterface UseDocumentSuspendingParams {\n suspense: true\n}\ninterface UseDocumentSynchronousParams {\n suspense: false\n}\n\ntype UseDocumentParams =\n | UseDocumentSuspendingParams\n | UseDocumentSynchronousParams\n\nexport type UseDocumentReturn<T> = [\n Doc<T>,\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => void\n]\n\nexport function useDocument<T>(\n id: AnyDocumentId,\n params: UseDocumentSuspendingParams\n): UseDocumentReturn<T>\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocumentSynchronousParams\n): UseDocumentReturn<T> | [undefined, () => void]\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params: UseDocumentParams = { suspense: false }\n): UseDocumentReturn<T> | [undefined, () => void] {\n // @ts-expect-error -- typescript doesn't realize we're discriminating these types the same way in both functions\n const handle = useDocHandle<T>(id, params)\n // Initialize with current doc state\n const [doc, setDoc] = useState<Doc<T> | undefined>(() => handle?.doc())\n const [deleteError, setDeleteError] = useState<Error>()\n\n // Reinitialize doc when handle changes\n useEffect(() => {\n setDoc(handle?.doc())\n }, [handle])\n\n useEffect(() => {\n if (!handle) {\n return\n }\n const onChange = () => setDoc(handle.doc())\n const onDelete = () => {\n setDeleteError(new Error(`Document ${id} was deleted`))\n }\n\n handle.on(\"change\", onChange)\n handle.on(\"delete\", onDelete)\n\n return () => {\n handle.removeListener(\"change\", onChange)\n handle.removeListener(\"delete\", onDelete)\n }\n }, [handle, id])\n\n const changeDoc = useCallback(\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n handle!.change(changeFn, options)\n },\n [handle]\n )\n\n if (deleteError) {\n throw deleteError\n }\n\n if (!doc) {\n return [undefined, () => {}]\n }\n return [doc, changeDoc]\n}\n", "import { useEffect, useState } from \"react\"\n\nexport function useSet<T>(items: T[]): Set<T> {\n const [set, setSet] = useState<Set<T>>(() => {\n return new Set<T>(items)\n })\n useEffect(() => {\n const newSet = new Set(items)\n if (identical(set, newSet)) {\n return\n }\n setSet(newSet)\n }, [set, items])\n return set\n}\n\nfunction identical<T>(s1: Set<T>, s2: Set<T>) {\n return s1.size === s2.size && Array.from(s1).every(v => s2.has(v))\n}\n", "import { AutomergeUrl, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { useState, useEffect } from \"react\"\nimport { useRepo } from \"./useRepo.js\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { wrapperCache } from \"./useDocHandle.js\"\nimport { useSet } from \"./helpers/useSet.js\"\n\ninterface UseDocHandlesParams {\n suspense?: boolean\n}\n\ntype DocHandleMap<T> = Map<AutomergeUrl, DocHandle<T> | undefined>\n\nexport function useDocHandles<T>(\n ids: AutomergeUrl[],\n { suspense = false }: UseDocHandlesParams = {}\n): DocHandleMap<T> {\n const idSet = useSet(ids)\n const repo = useRepo()\n const [handleMap, setHandleMap] = useState<DocHandleMap<T>>(() => {\n const map = new Map()\n\n // Initialize the map with any handles that are ready\n for (const id of idSet.values()) {\n let progress\n try {\n progress = repo.findWithProgress<T>(id)\n } catch (e) {\n continue\n }\n\n const state = progress.peek()\n if (state.state === \"ready\") {\n map.set(id, state.handle)\n }\n }\n\n return map\n })\n\n const pendingPromises: PromiseWrapper<DocHandle<T>>[] = []\n const nextHandleMap = new Map<AutomergeUrl, DocHandle<T> | undefined>()\n\n // Check if we need any new wrappers\n for (const id of idSet.values()) {\n let handle = handleMap.get(id)\n let wrapper = wrapperCache.get(id)\n if (!wrapper) {\n try {\n const promise = repo.find<T>(id)\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n } catch (e) {\n continue\n }\n }\n\n // Try to read each wrapper.\n // Update handleMap with any available handles,\n // and collect any pending promises\n try {\n handle ??= wrapper.read() as DocHandle<T>\n nextHandleMap.set(id, handle)\n } catch (e) {\n if (e instanceof Promise) {\n pendingPromises.push(wrapper as PromiseWrapper<DocHandle<T>>)\n } else {\n nextHandleMap.set(id, undefined)\n }\n }\n }\n\n // Suspense is handled quasi-synchronously below by throwing if we still have\n // unresolved promises.\n useEffect(() => {\n if (pendingPromises.length > 0) {\n void Promise.allSettled(pendingPromises.map(p => p.promise)).then(\n handles => {\n handles.forEach(r => {\n if (r.status === \"fulfilled\") {\n const h = r.value as DocHandle<T>\n nextHandleMap.set(h.url, h)\n }\n })\n setHandleMap(nextHandleMap)\n }\n )\n } else {\n setHandleMap(nextHandleMap)\n }\n }, [suspense, idSet])\n\n // If any promises are pending, suspend with Promise.all\n // Note that this behaviour is different from the synchronous\n // form where we get gradual load-in of child documents.\n // I couldn't find an obvious way of incremental loading with\n // a single hook for suspense.\n // (But maybe with suspense this hook is less useful?)\n if (suspense && pendingPromises.length > 0) {\n throw Promise.all(pendingPromises.map(p => p.promise))\n }\n\n return handleMap\n}\n", "import { AutomergeUrl } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandles } from \"./useDocHandles.js\"\n\ntype DocMap<T> = Map<AutomergeUrl, Doc<T>>\ntype ChangeDocFn<T> = (\n id: AutomergeUrl,\n changeFn: ChangeFn<T>,\n options?: ChangeOptions<T>\n) => void\n\ninterface UseDocumentsOptions {\n suspense?: boolean\n}\n\nexport function useDocuments<T>(\n ids: AutomergeUrl[],\n { suspense = true }: UseDocumentsOptions = {}\n): [DocMap<T>, ChangeDocFn<T>] {\n const handleMap = useDocHandles<T>(ids, { suspense })\n const [docMap, setDocMap] = useState<DocMap<T>>(() => {\n const docs: DocMap<T> = new Map()\n handleMap.forEach(handle => {\n const url = handle?.url\n if (url) {\n docs.set(url, handle?.doc())\n }\n })\n return docs\n })\n\n useEffect(() => {\n const listeners = new Map<AutomergeUrl, () => void>()\n\n handleMap.forEach((handle, id) => {\n if (handle) {\n const onChange = () => {\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc())\n return next\n })\n }\n\n // Initial state\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc())\n return next\n })\n\n handle.on(\"change\", onChange)\n listeners.set(id, onChange)\n }\n })\n\n // Clear docs that are no longer in handleMap\n setDocMap(prev => {\n const next = new Map(prev)\n for (const [id] of next) {\n if (!handleMap.has(id)) {\n next.delete(id)\n }\n }\n return next\n })\n\n return () => {\n handleMap.forEach((handle, id) => {\n const listener = listeners.get(id)\n if (handle && listener) {\n handle.removeListener(\"change\", listener)\n }\n })\n }\n }, [handleMap])\n\n const changeDoc = useCallback(\n (id: AutomergeUrl, changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n const handle = handleMap.get(id)\n if (handle) {\n handle.change(changeFn, options)\n }\n },\n [handleMap]\n )\n\n return [docMap, changeDoc]\n}\n", "\"use strict\";\nvar react_1 = require(\"react\");\nvar isFunction = function (setStateAction) {\n return typeof setStateAction === \"function\";\n};\nvar useStateRef = function (initialState) {\n var _a = react_1.useState(initialState), state = _a[0], setState = _a[1];\n var ref = react_1.useRef(state);\n var dispatch = react_1.useCallback(function (setStateAction) {\n ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;\n setState(ref.current);\n }, []);\n return [state, dispatch, ref];\n};\nmodule.exports = useStateRef;\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "import {\n DocHandle,\n DocHandleEphemeralMessagePayload,\n} from \"@automerge/automerge-repo/slim\"\nimport { useEffect } from \"react\"\nimport useStateRef from \"react-usestateref\"\nimport { EventEmitter } from \"eventemitter3\"\n\n// Emits new_peer event when a new peer is seen\nexport const peerEvents = new EventEmitter()\n\nexport interface UseRemoteAwarenessProps<T> {\n /** The handle to receive ephemeral state on */\n handle?: DocHandle<T>\n /** Our user ID */\n localUserId?: string\n /** How long to wait (in ms) before marking a peer as offline */\n offlineTimeout?: number\n /** Function to provide current epoch time */\n getTime?: () => number\n}\n\n/** A map from peer ID to their state */\nexport type PeerStates = Record<string, any>\n/** A map from peer ID to their last heartbeat timestamp */\nexport type Heartbeats = Record<string, number>\n\n// {@link @microsoft/my-control-library/lib/Button#Button | the Button class}\n\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook returns read-only state for remote clients.\n * It also returns their heartbeat status.\n * It is intended to be used alongside useLocalAwareness.\n *\n * @param {string} props.handle A document handle to associate with\n * @param {string?} props.localUserId Automerge BroadcastChannel sometimes sends us our own messages; optionally filters them\n * @param {number?30000} props.offlineTimeout How long to wait (in ms) before marking a peer as offline\n * @param {function?} props.getTime Function to provide current epoch time (used for testing)\n * @returns [ peerStates: { [userId]: state, ... }, { [userId]: heartbeatEpochTime, ...} ]\n */\nexport const useRemoteAwareness = <T>({\n handle,\n localUserId,\n offlineTimeout = 30000,\n getTime = () => new Date().getTime(),\n}: UseRemoteAwarenessProps<T>): [PeerStates, Heartbeats] => {\n // TODO: You should be able to use multiple instances of this hook on the same handle (write test)\n // TODO: This should support some kind of caching or memoization when switching between channelIDs\n const [peerStates, setPeerStates, peerStatesRef] = useStateRef<PeerStates>({})\n const [heartbeats, setHeartbeats, heartbeatsRef] = useStateRef<Heartbeats>({})\n useEffect(() => {\n if (!handle) {\n return\n }\n\n // Receive incoming message\n const handleIncomingUpdate = (\n event: DocHandleEphemeralMessagePayload<T>\n ) => {\n const [userId, state] = event.message as [string, unknown]\n if (userId === localUserId) return\n if (!heartbeatsRef.current[userId]) peerEvents.emit(\"new_peer\", event) // Let useLocalAwareness know we've seen a new peer\n setPeerStates({\n ...peerStatesRef.current,\n [userId]: state,\n })\n setHeartbeats({\n ...heartbeatsRef.current,\n [userId]: getTime(),\n })\n }\n // Remove peers we haven't seen recently\n const pruneOfflinePeers = () => {\n const peerStates = { ...peerStatesRef.current }\n const heartbeats = { ...heartbeatsRef.current }\n const time = getTime()\n let hasChanges = false\n for (const key in heartbeats) {\n if (time - heartbeats[key] > offlineTimeout) {\n delete peerStates[key]\n delete heartbeats[key]\n hasChanges = true\n }\n }\n if (hasChanges) {\n setPeerStates(peerStates)\n setHeartbeats(heartbeats)\n }\n }\n handle.on(\"ephemeral-message\", handleIncomingUpdate)\n // Check for offline peers every `offlineTimeout` ms\n const pruneOfflinePeersIntervalId = setInterval(\n pruneOfflinePeers,\n offlineTimeout\n )\n return () => {\n handle.removeListener(\"ephemeral-message\", handleIncomingUpdate)\n clearInterval(pruneOfflinePeersIntervalId)\n }\n }, [handle, localUserId, offlineTimeout, getTime])\n\n return [peerStates, heartbeats]\n}\n", "import { useEffect } from \"react\"\nimport useStateRef from \"react-usestateref\"\nimport { peerEvents } from \"./useRemoteAwareness.js\"\nimport { DocHandle } from \"@automerge/automerge-repo/slim\"\n\nexport interface UseLocalAwarenessProps {\n /** The document handle to send ephemeral state on */\n handle?: DocHandle<unknown>\n /** Our user ID **/\n userId: string\n /** The initial state object/primitive we should advertise */\n initialState: any\n /** How frequently to send heartbeats */\n heartbeatTime?: number\n}\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook maintains state for the local client.\n * Like React.useState, it returns a [state, setState] array.\n * It is intended to be used alongside useRemoteAwareness.\n *\n * When state is changed it is broadcast to all clients.\n * It also broadcasts a heartbeat to let other clients know it is online.\n *\n * Note that userIds aren't secure (yet). Any client can lie about theirs.\n *\n * @param {string} props.userId Unique user ID. Clients can lie about this.\n * @param {any} props.initialState Initial state object/primitive\n * @param {number?1500} props.heartbeatTime How often to send a heartbeat (in ms)\n * @returns [state, setState]\n */\nexport const useLocalAwareness = ({\n handle,\n userId,\n initialState,\n heartbeatTime = 15000,\n}: UseLocalAwarenessProps) => {\n const [localState, setLocalState, localStateRef] = useStateRef(initialState)\n\n const setState = (stateOrUpdater: any) => {\n const state =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(localStateRef.current)\n : stateOrUpdater\n setLocalState(state)\n // TODO: Send deltas instead of entire state\n if (handle) {\n handle.broadcast([userId, state])\n }\n }\n\n useEffect(() => {\n // Don't broadcast if userId or handle isn't set: this avoids bogus broadcasts\n // during the loading of a userId document or handle.\n if (!userId || !handle) {\n return\n }\n\n // Send periodic heartbeats\n const heartbeat = () =>\n void handle.broadcast([userId, localStateRef.current])\n heartbeat() // Initial heartbeat\n // TODO: we don't need to send a heartbeat if we've changed state recently; use recursive setTimeout instead of setInterval\n const heartbeatIntervalId = setInterval(heartbeat, heartbeatTime)\n return () => void clearInterval(heartbeatIntervalId)\n }, [handle, userId, heartbeatTime])\n\n useEffect(() => {\n // Send entire state to new peers\n if (!handle || !userId) {\n return\n }\n\n let broadcastTimeoutId: ReturnType<typeof setTimeout>\n const newPeerEvents = peerEvents.on(\"new_peer\", () => {\n broadcastTimeoutId = setTimeout(\n () => handle.broadcast([userId, localStateRef.current]),\n 500 // Wait for the peer to be ready\n )\n })\n return () => {\n newPeerEvents.off(\"new_peer\")\n broadcastTimeoutId && clearTimeout(broadcastTimeoutId)\n }\n }, [handle, userId, peerEvents])\n\n // TODO: Send an \"offline\" message on unmount\n // useEffect(\n // () => () => void handle.broadcast(null), // Same as Yjs awareness\n // []\n // );\n\n return [localState, setState]\n}\n", "const MAX_I64 = BigInt(\"9223372036854775807\"); // 2n ** 63n - 1n;\n/**\n * Recursively validate a value before batch insertion. Checks for\n * - undefined values\n * - proxy references to the same document (common footgun)\n */\nexport function validateForBatchInsert(value, context, path) {\n if (value === undefined) {\n throw new RangeError([\n `Cannot assign undefined value at ${printPath(path)}, `,\n \"You might consider setting the property's value to `null`, \",\n \"or using `delete` to remove it altogether.\",\n ].join(\"\"));\n }\n if (value === null)\n return;\n const type = typeof value;\n if (type !== \"object\")\n return;\n if (context && isSameDocument(value, context)) {\n throw new RangeError(\"Cannot create a reference to an existing document object\");\n }\n if (value instanceof Array) {\n for (let i = 0; i < value.length; i++) {\n validateForBatchInsert(value[i], context, [...path, i]);\n }\n }\n else if (Object.prototype.toString.call(value) === \"[object Object]\") {\n for (const k in value) {\n validateForBatchInsert(value[k], context, [...path, k]);\n }\n }\n}\nimport { getWriteableCounter } from \"./counter.js\";\nimport { STATE, TRACE, IS_PROXY, OBJECT_ID, CLEAR_CACHE, COUNTER, INT, UINT, F64, IMMUTABLE_STRING, } from \"./constants.js\";\nimport { ImmutableString } from \"./immutable_string.js\";\nfunction parseListIndex(key) {\n if (typeof key === \"string\" && /^[0-9]+$/.test(key))\n key = parseInt(key, 10);\n if (typeof key !== \"number\") {\n return key;\n }\n if (key < 0 || isNaN(key) || key === Infinity || key === -Infinity) {\n throw new RangeError(\"A list index must be positive, but you passed \" + key);\n }\n return key;\n}\nfunction valueAt(target, prop) {\n const { context, objectId, path } = target;\n const value = context.getWithType(objectId, prop);\n if (value === null) {\n return;\n }\n const datatype = value[0];\n const val = value[1];\n switch (datatype) {\n case undefined:\n return;\n case \"map\":\n return mapProxy(context, val, [...path, prop]);\n case \"list\":\n return listProxy(context, val, [...path, prop]);\n case \"text\":\n return context.text(val);\n case \"str\":\n return new ImmutableString(val);\n case \"uint\":\n return val;\n case \"int\":\n return val;\n case \"f64\":\n return val;\n case \"boolean\":\n return val;\n case \"null\":\n return null;\n case \"bytes\":\n return val;\n case \"timestamp\":\n return val;\n case \"counter\": {\n const counter = getWriteableCounter(val, context, path, objectId, prop);\n return counter;\n }\n default:\n throw RangeError(`datatype ${datatype} unimplemented`);\n }\n}\nfunction import_value(value, path, context) {\n const type = typeof value;\n switch (type) {\n case \"object\":\n if (value == null) {\n return [null, \"null\"];\n }\n else if (value[UINT]) {\n return [value.value, \"uint\"];\n }\n else if (value[INT]) {\n return [value.value, \"int\"];\n }\n else if (value[F64]) {\n return [value.value, \"f64\"];\n }\n else if (value[COUNTER]) {\n return [value.value, \"counter\"];\n }\n else if (value instanceof Date) {\n return [value.getTime(), \"timestamp\"];\n }\n else if (isImmutableString(value)) {\n return [value.toString(), \"str\"];\n }\n else if (value instanceof Uint8Array) {\n return [value, \"bytes\"];\n }\n else if (value instanceof Array) {\n return [value, \"list\"];\n }\n else if (Object.prototype.toString.call(value) === \"[object Object]\") {\n return [value, \"map\"];\n }\n else if (isSameDocument(value, context)) {\n throw new RangeError(\"Cannot create a reference to an existing document object\");\n }\n else {\n throw new RangeError(`Cannot assign unknown object: ${value}`);\n }\n case \"boolean\":\n return [value, \"boolean\"];\n case \"bigint\":\n if (value > MAX_I64) {\n return [value, \"uint\"];\n }\n else {\n return [value, \"int\"];\n }\n case \"number\":\n if (Number.isInteger(value)) {\n return [value, \"int\"];\n }\n else {\n return [value, \"f64\"];\n }\n case \"string\":\n return [value, \"text\"];\n case \"undefined\":\n throw new RangeError([\n `Cannot assign undefined value at ${printPath(path)}, `,\n \"because `undefined` is not a valid JSON data type. \",\n \"You might consider setting the property's value to `null`, \",\n \"or using `delete` to remove it altogether.\",\n ].join(\"\"));\n default:\n throw new RangeError([\n `Cannot assign ${type} value at ${printPath(path)}. `,\n `All JSON primitive datatypes (object, array, string, number, boolean, null) `,\n `are supported in an Automerge document; ${type} values are not. `,\n ].join(\"\"));\n }\n}\n// When we assign a value to a property in a proxy we recursively walk through\n// the value we are assigning and copy it into the document. This is generally\n// desirable behaviour. However, a very common bug is to accidentally assign a\n// value which is already in the document to another key within the same\n// document, this often leads to surprising behaviour where users expected to\n// _move_ the object, but it is instead copied. To avoid this we check if the\n// value is from the same document and if it is we throw an error, this means\n// we require an explicit Object.assign call to copy the object, thus avoiding\n// the footgun\nfunction isSameDocument(val, context) {\n var _b, _c;\n // Date is technically an object, but immutable, so allowing people to assign\n // a date from one place in the document to another place in the document is\n // not likely to be a bug\n if (val instanceof Date) {\n return false;\n }\n // this depends on __wbg_ptr being the wasm pointer\n // a new version of wasm-bindgen will break this\n // but the tests should expose the break\n if (val && ((_c = (_b = val[STATE]) === null || _b === void 0 ? void 0 : _b.handle) === null || _c === void 0 ? void 0 : _c.__wbg_ptr) === context.__wbg_ptr) {\n return true;\n }\n return false;\n}\nconst MapHandler = {\n get(target, key) {\n const { context, objectId, cache } = target;\n if (key === Symbol.toStringTag) {\n return target[Symbol.toStringTag];\n }\n if (key === OBJECT_ID)\n return objectId;\n if (key === IS_PROXY)\n return true;\n if (key === TRACE)\n return target.trace;\n if (key === STATE)\n return { handle: context };\n if (!cache[key]) {\n cache[key] = valueAt(target, key);\n }\n return cache[key];\n },\n set(target, key, val) {\n const { context, objectId, path } = target;\n target.cache = {}; // reset cache on set\n if (isSameDocument(val, context)) {\n throw new RangeError(\"Cannot create a reference to an existing document object\");\n }\n if (key === TRACE) {\n target.trace = val;\n return true;\n }\n if (key === CLEAR_CACHE) {\n return true;\n }\n const [value, datatype] = import_value(val, [...path, key], context);\n switch (datatype) {\n case \"list\":\n case \"map\": {\n validateForBatchInsert(value, context, [...path, key]);\n context.putObjectFromHydrate(objectId, key, value);\n break;\n }\n case \"text\": {\n context.putObject(objectId, key, value);\n break;\n }\n default:\n context.put(objectId, key, value, datatype);\n }\n return true;\n },\n deleteProperty(target, key) {\n const { context, objectId } = target;\n target.cache = {}; // reset cache on delete\n context.delete(objectId, key);\n return true;\n },\n has(target, key) {\n const value = this.get(target, key);\n return value !== undefined;\n },\n getOwnPropertyDescriptor(target, key) {\n // const { context, objectId } = target\n const value = this.get(target, key);\n if (typeof value !== \"undefined\") {\n return {\n configurable: true,\n enumerable: true,\n value,\n };\n }\n },\n ownKeys(target) {\n const { context, objectId } = target;\n // FIXME - this is a tmp workaround until fix the dupe key bug in keys()\n const keys = context.keys(objectId);\n return [...new Set(keys)];\n },\n};\nconst ListHandler = {\n get(target, index) {\n const { context, objectId } = target;\n index = parseListIndex(index);\n if (index === Symbol.hasInstance) {\n return (instance) => {\n return Array.isArray(instance);\n };\n }\n if (index === Symbol.toStringTag) {\n return target[Symbol.toStringTag];\n }\n if (index === OBJECT_ID)\n return objectId;\n if (index === IS_PROXY)\n return true;\n if (index === TRACE)\n return target.trace;\n if (index === STATE)\n return { handle: context };\n if (index === \"length\")\n return context.length(objectId);\n if (typeof index === \"number\") {\n return valueAt(target, index);\n }\n else {\n return listMethods(target)[index];\n }\n },\n set(target, index, val) {\n const { context, objectId, path } = target;\n index = parseListIndex(index);\n if (isSameDocument(val, context)) {\n throw new RangeError(\"Cannot create a reference to an existing document object\");\n }\n if (index === CLEAR_CACHE) {\n return true;\n }\n if (index === TRACE) {\n target.trace = val;\n return true;\n }\n if (typeof index == \"string\") {\n throw new RangeError(\"list index must be a number\");\n }\n const [value, datatype] = import_value(val, [...path, index], context);\n switch (datatype) {\n case \"list\":\n case \"map\": {\n validateForBatchInsert(value, context, [...path, index]);\n if (index >= context.length(objectId)) {\n context.insertObjectFromHydrate(objectId, index, value);\n }\n else {\n context.putObjectFromHydrate(objectId, index, value);\n }\n break;\n }\n case \"text\": {\n if (index >= context.length(objectId)) {\n context.insertObject(objectId, index, value);\n }\n else {\n context.putObject(objectId, index, value);\n }\n break;\n }\n default:\n if (index >= context.length(objectId)) {\n context.insert(objectId, index, value, datatype);\n }\n else {\n context.put(objectId, index, value, datatype);\n }\n }\n return true;\n },\n deleteProperty(target, index) {\n const { context, objectId } = target;\n index = parseListIndex(index);\n const elem = context.get(objectId, index);\n if (elem != null && elem[0] == \"counter\") {\n throw new TypeError(\"Unsupported operation: deleting a counter from a list\");\n }\n context.delete(objectId, index);\n return true;\n },\n has(target, index) {\n const { context, objectId } = target;\n index = parseListIndex(index);\n if (typeof index === \"number\") {\n return index < context.length(objectId);\n }\n return index === \"length\";\n },\n getOwnPropertyDescriptor(target, index) {\n const { context, objectId } = target;\n if (index === \"length\")\n return { writable: true, value: context.length(objectId) };\n if (index === OBJECT_ID)\n return { configurable: false, enumerable: false, value: objectId };\n index = parseListIndex(index);\n const value = valueAt(target, index);\n return { configurable: true, enumerable: true, value };\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target);\n },\n ownKeys( /*target*/) {\n const keys = [];\n // uncommenting this causes assert.deepEqual() to fail when comparing to a pojo array\n // but not uncommenting it causes for (i in list) {} to not enumerate values properly\n //const {context, objectId } = target\n //for (let i = 0; i < target.context.length(objectId); i++) { keys.push(i.toString()) }\n keys.push(\"length\");\n return keys;\n },\n};\nexport function mapProxy(context, objectId, path) {\n const target = {\n context,\n objectId,\n path: path || [],\n cache: {},\n };\n const proxied = {};\n Object.assign(proxied, target);\n const result = new Proxy(proxied, MapHandler);\n // conversion through unknown is necessary because the types are so different\n return result;\n}\nexport function listProxy(context, objectId, path) {\n const target = {\n context,\n objectId,\n path: path || [],\n cache: {},\n };\n const proxied = [];\n Object.assign(proxied, target);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return new Proxy(proxied, ListHandler);\n}\nexport function rootProxy(context) {\n /* eslint-disable-next-line */\n return mapProxy(context, \"_root\", []);\n}\nfunction listMethods(target) {\n const { context, objectId, path } = target;\n const methods = {\n at(index) {\n return valueAt(target, index);\n },\n deleteAt(index, numDelete) {\n if (typeof numDelete === \"number\") {\n context.splice(objectId, index, numDelete);\n }\n else {\n context.delete(objectId, index);\n }\n return this;\n },\n fill(val, start, end) {\n const [value, datatype] = import_value(val, [...path, start], context);\n const length = context.length(objectId);\n start = parseListIndex(start || 0);\n end = parseListIndex(end || length);\n for (let i = start; i < Math.min(end, length); i++) {\n if (datatype === \"list\" || datatype === \"map\") {\n context.putObject(objectId, i, value);\n }\n else if (datatype === \"text\") {\n context.putObject(objectId, i, value);\n }\n else {\n context.put(objectId, i, value, datatype);\n }\n }\n return this;\n },\n indexOf(searchElement, start = 0) {\n const length = context.length(objectId);\n for (let i = start; i < length; i++) {\n const valueWithType = context.getWithType(objectId, i);\n if (!valueWithType) {\n continue;\n }\n const [valType, value] = valueWithType;\n // Either the target element is an object, and we return if we have found\n // the same object or it is a primitive value and we return if it matches\n // the current value\n const isObject = [\"map\", \"list\", \"text\"].includes(valType);\n if (!isObject) {\n // If the element is not an object, then check if the value is equal to the target\n if (value === searchElement) {\n return i;\n }\n else {\n continue;\n }\n }\n // if it's an object, but the type of the search element is a string, then we\n // need to check if the object is a text object with the same value as the search element\n if (valType === \"text\" && typeof searchElement === \"string\") {\n if (searchElement === valueAt(target, i)) {\n return i;\n }\n }\n // The only possible match now is if the searchElement is an object already in the\n // automerge document with the same object ID as the value\n if (searchElement[OBJECT_ID] === value) {\n return i;\n }\n }\n return -1;\n },\n insertAt(index, ...values) {\n this.splice(index, 0, ...values);\n return this;\n },\n pop() {\n const length = context.length(objectId);\n if (length == 0) {\n return undefined;\n }\n const last = valueAt(target, length - 1);\n context.delete(objectId, length - 1);\n return last;\n },\n push(...values) {\n const len = context.length(objectId);\n this.splice(len, 0, ...values);\n return context.length(objectId);\n },\n shift() {\n if (context.length(objectId) == 0)\n return;\n const first = valueAt(target, 0);\n context.delete(objectId, 0);\n return first;\n },\n splice(index, del, ...vals) {\n index = parseListIndex(index);\n // if del is undefined, delete until the end of the list\n if (typeof del !== \"number\") {\n del = context.length(objectId) - index;\n }\n del = parseListIndex(del);\n for (const val of vals) {\n if (isSameDocument(val, context)) {\n throw new RangeError(\"Cannot create a reference to an existing document object\");\n }\n }\n // Read values to be deleted (for return value) before mutating\n const result = [];\n for (let i = 0; i < del; i++) {\n const value = valueAt(target, index + i);\n if (value !== undefined) {\n result.push(value);\n }\n }\n // Validate all values before the WASM call\n for (let i = 0; i < vals.length; i++) {\n try {\n validateForBatchInsert(vals[i], context, [...path, index + i]);\n }\n catch (e) {\n if (e instanceof RangeError) {\n throw new RangeError(`${e.message} (at index ${i} in the input)`);\n }\n else {\n throw e;\n }\n }\n }\n // Single WASM call for both deletes and inserts\n context.spliceFromHydrate(objectId, index, del, vals);\n return result;\n },\n unshift(...values) {\n this.splice(0, 0, ...values);\n return context.length(objectId);\n },\n entries() {\n let i = 0;\n const iterator = {\n next: () => {\n const value = valueAt(target, i);\n if (value === undefined) {\n return { value: undefined, done: true };\n }\n else {\n return { value: [i++, value], done: false };\n }\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n return iterator;\n },\n keys() {\n let i = 0;\n const len = context.length(objectId);\n const iterator = {\n next: () => {\n if (i < len) {\n return { value: i++, done: false };\n }\n return { value: undefined, done: true };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n return iterator;\n },\n values() {\n let i = 0;\n const iterator = {\n next: () => {\n const value = valueAt(target, i++);\n if (value === undefined) {\n return { value: undefined, done: true };\n }\n else {\n return { value, done: false };\n }\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n return iterator;\n },\n toArray() {\n const list = [];\n let value;\n do {\n value = valueAt(target, list.length);\n if (value !== undefined) {\n list.push(value);\n }\n } while (value !== undefined);\n return list;\n },\n map(f) {\n return this.toArray().map(f);\n },\n toString() {\n return this.toArray().toString();\n },\n toLocaleString() {\n return this.toArray().toLocaleString();\n },\n forEach(f) {\n return this.toArray().forEach(f);\n },\n // todo: real concat function is different\n concat(other) {\n return this.toArray().concat(other);\n },\n every(f) {\n return this.toArray().every(f);\n },\n filter(f) {\n return this.toArray().filter(f);\n },\n find(f) {\n let index = 0;\n for (const v of this) {\n if (f(v, index)) {\n return v;\n }\n index += 1;\n }\n },\n findIndex(f) {\n let index = 0;\n for (const v of this) {\n if (f(v, index)) {\n return index;\n }\n index += 1;\n }\n return -1;\n },\n includes(elem) {\n return this.find(e => e === elem) !== undefined;\n },\n join(sep) {\n return this.toArray().join(sep);\n },\n reduce(f, initialValue) {\n return this.toArray().reduce(f, initialValue);\n },\n reduceRight(f, initialValue) {\n return this.toArray().reduceRight(f, initialValue);\n },\n lastIndexOf(search, fromIndex = +Infinity) {\n // this can be faster\n return this.toArray().lastIndexOf(search, fromIndex);\n },\n slice(index, num) {\n return this.toArray().slice(index, num);\n },\n some(f) {\n let index = 0;\n for (const v of this) {\n if (f(v, index)) {\n return true;\n }\n index += 1;\n }\n return false;\n },\n [Symbol.iterator]: function* () {\n let i = 0;\n let value = valueAt(target, i);\n while (value !== undefined) {\n yield value;\n i += 1;\n value = valueAt(target, i);\n }\n },\n };\n return methods;\n}\nfunction textMethods(target) {\n const { context, objectId } = target;\n const methods = {\n set(index, value) {\n return (this[index] = value);\n },\n get(index) {\n return this[index];\n },\n toString() {\n return context.text(objectId).replace(//g, \"\");\n },\n toSpans() {\n const spans = [];\n let chars = \"\";\n const length = context.length(objectId);\n for (let i = 0; i < length; i++) {\n const value = this[i];\n if (typeof value === \"string\") {\n chars += value;\n }\n else {\n if (chars.length > 0) {\n spans.push(chars);\n chars = \"\";\n }\n spans.push(value);\n }\n }\n if (chars.length > 0) {\n spans.push(chars);\n }\n return spans;\n },\n toJSON() {\n return this.toString();\n },\n indexOf(o, start = 0) {\n const text = context.text(objectId);\n return text.indexOf(o, start);\n },\n insertAt(index, ...values) {\n if (values.every(v => typeof v === \"string\")) {\n context.splice(objectId, index, 0, values.join(\"\"));\n }\n else {\n listMethods(target).insertAt(index, ...values);\n }\n },\n };\n return methods;\n}\nfunction printPath(path) {\n // print the path as a json pointer\n const jsonPointerComponents = path.map(component => {\n // if its a number just turn it into a string\n if (typeof component === \"number\") {\n return component.toString();\n }\n else if (typeof component === \"string\") {\n // otherwise we have to escape `/` and `~` characters\n return component.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n }\n });\n if (path.length === 0) {\n return \"\";\n }\n else {\n return \"/\" + jsonPointerComponents.join(\"/\");\n }\n}\n/*\n * Check if an object is a {@link ImmutableString}\n */\nexport function isImmutableString(obj) {\n // We used to determine whether something was a ImmutableString by doing an instanceof check, but\n // this doesn't work if the automerge module is loaded twice somehow. Instead, use the presence\n // of a symbol to determine if something is a ImmutableString\n return (typeof obj === \"object\" &&\n obj !== null &&\n Object.prototype.hasOwnProperty.call(obj, IMMUTABLE_STRING));\n}\nexport function isCounter(obj) {\n // We used to determine whether something was a Counter by doing an instanceof check, but\n // this doesn't work if the automerge module is loaded twice somehow. Instead, use the presence\n // of a symbol to determine if something is a Counter\n return (typeof obj === \"object\" &&\n obj !== null &&\n Object.prototype.hasOwnProperty.call(obj, COUNTER));\n}\n", "/* @ts-self-types=\"./automerge_wasm.d.ts\" */\n\nexport class Automerge {\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(Automerge.prototype);\n obj.__wbg_ptr = ptr;\n AutomergeFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n AutomergeFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_automerge_free(ptr, 0);\n }\n /**\n * @param {any} object\n * @param {any} meta\n * @returns {any}\n */\n applyAndReturnPatches(object, meta) {\n const ret = wasm.automerge_applyAndReturnPatches(this.__wbg_ptr, object, meta);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Change[]} changes\n */\n applyChanges(changes) {\n const ret = wasm.automerge_applyChanges(this.__wbg_ptr, changes);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {any} object\n * @param {any} meta\n * @returns {any}\n */\n applyPatches(object, meta) {\n const ret = wasm.automerge_applyPatches(this.__wbg_ptr, object, meta);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {string | null} [actor]\n * @returns {Automerge}\n */\n clone(actor) {\n var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len0 = WASM_VECTOR_LEN;\n const ret = wasm.automerge_clone(this.__wbg_ptr, ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return Automerge.__wrap(ret[0]);\n }\n /**\n * @param {string | null} [message]\n * @param {number | null} [time]\n * @returns {Hash | null}\n */\n commit(message, time) {\n var ptr0 = isLikeNone(message) ? 0 : passStringToWasm0(message, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len0 = WASM_VECTOR_LEN;\n const ret = wasm.automerge_commit(this.__wbg_ptr, ptr0, len0, !isLikeNone(time), isLikeNone(time) ? 0 : time);\n return ret;\n }\n /**\n * @param {ObjID} obj\n * @param {Prop} prop\n */\n delete(obj, prop) {\n const ret = wasm.automerge_delete(this.__wbg_ptr, obj, prop);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {Heads} before\n * @param {Heads} after\n * @returns {Patch[]}\n */\n diff(before, after) {\n const ret = wasm.automerge_diff(this.__wbg_ptr, before, after);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {Patch[]}\n */\n diffIncremental() {\n const ret = wasm.automerge_diffIncremental(this.__wbg_ptr);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Prop[] | string} path\n * @param {Heads} before\n * @param {Heads} after\n * @param {any} options\n * @returns {Array<any>}\n */\n diffPath(path, before, after, options) {\n const ret = wasm.automerge_diffPath(this.__wbg_ptr, path, before, after, options);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n dump() {\n wasm.automerge_dump(this.__wbg_ptr);\n }\n /**\n * @param {string | null} [message]\n * @param {number | null} [time]\n * @returns {Hash}\n */\n emptyChange(message, time) {\n var ptr0 = isLikeNone(message) ? 0 : passStringToWasm0(message, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len0 = WASM_VECTOR_LEN;\n const ret = wasm.automerge_emptyChange(this.__wbg_ptr, ptr0, len0, !isLikeNone(time), isLikeNone(time) ? 0 : time);\n return ret;\n }\n /**\n * @param {boolean} enable\n * @returns {boolean}\n */\n enableFreeze(enable) {\n const ret = wasm.automerge_enableFreeze(this.__wbg_ptr, enable);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return ret[0] !== 0;\n }\n /**\n * @param {string | null | undefined} actor\n * @param {any} heads\n * @returns {Automerge}\n */\n fork(actor, heads) {\n var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len0 = WASM_VECTOR_LEN;\n const ret = wasm.automerge_fork(this.__wbg_ptr, ptr0, len0, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return Automerge.__wrap(ret[0]);\n }\n /**\n * @param {SyncState} state\n * @returns {SyncMessage | null}\n */\n generateSyncMessage(state) {\n _assertClass(state, SyncState);\n const ret = wasm.automerge_generateSyncMessage(this.__wbg_ptr, state.__wbg_ptr);\n return ret;\n }\n /**\n * @param {any} obj\n * @param {any} prop\n * @param {any} heads\n * @returns {any}\n */\n get(obj, prop, heads) {\n const ret = wasm.automerge_get(this.__wbg_ptr, obj, prop, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {Actor}\n */\n getActorId() {\n let deferred1_0;\n let deferred1_1;\n try {\n const ret = wasm.automerge_getActorId(this.__wbg_ptr);\n deferred1_0 = ret[0];\n deferred1_1 = ret[1];\n return getStringFromWasm0(ret[0], ret[1]);\n } finally {\n wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);\n }\n }\n /**\n * @param {any} obj\n * @param {any} arg\n * @param {any} heads\n * @returns {Array<any>}\n */\n getAll(obj, arg, heads) {\n const ret = wasm.automerge_getAll(this.__wbg_ptr, obj, arg, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} text\n * @param {number} index\n * @param {any} heads\n * @returns {any}\n */\n getBlock(text, index, heads) {\n const ret = wasm.automerge_getBlock(this.__wbg_ptr, text, index, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Hash} hash\n * @returns {Change | null}\n */\n getChangeByHash(hash) {\n const ret = wasm.automerge_getChangeByHash(this.__wbg_ptr, hash);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Hash} hash\n * @returns {ChangeMetadata | null}\n */\n getChangeMetaByHash(hash) {\n const ret = wasm.automerge_getChangeMetaByHash(this.__wbg_ptr, hash);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Heads} have_deps\n * @returns {Change[]}\n */\n getChanges(have_deps) {\n const ret = wasm.automerge_getChanges(this.__wbg_ptr, have_deps);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Automerge} other\n * @returns {Change[]}\n */\n getChangesAdded(other) {\n _assertClass(other, Automerge);\n const ret = wasm.automerge_getChangesAdded(this.__wbg_ptr, other.__wbg_ptr);\n return ret;\n }\n /**\n * @param {Heads} have_deps\n * @returns {ChangeMetadata[]}\n */\n getChangesMeta(have_deps) {\n const ret = wasm.automerge_getChangesMeta(this.__wbg_ptr, have_deps);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} position\n * @param {any} heads\n * @param {any} move_cursor\n * @returns {string}\n */\n getCursor(obj, position, heads, move_cursor) {\n let deferred2_0;\n let deferred2_1;\n try {\n const ret = wasm.automerge_getCursor(this.__wbg_ptr, obj, position, heads, move_cursor);\n var ptr1 = ret[0];\n var len1 = ret[1];\n if (ret[3]) {\n ptr1 = 0; len1 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * @param {any} obj\n * @param {any} cursor\n * @param {any} heads\n * @returns {number}\n */\n getCursorPosition(obj, cursor, heads) {\n const ret = wasm.automerge_getCursorPosition(this.__wbg_ptr, obj, cursor, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return ret[0];\n }\n /**\n * @param {Hash} hash\n * @returns {DecodedChange | null}\n */\n getDecodedChangeByHash(hash) {\n const ret = wasm.automerge_getDecodedChangeByHash(this.__wbg_ptr, hash);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {Heads}\n */\n getHeads() {\n const ret = wasm.automerge_getHeads(this.__wbg_ptr);\n return ret;\n }\n /**\n * @returns {Change | null}\n */\n getLastLocalChange() {\n const ret = wasm.automerge_getLastLocalChange(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {any} heads\n * @returns {Array<any>}\n */\n getMissingDeps(heads) {\n const ret = wasm.automerge_getMissingDeps(this.__wbg_ptr, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} prop\n * @param {any} heads\n * @returns {any}\n */\n getWithType(obj, prop, heads) {\n const ret = wasm.automerge_getWithType(this.__wbg_ptr, obj, prop, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {SyncState} state\n * @returns {boolean}\n */\n hasOurChanges(state) {\n _assertClass(state, SyncState);\n const ret = wasm.automerge_hasOurChanges(this.__wbg_ptr, state.__wbg_ptr);\n return ret !== 0;\n }\n /**\n * @param {ObjID} obj\n * @param {Prop} prop\n * @param {number} value\n */\n increment(obj, prop, value) {\n const ret = wasm.automerge_increment(this.__wbg_ptr, obj, prop, value);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * Initialize the root object of an empty document from a JS object.\n * This is much faster than setting keys one at a time for large initial states.\n * @param {any} value\n */\n initRootFromHydrate(value) {\n const ret = wasm.automerge_initRootFromHydrate(this.__wbg_ptr, value);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {any} obj\n * @param {number} index\n * @param {any} value\n * @param {any} datatype\n */\n insert(obj, index, value, datatype) {\n const ret = wasm.automerge_insert(this.__wbg_ptr, obj, index, value, datatype);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {number} index\n * @param {ObjType} value\n * @returns {ObjID}\n */\n insertObject(obj, index, value) {\n let deferred2_0;\n let deferred2_1;\n try {\n const ret = wasm.automerge_insertObject(this.__wbg_ptr, obj, index, value);\n var ptr1 = ret[0];\n var len1 = ret[1];\n if (ret[3]) {\n ptr1 = 0; len1 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * Insert a nested JavaScript value into a list using batch insertion.\n * This is much faster than insertObject for large nested objects.\n * The value is inserted at the given index, shifting subsequent elements.\n * @param {ObjID} obj\n * @param {number} index\n * @param {any} value\n * @returns {ObjID}\n */\n insertObjectFromHydrate(obj, index, value) {\n const ret = wasm.automerge_insertObjectFromHydrate(this.__wbg_ptr, obj, index, value);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n integrate() {\n wasm.automerge_integrate(this.__wbg_ptr);\n }\n /**\n * @param {Heads} heads\n */\n isolate(heads) {\n const ret = wasm.automerge_isolate(this.__wbg_ptr, heads);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {number} index\n */\n joinBlock(obj, index) {\n const ret = wasm.automerge_joinBlock(this.__wbg_ptr, obj, index);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {Array<any>}\n */\n keys(obj, heads) {\n const ret = wasm.automerge_keys(this.__wbg_ptr, obj, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {number}\n */\n length(obj, heads) {\n const ret = wasm.automerge_length(this.__wbg_ptr, obj, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return ret[0];\n }\n /**\n * @param {Uint8Array} data\n * @returns {number}\n */\n loadIncremental(data) {\n const ret = wasm.automerge_loadIncremental(this.__wbg_ptr, data);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return ret[0];\n }\n /**\n * @param {any} obj\n * @param {any} range\n * @param {any} name\n * @param {any} value\n * @param {any} datatype\n */\n mark(obj, range, name, value, datatype) {\n const ret = wasm.automerge_mark(this.__wbg_ptr, obj, range, name, value, datatype);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {any}\n */\n marks(obj, heads) {\n const ret = wasm.automerge_marks(this.__wbg_ptr, obj, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {number} index\n * @param {any} heads\n * @returns {object}\n */\n marksAt(obj, index, heads) {\n const ret = wasm.automerge_marksAt(this.__wbg_ptr, obj, index, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @param {any} meta\n * @returns {any}\n */\n materialize(obj, heads, meta) {\n const ret = wasm.automerge_materialize(this.__wbg_ptr, obj, heads, meta);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {Automerge} other\n * @returns {Heads}\n */\n merge(other) {\n _assertClass(other, Automerge);\n const ret = wasm.automerge_merge(this.__wbg_ptr, other.__wbg_ptr);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {string | null} [actor]\n * @returns {Automerge}\n */\n static new(actor) {\n var ptr0 = isLikeNone(actor) ? 0 : passStringToWasm0(actor, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len0 = WASM_VECTOR_LEN;\n const ret = wasm.automerge_new(ptr0, len0);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return Automerge.__wrap(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {object}\n */\n objInfo(obj, heads) {\n const ret = wasm.automerge_objInfo(this.__wbg_ptr, obj, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {number}\n */\n pendingOps() {\n const ret = wasm.automerge_pendingOps(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {any} obj\n * @param {any} value\n * @param {any} datatype\n */\n push(obj, value, datatype) {\n const ret = wasm.automerge_push(this.__wbg_ptr, obj, value, datatype);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {ObjType} value\n * @returns {ObjID}\n */\n pushObject(obj, value) {\n let deferred2_0;\n let deferred2_1;\n try {\n const ret = wasm.automerge_pushObject(this.__wbg_ptr, obj, value);\n var ptr1 = ret[0];\n var len1 = ret[1];\n if (ret[3]) {\n ptr1 = 0; len1 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * @param {any} obj\n * @param {any} prop\n * @param {any} value\n * @param {any} datatype\n */\n put(obj, prop, value, datatype) {\n const ret = wasm.automerge_put(this.__wbg_ptr, obj, prop, value, datatype);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {Prop} prop\n * @param {ObjType} value\n * @returns {ObjID}\n */\n putObject(obj, prop, value) {\n const ret = wasm.automerge_putObject(this.__wbg_ptr, obj, prop, value);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * Put a nested JavaScript value as a new object tree using batch insertion.\n * This is much faster than putObject for large nested objects.\n * For map keys this overwrites any existing value. For list indices this\n * overwrites the element at that index.\n * @param {ObjID} obj\n * @param {Prop} prop\n * @param {any} value\n * @returns {ObjID}\n */\n putObjectFromHydrate(obj, prop, value) {\n const ret = wasm.automerge_putObjectFromHydrate(this.__wbg_ptr, obj, prop, value);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {SyncState} state\n * @param {SyncMessage} message\n */\n receiveSyncMessage(state, message) {\n _assertClass(state, SyncState);\n const ret = wasm.automerge_receiveSyncMessage(this.__wbg_ptr, state.__wbg_ptr, message);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {string} datatype\n * @param {Function} construct\n * @param {(arg: any) => any | undefined} deconstruct\n */\n registerDatatype(datatype, construct, deconstruct) {\n const ret = wasm.automerge_registerDatatype(this.__wbg_ptr, datatype, construct, deconstruct);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n resetDiffCursor() {\n wasm.automerge_resetDiffCursor(this.__wbg_ptr);\n }\n /**\n * @returns {number}\n */\n rollback() {\n const ret = wasm.automerge_rollback(this.__wbg_ptr);\n return ret;\n }\n /**\n * @returns {Uint8Array}\n */\n save() {\n const ret = wasm.automerge_save(this.__wbg_ptr);\n return ret;\n }\n /**\n * @returns {Uint8Array}\n */\n saveAndVerify() {\n const ret = wasm.automerge_saveAndVerify(this.__wbg_ptr);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} hashes\n * @returns {Uint8Array}\n */\n saveBundle(hashes) {\n const ret = wasm.automerge_saveBundle(this.__wbg_ptr, hashes);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {Uint8Array}\n */\n saveIncremental() {\n const ret = wasm.automerge_saveIncremental(this.__wbg_ptr);\n return ret;\n }\n /**\n * @returns {Uint8Array}\n */\n saveNoCompress() {\n const ret = wasm.automerge_saveNoCompress(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {Heads} heads\n * @returns {Uint8Array}\n */\n saveSince(heads) {\n const ret = wasm.automerge_saveSince(this.__wbg_ptr, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {Array<any>}\n */\n spans(obj, heads) {\n const ret = wasm.automerge_spans(this.__wbg_ptr, obj, heads);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @param {any} obj\n * @param {number} start\n * @param {number} delete_count\n * @param {any} text\n */\n splice(obj, start, delete_count, text) {\n const ret = wasm.automerge_splice(this.__wbg_ptr, obj, start, delete_count, text);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * Splice values into a list using batch insertion.\n * This is much faster than individual insert calls for multiple values.\n * @param {ObjID} obj\n * @param {number} index\n * @param {number} del\n * @param {any} values\n */\n spliceFromHydrate(obj, index, del, values) {\n const ret = wasm.automerge_spliceFromHydrate(this.__wbg_ptr, obj, index, del, values);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {number} index\n * @param {{[key: string]: MaterializeValue}} block\n */\n splitBlock(obj, index, block) {\n const ret = wasm.automerge_splitBlock(this.__wbg_ptr, obj, index, block);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @returns {Stats}\n */\n stats() {\n const ret = wasm.automerge_stats(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {any} obj\n * @param {any} heads\n * @returns {string}\n */\n text(obj, heads) {\n let deferred2_0;\n let deferred2_1;\n try {\n const ret = wasm.automerge_text(this.__wbg_ptr, obj, heads);\n var ptr1 = ret[0];\n var len1 = ret[1];\n if (ret[3]) {\n ptr1 = 0; len1 = 0;\n throw takeFromExternrefTable0(ret[2]);\n }\n deferred2_0 = ptr1;\n deferred2_1 = len1;\n return getStringFromWasm0(ptr1, len1);\n } finally {\n wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);\n }\n }\n /**\n * @param {any} meta\n * @returns {MaterializeValue}\n */\n toJS(meta) {\n const ret = wasm.automerge_toJS(this.__wbg_ptr, meta);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n }\n /**\n * @returns {Hash[]}\n */\n topoHistoryTraversal() {\n const ret = wasm.automerge_topoHistoryTraversal(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {ObjID} obj\n * @param {MarkRange} range\n * @param {string} name\n */\n unmark(obj, range, name) {\n const ret = wasm.automerge_unmark(this.__wbg_ptr, obj, range, name);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {number} index\n * @param {{[key: string]: MaterializeValue}} block\n */\n updateBlock(obj, index, block) {\n const ret = wasm.automerge_updateBlock(this.__wbg_ptr, obj, index, block);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n updateDiffCursor() {\n wasm.automerge_updateDiffCursor(this.__wbg_ptr);\n }\n /**\n * @param {ObjID} obj\n * @param {Span[]} args\n * @param {UpdateSpansConfig | undefined | null} config\n */\n updateSpans(obj, args, config) {\n const ret = wasm.automerge_updateSpans(this.__wbg_ptr, obj, args, config);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {ObjID} obj\n * @param {string} new_text\n */\n updateText(obj, new_text) {\n const ret = wasm.automerge_updateText(this.__wbg_ptr, obj, new_text);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n}\nif (Symbol.dispose) Automerge.prototype[Symbol.dispose] = Automerge.prototype.free;\n\nexport class SyncState {\n static __wrap(ptr) {\n ptr = ptr >>> 0;\n const obj = Object.create(SyncState.prototype);\n obj.__wbg_ptr = ptr;\n SyncStateFinalization.register(obj, obj.__wbg_ptr, obj);\n return obj;\n }\n __destroy_into_raw() {\n const ptr = this.__wbg_ptr;\n this.__wbg_ptr = 0;\n SyncStateFinalization.unregister(this);\n return ptr;\n }\n free() {\n const ptr = this.__destroy_into_raw();\n wasm.__wbg_syncstate_free(ptr, 0);\n }\n /**\n * @returns {SyncState}\n */\n clone() {\n const ret = wasm.syncstate_clone(this.__wbg_ptr);\n return SyncState.__wrap(ret);\n }\n /**\n * @returns {Heads}\n */\n get lastSentHeads() {\n const ret = wasm.syncstate_lastSentHeads(this.__wbg_ptr);\n return ret;\n }\n /**\n * @param {Heads} heads\n */\n set lastSentHeads(heads) {\n const ret = wasm.syncstate_set_lastSentHeads(this.__wbg_ptr, heads);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @param {Heads} hashes\n */\n set sentHashes(hashes) {\n const ret = wasm.syncstate_set_sentHashes(this.__wbg_ptr, hashes);\n if (ret[1]) {\n throw takeFromExternrefTable0(ret[0]);\n }\n }\n /**\n * @returns {Heads}\n */\n get sharedHeads() {\n const ret = wasm.syncstate_sharedHeads(this.__wbg_ptr);\n return ret;\n }\n}\nif (Symbol.dispose) SyncState.prototype[Symbol.dispose] = SyncState.prototype.free;\n\n/**\n * @param {any} options\n * @returns {Automerge}\n */\nexport function create(options) {\n const ret = wasm.create(options);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return Automerge.__wrap(ret[0]);\n}\n\n/**\n * @param {Uint8Array} change\n * @returns {DecodedChange}\n */\nexport function decodeChange(change) {\n const ret = wasm.decodeChange(change);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * @param {Uint8Array} msg\n * @returns {DecodedSyncMessage}\n */\nexport function decodeSyncMessage(msg) {\n const ret = wasm.decodeSyncMessage(msg);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * @param {Uint8Array} data\n * @returns {SyncState}\n */\nexport function decodeSyncState(data) {\n const ret = wasm.decodeSyncState(data);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return SyncState.__wrap(ret[0]);\n}\n\n/**\n * @param {any} change\n * @returns {Uint8Array}\n */\nexport function encodeChange(change) {\n const ret = wasm.encodeChange(change);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * @param {any} message\n * @returns {SyncMessage}\n */\nexport function encodeSyncMessage(message) {\n const ret = wasm.encodeSyncMessage(message);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * @param {SyncState} state\n * @returns {Uint8Array}\n */\nexport function encodeSyncState(state) {\n _assertClass(state, SyncState);\n const ret = wasm.encodeSyncState(state.__wbg_ptr);\n return ret;\n}\n\n/**\n * @param {SyncState} state\n * @returns {JsSyncState}\n */\nexport function exportSyncState(state) {\n _assertClass(state, SyncState);\n const ret = wasm.exportSyncState(state.__wbg_ptr);\n return ret;\n}\n\n/**\n * @param {any} state\n * @returns {SyncState}\n */\nexport function importSyncState(state) {\n const ret = wasm.importSyncState(state);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return SyncState.__wrap(ret[0]);\n}\n\n/**\n * @returns {SyncState}\n */\nexport function initSyncState() {\n const ret = wasm.initSyncState();\n return SyncState.__wrap(ret);\n}\n\n/**\n * @param {Uint8Array} data\n * @param {any} options\n * @returns {Automerge}\n */\nexport function load(data, options) {\n const ret = wasm.load(data, options);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return Automerge.__wrap(ret[0]);\n}\n\n/**\n * @param {Uint8Array} bundle\n * @returns {any}\n */\nexport function readBundle(bundle) {\n const ret = wasm.readBundle(bundle);\n if (ret[2]) {\n throw takeFromExternrefTable0(ret[1]);\n }\n return takeFromExternrefTable0(ret[0]);\n}\n\n/**\n * @returns {WasmReleaseInfo}\n */\nexport function wasmReleaseInfo() {\n const ret = wasm.wasmReleaseInfo();\n return ret;\n}\n\nfunction __wbg_get_imports() {\n const import0 = {\n __proto__: null,\n __wbg_BigInt_b7bbccdff258c9f2: function(arg0) {\n const ret = BigInt(arg0);\n return ret;\n },\n __wbg_Error_8c4e43fe74559d73: function(arg0, arg1) {\n const ret = Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_String_8f0eb39a4a4c2f66: function(arg0, arg1) {\n const ret = String(arg1);\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg___wbindgen_boolean_get_bbbb1c18aa2f5e25: function(arg0) {\n const v = arg0;\n const ret = typeof(v) === 'boolean' ? v : undefined;\n return isLikeNone(ret) ? 0xFFFFFF : ret ? 1 : 0;\n },\n __wbg___wbindgen_debug_string_0bc8482c6e3508ae: function(arg0, arg1) {\n const ret = debugString(arg1);\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg___wbindgen_gt_d7bb3629eac381f5: function(arg0, arg1) {\n const ret = arg0 > arg1;\n return ret;\n },\n __wbg___wbindgen_is_bigint_31b12575b56f32fc: function(arg0) {\n const ret = typeof(arg0) === 'bigint';\n return ret;\n },\n __wbg___wbindgen_is_function_0095a73b8b156f76: function(arg0) {\n const ret = typeof(arg0) === 'function';\n return ret;\n },\n __wbg___wbindgen_is_null_ac34f5003991759a: function(arg0) {\n const ret = arg0 === null;\n return ret;\n },\n __wbg___wbindgen_is_object_5ae8e5880f2c1fbd: function(arg0) {\n const val = arg0;\n const ret = typeof(val) === 'object' && val !== null;\n return ret;\n },\n __wbg___wbindgen_is_string_cd444516edc5b180: function(arg0) {\n const ret = typeof(arg0) === 'string';\n return ret;\n },\n __wbg___wbindgen_is_undefined_9e4d92534c42d778: function(arg0) {\n const ret = arg0 === undefined;\n return ret;\n },\n __wbg___wbindgen_jsval_loose_eq_9dd77d8cd6671811: function(arg0, arg1) {\n const ret = arg0 == arg1;\n return ret;\n },\n __wbg___wbindgen_lt_bb59cc3d23526e0d: function(arg0, arg1) {\n const ret = arg0 < arg1;\n return ret;\n },\n __wbg___wbindgen_neg_6b4d356dff49dcc6: function(arg0) {\n const ret = -arg0;\n return ret;\n },\n __wbg___wbindgen_number_get_8ff4255516ccad3e: function(arg0, arg1) {\n const obj = arg1;\n const ret = typeof(obj) === 'number' ? obj : undefined;\n getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);\n },\n __wbg___wbindgen_string_get_72fb696202c56729: function(arg0, arg1) {\n const obj = arg1;\n const ret = typeof(obj) === 'string' ? obj : undefined;\n var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg___wbindgen_throw_be289d5034ed271b: function(arg0, arg1) {\n throw new Error(getStringFromWasm0(arg0, arg1));\n },\n __wbg_apply_2e22c45cb4f12415: function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.apply(arg0, arg1, arg2);\n return ret;\n }, arguments); },\n __wbg_assign_6170c0d04d5c26f4: function(arg0, arg1) {\n const ret = Object.assign(arg0, arg1);\n return ret;\n },\n __wbg_call_389efe28435a9388: function() { return handleError(function (arg0, arg1) {\n const ret = arg0.call(arg1);\n return ret;\n }, arguments); },\n __wbg_call_4708e0c13bdc8e95: function() { return handleError(function (arg0, arg1, arg2) {\n const ret = arg0.call(arg1, arg2);\n return ret;\n }, arguments); },\n __wbg_concat_f6e5ebc81f4917f1: function(arg0, arg1) {\n const ret = arg0.concat(arg1);\n return ret;\n },\n __wbg_defineProperty_fc8692a66be8fe2d: function(arg0, arg1, arg2) {\n const ret = Object.defineProperty(arg0, arg1, arg2);\n return ret;\n },\n __wbg_deleteProperty_8c8a05da881fea59: function() { return handleError(function (arg0, arg1) {\n const ret = Reflect.deleteProperty(arg0, arg1);\n return ret;\n }, arguments); },\n __wbg_done_57b39ecd9addfe81: function(arg0) {\n const ret = arg0.done;\n return ret;\n },\n __wbg_entries_58c7934c745daac7: function(arg0) {\n const ret = Object.entries(arg0);\n return ret;\n },\n __wbg_error_7534b8e9a36f1ab4: function(arg0, arg1) {\n let deferred0_0;\n let deferred0_1;\n try {\n deferred0_0 = arg0;\n deferred0_1 = arg1;\n console.error(getStringFromWasm0(arg0, arg1));\n } finally {\n wasm.__wbindgen_free(deferred0_0, deferred0_1, 1);\n }\n },\n __wbg_for_c3adefd268cb6f1c: function(arg0, arg1) {\n const ret = Symbol.for(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_freeze_661d9047fd889cd0: function(arg0) {\n const ret = Object.freeze(arg0);\n return ret;\n },\n __wbg_from_bddd64e7d5ff6941: function(arg0) {\n const ret = Array.from(arg0);\n return ret;\n },\n __wbg_getRandomValues_1c61fac11405ffdc: function() { return handleError(function (arg0, arg1) {\n globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));\n }, arguments); },\n __wbg_getTime_1e3cd1391c5c3995: function(arg0) {\n const ret = arg0.getTime();\n return ret;\n },\n __wbg_get_9b94d73e6221f75c: function(arg0, arg1) {\n const ret = arg0[arg1 >>> 0];\n return ret;\n },\n __wbg_get_b3ed3ad4be2bc8ac: function() { return handleError(function (arg0, arg1) {\n const ret = Reflect.get(arg0, arg1);\n return ret;\n }, arguments); },\n __wbg_instanceof_ArrayBuffer_c367199e2fa2aa04: function(arg0) {\n let result;\n try {\n result = arg0 instanceof ArrayBuffer;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n },\n __wbg_instanceof_Date_1b9f15b87f10aa4c: function(arg0) {\n let result;\n try {\n result = arg0 instanceof Date;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n },\n __wbg_instanceof_Object_1c6af87502b733ed: function(arg0) {\n let result;\n try {\n result = arg0 instanceof Object;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n },\n __wbg_instanceof_Uint8Array_9b9075935c74707c: function(arg0) {\n let result;\n try {\n result = arg0 instanceof Uint8Array;\n } catch (_) {\n result = false;\n }\n const ret = result;\n return ret;\n },\n __wbg_isArray_a2cef7634fcb7c0d: function(arg0) {\n const ret = Array.isArray(arg0);\n return ret;\n },\n __wbg_isArray_d314bb98fcf08331: function(arg0) {\n const ret = Array.isArray(arg0);\n return ret;\n },\n __wbg_iterator_6ff6560ca1568e55: function() {\n const ret = Symbol.iterator;\n return ret;\n },\n __wbg_keys_b50a709a76add04e: function(arg0) {\n const ret = Object.keys(arg0);\n return ret;\n },\n __wbg_length_32ed9a279acd054c: function(arg0) {\n const ret = arg0.length;\n return ret;\n },\n __wbg_length_35a7bace40f36eac: function(arg0) {\n const ret = arg0.length;\n return ret;\n },\n __wbg_length_68dc7c5cf1b6d349: function(arg0) {\n const ret = arg0.length;\n return ret;\n },\n __wbg_log_6b5ca2e6124b2808: function(arg0) {\n console.log(arg0);\n },\n __wbg_log_b948c93e3e66d64f: function(arg0, arg1) {\n console.log(arg0, arg1);\n },\n __wbg_new_245cd5c49157e602: function(arg0) {\n const ret = new Date(arg0);\n return ret;\n },\n __wbg_new_361308b2356cecd0: function() {\n const ret = new Object();\n return ret;\n },\n __wbg_new_3eb36ae241fe6f44: function() {\n const ret = new Array();\n return ret;\n },\n __wbg_new_72b49615380db768: function(arg0, arg1) {\n const ret = new Error(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_new_8a6f238a6ece86ea: function() {\n const ret = new Error();\n return ret;\n },\n __wbg_new_911dabf69fa7eb20: function(arg0, arg1) {\n const ret = new RangeError(getStringFromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_new_dd2b680c8bf6ae29: function(arg0) {\n const ret = new Uint8Array(arg0);\n return ret;\n },\n __wbg_new_from_slice_a3d2629dc1826784: function(arg0, arg1) {\n const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));\n return ret;\n },\n __wbg_next_3482f54c49e8af19: function() { return handleError(function (arg0) {\n const ret = arg0.next();\n return ret;\n }, arguments); },\n __wbg_next_418f80d8f5303233: function(arg0) {\n const ret = arg0.next;\n return ret;\n },\n __wbg_ownKeys_c7100fb5fa376c6f: function() { return handleError(function (arg0) {\n const ret = Reflect.ownKeys(arg0);\n return ret;\n }, arguments); },\n __wbg_prototypesetcall_bdcdcc5842e4d77d: function(arg0, arg1, arg2) {\n Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);\n },\n __wbg_push_8ffdcb2063340ba5: function(arg0, arg1) {\n const ret = arg0.push(arg1);\n return ret;\n },\n __wbg_set_3f1d0b984ed272ed: function(arg0, arg1, arg2) {\n arg0[arg1] = arg2;\n },\n __wbg_set_6cb8631f80447a67: function() { return handleError(function (arg0, arg1, arg2) {\n const ret = Reflect.set(arg0, arg1, arg2);\n return ret;\n }, arguments); },\n __wbg_set_f43e577aea94465b: function(arg0, arg1, arg2) {\n arg0[arg1 >>> 0] = arg2;\n },\n __wbg_slice_b0fa09b1e0041d42: function(arg0, arg1, arg2) {\n const ret = arg0.slice(arg1 >>> 0, arg2 >>> 0);\n return ret;\n },\n __wbg_stack_0ed75d68575b0f3c: function(arg0, arg1) {\n const ret = arg1.stack;\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg_stringify_e4a940b133e6b7d8: function(arg0, arg1) {\n const ret = JSON.stringify(arg1);\n var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n var len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg_toString_3cadee6e7c22b39e: function() { return handleError(function (arg0, arg1) {\n const ret = arg0.toString(arg1);\n return ret;\n }, arguments); },\n __wbg_toString_56d946daff83867b: function(arg0, arg1, arg2) {\n const ret = arg1.toString(arg2);\n const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);\n const len1 = WASM_VECTOR_LEN;\n getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);\n getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);\n },\n __wbg_toString_b388ecd2d3c517c3: function(arg0) {\n const ret = arg0.toString();\n return ret;\n },\n __wbg_unshift_a4a28a3b4a2e621b: function(arg0, arg1) {\n const ret = arg0.unshift(arg1);\n return ret;\n },\n __wbg_value_0546255b415e96c1: function(arg0) {\n const ret = arg0.value;\n return ret;\n },\n __wbg_values_5da93bc719d272cf: function(arg0) {\n const ret = Object.values(arg0);\n return ret;\n },\n __wbindgen_cast_0000000000000001: function(arg0) {\n // Cast intrinsic for `F64 -> Externref`.\n const ret = arg0;\n return ret;\n },\n __wbindgen_cast_0000000000000002: function(arg0) {\n // Cast intrinsic for `I64 -> Externref`.\n const ret = arg0;\n return ret;\n },\n __wbindgen_cast_0000000000000003: function(arg0, arg1) {\n // Cast intrinsic for `Ref(String) -> Externref`.\n const ret = getStringFromWasm0(arg0, arg1);\n return ret;\n },\n __wbindgen_cast_0000000000000004: function(arg0) {\n // Cast intrinsic for `U64 -> Externref`.\n const ret = BigInt.asUintN(64, arg0);\n return ret;\n },\n __wbindgen_init_externref_table: function() {\n const table = wasm.__wbindgen_externrefs;\n const offset = table.grow(4);\n table.set(0, undefined);\n table.set(offset + 0, undefined);\n table.set(offset + 1, null);\n table.set(offset + 2, true);\n table.set(offset + 3, false);\n },\n };\n return {\n __proto__: null,\n \"./automerge_wasm_bg.js\": import0,\n };\n}\n\nconst AutomergeFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_automerge_free(ptr >>> 0, 1));\nconst SyncStateFinalization = (typeof FinalizationRegistry === 'undefined')\n ? { register: () => {}, unregister: () => {} }\n : new FinalizationRegistry(ptr => wasm.__wbg_syncstate_free(ptr >>> 0, 1));\n\nfunction addToExternrefTable0(obj) {\n const idx = wasm.__externref_table_alloc();\n wasm.__wbindgen_externrefs.set(idx, obj);\n return idx;\n}\n\nfunction _assertClass(instance, klass) {\n if (!(instance instanceof klass)) {\n throw new Error(`expected instance of ${klass.name}`);\n }\n}\n\nfunction debugString(val) {\n // primitive types\n const type = typeof val;\n if (type == 'number' || type == 'boolean' || val == null) {\n return `${val}`;\n }\n if (type == 'string') {\n return `\"${val}\"`;\n }\n if (type == 'symbol') {\n const description = val.description;\n if (description == null) {\n return 'Symbol';\n } else {\n return `Symbol(${description})`;\n }\n }\n if (type == 'function') {\n const name = val.name;\n if (typeof name == 'string' && name.length > 0) {\n return `Function(${name})`;\n } else {\n return 'Function';\n }\n }\n // objects\n if (Array.isArray(val)) {\n const length = val.length;\n let debug = '[';\n if (length > 0) {\n debug += debugString(val[0]);\n }\n for(let i = 1; i < length; i++) {\n debug += ', ' + debugString(val[i]);\n }\n debug += ']';\n return debug;\n }\n // Test for built-in\n const builtInMatches = /\\[object ([^\\]]+)\\]/.exec(toString.call(val));\n let className;\n if (builtInMatches && builtInMatches.length > 1) {\n className = builtInMatches[1];\n } else {\n // Failed to match the standard '[object ClassName]'\n return toString.call(val);\n }\n if (className == 'Object') {\n // we're a user defined class or Object\n // JSON.stringify avoids problems with cycles, and is generally much\n // easier than looping through ownProperties of `val`.\n try {\n return 'Object(' + JSON.stringify(val) + ')';\n } catch (_) {\n return 'Object';\n }\n }\n // errors\n if (val instanceof Error) {\n return `${val.name}: ${val.message}\\n${val.stack}`;\n }\n // TODO we could test for more things here, like `Set`s and `Map`s.\n return className;\n}\n\nfunction getArrayU8FromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);\n}\n\nlet cachedDataViewMemory0 = null;\nfunction getDataViewMemory0() {\n if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {\n cachedDataViewMemory0 = new DataView(wasm.memory.buffer);\n }\n return cachedDataViewMemory0;\n}\n\nfunction getStringFromWasm0(ptr, len) {\n ptr = ptr >>> 0;\n return decodeText(ptr, len);\n}\n\nlet cachedUint8ArrayMemory0 = null;\nfunction getUint8ArrayMemory0() {\n if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {\n cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);\n }\n return cachedUint8ArrayMemory0;\n}\n\nfunction handleError(f, args) {\n try {\n return f.apply(this, args);\n } catch (e) {\n const idx = addToExternrefTable0(e);\n wasm.__wbindgen_exn_store(idx);\n }\n}\n\nfunction isLikeNone(x) {\n return x === undefined || x === null;\n}\n\nfunction passStringToWasm0(arg, malloc, realloc) {\n if (realloc === undefined) {\n const buf = cachedTextEncoder.encode(arg);\n const ptr = malloc(buf.length, 1) >>> 0;\n getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);\n WASM_VECTOR_LEN = buf.length;\n return ptr;\n }\n\n let len = arg.length;\n let ptr = malloc(len, 1) >>> 0;\n\n const mem = getUint8ArrayMemory0();\n\n let offset = 0;\n\n for (; offset < len; offset++) {\n const code = arg.charCodeAt(offset);\n if (code > 0x7F) break;\n mem[ptr + offset] = code;\n }\n if (offset !== len) {\n if (offset !== 0) {\n arg = arg.slice(offset);\n }\n ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;\n const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);\n const ret = cachedTextEncoder.encodeInto(arg, view);\n\n offset += ret.written;\n ptr = realloc(ptr, len, offset, 1) >>> 0;\n }\n\n WASM_VECTOR_LEN = offset;\n return ptr;\n}\n\nfunction takeFromExternrefTable0(idx) {\n const value = wasm.__wbindgen_externrefs.get(idx);\n wasm.__externref_table_dealloc(idx);\n return value;\n}\n\nlet cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\ncachedTextDecoder.decode();\nconst MAX_SAFARI_DECODE_BYTES = 2146435072;\nlet numBytesDecoded = 0;\nfunction decodeText(ptr, len) {\n numBytesDecoded += len;\n if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {\n cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });\n cachedTextDecoder.decode();\n numBytesDecoded = len;\n }\n return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));\n}\n\nconst cachedTextEncoder = new TextEncoder();\n\nif (!('encodeInto' in cachedTextEncoder)) {\n cachedTextEncoder.encodeInto = function (arg, view) {\n const buf = cachedTextEncoder.encode(arg);\n view.set(buf);\n return {\n read: arg.length,\n written: buf.length\n };\n };\n}\n\nlet WASM_VECTOR_LEN = 0;\n\nlet wasmModule, wasm;\nfunction __wbg_finalize_init(instance, module) {\n wasm = instance.exports;\n wasmModule = module;\n cachedDataViewMemory0 = null;\n cachedUint8ArrayMemory0 = null;\n wasm.__wbindgen_start();\n return wasm;\n}\n\nasync function __wbg_load(module, imports) {\n if (typeof Response === 'function' && module instanceof Response) {\n if (typeof WebAssembly.instantiateStreaming === 'function') {\n try {\n return await WebAssembly.instantiateStreaming(module, imports);\n } catch (e) {\n const validResponse = module.ok && expectedResponseType(module.type);\n\n if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {\n console.warn(\"`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n\", e);\n\n } else { throw e; }\n }\n }\n\n const bytes = await module.arrayBuffer();\n return await WebAssembly.instantiate(bytes, imports);\n } else {\n const instance = await WebAssembly.instantiate(module, imports);\n\n if (instance instanceof WebAssembly.Instance) {\n return { instance, module };\n } else {\n return instance;\n }\n }\n\n function expectedResponseType(type) {\n switch (type) {\n case 'basic': case 'cors': case 'default': return true;\n }\n return false;\n }\n}\n\nfunction initSync(module) {\n if (wasm !== undefined) return wasm;\n\n\n if (module !== undefined) {\n if (Object.getPrototypeOf(module) === Object.prototype) {\n ({module} = module)\n } else {\n console.warn('using deprecated parameters for `initSync()`; pass a single object instead')\n }\n }\n\n const imports = __wbg_get_imports();\n if (!(module instanceof WebAssembly.Module)) {\n module = new WebAssembly.Module(module);\n }\n const instance = new WebAssembly.Instance(module, imports);\n return __wbg_finalize_init(instance, module);\n}\n\nasync function __wbg_init(module_or_path) {\n if (wasm !== undefined) return wasm;\n\n\n if (module_or_path !== undefined) {\n if (Object.getPrototypeOf(module_or_path) === Object.prototype) {\n ({module_or_path} = module_or_path)\n } else {\n console.warn('using deprecated parameters for the initialization function; pass a single object instead')\n }\n }\n\n if (module_or_path === undefined) {\n module_or_path = new /* @vite-ignore */ URL('automerge_wasm_bg.wasm', import.meta.url);\n }\n const imports = __wbg_get_imports();\n\n if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {\n module_or_path = fetch(module_or_path);\n }\n\n const { instance, module } = await __wbg_load(await module_or_path, imports);\n\n return __wbg_finalize_init(instance, module);\n}\n\nexport { initSync, __wbg_init as default };\n", "var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isImmutableString, rootProxy, validateForBatchInsert, } from \"./proxies.js\";\nexport { isImmutableString, isCounter } from \"./proxies.js\";\nimport { STATE } from \"./constants.js\";\nimport { Counter, } from \"./types.js\";\nexport { Counter, Int, Uint, Float64, } from \"./types.js\";\nconst _SyncStateSymbol = Symbol(\"_syncstate\");\nimport { ApiHandler, UseApi } from \"./low_level.js\";\nimport { JS_GIT_HEAD } from \"./generated/release-info.js\";\nexport { initializeWasm, initializeBase64Wasm, wasmInitialized, isWasmInitialized, } from \"./low_level.js\";\nimport { ImmutableString } from \"./immutable_string.js\";\nexport { ImmutableString } from \"./immutable_string.js\";\nimport { _state, _is_proxy, _clear_cache, _trace, _obj, } from \"./internal_state.js\";\nexport { applyPatch, applyPatches } from \"./apply_patches.js\";\nimport { conflictAt } from \"./conflicts.js\";\n/**\n * Function for use in {@link change} which inserts values into a list at a given index\n * @param list\n * @param index\n * @param values\n */\nexport function insertAt(list, index, ...values) {\n if (!_is_proxy(list)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n //eslint-disable-next-line no-extra-semi\n ;\n list.insertAt(index, ...values);\n}\n/**\n * Function for use in {@link change} which deletes values from a list at a given index\n * @param list\n * @param index\n * @param numDelete\n */\nexport function deleteAt(list, index, numDelete) {\n if (!_is_proxy(list)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n //eslint-disable-next-line no-extra-semi\n ;\n list.deleteAt(index, numDelete);\n}\n/** @hidden **/\nexport function use(api) {\n UseApi(api);\n}\n/** @hidden */\nexport function getBackend(doc) {\n return _state(doc).handle;\n}\nfunction importOpts(_actor) {\n if (typeof _actor === \"object\") {\n return _actor;\n }\n else {\n return { actor: _actor };\n }\n}\nexport function getChangesSince(state, heads) {\n const n = _state(state);\n return n.handle.getChanges(heads);\n}\nexport function getChangesMetaSince(state, heads) {\n const n = _state(state);\n return n.handle.getChangesMeta(heads);\n}\nfunction cursorToIndex(state, value, index) {\n if (typeof index == \"string\") {\n if (/^-?[0-9]+@[0-9a-zA-Z]+$|^[se]$/.test(index)) {\n return state.handle.getCursorPosition(value, index);\n }\n else {\n throw new RangeError(\"index must be a number or cursor\");\n }\n }\n else {\n return index;\n }\n}\n/**\n * Create a new automerge document\n *\n * @typeParam T - The type of value contained in the document. This will be the\n * type that is passed to the change closure in {@link change}\n * @param _opts - Either an actorId or an {@link InitOptions} (which may\n * contain an actorId). If this is null the document will be initialised with a\n * random actor ID\n */\nexport function init(_opts) {\n const opts = importOpts(_opts);\n const freeze = !!opts.freeze;\n const patchCallback = opts.patchCallback;\n const actor = opts.actor;\n const handle = ApiHandler.create({ actor });\n handle.enableFreeze(!!opts.freeze);\n registerDatatypes(handle);\n const doc = handle.materialize(\"/\", undefined, {\n handle,\n heads: undefined,\n freeze,\n patchCallback,\n });\n return doc;\n}\n/**\n * Make an immutable view of an automerge document as at `heads`\n *\n * @remarks\n * The document returned from this function cannot be passed to {@link change}.\n * This is because it shares the same underlying memory as `doc`, but it is\n * consequently a very cheap copy.\n *\n * Note that this function will throw an error if any of the hashes in `heads`\n * are not in the document.\n *\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to create a view of\n * @param heads - The hashes of the heads to create a view at\n */\nexport function view(doc, heads) {\n const state = _state(doc);\n const handle = state.handle;\n return state.handle.materialize(\"/\", heads, Object.assign(Object.assign({}, state), { handle,\n heads }));\n}\n/**\n * Make a full writable copy of an automerge document\n *\n * @remarks\n * Unlike {@link view} this function makes a full copy of the memory backing\n * the document and can thus be passed to {@link change}. It also generates a\n * new actor ID so that changes made in the new document do not create duplicate\n * sequence numbers with respect to the old document. If you need control over\n * the actor ID which is generated you can pass the actor ID as the second\n * argument\n *\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to clone\n * @param _opts - Either an actor ID to use for the new doc or an {@link InitOptions}\n */\nexport function clone(doc, _opts) {\n const state = _state(doc);\n const heads = state.heads;\n const opts = importOpts(_opts);\n const handle = state.handle.fork(opts.actor, heads);\n handle.updateDiffCursor();\n // `change` uses the presence of state.heads to determine if we are in a view\n // set it to undefined to indicate that this is a full fat document\n const { heads: _oldHeads } = state, stateSansHeads = __rest(state, [\"heads\"]);\n stateSansHeads.patchCallback = opts.patchCallback;\n return handle.applyPatches(doc, Object.assign(Object.assign({}, stateSansHeads), { handle }));\n}\n/** Explicity free the memory backing a document. Note that this is note\n * necessary in environments which support\n * [`FinalizationRegistry`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry)\n */\nexport function free(doc) {\n return _state(doc).handle.free();\n}\n/**\n * Create an automerge document from a POJO\n *\n * @param initialState - The initial state which will be copied into the document\n * @typeParam T - The type of the value passed to `from` _and_ the type the resulting document will contain\n * @typeParam actor - The actor ID of the resulting document, if this is null a random actor ID will be used\n *\n * @example\n * ```\n * const doc = automerge.from({\n * tasks: [\n * {description: \"feed dogs\", done: false}\n * ]\n * })\n * ```\n */\nexport function from(initialState, _opts) {\n const opts = importOpts(_opts);\n if (typeof initialState !== \"object\" || Array.isArray(initialState)) {\n initialState = Object.assign({}, initialState);\n }\n validateForBatchInsert(initialState, null, []);\n const doc = init(_opts);\n return _change(doc, \"from\", {}, d => {\n _state(doc).handle.initRootFromHydrate(initialState);\n return d;\n }).newDoc;\n}\n/**\n * Update the contents of an automerge document\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to update\n * @param options - Either a message, an {@link ChangeOptions}, or a {@link ChangeFn}\n * @param callback - A `ChangeFn` to be used if `options` was a `string`\n *\n * Note that if the second argument is a function it will be used as the `ChangeFn` regardless of what the third argument is.\n *\n * @example A simple change\n * ```\n * let doc1 = automerge.init()\n * doc1 = automerge.change(doc1, d => {\n * d.key = \"value\"\n * })\n * assert.equal(doc1.key, \"value\")\n * ```\n *\n * @example A change with a message\n *\n * ```\n * doc1 = automerge.change(doc1, \"add another value\", d => {\n * d.key2 = \"value2\"\n * })\n * ```\n *\n * @example A change with a message and a timestamp\n *\n * ```\n * doc1 = automerge.change(doc1, {message: \"add another value\", time: 1640995200}, d => {\n * d.key2 = \"value2\"\n * })\n * ```\n *\n * @example responding to a patch callback\n * ```\n * let patchedPath\n * let patchCallback = patch => {\n * patchedPath = patch.path\n * }\n * doc1 = automerge.change(doc1, {message: \"add another value\", time: 1640995200, patchCallback}, d => {\n * d.key2 = \"value2\"\n * })\n * assert.equal(patchedPath, [\"key2\"])\n * ```\n */\nexport function change(doc, options, callback) {\n if (typeof options === \"function\") {\n return _change(doc, \"change\", {}, options).newDoc;\n }\n else if (typeof callback === \"function\") {\n if (typeof options === \"string\") {\n options = { message: options };\n }\n return _change(doc, \"change\", options, callback).newDoc;\n }\n else {\n throw RangeError(\"Invalid args for change\");\n }\n}\n/**\n * Make a change to the document as it was at a particular point in history\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to update\n * @param scope - The heads representing the point in history to make the change\n * @param options - Either a message or a {@link ChangeOptions} for the new change\n * @param callback - A `ChangeFn` to be used if `options` was a `string`\n *\n * @remarks\n * This function is similar to {@link change} but allows you to make changes to\n * the document as if it were at a particular point in time. To understand this\n * imagine a document created with the following history:\n *\n * ```ts\n * let doc = automerge.from({..})\n * doc = automerge.change(doc, () => {...})\n *\n * const heads = automerge.getHeads(doc)\n *\n * // fork the document make a change\n * let fork = automerge.fork(doc)\n * fork = automerge.change(fork, () => {...})\n * const headsOnFork = automerge.getHeads(fork)\n *\n * // make a change on the original doc\n * doc = automerge.change(doc, () => {...})\n * const headsOnOriginal = automerge.getHeads(doc)\n *\n * // now merge the changes back to the original document\n * doc = automerge.merge(doc, fork)\n *\n * // The heads of the document will now be (headsOnFork, headsOnOriginal)\n * ```\n *\n * {@link ChangeAt} produces an equivalent history, but without having to\n * create a fork of the document. In particular the `newHeads` field of the\n * returned {@link ChangeAtResult} will be the same as `headsOnFork`.\n *\n * Why would you want this? It's typically used in conjunction with {@link diff}\n * to reconcile state which is managed concurrently with the document. For\n * example, if you have a text editor component which the user is modifying\n * and you can't send the changes to the document synchronously you might follow\n * a workflow like this:\n *\n * * On initialization save the current heads of the document in the text editor state\n * * Every time the user makes a change record the change in the text editor state\n *\n * Now from time to time reconcile the editor state and the document\n * * Load the last saved heads from the text editor state, call them `oldHeads`\n * * Apply all the unreconciled changes to the document using `changeAt(doc, oldHeads, ...)`\n * * Get the diff from the resulting document to the current document using {@link diff}\n * passing the {@link ChangeAtResult.newHeads} as the `before` argument and the\n * heads of the entire document as the `after` argument.\n * * Apply the diff to the text editor state\n * * Save the current heads of the document in the text editor state\n */\nexport function changeAt(doc, scope, options, callback) {\n if (typeof options === \"function\") {\n return _change(doc, \"changeAt\", {}, options, scope);\n }\n else if (typeof callback === \"function\") {\n if (typeof options === \"string\") {\n options = { message: options };\n }\n return _change(doc, \"changeAt\", options, callback, scope);\n }\n else {\n throw RangeError(\"Invalid args for changeAt\");\n }\n}\nfunction progressDocument(doc, source, heads, callback) {\n if (heads == null) {\n return doc;\n }\n const state = _state(doc);\n const nextState = Object.assign(Object.assign({}, state), { heads: undefined });\n const { value: nextDoc, patches } = state.handle.applyAndReturnPatches(doc, nextState);\n if (patches.length > 0) {\n if (callback != null) {\n callback(patches, { before: doc, after: nextDoc, source });\n }\n const newState = _state(nextDoc);\n newState.mostRecentPatch = {\n before: _state(doc).heads,\n after: newState.handle.getHeads(),\n patches,\n };\n }\n state.heads = heads;\n return nextDoc;\n}\nfunction _change(doc, source, options, callback, scope) {\n if (typeof callback !== \"function\") {\n throw new RangeError(\"invalid change function\");\n }\n const state = _state(doc);\n if (doc === undefined || state === undefined) {\n throw new RangeError(\"must be the document root\");\n }\n if (state.heads) {\n throw new RangeError(\"Attempting to change an outdated document. Use Automerge.clone() if you wish to make a writable copy.\");\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n let heads = state.handle.getHeads();\n if (scope && headsEqual(scope, heads)) {\n scope = undefined;\n }\n if (scope) {\n state.handle.isolate(scope);\n heads = scope;\n }\n if (!(\"time\" in options)) {\n options.time = Math.floor(Date.now() / 1000);\n }\n try {\n state.heads = heads;\n const root = rootProxy(state.handle);\n callback(root);\n if (state.handle.pendingOps() === 0) {\n state.heads = undefined;\n if (scope) {\n state.handle.integrate();\n }\n return {\n newDoc: doc,\n newHeads: null,\n };\n }\n else {\n const newHead = state.handle.commit(options.message, options.time);\n state.handle.integrate();\n return {\n newDoc: progressDocument(doc, source, heads, options.patchCallback || state.patchCallback),\n newHeads: newHead != null ? [newHead] : null,\n };\n }\n }\n catch (e) {\n state.heads = undefined;\n state.handle.rollback();\n throw e;\n }\n}\n/**\n * Make a change to a document which does not modify the document\n *\n * @param doc - The doc to add the empty change to\n * @param options - Either a message or a {@link ChangeOptions} for the new change\n *\n * Why would you want to do this? One reason might be that you have merged\n * changes from some other peers and you want to generate a change which\n * depends on those merged changes so that you can sign the new change with all\n * of the merged changes as part of the new change.\n */\nexport function emptyChange(doc, options) {\n if (options === undefined) {\n options = {};\n }\n if (typeof options === \"string\") {\n options = { message: options };\n }\n if (!(\"time\" in options)) {\n options.time = Math.floor(Date.now() / 1000);\n }\n const state = _state(doc);\n if (state.heads) {\n throw new RangeError(\"Attempting to change an outdated document. Use Automerge.clone() if you wish to make a writable copy.\");\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n const heads = state.handle.getHeads();\n state.handle.emptyChange(options.message, options.time);\n return progressDocument(doc, \"emptyChange\", heads);\n}\n/**\n * Load an automerge document from a compressed document produce by {@link save}\n *\n * @typeParam T - The type of the value which is contained in the document.\n * Note that no validation is done to make sure this type is in\n * fact the type of the contained value so be a bit careful\n * @param data - The compressed document\n * @param _opts - Either an actor ID or some {@link InitOptions}, if the actor\n * ID is null a random actor ID will be created\n *\n * Note that `load` will throw an error if passed incomplete content (for\n * example if you are receiving content over the network and don't know if you\n * have the complete document yet). If you need to handle incomplete content use\n * {@link init} followed by {@link loadIncremental}.\n */\nexport function load(data, _opts) {\n const opts = importOpts(_opts);\n if (opts.patchCallback) {\n return loadIncremental(init(opts), data);\n }\n const actor = opts.actor;\n const patchCallback = opts.patchCallback;\n const unchecked = opts.unchecked || false;\n const allowMissingDeps = opts.allowMissingChanges || false;\n const convertImmutableStringsToText = opts.convertImmutableStringsToText || false;\n const handle = ApiHandler.load(data, {\n actor,\n unchecked,\n allowMissingDeps,\n convertImmutableStringsToText,\n });\n handle.enableFreeze(!!opts.freeze);\n registerDatatypes(handle);\n const doc = handle.materialize(\"/\", undefined, {\n handle,\n heads: undefined,\n patchCallback,\n });\n return doc;\n}\n/**\n * Load changes produced by {@link saveIncremental}, or partial changes\n *\n * @typeParam T - The type of the value which is contained in the document.\n * Note that no validation is done to make sure this type is in\n * fact the type of the contained value so be a bit careful\n * @param data - The compressedchanges\n * @param opts - an {@link ApplyOptions}\n *\n * This function is useful when staying up to date with a connected peer.\n * Perhaps the other end sent you a full compresed document which you loaded\n * with {@link load} and they're sending you the result of\n * {@link getLastLocalChange} every time they make a change.\n *\n * Note that this function will succesfully load the results of {@link save} as\n * well as {@link getLastLocalChange} or any other incremental change.\n */\nexport function loadIncremental(doc, data, opts) {\n if (!opts) {\n opts = {};\n }\n const state = _state(doc);\n if (state.heads) {\n throw new RangeError(\"Attempting to change an out of date document - set at: \" + _trace(doc));\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n const heads = state.handle.getHeads();\n state.handle.loadIncremental(data);\n return progressDocument(doc, \"loadIncremental\", heads, opts.patchCallback || state.patchCallback);\n}\n/**\n * Create binary save data to be appended to a save file or fed into {@link loadIncremental}\n *\n * @typeParam T - The type of the value which is contained in the document.\n * Note that no validation is done to make sure this type is in\n * fact the type of the contained value so be a bit careful\n *\n * This function is useful for incrementally saving state. The data can be appended to a\n * automerge save file, or passed to a document replicating its state.\n *\n */\nexport function saveIncremental(doc) {\n const state = _state(doc);\n if (state.heads) {\n throw new RangeError(\"Attempting to change an out of date document - set at: \" + _trace(doc));\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n return state.handle.saveIncremental();\n}\n/**\n * Export the contents of a document to a compressed format\n *\n * @param doc - The doc to save\n *\n * The returned bytes can be passed to {@link load} or {@link loadIncremental}\n */\nexport function save(doc) {\n return _state(doc).handle.save();\n}\n/**\n * Merge `remote` into `local`\n * @typeParam T - The type of values contained in each document\n * @param local - The document to merge changes into\n * @param remote - The document to merge changes from\n *\n * @returns - The merged document\n *\n * Often when you are merging documents you will also need to clone them. Both\n * arguments to `merge` are frozen after the call so you can no longer call\n * mutating methods (such as {@link change}) on them. The symtom of this will be\n * an error which says \"Attempting to change an out of date document\". To\n * overcome this call {@link clone} on the argument before passing it to {@link\n * merge}.\n */\nexport function merge(local, remote) {\n const localState = _state(local);\n if (localState.heads) {\n throw new RangeError(\"Attempting to change an out of date document - set at: \" + _trace(local));\n }\n const heads = localState.handle.getHeads();\n const remoteState = _state(remote);\n const changes = localState.handle.getChangesAdded(remoteState.handle);\n localState.handle.applyChanges(changes);\n return progressDocument(local, \"merge\", heads, localState.patchCallback);\n}\n/**\n * Get the actor ID associated with the document\n */\nexport function getActorId(doc) {\n const state = _state(doc);\n return state.handle.getActorId();\n}\n/**\n * Get the conflicts associated with a property\n *\n * The values of properties in a map in automerge can be conflicted if there\n * are concurrent \"put\" operations to the same key. Automerge chooses one value\n * arbitrarily (but deterministically, any two nodes who have the same set of\n * changes will choose the same value) from the set of conflicting values to\n * present as the value of the key.\n *\n * Sometimes you may want to examine these conflicts, in this case you can use\n * {@link getConflicts} to get the conflicts for the key.\n *\n * @example\n * ```\n * import * as automerge from \"@automerge/automerge\"\n *\n * type Profile = {\n * pets: Array<{name: string, type: string}>\n * }\n *\n * let doc1 = automerge.init<Profile>(\"aaaa\")\n * doc1 = automerge.change(doc1, d => {\n * d.pets = [{name: \"Lassie\", type: \"dog\"}]\n * })\n * let doc2 = automerge.init<Profile>(\"bbbb\")\n * doc2 = automerge.merge(doc2, automerge.clone(doc1))\n *\n * doc2 = automerge.change(doc2, d => {\n * d.pets[0].name = \"Beethoven\"\n * })\n *\n * doc1 = automerge.change(doc1, d => {\n * d.pets[0].name = \"Babe\"\n * })\n *\n * const doc3 = automerge.merge(doc1, doc2)\n *\n * // Note that here we pass `doc3.pets`, not `doc3`\n * let conflicts = automerge.getConflicts(doc3.pets[0], \"name\")\n *\n * // The two conflicting values are the keys of the conflicts object\n * assert.deepEqual(Object.values(conflicts), [\"Babe\", Beethoven\"])\n * ```\n */\nexport function getConflicts(doc, prop) {\n const state = _state(doc, false);\n const objectId = _obj(doc);\n if (objectId != null) {\n const withinChangeCallback = _is_proxy(doc);\n return conflictAt(state.handle, objectId, prop, withinChangeCallback);\n }\n else {\n return undefined;\n }\n}\n/**\n * Get the binary representation of the last change which was made to this doc\n *\n * This is most useful when staying in sync with other peers, every time you\n * make a change locally via {@link change} you immediately call {@link\n * getLastLocalChange} and send the result over the network to other peers.\n */\nexport function getLastLocalChange(doc) {\n const state = _state(doc);\n return state.handle.getLastLocalChange() || undefined;\n}\n/**\n * Return the object ID of an arbitrary javascript value\n *\n * This is useful to determine if something is actually an automerge document,\n * if `doc` is not an automerge document this will return null.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getObjectId(doc, prop) {\n if (prop) {\n const state = _state(doc, false);\n const objectId = _obj(doc);\n if (!state || !objectId) {\n return null;\n }\n return state.handle.get(objectId, prop);\n }\n else {\n return _obj(doc);\n }\n}\n/**\n * Get the changes which are in `newState` but not in `oldState`. The returned\n * changes can be loaded in `oldState` via {@link applyChanges}.\n *\n * Note that this will crash if there are changes in `oldState` which are not in `newState`.\n */\nexport function getChanges(oldState, newState) {\n const n = _state(newState);\n return n.handle.getChanges(getHeads(oldState));\n}\n/**\n * Get all the changes in a document\n *\n * This is different to {@link save} because the output is an array of changes\n * which can be individually applied via {@link applyChanges}`\n *\n */\nexport function getAllChanges(doc) {\n const state = _state(doc);\n return state.handle.getChanges([]);\n}\n/**\n * Apply changes received from another document\n *\n * `doc` will be updated to reflect the `changes`. If there are changes which\n * we do not have dependencies for yet those will be stored in the document and\n * applied when the depended on changes arrive.\n *\n * You can use the {@link ApplyOptions} to pass a patchcallback which will be\n * informed of any changes which occur as a result of applying the changes\n *\n */\nexport function applyChanges(doc, changes, opts) {\n const state = _state(doc);\n if (!opts) {\n opts = {};\n }\n if (state.heads) {\n throw new RangeError(\"Attempting to change an outdated document. Use Automerge.clone() if you wish to make a writable copy.\");\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n const heads = state.handle.getHeads();\n state.handle.applyChanges(changes);\n state.heads = heads;\n return [\n progressDocument(doc, \"applyChanges\", heads, opts.patchCallback || state.patchCallback),\n ];\n}\n/** @hidden */\nexport function getHistory(doc) {\n const history = getAllChanges(doc);\n return history.map((change, index) => ({\n get change() {\n return decodeChange(change);\n },\n get snapshot() {\n const [state] = applyChanges(init(), history.slice(0, index + 1));\n return state;\n },\n }));\n}\n/**\n * Create a set of patches representing the change from one set of heads to another\n *\n * If either of the heads are missing from the document the returned set of patches will be empty\n */\nexport function diff(doc, before, after) {\n checkHeads(before, \"before heads\");\n checkHeads(after, \"after heads\");\n const state = _state(doc);\n if (state.mostRecentPatch &&\n equals(state.mostRecentPatch.before, before) &&\n equals(state.mostRecentPatch.after, after)) {\n return state.mostRecentPatch.patches;\n }\n return state.handle.diff(before, after);\n}\n/**\n * Create a set of patches representing the change from one set of heads to another at a given path\n * @experimental\n * @param doc - The document to update\n * @param path - path of the object to diff\n * @param before - before Heads for the diff\n * @param after - after Heads for the diff\n * @param opts - Options is { recursive: bool } to diff sub objects as well. Default is true\n *\n * This is an experimental API\n */\nexport function diffPath(doc, path, before, after, opts) {\n checkHeads(before, \"before\");\n checkHeads(after, \"after\");\n const state = _state(doc);\n const objPath = absoluteObjPath(doc, path, \"diff\");\n return state.handle.diffPath(objPath, before, after, opts);\n}\nfunction headsEqual(heads1, heads2) {\n if (heads1.length !== heads2.length) {\n return false;\n }\n for (let i = 0; i < heads1.length; i++) {\n if (heads1[i] !== heads2[i]) {\n return false;\n }\n }\n return true;\n}\nfunction checkHeads(heads, fieldname) {\n if (!Array.isArray(heads)) {\n throw new Error(`invalid ${fieldname}: must be an array`);\n }\n}\n/** @hidden */\n// FIXME : no tests\n// FIXME can we just use deep equals now?\nexport function equals(val1, val2) {\n if (!isObject(val1) || !isObject(val2))\n return val1 === val2;\n const keys1 = Object.keys(val1).sort(), keys2 = Object.keys(val2).sort();\n if (keys1.length !== keys2.length)\n return false;\n for (let i = 0; i < keys1.length; i++) {\n if (keys1[i] !== keys2[i])\n return false;\n if (!equals(val1[keys1[i]], val2[keys2[i]]))\n return false;\n }\n return true;\n}\n/**\n * encode a {@link SyncState} into binary to send over the network\n *\n * @group sync\n * */\nexport function encodeSyncState(state) {\n const sync = ApiHandler.importSyncState(state);\n const result = ApiHandler.encodeSyncState(sync);\n sync.free();\n return result;\n}\n/**\n * Decode some binary data into a {@link SyncState}\n *\n * @group sync\n */\nexport function decodeSyncState(state) {\n const sync = ApiHandler.decodeSyncState(state);\n const result = ApiHandler.exportSyncState(sync);\n sync.free();\n return result;\n}\n/**\n * Generate a sync message to send to the peer represented by `inState`\n * @param doc - The doc to generate messages about\n * @param inState - The {@link SyncState} representing the peer we are talking to\n *\n * @group sync\n *\n * @returns An array of `[newSyncState, syncMessage | null]` where\n * `newSyncState` should replace `inState` and `syncMessage` should be sent to\n * the peer if it is not null. If `syncMessage` is null then we are up to date.\n */\nexport function generateSyncMessage(doc, inState) {\n const state = _state(doc);\n const syncState = ApiHandler.importSyncState(inState);\n const message = state.handle.generateSyncMessage(syncState);\n const outState = ApiHandler.exportSyncState(syncState);\n return [outState, message];\n}\n/**\n * Update a document and our sync state on receiving a sync message\n *\n * @group sync\n *\n * @param doc - The doc the sync message is about\n * @param inState - The {@link SyncState} for the peer we are communicating with\n * @param message - The message which was received\n * @param opts - Any {@link ApplyOption}s, used for passing a\n * {@link PatchCallback} which will be informed of any changes\n * in `doc` which occur because of the received sync message.\n *\n * @returns An array of `[newDoc, newSyncState, null]` where\n * `newDoc` is the updated state of `doc`, `newSyncState` should replace\n * `inState`.\n *\n * @remarks Note that this function has three return values for legacy reasons.\n * The third value used to be a sync message to send back but this is now\n * always null and you should instead call `generateSyncMessage` after calling\n * `receiveSyncMessage` to see if there are new messages to send.\n */\nexport function receiveSyncMessage(doc, inState, message, opts) {\n const syncState = ApiHandler.importSyncState(inState);\n if (!opts) {\n opts = {};\n }\n const state = _state(doc);\n if (state.heads) {\n throw new RangeError(\"Attempting to change an outdated document. Use Automerge.clone() if you wish to make a writable copy.\");\n }\n if (_is_proxy(doc)) {\n throw new RangeError(\"Calls to Automerge.change cannot be nested\");\n }\n const heads = state.handle.getHeads();\n state.handle.receiveSyncMessage(syncState, message);\n const outSyncState = ApiHandler.exportSyncState(syncState);\n return [\n progressDocument(doc, \"receiveSyncMessage\", heads, opts.patchCallback || state.patchCallback),\n outSyncState,\n null,\n ];\n}\n/**\n * Check whether the replica represented by `remoteState` has all our changes\n *\n * @param doc - The doc to check whether the remote has changes for\n * @param remoteState - The {@link SyncState} representing the peer we are talking to\n *\n * @group sync\n *\n * @returns true if the remote has all of our changes\n */\nexport function hasOurChanges(doc, remoteState) {\n const state = _state(doc);\n const syncState = ApiHandler.importSyncState(remoteState);\n return state.handle.hasOurChanges(syncState);\n}\n/**\n * Create a new, blank {@link SyncState}\n *\n * When communicating with a peer for the first time use this to generate a new\n * {@link SyncState} for them\n *\n * @group sync\n */\nexport function initSyncState() {\n return ApiHandler.exportSyncState(ApiHandler.initSyncState());\n}\n/** @hidden */\nexport function encodeChange(change) {\n return ApiHandler.encodeChange(change);\n}\n/** @hidden */\nexport function decodeChange(data) {\n return ApiHandler.decodeChange(data);\n}\n/** @hidden */\nexport function encodeSyncMessage(message) {\n return ApiHandler.encodeSyncMessage(message);\n}\n/** @hidden */\nexport function decodeSyncMessage(message) {\n return ApiHandler.decodeSyncMessage(message);\n}\n/**\n * Get any changes in `doc` which are not dependencies of `heads`\n */\nexport function getMissingDeps(doc, heads) {\n const state = _state(doc);\n return state.handle.getMissingDeps(heads);\n}\n/**\n * Get the hashes of the heads of this document\n */\nexport function getHeads(doc) {\n const state = _state(doc);\n return state.heads || state.handle.getHeads();\n}\n/** @hidden */\nexport function dump(doc) {\n const state = _state(doc);\n state.handle.dump();\n}\n/** @hidden */\nexport function toJS(doc) {\n const state = _state(doc);\n const enabled = state.handle.enableFreeze(false);\n const result = state.handle.materialize(\"/\", state.heads);\n state.handle.enableFreeze(enabled);\n return result;\n}\nexport function isAutomerge(doc) {\n if (typeof doc == \"object\" && doc !== null) {\n return getObjectId(doc) === \"_root\" && !!Reflect.get(doc, STATE);\n }\n else {\n return false;\n }\n}\nfunction isObject(obj) {\n return typeof obj === \"object\" && obj !== null;\n}\nexport function saveSince(doc, heads) {\n const state = _state(doc);\n const result = state.handle.saveSince(heads);\n return result;\n}\n/**\n * Returns true if the document has all of the given heads somewhere in its history\n */\nexport function hasHeads(doc, heads) {\n const state = _state(doc);\n for (const hash of heads) {\n if (!state.handle.getChangeByHash(hash)) {\n return false;\n }\n }\n return true;\n}\nfunction registerDatatypes(handle) {\n handle.registerDatatype(\"counter\", (n) => new Counter(n), n => {\n if (n instanceof Counter) {\n return n.value;\n }\n });\n handle.registerDatatype(\"str\", (n) => {\n return new ImmutableString(n);\n }, s => {\n if (isImmutableString(s)) {\n return s.val;\n }\n });\n}\n/**\n * @hidden\n */\nexport function topoHistoryTraversal(doc) {\n const state = _state(doc);\n return state.handle.topoHistoryTraversal();\n}\n/**\n * Decode a change hash into the details of this change\n *\n * This should be considered a semi-stable API. We try not to change the\n * encoding in backwards incompatible ways but we won't bump a major version if\n * we do have to change it\n */\nexport function inspectChange(doc, changeHash) {\n const state = _state(doc);\n return state.handle.getDecodedChangeByHash(changeHash);\n}\n/**\n * Return some internal statistics about the document\n */\nexport function stats(doc) {\n var _a, _b, _c, _d, _e, _f;\n const state = _state(doc);\n const wasmStats = state.handle.stats();\n const release = releaseInfo();\n return Object.assign(Object.assign({}, wasmStats), { cargoPackageName: (_b = (_a = release.wasm) === null || _a === void 0 ? void 0 : _a.cargoPackageName) !== null && _b !== void 0 ? _b : \"unknown\", cargoPackageVersion: (_d = (_c = release.wasm) === null || _c === void 0 ? void 0 : _c.cargoPackageVersion) !== null && _d !== void 0 ? _d : \"unknown\", rustcVersion: (_f = (_e = release.wasm) === null || _e === void 0 ? void 0 : _e.rustcVersion) !== null && _f !== void 0 ? _f : \"unknown\" });\n}\n/**\n * Get release information about the automerge library.\n *\n * Returns metadata about both the JavaScript wrapper and the WebAssembly\n * module, including git commit hashes. If js.gitHead !== wasm.gitHead,\n * the JS and WASM were built from different commits.\n *\n * If the WASM module has not been initialized, wasm will be null.\n */\nexport function releaseInfo() {\n let wasm = null;\n try {\n wasm = ApiHandler.wasmReleaseInfo();\n }\n catch (_a) {\n // WASM not initialized - leave as null\n }\n return {\n js: {\n gitHead: JS_GIT_HEAD,\n },\n wasm,\n };\n}\n/**\n * Modify a string\n *\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to modify\n * @param path - The path to the string to modify\n * @param index - The position (as a {@link Cursor} or index) to edit.\n * If a cursor is used then the edit happens such that the cursor will\n * now point to the end of the newText, so you can continue to reuse\n * the same cursor for multiple calls to splice.\n * @param del - The number of code units to delete, a positive number\n * deletes N characters after the cursor, a negative number deletes\n * N characters before the cursor.\n * @param newText - The string to insert (if any).\n */\nexport function splice(doc, path, index, del, newText) {\n const objPath = absoluteObjPath(doc, path, \"splice\");\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const state = _state(doc, false);\n _clear_cache(doc);\n index = cursorToIndex(state, objPath, index);\n try {\n return state.handle.splice(objPath, index, del, newText);\n }\n catch (e) {\n throw new RangeError(`Cannot splice: ${e}`);\n }\n}\n/**\n * Update the value of a string\n *\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document to modify\n * @param path - The path to the string to modify\n * @param newText - The new text to update the value to\n *\n * @remarks\n * This will calculate a diff between the current value and the new value and\n * then convert that diff into calls to {@link splice}. This will produce results\n * which don't merge as well as directly capturing the user input actions, but\n * sometimes it's not possible to capture user input and this is the best you\n * can do.\n *\n * This is an experimental API and may change in the future.\n *\n * @beta\n */\nexport function updateText(doc, path, newText) {\n const objPath = absoluteObjPath(doc, path, \"updateText\");\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const state = _state(doc, false);\n _clear_cache(doc);\n try {\n return state.handle.updateText(objPath, newText);\n }\n catch (e) {\n throw new RangeError(`Cannot updateText: ${e}`);\n }\n}\n/**\n * Return the text + block markers at a given path\n *\n * @remarks\n * Rich text in automerge is represented as a sequence of characters with block\n * markers appearing inline with the text, and inline formatting spans overlaid\n * on the whole sequence. Block markers are normal automerge maps, but they are\n * only visible via either the {@link block} function or the {@link spans}\n * function. This function returns the current state of the spans\n */\nexport function spans(doc, path) {\n const state = _state(doc, false);\n const objPath = absoluteObjPath(doc, path, \"spans\");\n try {\n return state.handle.spans(objPath, state.heads);\n }\n catch (e) {\n throw new RangeError(`Cannot splice: ${e}`);\n }\n}\n/**\n * Get the block marker at the given index\n */\nexport function block(doc, path, index) {\n const objPath = absoluteObjPath(doc, path, \"splitBlock\");\n const state = _state(doc, false);\n index = cursorToIndex(state, objPath, index);\n try {\n return state.handle.getBlock(objPath, index);\n }\n catch (e) {\n throw new RangeError(`Cannot get block: ${e}`);\n }\n}\n/**\n * Insert a new block marker at the given index\n */\nexport function splitBlock(doc, path, index, block) {\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const objPath = absoluteObjPath(doc, path, \"splitBlock\");\n const state = _state(doc, false);\n _clear_cache(doc);\n index = cursorToIndex(state, objPath, index);\n try {\n state.handle.splitBlock(objPath, index, block);\n }\n catch (e) {\n throw new RangeError(`Cannot splice: ${e}`);\n }\n}\n/**\n * Delete the block marker at the given index\n */\nexport function joinBlock(doc, path, index) {\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const objPath = absoluteObjPath(doc, path, \"joinBlock\");\n const state = _state(doc, false);\n _clear_cache(doc);\n index = cursorToIndex(state, objPath, index);\n try {\n state.handle.joinBlock(objPath, index);\n }\n catch (e) {\n throw new RangeError(`Cannot joinBlock: ${e}`);\n }\n}\n/**\n * Update the block marker at the given index\n */\nexport function updateBlock(doc, path, index, block) {\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const objPath = absoluteObjPath(doc, path, \"updateBlock\");\n const state = _state(doc, false);\n _clear_cache(doc);\n index = cursorToIndex(state, objPath, index);\n try {\n state.handle.updateBlock(objPath, index, block);\n }\n catch (e) {\n throw new RangeError(`Cannot updateBlock: ${e}`);\n }\n}\n/**\n * Update the spans at the given path\n *\n * @remarks\n * Like {@link updateText} this will diff `newSpans` against the current state\n * of the text at `path` and perform a reasonably minimal number of operations\n * required to update the spans to the new state.\n *\n * When updating spans, we need to know what to set the \"expand\" behavior of\n * newly created marks to. By default we set it to \"both\", meaning that the\n * spans will expand on either, but this can be overridden by passing\n * `{ defaultExpand: \"<expand>\"}` as the final `config` parameter. You\n * can also pass `{perMarkExpand: {\"<markname>\": \"<expand config>\"}` to\n * set the expand configuration for specific marks where it should be\n * different from the default.\n */\nexport function updateSpans(doc, path, newSpans, config) {\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const objPath = absoluteObjPath(doc, path, \"updateSpans\");\n const state = _state(doc, false);\n _clear_cache(doc);\n try {\n state.handle.updateSpans(objPath, newSpans, config);\n }\n catch (e) {\n throw new RangeError(`Cannot updateSpans: ${e}`);\n }\n}\n/**\n * Returns a cursor for the given position in a string.\n *\n * @remarks\n * A cursor represents a relative position, \"before character X\",\n * rather than an absolute position. As the document is edited, the\n * cursor remains stable relative to its context, just as you'd expect\n * from a cursor in a concurrent text editor.\n *\n * The string representation is shareable, and so you can use this both\n * to edit the document yourself (using {@link splice}) or to share multiple\n * collaborator's current cursor positions over the network.\n *\n * The cursor's `position` can be an index in the string, `'start'` or `'end'`.\n * - `'start'` ensures this cursor always resolves to `0`\n * - `'end'` ensures this cursor always resolves to `string.length`\n *\n * Start cursors can be created by passing any negative number in `position`.\n *\n * End cursors can be created by passing a number `>= string.length` in `position`.\n *\n * `move` determines the position the cursor resolves to if the character at\n * `index` is removed:\n * - `'after'` causes the cursor to resolve towards `string.length`\n * - `'before'` causes the cursor to resolve towards `0`\n *\n * `move` is `'after'` by default.\n *\n * @typeParam T - The type of the value contained in the document\n * @param doc - The document\n * @param path - The path to the string\n * @param position - The position of the cursor, either an index, `'start'` or `'end'`\n * @param move - The direction the cursor should resolve to, defaults to 'after'\n */\nexport function getCursor(doc, path, position, move) {\n const objPath = absoluteObjPath(doc, path, \"getCursor\");\n const state = _state(doc, false);\n try {\n return state.handle.getCursor(objPath, position, state.heads, move);\n }\n catch (e) {\n throw new RangeError(`Cannot getCursor: ${e}`);\n }\n}\n/**\n * Returns the current index of the cursor.\n *\n * @typeParam T - The type of the value contained in the document\n *\n * @param doc - The document\n * @param path - The path to the string\n * @param index - The cursor\n */\nexport function getCursorPosition(doc, path, cursor) {\n const objPath = absoluteObjPath(doc, path, \"getCursorPosition\");\n const state = _state(doc, false);\n try {\n return state.handle.getCursorPosition(objPath, cursor, state.heads);\n }\n catch (e) {\n throw new RangeError(`Cannot getCursorPosition: ${e}`);\n }\n}\nexport function mark(doc, path, range, name, value) {\n const objPath = absoluteObjPath(doc, path, \"mark\");\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const state = _state(doc, false);\n try {\n return state.handle.mark(objPath, range, name, value);\n }\n catch (e) {\n throw new RangeError(`Cannot mark: ${e}`);\n }\n}\nexport function unmark(doc, path, range, name) {\n const objPath = absoluteObjPath(doc, path, \"unmark\");\n if (!_is_proxy(doc)) {\n throw new RangeError(\"object cannot be modified outside of a change block\");\n }\n const state = _state(doc, false);\n try {\n return state.handle.unmark(objPath, range, name);\n }\n catch (e) {\n throw new RangeError(`Cannot unmark: ${e}`);\n }\n}\nexport function marks(doc, path) {\n const objPath = absoluteObjPath(doc, path, \"marks\");\n const state = _state(doc, false);\n try {\n return state.handle.marks(objPath);\n }\n catch (e) {\n throw new RangeError(`Cannot call marks(): ${e}`);\n }\n}\nexport function marksAt(doc, path, index) {\n const objPath = absoluteObjPath(doc, path, \"marksAt\");\n const state = _state(doc, false);\n try {\n return state.handle.marksAt(objPath, index);\n }\n catch (e) {\n throw new RangeError(`Cannot call marksAt(): ${e}`);\n }\n}\nfunction absoluteObjPath(doc, path, functionName) {\n path = path.slice();\n const objectId = _obj(doc);\n if (!objectId) {\n throw new RangeError(`invalid object for ${functionName}`);\n }\n path.unshift(objectId);\n return path.join(\"/\");\n}\n/**\n * @deprecated This method has been renamed to {@link isImmutableString}\n */\nexport const isRawString = isImmutableString;\n/**\n * @deprecated This type has been renamed to {@link ImmutableString}\n */\nexport const RawString = ImmutableString;\n/**\n * EXPERIMENTAL: save a bundle of changes from a document to an encoded form\n * @experimental\n * @param doc - The document containing the changes to save\n * @param hashes - The hashes of the changes to save to a bundle\n * @returns\n */\nexport function saveBundle(doc, hashes) {\n const state = _state(doc, false);\n return state.handle.saveBundle(hashes);\n}\n/**\n * EXPERIMENTAL: Load a bundle of changes to examine them\n * @experimental\n * @param bundle - The encoded bundle to read\n */\nexport function readBundle(bundle) {\n return ApiHandler.readBundle(bundle);\n}\n", "let decoder\ntry {\n\tdecoder = new TextDecoder()\n} catch(error) {}\nlet src\nlet srcEnd\nlet position = 0\nlet alreadySet\nconst EMPTY_ARRAY = []\nconst LEGACY_RECORD_INLINE_ID = 105\nconst RECORD_DEFINITIONS_ID = 0xdffe\nconst RECORD_INLINE_ID = 0xdfff // temporary first-come first-serve tag // proposed tag: 0x7265 // 're'\nconst BUNDLED_STRINGS_ID = 0xdff9\nconst PACKED_TABLE_TAG_ID = 51\nconst PACKED_REFERENCE_TAG_ID = 6\nconst STOP_CODE = {}\nlet maxArraySize = 112810000 // This is the maximum array size in V8. We would potentially detect and set it higher\n// for JSC, but this is pretty large and should be sufficient for most use cases\nlet maxMapSize = 16810000 // JavaScript has a fixed maximum map size of about 16710000, but JS itself enforces this,\n// so we don't need to\n\nlet maxObjectSize = 16710000; // This is the maximum number of keys in a Map. It takes over a minute to create this\n// many keys in an object, so also probably a reasonable choice there.\nlet strings = EMPTY_ARRAY\nlet stringPosition = 0\nlet currentDecoder = {}\nlet currentStructures\nlet srcString\nlet srcStringStart = 0\nlet srcStringEnd = 0\nlet bundledStrings\nlet referenceMap\nlet currentExtensions = []\nlet currentExtensionRanges = []\nlet packedValues\nlet dataView\nlet restoreMapsAsObject\nlet defaultOptions = {\n\tuseRecords: false,\n\tmapsAsObjects: true\n}\nlet sequentialMode = false\nlet inlineObjectReadThreshold = 2;\nvar BlockedFunction // we use search and replace to change the next call to BlockedFunction to avoid CSP issues for\n// no-eval build\ntry {\n\tnew Function('')\n} catch(error) {\n\t// if eval variants are not supported, do not create inline object readers ever\n\tinlineObjectReadThreshold = Infinity\n}\n\n\n\nexport class Decoder {\n\tconstructor(options) {\n\t\tif (options) {\n\t\t\tif ((options.keyMap || options._keyMap) && !options.useRecords) {\n\t\t\t\toptions.useRecords = false\n\t\t\t\toptions.mapsAsObjects = true\n\t\t\t}\n\t\t\tif (options.useRecords === false && options.mapsAsObjects === undefined)\n\t\t\t\toptions.mapsAsObjects = true\n\t\t\tif (options.getStructures)\n\t\t\t\toptions.getShared = options.getStructures\n\t\t\tif (options.getShared && !options.structures)\n\t\t\t\t(options.structures = []).uninitialized = true // this is what we use to denote an uninitialized structures\n\t\t\tif (options.keyMap) {\n\t\t\t\tthis.mapKey = new Map()\n\t\t\t\tfor (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k)\n\t\t\t}\n\t\t}\n\t\tObject.assign(this, options)\n\t}\n\t/*\n\tdecodeKey(key) {\n\t\treturn this.keyMap\n\t\t\t? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key\n\t\t\t: key\n\t}\n\t*/\n\tdecodeKey(key) {\n\t\treturn this.keyMap ? this.mapKey.get(key) || key : key\n\t}\n\t\n\tencodeKey(key) {\n\t\treturn this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key\n\t}\n\n\tencodeKeys(rec) {\n\t\tif (!this._keyMap) return rec\n\t\tlet map = new Map()\n\t\tfor (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v)\n\t\treturn map\n\t}\n\n\tdecodeKeys(map) {\n\t\tif (!this._keyMap || map.constructor.name != 'Map') return map\n\t\tif (!this._mapKey) {\n\t\t\tthis._mapKey = new Map()\n\t\t\tfor (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k)\n\t\t}\n\t\tlet res = {}\n\t\t//map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v)\n\t\tmap.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v)\n\t\treturn res\n\t}\n\t\n\tmapDecode(source, end) {\n\t\n\t\tlet res = this.decode(source)\n\t\tif (this._keyMap) { \n\t\t\t//Experiemntal support for Optimised KeyMap decoding \n\t\t\tswitch (res.constructor.name) {\n\t\t\t\tcase 'Array': return res.map(r => this.decodeKeys(r))\n\t\t\t\t//case 'Map': return this.decodeKeys(res)\n\t\t\t}\n\t\t}\n\t\treturn res\n\t}\n\n\tdecode(source, end) {\n\t\tif (src) {\n\t\t\t// re-entrant execution, save the state and restore it after we do this decode\n\t\t\treturn saveState(() => {\n\t\t\t\tclearSource()\n\t\t\t\treturn this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end)\n\t\t\t})\n\t\t}\n\t\tsrcEnd = end > -1 ? end : source.length\n\t\tposition = 0\n\t\tstringPosition = 0\n\t\tsrcStringEnd = 0\n\t\tsrcString = null\n\t\tstrings = EMPTY_ARRAY\n\t\tbundledStrings = null\n\t\tsrc = source\n\t\t// this provides cached access to the data view for a buffer if it is getting reused, which is a recommend\n\t\t// technique for getting data from a database where it can be copied into an existing buffer instead of creating\n\t\t// new ones\n\t\ttry {\n\t\t\tdataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength))\n\t\t} catch(error) {\n\t\t\t// if it doesn't have a buffer, maybe it is the wrong type of object\n\t\t\tsrc = null\n\t\t\tif (source instanceof Uint8Array)\n\t\t\t\tthrow error\n\t\t\tthrow new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source))\n\t\t}\n\t\tif (this instanceof Decoder) {\n\t\t\tcurrentDecoder = this\n\t\t\tpackedValues = this.sharedValues &&\n\t\t\t\t(this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) :\n\t\t\t\tthis.sharedValues)\n\t\t\tif (this.structures) {\n\t\t\t\tcurrentStructures = this.structures\n\t\t\t\treturn checkedRead()\n\t\t\t} else if (!currentStructures || currentStructures.length > 0) {\n\t\t\t\tcurrentStructures = []\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentDecoder = defaultOptions\n\t\t\tif (!currentStructures || currentStructures.length > 0)\n\t\t\t\tcurrentStructures = []\n\t\t\tpackedValues = null\n\t\t}\n\t\treturn checkedRead()\n\t}\n\tdecodeMultiple(source, forEach) {\n\t\tlet values, lastPosition = 0\n\t\ttry {\n\t\t\tlet size = source.length\n\t\t\tsequentialMode = true\n\t\t\tlet value = this ? this.decode(source, size) : defaultDecoder.decode(source, size)\n\t\t\tif (forEach) {\n\t\t\t\tif (forEach(value) === false) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tif (forEach(checkedRead()) === false) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvalues = [ value ]\n\t\t\t\twhile(position < size) {\n\t\t\t\t\tlastPosition = position\n\t\t\t\t\tvalues.push(checkedRead())\n\t\t\t\t}\n\t\t\t\treturn values\n\t\t\t}\n\t\t} catch(error) {\n\t\t\terror.lastPosition = lastPosition\n\t\t\terror.values = values\n\t\t\tthrow error\n\t\t} finally {\n\t\t\tsequentialMode = false\n\t\t\tclearSource()\n\t\t}\n\t}\n}\nexport function getPosition() {\n\treturn position\n}\nexport function checkedRead() {\n\ttry {\n\t\tlet result = read()\n\t\tif (bundledStrings) {\n\t\t\tif (position >= bundledStrings.postBundlePosition) {\n\t\t\t\tlet error = new Error('Unexpected bundle position');\n\t\t\t\terror.incomplete = true;\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\t// bundled strings to skip past\n\t\t\tposition = bundledStrings.postBundlePosition;\n\t\t\tbundledStrings = null;\n\t\t}\n\n\t\tif (position == srcEnd) {\n\t\t\t// finished reading this source, cleanup references\n\t\t\tcurrentStructures = null\n\t\t\tsrc = null\n\t\t\tif (referenceMap)\n\t\t\t\treferenceMap = null\n\t\t} else if (position > srcEnd) {\n\t\t\t// over read\n\t\t\tlet error = new Error('Unexpected end of CBOR data')\n\t\t\terror.incomplete = true\n\t\t\tthrow error\n\t\t} else if (!sequentialMode) {\n\t\t\tthrow new Error('Data read, but end of buffer not reached')\n\t\t}\n\t\t// else more to read, but we are reading sequentially, so don't clear source yet\n\t\treturn result\n\t} catch(error) {\n\t\tclearSource()\n\t\tif (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) {\n\t\t\terror.incomplete = true\n\t\t}\n\t\tthrow error\n\t}\n}\n\nexport function read() {\n\tlet token = src[position++]\n\tlet majorType = token >> 5\n\ttoken = token & 0x1f\n\tif (token > 0x17) {\n\t\tswitch (token) {\n\t\t\tcase 0x18:\n\t\t\t\ttoken = src[position++]\n\t\t\t\tbreak\n\t\t\tcase 0x19:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\treturn getFloat16()\n\t\t\t\t}\n\t\t\t\ttoken = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tbreak\n\t\t\tcase 0x1a:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\tlet value = dataView.getFloat32(position)\n\t\t\t\t\tif (currentDecoder.useFloat32 > 2) {\n\t\t\t\t\t\t// this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\tlet multiplier = mult10[((src[position] & 0x7f) << 1) | (src[position + 1] >> 7)]\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\treturn ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n\t\t\t\t\t}\n\t\t\t\t\tposition += 4\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\ttoken = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tbreak\n\t\t\tcase 0x1b:\n\t\t\t\tif (majorType == 7) {\n\t\t\t\t\tlet value = dataView.getFloat64(position)\n\t\t\t\t\tposition += 8\n\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\tif (majorType > 1) {\n\t\t\t\t\tif (dataView.getUint32(position) > 0)\n\t\t\t\t\t\tthrow new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295')\n\t\t\t\t\ttoken = dataView.getUint32(position + 4)\n\t\t\t\t} else if (currentDecoder.int64AsNumber) {\n\t\t\t\t\ttoken = dataView.getUint32(position) * 0x100000000\n\t\t\t\t\ttoken += dataView.getUint32(position + 4)\n\t\t\t\t} else\n\t\t\t\t\ttoken = dataView.getBigUint64(position)\n\t\t\t\tposition += 8\n\t\t\t\tbreak\n\t\t\tcase 0x1f: \n\t\t\t\t// indefinite length\n\t\t\t\tswitch(majorType) {\n\t\t\t\t\tcase 2: // byte string\n\t\t\t\t\tcase 3: // text string\n\t\t\t\t\t\tthrow new Error('Indefinite length not supported for byte or text strings')\n\t\t\t\t\tcase 4: // array\n\t\t\t\t\t\tlet array = []\n\t\t\t\t\t\tlet value, i = 0\n\t\t\t\t\t\twhile ((value = read()) != STOP_CODE) {\n\t\t\t\t\t\t\tif (i >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)\n\t\t\t\t\t\t\tarray[i++] = value\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array)\n\t\t\t\t\tcase 5: // map\n\t\t\t\t\t\tlet key\n\t\t\t\t\t\tif (currentDecoder.mapsAsObjects) {\n\t\t\t\t\t\t\tlet object = {}\n\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\tif (currentDecoder.keyMap) {\n\t\t\t\t\t\t\t\twhile((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)\n\t\t\t\t\t\t\t\t\tobject[safeKey(currentDecoder.decodeKey(key))] = read()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\twhile ((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) throw new Error(`Property count exceeds ${maxMapSize}`)\n\t\t\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn object\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (restoreMapsAsObject) {\n\t\t\t\t\t\t\t\tcurrentDecoder.mapsAsObjects = true\n\t\t\t\t\t\t\t\trestoreMapsAsObject = false\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlet map = new Map()\n\t\t\t\t\t\t\tif (currentDecoder.keyMap) {\n\t\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\t\twhile((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(`Map size exceeds ${maxMapSize}`);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmap.set(currentDecoder.decodeKey(key), read())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tlet i = 0;\n\t\t\t\t\t\t\t\twhile ((key = read()) != STOP_CODE) {\n\t\t\t\t\t\t\t\t\tif (i++ >= maxMapSize) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(`Map size exceeds ${maxMapSize}`);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tmap.set(key, read())\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn map\n\t\t\t\t\t\t}\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\treturn STOP_CODE\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new Error('Invalid major type for indefinite length ' + majorType)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tthrow new Error('Unknown token ' + token)\n\t\t}\n\t}\n\tswitch (majorType) {\n\t\tcase 0: // positive int\n\t\t\treturn token\n\t\tcase 1: // negative int\n\t\t\treturn ~token\n\t\tcase 2: // buffer\n\t\t\treturn readBin(token)\n\t\tcase 3: // string\n\t\t\tif (srcStringEnd >= position) {\n\t\t\t\treturn srcString.slice(position - srcStringStart, (position += token) - srcStringStart)\n\t\t\t}\n\t\t\tif (srcStringEnd == 0 && srcEnd < 140 && token < 32) {\n\t\t\t\t// for small blocks, avoiding the overhead of the extract call is helpful\n\t\t\t\tlet string = token < 16 ? shortStringInJS(token) : longStringInJS(token)\n\t\t\t\tif (string != null)\n\t\t\t\t\treturn string\n\t\t\t}\n\t\t\treturn readFixedString(token)\n\t\tcase 4: // array\n\t\t\tif (token >= maxArraySize) throw new Error(`Array length exceeds ${maxArraySize}`)\n\t\t\tlet array = new Array(token)\n\t\t //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read())\t\n\t\t\t//else \n\t\t\tfor (let i = 0; i < token; i++) array[i] = read()\n\t\t\treturn array\n\t\tcase 5: // map\n\t\t\tif (token >= maxMapSize) throw new Error(`Map size exceeds ${maxArraySize}`)\n\t\t\tif (currentDecoder.mapsAsObjects) {\n\t\t\t\tlet object = {}\n\t\t\t\tif (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read()\n\t\t\t\telse for (let i = 0; i < token; i++) object[safeKey(read())] = read()\n\t\t\t\treturn object\n\t\t\t} else {\n\t\t\t\tif (restoreMapsAsObject) {\n\t\t\t\t\tcurrentDecoder.mapsAsObjects = true\n\t\t\t\t\trestoreMapsAsObject = false\n\t\t\t\t}\n\t\t\t\tlet map = new Map()\n\t\t\t\tif (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read())\n\t\t\t\telse for (let i = 0; i < token; i++) map.set(read(), read())\n\t\t\t\treturn map\n\t\t\t}\n\t\tcase 6: // extension\n\t\t\tif (token >= BUNDLED_STRINGS_ID) {\n\t\t\t\tlet structure = currentStructures[token & 0x1fff] // check record structures first\n\t\t\t\t// At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000))\n\t\t\t\tif (structure) {\n\t\t\t\t\tif (!structure.read) structure.read = createStructureReader(structure)\n\t\t\t\t\treturn structure.read()\n\t\t\t\t}\n\t\t\t\tif (token < 0x10000) {\n\t\t\t\t\tif (token == RECORD_INLINE_ID) { // we do a special check for this so that we can keep the\n\t\t\t\t\t\t// currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)\n\t\t\t\t\t\tlet length = readJustLength()\n\t\t\t\t\t\tlet id = read()\n\t\t\t\t\t\tlet structure = read()\n\t\t\t\t\t\trecordDefinition(id, structure)\n\t\t\t\t\t\tlet object = {}\n\t\t\t\t\t\tif (currentDecoder.keyMap) for (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\tlet key = currentDecoder.decodeKey(structure[i - 2])\n\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse for (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\tlet key = structure[i - 2]\n\t\t\t\t\t\t\tobject[safeKey(key)] = read()\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn object\n\t\t\t\t\t}\n\t\t\t\t\telse if (token == RECORD_DEFINITIONS_ID) {\n\t\t\t\t\t\tlet length = readJustLength()\n\t\t\t\t\t\tlet id = read()\n\t\t\t\t\t\tfor (let i = 2; i < length; i++) {\n\t\t\t\t\t\t\trecordDefinition(id++, read())\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn read()\n\t\t\t\t\t} else if (token == BUNDLED_STRINGS_ID) {\n\t\t\t\t\t\treturn readBundleExt()\n\t\t\t\t\t}\n\t\t\t\t\tif (currentDecoder.getShared) {\n\t\t\t\t\t\tloadShared()\n\t\t\t\t\t\tstructure = currentStructures[token & 0x1fff]\n\t\t\t\t\t\tif (structure) {\n\t\t\t\t\t\t\tif (!structure.read)\n\t\t\t\t\t\t\t\tstructure.read = createStructureReader(structure)\n\t\t\t\t\t\t\treturn structure.read()\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet extension = currentExtensions[token]\n\t\t\tif (extension) {\n\t\t\t\tif (extension.handlesRead)\n\t\t\t\t\treturn extension(read)\n\t\t\t\telse\n\t\t\t\t\treturn extension(read())\n\t\t\t} else {\n\t\t\t\tlet input = read()\n\t\t\t\tfor (let i = 0; i < currentExtensionRanges.length; i++) {\n\t\t\t\t\tlet value = currentExtensionRanges[i](token, input)\n\t\t\t\t\tif (value !== undefined)\n\t\t\t\t\t\treturn value\n\t\t\t\t}\n\t\t\t\treturn new Tag(input, token)\n\t\t\t}\n\t\tcase 7: // fixed value\n\t\t\tswitch (token) {\n\t\t\t\tcase 0x14: return false\n\t\t\t\tcase 0x15: return true\n\t\t\t\tcase 0x16: return null\n\t\t\t\tcase 0x17: return; // undefined\n\t\t\t\tcase 0x1f:\n\t\t\t\tdefault:\n\t\t\t\t\tlet packedValue = (packedValues || getPackedValues())[token]\n\t\t\t\t\tif (packedValue !== undefined)\n\t\t\t\t\t\treturn packedValue\n\t\t\t\t\tthrow new Error('Unknown token ' + token)\n\t\t\t}\n\t\tdefault: // negative int\n\t\t\tif (isNaN(token)) {\n\t\t\t\tlet error = new Error('Unexpected end of CBOR data')\n\t\t\t\terror.incomplete = true\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\tthrow new Error('Unknown CBOR token ' + token)\n\t}\n}\nconst validName = /^[a-zA-Z_$][a-zA-Z\\d_$]*$/\nfunction createStructureReader(structure) {\n\tif (!structure) throw new Error('Structure is required in record definition');\n\tfunction readObject() {\n\t\t// get the array size from the header\n\t\tlet length = src[position++]\n\t\t//let majorType = token >> 5\n\t\tlength = length & 0x1f\n\t\tif (length > 0x17) {\n\t\t\tswitch (length) {\n\t\t\t\tcase 0x18:\n\t\t\t\t\tlength = src[position++]\n\t\t\t\t\tbreak\n\t\t\t\tcase 0x19:\n\t\t\t\t\tlength = dataView.getUint16(position)\n\t\t\t\t\tposition += 2\n\t\t\t\t\tbreak\n\t\t\t\tcase 0x1a:\n\t\t\t\t\tlength = dataView.getUint32(position)\n\t\t\t\t\tposition += 4\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new Error('Expected array header, but got ' + src[position - 1])\n\t\t\t}\n\t\t}\n\t\t// This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function\n\t\tlet compiledReader = this.compiledReader // first look to see if we have the fast compiled function\n\t\twhile(compiledReader) {\n\t\t\t// we have a fast compiled object literal reader\n\t\t\tif (compiledReader.propertyCount === length)\n\t\t\t\treturn compiledReader(read) // with the right length, so we use it\n\t\t\tcompiledReader = compiledReader.next // see if there is another reader with the right length\n\t\t}\n\t\tif (this.slowReads++ >= inlineObjectReadThreshold) { // create a fast compiled reader\n\t\t\tlet array = this.length == length ? this : this.slice(0, length)\n\t\t\tcompiledReader = currentDecoder.keyMap \n\t\t\t? new Function('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}')\n\t\t\t: new Function('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}')\n\t\t\tif (this.compiledReader)\n\t\t\t\tcompiledReader.next = this.compiledReader // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure\n\t\t\tcompiledReader.propertyCount = length\n\t\t\tthis.compiledReader = compiledReader\n\t\t\treturn compiledReader(read)\n\t\t}\n\t\tlet object = {}\n\t\tif (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read()\n\t\telse for (let i = 0; i < length; i++) {\n\t\t\tobject[safeKey(this[i])] = read();\n\t\t}\n\t\treturn object\n\t}\n\tstructure.slowReads = 0\n\treturn readObject\n}\n\nfunction safeKey(key) {\n\t// protect against prototype pollution\n\tif (typeof key === 'string') return key === '__proto__' ? '__proto_' : key\n\tif (typeof key === 'number' || typeof key === 'boolean' || typeof key === 'bigint') return key.toString();\n\tif (key == null) return key + '';\n\t// protect against expensive (DoS) string conversions\n\tthrow new Error('Invalid property name type ' + typeof key);\n}\n\nlet readFixedString = readStringJS\nlet readString8 = readStringJS\nlet readString16 = readStringJS\nlet readString32 = readStringJS\n\nexport let isNativeAccelerationEnabled = false\nexport function setExtractor(extractStrings) {\n\tisNativeAccelerationEnabled = true\n\treadFixedString = readString(1)\n\treadString8 = readString(2)\n\treadString16 = readString(3)\n\treadString32 = readString(5)\n\tfunction readString(headerLength) {\n\t\treturn function readString(length) {\n\t\t\tlet string = strings[stringPosition++]\n\t\t\tif (string == null) {\n\t\t\t\tif (bundledStrings)\n\t\t\t\t\treturn readStringJS(length)\n\t\t\t\tlet extraction = extractStrings(position, srcEnd, length, src)\n\t\t\t\tif (typeof extraction == 'string') {\n\t\t\t\t\tstring = extraction\n\t\t\t\t\tstrings = EMPTY_ARRAY\n\t\t\t\t} else {\n\t\t\t\t\tstrings = extraction\n\t\t\t\t\tstringPosition = 1\n\t\t\t\t\tsrcStringEnd = 1 // even if a utf-8 string was decoded, must indicate we are in the midst of extracted strings and can't skip strings\n\t\t\t\t\tstring = strings[0]\n\t\t\t\t\tif (string === undefined)\n\t\t\t\t\t\tthrow new Error('Unexpected end of buffer')\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet srcStringLength = string.length\n\t\t\tif (srcStringLength <= length) {\n\t\t\t\tposition += length\n\t\t\t\treturn string\n\t\t\t}\n\t\t\tsrcString = string\n\t\t\tsrcStringStart = position\n\t\t\tsrcStringEnd = position + srcStringLength\n\t\t\tposition += length\n\t\t\treturn string.slice(0, length) // we know we just want the beginning\n\t\t}\n\t}\n}\nfunction readStringJS(length) {\n\tlet result\n\tif (length < 16) {\n\t\tif (result = shortStringInJS(length))\n\t\t\treturn result\n\t}\n\tif (length > 64 && decoder)\n\t\treturn decoder.decode(src.subarray(position, position += length))\n\tconst end = position + length\n\tconst units = []\n\tresult = ''\n\twhile (position < end) {\n\t\tconst byte1 = src[position++]\n\t\tif ((byte1 & 0x80) === 0) {\n\t\t\t// 1 byte\n\t\t\tunits.push(byte1)\n\t\t} else if ((byte1 & 0xe0) === 0xc0) {\n\t\t\t// 2 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 6) | byte2)\n\t\t} else if ((byte1 & 0xf0) === 0xe0) {\n\t\t\t// 3 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tunits.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3)\n\t\t} else if ((byte1 & 0xf8) === 0xf0) {\n\t\t\t// 4 bytes\n\t\t\tconst byte2 = src[position++] & 0x3f\n\t\t\tconst byte3 = src[position++] & 0x3f\n\t\t\tconst byte4 = src[position++] & 0x3f\n\t\t\tlet unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4\n\t\t\tif (unit > 0xffff) {\n\t\t\t\tunit -= 0x10000\n\t\t\t\tunits.push(((unit >>> 10) & 0x3ff) | 0xd800)\n\t\t\t\tunit = 0xdc00 | (unit & 0x3ff)\n\t\t\t}\n\t\t\tunits.push(unit)\n\t\t} else {\n\t\t\tunits.push(byte1)\n\t\t}\n\n\t\tif (units.length >= 0x1000) {\n\t\t\tresult += fromCharCode.apply(String, units)\n\t\t\tunits.length = 0\n\t\t}\n\t}\n\n\tif (units.length > 0) {\n\t\tresult += fromCharCode.apply(String, units)\n\t}\n\n\treturn result\n}\nlet fromCharCode = String.fromCharCode\nfunction longStringInJS(length) {\n\tlet start = position\n\tlet bytes = new Array(length)\n\tfor (let i = 0; i < length; i++) {\n\t\tconst byte = src[position++];\n\t\tif ((byte & 0x80) > 0) {\n\t\t\tposition = start\n \t\t\treturn\n \t\t}\n \t\tbytes[i] = byte\n \t}\n \treturn fromCharCode.apply(String, bytes)\n}\nfunction shortStringInJS(length) {\n\tif (length < 4) {\n\t\tif (length < 2) {\n\t\t\tif (length === 0)\n\t\t\t\treturn ''\n\t\t\telse {\n\t\t\t\tlet a = src[position++]\n\t\t\t\tif ((a & 0x80) > 1) {\n\t\t\t\t\tposition -= 1\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a)\n\t\t\t}\n\t\t} else {\n\t\t\tlet a = src[position++]\n\t\t\tlet b = src[position++]\n\t\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0) {\n\t\t\t\tposition -= 2\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 3)\n\t\t\t\treturn fromCharCode(a, b)\n\t\t\tlet c = src[position++]\n\t\t\tif ((c & 0x80) > 0) {\n\t\t\t\tposition -= 3\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c)\n\t\t}\n\t} else {\n\t\tlet a = src[position++]\n\t\tlet b = src[position++]\n\t\tlet c = src[position++]\n\t\tlet d = src[position++]\n\t\tif ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) {\n\t\t\tposition -= 4\n\t\t\treturn\n\t\t}\n\t\tif (length < 6) {\n\t\t\tif (length === 4)\n\t\t\t\treturn fromCharCode(a, b, c, d)\n\t\t\telse {\n\t\t\t\tlet e = src[position++]\n\t\t\t\tif ((e & 0x80) > 0) {\n\t\t\t\t\tposition -= 5\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e)\n\t\t\t}\n\t\t} else if (length < 8) {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0) {\n\t\t\t\tposition -= 6\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 7)\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f)\n\t\t\tlet g = src[position++]\n\t\t\tif ((g & 0x80) > 0) {\n\t\t\t\tposition -= 7\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn fromCharCode(a, b, c, d, e, f, g)\n\t\t} else {\n\t\t\tlet e = src[position++]\n\t\t\tlet f = src[position++]\n\t\t\tlet g = src[position++]\n\t\t\tlet h = src[position++]\n\t\t\tif ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) {\n\t\t\t\tposition -= 8\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (length < 10) {\n\t\t\t\tif (length === 8)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h)\n\t\t\t\telse {\n\t\t\t\t\tlet i = src[position++]\n\t\t\t\t\tif ((i & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 9\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i)\n\t\t\t\t}\n\t\t\t} else if (length < 12) {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0) {\n\t\t\t\t\tposition -= 10\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 11)\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j)\n\t\t\t\tlet k = src[position++]\n\t\t\t\tif ((k & 0x80) > 0) {\n\t\t\t\t\tposition -= 11\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k)\n\t\t\t} else {\n\t\t\t\tlet i = src[position++]\n\t\t\t\tlet j = src[position++]\n\t\t\t\tlet k = src[position++]\n\t\t\t\tlet l = src[position++]\n\t\t\t\tif ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) {\n\t\t\t\t\tposition -= 12\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif (length < 14) {\n\t\t\t\t\tif (length === 12)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l)\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\t\tif ((m & 0x80) > 0) {\n\t\t\t\t\t\t\tposition -= 13\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet m = src[position++]\n\t\t\t\t\tlet n = src[position++]\n\t\t\t\t\tif ((m & 0x80) > 0 || (n & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 14\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tif (length < 15)\n\t\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n)\n\t\t\t\t\tlet o = src[position++]\n\t\t\t\t\tif ((o & 0x80) > 0) {\n\t\t\t\t\t\tposition -= 15\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readBin(length) {\n\treturn currentDecoder.copyBuffers ?\n\t\t// specifically use the copying slice (not the node one)\n\t\tUint8Array.prototype.slice.call(src, position, position += length) :\n\t\tsrc.subarray(position, position += length)\n}\nfunction readExt(length) {\n\tlet type = src[position++]\n\tif (currentExtensions[type]) {\n\t\treturn currentExtensions[type](src.subarray(position, position += length))\n\t}\n\telse\n\t\tthrow new Error('Unknown extension type ' + type)\n}\nlet f32Array = new Float32Array(1)\nlet u8Array = new Uint8Array(f32Array.buffer, 0, 4)\nfunction getFloat16() {\n\tlet byte0 = src[position++]\n\tlet byte1 = src[position++]\n\tlet exponent = (byte0 & 0x7f) >> 2;\n\tif (exponent === 0x1f) { // specials\n\t\tif (byte1 || (byte0 & 3))\n\t\t\treturn NaN;\n\t\treturn (byte0 & 0x80) ? -Infinity : Infinity;\n\t}\n\tif (exponent === 0) { // sub-normals\n\t\t// significand with 10 fractional bits and divided by 2^14\n\t\tlet abs = (((byte0 & 3) << 8) | byte1) / (1 << 24)\n\t\treturn (byte0 & 0x80) ? -abs : abs\n\t}\n\n\tu8Array[3] = (byte0 & 0x80) | // sign bit\n\t\t((exponent >> 1) + 56) // 4 of 5 of the exponent bits, re-offset-ed\n\tu8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits\n\t\t(byte1 >> 3) // next 5 bits of mantissa\n\tu8Array[1] = byte1 << 5; // last three bits of mantissa\n\tu8Array[0] = 0;\n\treturn f32Array[0];\n}\n\nlet keyCache = new Array(4096)\nfunction readKey() {\n\tlet length = src[position++]\n\tif (length >= 0x60 && length < 0x78) {\n\t\t// fixstr, potentially use key cache\n\t\tlength = length - 0x60\n\t\tif (srcStringEnd >= position) // if it has been extracted, must use it (and faster anyway)\n\t\t\treturn srcString.slice(position - srcStringStart, (position += length) - srcStringStart)\n\t\telse if (!(srcStringEnd == 0 && srcEnd < 180))\n\t\t\treturn readFixedString(length)\n\t} else { // not cacheable, go back and do a standard read\n\t\tposition--\n\t\treturn read()\n\t}\n\tlet key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 0xfff\n\tlet entry = keyCache[key]\n\tlet checkPosition = position\n\tlet end = position + length - 3\n\tlet chunk\n\tlet i = 0\n\tif (entry && entry.bytes == length) {\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = dataView.getUint32(checkPosition)\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcheckPosition += 4\n\t\t}\n\t\tend += 3\n\t\twhile (checkPosition < end) {\n\t\t\tchunk = src[checkPosition++]\n\t\t\tif (chunk != entry[i++]) {\n\t\t\t\tcheckPosition = 0x70000000\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (checkPosition === end) {\n\t\t\tposition = checkPosition\n\t\t\treturn entry.string\n\t\t}\n\t\tend -= 3\n\t\tcheckPosition = position\n\t}\n\tentry = []\n\tkeyCache[key] = entry\n\tentry.bytes = length\n\twhile (checkPosition < end) {\n\t\tchunk = dataView.getUint32(checkPosition)\n\t\tentry.push(chunk)\n\t\tcheckPosition += 4\n\t}\n\tend += 3\n\twhile (checkPosition < end) {\n\t\tchunk = src[checkPosition++]\n\t\tentry.push(chunk)\n\t}\n\t// for small blocks, avoiding the overhead of the extract call is helpful\n\tlet string = length < 16 ? shortStringInJS(length) : longStringInJS(length)\n\tif (string != null)\n\t\treturn entry.string = string\n\treturn entry.string = readFixedString(length)\n}\n\nexport class Tag {\n\tconstructor(value, tag) {\n\t\tthis.value = value\n\t\tthis.tag = tag\n\t}\n}\n\ncurrentExtensions[0] = (dateString) => {\n\t// string date extension\n\treturn new Date(dateString)\n}\n\ncurrentExtensions[1] = (epochSec) => {\n\t// numeric date extension\n\treturn new Date(Math.round(epochSec * 1000))\n}\n\ncurrentExtensions[2] = (buffer) => {\n\t// bigint extension\n\tlet value = BigInt(0)\n\tfor (let i = 0, l = buffer.byteLength; i < l; i++) {\n\t\tvalue = BigInt(buffer[i]) + (value << BigInt(8))\n\t}\n\treturn value\n}\n\ncurrentExtensions[3] = (buffer) => {\n\t// negative bigint extension\n\treturn BigInt(-1) - currentExtensions[2](buffer)\n}\ncurrentExtensions[4] = (fraction) => {\n\t// best to reparse to maintain accuracy\n\treturn +(fraction[1] + 'e' + fraction[0])\n}\n\ncurrentExtensions[5] = (fraction) => {\n\t// probably not sufficiently accurate\n\treturn fraction[1] * Math.exp(fraction[0] * Math.log(2))\n}\n\n// the registration of the record definition extension\nconst recordDefinition = (id, structure) => {\n\tid = id - 0xe000\n\tlet existingStructure = currentStructures[id]\n\tif (existingStructure && existingStructure.isShared) {\n\t\t(currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure\n\t}\n\tcurrentStructures[id] = structure\n\n\tstructure.read = createStructureReader(structure)\n}\ncurrentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => {\n\tlet length = data.length\n\tlet structure = data[1]\n\trecordDefinition(data[0], structure)\n\tlet object = {}\n\tfor (let i = 2; i < length; i++) {\n\t\tlet key = structure[i - 2]\n\t\tobject[safeKey(key)] = data[i]\n\t}\n\treturn object\n}\ncurrentExtensions[14] = (value) => {\n\tif (bundledStrings)\n\t\treturn bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 += value)\n\treturn new Tag(value, 14)\n}\ncurrentExtensions[15] = (value) => {\n\tif (bundledStrings)\n\t\treturn bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value)\n\treturn new Tag(value, 15)\n}\nlet glbl = { Error, RegExp }\ncurrentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object\n\treturn (glbl[data[0]] || Error)(data[1], data[2])\n}\nconst packedTable = (read) => {\n\tif (src[position++] != 0x84) {\n\t\tlet error = new Error('Packed values structure must be followed by a 4 element array')\n\t\tif (src.length < position)\n\t\t\terror.incomplete = true\n\t\tthrow error\n\t}\n\tlet newPackedValues = read() // packed values\n\tif (!newPackedValues || !newPackedValues.length) {\n\t\tlet error = new Error('Packed values structure must be followed by a 4 element array')\n\t\terror.incomplete = true\n\t\tthrow error\n\t}\n\tpackedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues\n\tpackedValues.prefixes = read()\n\tpackedValues.suffixes = read()\n\treturn read() // read the rump\n}\npackedTable.handlesRead = true\ncurrentExtensions[51] = packedTable\n\ncurrentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference\n\tif (!packedValues) {\n\t\tif (currentDecoder.getShared)\n\t\t\tloadShared()\n\t\telse\n\t\t\treturn new Tag(data, PACKED_REFERENCE_TAG_ID)\n\t}\n\tif (typeof data == 'number')\n\t\treturn packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))]\n\tlet error = new Error('No support for non-integer packed references yet')\n\tif (data === undefined)\n\t\terror.incomplete = true\n\tthrow error\n}\n\n// The following code is an incomplete implementation of http://cbor.schmorp.de/stringref\n// the real thing would need to implemennt more logic to populate the stringRefs table and\n// maintain a stack of stringRef \"namespaces\".\n//\n// currentExtensions[25] = (id) => {\n// \treturn stringRefs[id]\n// }\n// currentExtensions[256] = (read) => {\n// \tstringRefs = []\n// \ttry {\n// \t\treturn read()\n// \t} finally {\n// \t\tstringRefs = null\n// \t}\n// }\n// currentExtensions[256].handlesRead = true\n\ncurrentExtensions[28] = (read) => { \n\t// shareable http://cbor.schmorp.de/value-sharing (for structured clones)\n\tif (!referenceMap) {\n\t\treferenceMap = new Map()\n\t\treferenceMap.id = 0\n\t}\n\tlet id = referenceMap.id++\n\tlet startingPosition = position\n\tlet token = src[position]\n\tlet target\n\t// TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read\n\t// ahead past references to record structure definitions\n\tif ((token >> 5) == 4)\n\t\ttarget = []\n\telse\n\t\ttarget = {}\n\n\tlet refEntry = { target } // a placeholder object\n\treferenceMap.set(id, refEntry)\n\tlet targetProperties = read() // read the next value as the target object to id\n\tif (refEntry.used) {// there is a cycle, so we have to assign properties to original target\n\t\tif (Object.getPrototypeOf(target) !== Object.getPrototypeOf(targetProperties)) {\n\t\t\t// this means that the returned target does not match the targetProperties, so we need rerun the read to\n\t\t\t// have the correctly create instance be assigned as a reference, then we do the copy the properties back to the\n\t\t\t// target\n\t\t\t// reset the position so that the read can be repeated\n\t\t\tposition = startingPosition\n\t\t\t// the returned instance is our new target for references\n\t\t\ttarget = targetProperties\n\t\t\treferenceMap.set(id, { target })\n\t\t\ttargetProperties = read()\n\t\t}\n\t\treturn Object.assign(target, targetProperties)\n\t}\n\trefEntry.target = targetProperties // the placeholder wasn't used, replace with the deserialized one\n\treturn targetProperties // no cycle, can just use the returned read object\n}\ncurrentExtensions[28].handlesRead = true\n\ncurrentExtensions[29] = (id) => {\n\t// sharedref http://cbor.schmorp.de/value-sharing (for structured clones)\n\tlet refEntry = referenceMap.get(id)\n\trefEntry.used = true\n\treturn refEntry.target\n}\n\ncurrentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md\n(currentExtensions[259] = (read) => {\n\t// https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec\n\t// for decoding as a standard Map\n\tif (currentDecoder.mapsAsObjects) {\n\t\tcurrentDecoder.mapsAsObjects = false\n\t\trestoreMapsAsObject = true\n\t}\n\treturn read()\n}).handlesRead = true\nfunction combine(a, b) {\n\tif (typeof a === 'string')\n\t\treturn a + b\n\tif (a instanceof Array)\n\t\treturn a.concat(b)\n\treturn Object.assign({}, a, b)\n}\nfunction getPackedValues() {\n\tif (!packedValues) {\n\t\tif (currentDecoder.getShared)\n\t\t\tloadShared()\n\t\telse\n\t\t\tthrow new Error('No packed values available')\n\t}\n\treturn packedValues\n}\nconst SHARED_DATA_TAG_ID = 0x53687264 // ascii 'Shrd'\ncurrentExtensionRanges.push((tag, input) => {\n\tif (tag >= 225 && tag <= 255)\n\t\treturn combine(getPackedValues().prefixes[tag - 224], input)\n\tif (tag >= 28704 && tag <= 32767)\n\t\treturn combine(getPackedValues().prefixes[tag - 28672], input)\n\tif (tag >= 1879052288 && tag <= 2147483647)\n\t\treturn combine(getPackedValues().prefixes[tag - 1879048192], input)\n\tif (tag >= 216 && tag <= 223)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 216])\n\tif (tag >= 27647 && tag <= 28671)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 27639])\n\tif (tag >= 1811940352 && tag <= 1879048191)\n\t\treturn combine(input, getPackedValues().suffixes[tag - 1811939328])\n\tif (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements)\n\t\treturn {\n\t\t\tpackedValues: packedValues,\n\t\t\tstructures: currentStructures.slice(0),\n\t\t\tversion: input,\n\t\t}\n\t}\n\tif (tag == 55799) // self-descriptive CBOR tag, just return input value\n\t\treturn input\n})\n\nconst isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1\nexport const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,\n\ttypeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array,\n\ttypeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array]\nconst typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86]\nfor (let i = 0; i < typedArrays.length; i++) {\n\tregisterTypedArray(typedArrays[i], typedArrayTags[i])\n}\nfunction registerTypedArray(TypedArray, tag) {\n\tlet dvMethod = 'get' + TypedArray.name.slice(0, -5)\n\tlet bytesPerElement;\n\tif (typeof TypedArray === 'function')\n\t\tbytesPerElement = TypedArray.BYTES_PER_ELEMENT;\n\telse\n\t\tTypedArray = null;\n\tfor (let littleEndian = 0; littleEndian < 2; littleEndian++) {\n\t\tif (!littleEndian && bytesPerElement == 1)\n\t\t\tcontinue\n\t\tlet sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : bytesPerElement == 8 ? 3 : 0\n\t\tcurrentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine) ? (buffer) => {\n\t\t\tif (!TypedArray)\n\t\t\t\tthrow new Error('Could not find typed array for code ' + tag)\n\t\t\tif (!currentDecoder.copyBuffers) {\n\t\t\t\t// try provide a direct view, but will only work if we are byte-aligned\n\t\t\t\tif (bytesPerElement === 1 ||\n\t\t\t\t\tbytesPerElement === 2 && !(buffer.byteOffset & 1) ||\n\t\t\t\t\tbytesPerElement === 4 && !(buffer.byteOffset & 3) ||\n\t\t\t\t\tbytesPerElement === 8 && !(buffer.byteOffset & 7))\n\t\t\t\t\treturn new TypedArray(buffer.buffer, buffer.byteOffset, buffer.byteLength >> sizeShift);\n\t\t\t}\n\t\t\t// we have to slice/copy here to get a new ArrayBuffer, if we are not word/byte aligned\n\t\t\treturn new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer)\n\t\t} : buffer => {\n\t\t\tif (!TypedArray)\n\t\t\t\tthrow new Error('Could not find typed array for code ' + tag)\n\t\t\tlet dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n\t\t\tlet elements = buffer.length >> sizeShift\n\t\t\tlet ta = new TypedArray(elements)\n\t\t\tlet method = dv[dvMethod]\n\t\t\tfor (let i = 0; i < elements; i++) {\n\t\t\t\tta[i] = method.call(dv, i << sizeShift, littleEndian)\n\t\t\t}\n\t\t\treturn ta\n\t\t}\n\t}\n}\n\nfunction readBundleExt() {\n\tlet length = readJustLength()\n\tlet bundlePosition = position + read()\n\tfor (let i = 2; i < length; i++) {\n\t\t// skip past bundles that were already read\n\t\tlet bundleLength = readJustLength() // this will increment position, so must add to position afterwards\n\t\tposition += bundleLength\n\t}\n\tlet dataPosition = position\n\tposition = bundlePosition\n\tbundledStrings = [readStringJS(readJustLength()), readStringJS(readJustLength())]\n\tbundledStrings.position0 = 0\n\tbundledStrings.position1 = 0\n\tbundledStrings.postBundlePosition = position\n\tposition = dataPosition\n\treturn read()\n}\n\nfunction readJustLength() {\n\tlet token = src[position++] & 0x1f\n\tif (token > 0x17) {\n\t\tswitch (token) {\n\t\t\tcase 0x18:\n\t\t\t\ttoken = src[position++]\n\t\t\t\tbreak\n\t\t\tcase 0x19:\n\t\t\t\ttoken = dataView.getUint16(position)\n\t\t\t\tposition += 2\n\t\t\t\tbreak\n\t\t\tcase 0x1a:\n\t\t\t\ttoken = dataView.getUint32(position)\n\t\t\t\tposition += 4\n\t\t\t\tbreak\n\t\t}\n\t}\n\treturn token\n}\n\nfunction loadShared() {\n\tif (currentDecoder.getShared) {\n\t\tlet sharedData = saveState(() => {\n\t\t\t// save the state in case getShared modifies our buffer\n\t\t\tsrc = null\n\t\t\treturn currentDecoder.getShared()\n\t\t}) || {}\n\t\tlet updatedStructures = sharedData.structures || []\n\t\tcurrentDecoder.sharedVersion = sharedData.version\n\t\tpackedValues = currentDecoder.sharedValues = sharedData.packedValues\n\t\tif (currentStructures === true)\n\t\t\tcurrentDecoder.structures = currentStructures = updatedStructures\n\t\telse\n\t\t\tcurrentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures))\n\t}\n}\n\nfunction saveState(callback) {\n\tlet savedSrcEnd = srcEnd\n\tlet savedPosition = position\n\tlet savedStringPosition = stringPosition\n\tlet savedSrcStringStart = srcStringStart\n\tlet savedSrcStringEnd = srcStringEnd\n\tlet savedSrcString = srcString\n\tlet savedStrings = strings\n\tlet savedReferenceMap = referenceMap\n\tlet savedBundledStrings = bundledStrings\n\n\t// TODO: We may need to revisit this if we do more external calls to user code (since it could be slow)\n\tlet savedSrc = new Uint8Array(src.slice(0, srcEnd)) // we copy the data in case it changes while external data is processed\n\tlet savedStructures = currentStructures\n\tlet savedDecoder = currentDecoder\n\tlet savedSequentialMode = sequentialMode\n\tlet value = callback()\n\tsrcEnd = savedSrcEnd\n\tposition = savedPosition\n\tstringPosition = savedStringPosition\n\tsrcStringStart = savedSrcStringStart\n\tsrcStringEnd = savedSrcStringEnd\n\tsrcString = savedSrcString\n\tstrings = savedStrings\n\treferenceMap = savedReferenceMap\n\tbundledStrings = savedBundledStrings\n\tsrc = savedSrc\n\tsequentialMode = savedSequentialMode\n\tcurrentStructures = savedStructures\n\tcurrentDecoder = savedDecoder\n\tdataView = new DataView(src.buffer, src.byteOffset, src.byteLength)\n\treturn value\n}\nexport function clearSource() {\n\tsrc = null\n\treferenceMap = null\n\tcurrentStructures = null\n}\n\nexport function addExtension(extension) {\n\tcurrentExtensions[extension.tag] = extension.decode\n}\n\nexport function setSizeLimits(limits) {\n\tif (limits.maxMapSize) maxMapSize = limits.maxMapSize;\n\tif (limits.maxArraySize) maxArraySize = limits.maxArraySize;\n\tif (limits.maxObjectSize) maxObjectSize = limits.maxObjectSize;\n}\n\nexport const mult10 = new Array(147) // this is a table matching binary exponents to the multiplier to determine significant digit rounding\nfor (let i = 0; i < 256; i++) {\n\tmult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103))\n}\nlet defaultDecoder = new Decoder({ useRecords: false })\nexport const decode = defaultDecoder.decode\nexport const decodeMultiple = defaultDecoder.decodeMultiple\nexport const FLOAT32_OPTIONS = {\n\tNEVER: 0,\n\tALWAYS: 1,\n\tDECIMAL_ROUND: 3,\n\tDECIMAL_FIT: 4\n}\nexport function roundFloat32(float32Number) {\n\tf32Array[0] = float32Number\n\tlet multiplier = mult10[((u8Array[3] & 0x7f) << 1) | (u8Array[2] >> 7)]\n\treturn ((multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5)) >> 0) / multiplier\n}\n", "import { Decoder, mult10, Tag, typedArrays, addExtension as decodeAddExtension } from './decode.js'\nlet textEncoder\ntry {\n\ttextEncoder = new TextEncoder()\n} catch (error) {}\nlet extensions, extensionClasses\nconst Buffer = typeof globalThis === 'object' && globalThis.Buffer;\nconst hasNodeBuffer = typeof Buffer !== 'undefined'\nconst ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array\nconst ByteArray = hasNodeBuffer ? Buffer : Uint8Array\nconst MAX_STRUCTURES = 0x100\nconst MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000\nlet serializationId = 1\nlet throwOnIterable\nlet target\nlet targetView\nlet position = 0\nlet safeEnd\nlet bundledStrings = null\nconst MAX_BUNDLE_SIZE = 0xf000\nconst hasNonLatin = /[\\u0080-\\uFFFF]/\nconst RECORD_SYMBOL = Symbol('record-id')\nexport class Encoder extends Decoder {\n\tconstructor(options) {\n\t\tsuper(options)\n\t\tthis.offset = 0\n\t\tlet typeBuffer\n\t\tlet start\n\t\tlet sharedStructures\n\t\tlet hasSharedUpdate\n\t\tlet structures\n\t\tlet referenceMap\n\t\toptions = options || {}\n\t\tlet encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) {\n\t\t\treturn target.utf8Write(string, position, maxBytes)\n\t\t} : (textEncoder && textEncoder.encodeInto) ?\n\t\t\tfunction(string, position) {\n\t\t\t\treturn textEncoder.encodeInto(string, target.subarray(position)).written\n\t\t\t} : false\n\n\t\tlet encoder = this\n\t\tlet hasSharedStructures = options.structures || options.saveStructures\n\t\tlet maxSharedStructures = options.maxSharedStructures\n\t\tif (maxSharedStructures == null)\n\t\t\tmaxSharedStructures = hasSharedStructures ? 128 : 0\n\t\tif (maxSharedStructures > 8190)\n\t\t\tthrow new Error('Maximum maxSharedStructure is 8190')\n\t\tlet isSequential = options.sequential\n\t\tif (isSequential) {\n\t\t\tmaxSharedStructures = 0\n\t\t}\n\t\tif (!this.structures)\n\t\t\tthis.structures = []\n\t\tif (this.saveStructures)\n\t\t\tthis.saveShared = this.saveStructures\n\t\tlet samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues\n\t\tlet sharedPackedObjectMap\n\t\tif (sharedValues) {\n\t\t\tsharedPackedObjectMap = Object.create(null)\n\t\t\tfor (let i = 0, l = sharedValues.length; i < l; i++) {\n\t\t\t\tsharedPackedObjectMap[sharedValues[i]] = i\n\t\t\t}\n\t\t}\n\t\tlet recordIdsToRemove = []\n\t\tlet transitionsCount = 0\n\t\tlet serializationsSinceTransitionRebuild = 0\n\t\t\n\t\tthis.mapEncode = function(value, encodeOptions) {\n\t\t\t// Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet)\n\t\t\tif (this._keyMap && !this._mapped) {\n\t\t\t\t//console.log('encoding ', value)\n\t\t\t\tswitch (value.constructor.name) {\n\t\t\t\t\tcase 'Array': \n\t\t\t\t\t\tvalue = value.map(r => this.encodeKeys(r))\n\t\t\t\t\t\tbreak\n\t\t\t\t\t//case 'Map': \n\t\t\t\t\t//\tvalue = this.encodeKeys(value)\n\t\t\t\t\t//\tbreak\n\t\t\t\t}\n\t\t\t\t//this._mapped = true\n\t\t\t}\n\t\t\treturn this.encode(value, encodeOptions)\n\t\t}\n\t\t\n\t\tthis.encode = function(value, encodeOptions)\t{\n\t\t\tif (!target) {\n\t\t\t\ttarget = new ByteArrayAllocate(8192)\n\t\t\t\ttargetView = new DataView(target.buffer, 0, 8192)\n\t\t\t\tposition = 0\n\t\t\t}\n\t\t\tsafeEnd = target.length - 10\n\t\t\tif (safeEnd - position < 0x800) {\n\t\t\t\t// don't start too close to the end, \n\t\t\t\ttarget = new ByteArrayAllocate(target.length)\n\t\t\t\ttargetView = new DataView(target.buffer, 0, target.length)\n\t\t\t\tsafeEnd = target.length - 10\n\t\t\t\tposition = 0\n\t\t\t} else if (encodeOptions === REUSE_BUFFER_MODE)\n\t\t\t\tposition = (position + 7) & 0x7ffffff8 // Word align to make any future copying of this buffer faster\n\t\t\tstart = position\n\t\t\tif (encoder.useSelfDescribedHeader) {\n\t\t\t\ttargetView.setUint32(position, 0xd9d9f700) // tag two byte, then self-descriptive tag\n\t\t\t\tposition += 3\n\t\t\t}\n\t\t\treferenceMap = encoder.structuredClone ? new Map() : null\n\t\t\tif (encoder.bundleStrings && typeof value !== 'string') {\n\t\t\t\tbundledStrings = []\n\t\t\t\tbundledStrings.size = Infinity // force a new bundle start on first string\n\t\t\t} else\n\t\t\t\tbundledStrings = null\n\n\t\t\tsharedStructures = encoder.structures\n\t\t\tif (sharedStructures) {\n\t\t\t\tif (sharedStructures.uninitialized) {\n\t\t\t\t\tlet sharedData = encoder.getShared() || {}\n\t\t\t\t\tencoder.structures = sharedStructures = sharedData.structures || []\n\t\t\t\t\tencoder.sharedVersion = sharedData.version\n\t\t\t\t\tlet sharedValues = encoder.sharedValues = sharedData.packedValues\n\t\t\t\t\tif (sharedValues) {\n\t\t\t\t\t\tsharedPackedObjectMap = {}\n\t\t\t\t\t\tfor (let i = 0, l = sharedValues.length; i < l; i++)\n\t\t\t\t\t\t\tsharedPackedObjectMap[sharedValues[i]] = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet sharedStructuresLength = sharedStructures.length\n\t\t\t\tif (sharedStructuresLength > maxSharedStructures && !isSequential)\n\t\t\t\t\tsharedStructuresLength = maxSharedStructures\n\t\t\t\tif (!sharedStructures.transitions) {\n\t\t\t\t\t// rebuild our structure transitions\n\t\t\t\t\tsharedStructures.transitions = Object.create(null)\n\t\t\t\t\tfor (let i = 0; i < sharedStructuresLength; i++) {\n\t\t\t\t\t\tlet keys = sharedStructures[i]\n\t\t\t\t\t\t//console.log('shared struct keys:', keys)\n\t\t\t\t\t\tif (!keys)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tlet nextTransition, transition = sharedStructures.transitions\n\t\t\t\t\t\tfor (let j = 0, l = keys.length; j < l; j++) {\n\t\t\t\t\t\t\tif (transition[RECORD_SYMBOL] === undefined)\n\t\t\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i\n\t\t\t\t\t\t\tlet key = keys[j]\n\t\t\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttransition[RECORD_SYMBOL] = i | 0x100000\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!isSequential)\n\t\t\t\t\tsharedStructures.nextId = sharedStructuresLength\n\t\t\t}\n\t\t\tif (hasSharedUpdate)\n\t\t\t\thasSharedUpdate = false\n\t\t\tstructures = sharedStructures || []\n\t\t\tpackedObjectMap = sharedPackedObjectMap\n\t\t\tif (options.pack) {\n\t\t\t\tlet packedValues = new Map()\n\t\t\t\tpackedValues.values = []\n\t\t\t\tpackedValues.encoder = encoder\n\t\t\t\tpackedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity)\n\t\t\t\tpackedValues.objectMap = sharedPackedObjectMap || false\n\t\t\t\tpackedValues.samplingPackedValues = samplingPackedValues\n\t\t\t\tfindRepetitiveStrings(value, packedValues)\n\t\t\t\tif (packedValues.values.length > 0) {\n\t\t\t\t\ttarget[position++] = 0xd8 // one-byte tag\n\t\t\t\t\ttarget[position++] = 51 // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\twriteArrayHeader(4)\n\t\t\t\t\tlet valuesArray = packedValues.values\n\t\t\t\t\tencode(valuesArray)\n\t\t\t\t\twriteArrayHeader(0) // prefixes\n\t\t\t\t\twriteArrayHeader(0) // suffixes\n\t\t\t\t\tpackedObjectMap = Object.create(sharedPackedObjectMap || null)\n\t\t\t\t\tfor (let i = 0, l = valuesArray.length; i < l; i++) {\n\t\t\t\t\t\tpackedObjectMap[valuesArray[i]] = i\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrowOnIterable = encodeOptions & THROW_ON_ITERABLE;\n\t\t\ttry {\n\t\t\t\tif (throwOnIterable)\n\t\t\t\t\treturn;\n\t\t\t\tencode(value)\n\t\t\t\tif (bundledStrings) {\n\t\t\t\t\twriteBundles(start, encode)\n\t\t\t\t}\n\t\t\t\tencoder.offset = position // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially\n\t\t\t\tif (referenceMap && referenceMap.idsToInsert) {\n\t\t\t\t\tposition += referenceMap.idsToInsert.length * 2\n\t\t\t\t\tif (position > safeEnd)\n\t\t\t\t\t\tmakeRoom(position)\n\t\t\t\t\tencoder.offset = position\n\t\t\t\t\tlet serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert)\n\t\t\t\t\treferenceMap = null\n\t\t\t\t\treturn serialized\n\t\t\t\t}\n\t\t\t\tif (encodeOptions & REUSE_BUFFER_MODE) {\n\t\t\t\t\ttarget.start = start\n\t\t\t\t\ttarget.end = position\n\t\t\t\t\treturn target\n\t\t\t\t}\n\t\t\t\treturn target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now\n\t\t\t} finally {\n\t\t\t\tif (sharedStructures) {\n\t\t\t\t\tif (serializationsSinceTransitionRebuild < 10)\n\t\t\t\t\t\tserializationsSinceTransitionRebuild++\n\t\t\t\t\tif (sharedStructures.length > maxSharedStructures)\n\t\t\t\t\t\tsharedStructures.length = maxSharedStructures\n\t\t\t\t\tif (transitionsCount > 10000) {\n\t\t\t\t\t\t// force a rebuild occasionally after a lot of transitions so it can get cleaned up\n\t\t\t\t\t\tsharedStructures.transitions = null\n\t\t\t\t\t\tserializationsSinceTransitionRebuild = 0\n\t\t\t\t\t\ttransitionsCount = 0\n\t\t\t\t\t\tif (recordIdsToRemove.length > 0)\n\t\t\t\t\t\t\trecordIdsToRemove = []\n\t\t\t\t\t} else if (recordIdsToRemove.length > 0 && !isSequential) {\n\t\t\t\t\t\tfor (let i = 0, l = recordIdsToRemove.length; i < l; i++) {\n\t\t\t\t\t\t\trecordIdsToRemove[i][RECORD_SYMBOL] = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecordIdsToRemove = []\n\t\t\t\t\t\t//sharedStructures.nextId = maxSharedStructures\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (hasSharedUpdate && encoder.saveShared) {\n\t\t\t\t\tif (encoder.structures.length > maxSharedStructures) {\n\t\t\t\t\t\tencoder.structures = encoder.structures.slice(0, maxSharedStructures)\n\t\t\t\t\t}\n\t\t\t\t\t// we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save\n\t\t\t\t\tlet returnBuffer = target.subarray(start, position)\n\t\t\t\t\tif (encoder.updateSharedData() === false)\n\t\t\t\t\t\treturn encoder.encode(value) // re-encode if it fails\n\t\t\t\t\treturn returnBuffer\n\t\t\t\t}\n\t\t\t\tif (encodeOptions & RESET_BUFFER_MODE)\n\t\t\t\t\tposition = start\n\t\t\t}\n\t\t}\n\t\tthis.findCommonStringsToPack = () => {\n\t\t\tsamplingPackedValues = new Map()\n\t\t\tif (!sharedPackedObjectMap)\n\t\t\t\tsharedPackedObjectMap = Object.create(null)\n\t\t\treturn (options) => {\n\t\t\t\tlet threshold = options && options.threshold || 4\n\t\t\t\tlet position = this.pack ? options.maxPrivatePackedValues || 16 : 0\n\t\t\t\tif (!sharedValues)\n\t\t\t\t\tsharedValues = this.sharedValues = []\n\t\t\t\tfor (let [ key, status ] of samplingPackedValues) {\n\t\t\t\t\tif (status.count > threshold) {\n\t\t\t\t\t\tsharedPackedObjectMap[key] = position++\n\t\t\t\t\t\tsharedValues.push(key)\n\t\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\twhile (this.saveShared && this.updateSharedData() === false) {}\n\t\t\t\tsamplingPackedValues = null\n\t\t\t}\n\t\t}\n\t\tconst encode = (value) => {\n\t\t\tif (position > safeEnd)\n\t\t\t\ttarget = makeRoom(position)\n\n\t\t\tvar type = typeof value\n\t\t\tvar length\n\t\t\tif (type === 'string') {\n\t\t\t\tif (packedObjectMap) {\n\t\t\t\t\tlet packedPosition = packedObjectMap[value]\n\t\t\t\t\tif (packedPosition >= 0) {\n\t\t\t\t\t\tif (packedPosition < 16)\n\t\t\t\t\t\t\ttarget[position++] = packedPosition + 0xe0 // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttarget[position++] = 0xc6 // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\t\t\t\t\tif (packedPosition & 1)\n\t\t\t\t\t\t\t\tencode((15 - packedPosition) >> 1)\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tencode((packedPosition - 16) >> 1)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn\n/*\t\t\t\t\t\t} else if (packedStatus.serializationId != serializationId) {\n\t\t\t\t\t\t\tpackedStatus.serializationId = serializationId\n\t\t\t\t\t\t\tpackedStatus.count = 1\n\t\t\t\t\t\t\tif (options.sharedPack) {\n\t\t\t\t\t\t\t\tlet sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1\n\t\t\t\t\t\t\t\tif (shareCount > (options.sharedPack.threshold || 5)) {\n\t\t\t\t\t\t\t\t\tlet sharedPosition = packedStatus.position = packedStatus.nextSharedPosition\n\t\t\t\t\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t\t\t\t\t\tif (sharedPosition < 16)\n\t\t\t\t\t\t\t\t\t\ttarget[position++] = sharedPosition + 0xc0\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} // else any in-doc incrementation?*/\n\t\t\t\t\t} else if (samplingPackedValues && !options.pack) {\n\t\t\t\t\t\tlet status = samplingPackedValues.get(value)\n\t\t\t\t\t\tif (status)\n\t\t\t\t\t\t\tstatus.count++\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tsamplingPackedValues.set(value, {\n\t\t\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlet strLength = value.length\n\t\t\t\tif (bundledStrings && strLength >= 4 && strLength < 0x400) {\n\t\t\t\t\tif ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) {\n\t\t\t\t\t\tlet extStart\n\t\t\t\t\t\tlet maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10\n\t\t\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\t\t\t\t\t\ttarget[position++] = 0xd9 // tag 16-bit\n\t\t\t\t\t\ttarget[position++] = 0xdf // tag 0xdff9\n\t\t\t\t\t\ttarget[position++] = 0xf9\n\t\t\t\t\t\t// TODO: If we only have one bundle with any string data, only write one string bundle\n\t\t\t\t\t\ttarget[position++] = bundledStrings.position ? 0x84 : 0x82 // array of 4 or 2 elements depending on if we write bundles\n\t\t\t\t\t\ttarget[position++] = 0x1a // 32-bit unsigned int\n\t\t\t\t\t\textStart = position - start\n\t\t\t\t\t\tposition += 4 // reserve for writing bundle reference\n\t\t\t\t\t\tif (bundledStrings.position) {\n\t\t\t\t\t\t\twriteBundles(start, encode) // write the last bundles\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbundledStrings = ['', ''] // create new ones\n\t\t\t\t\t\tbundledStrings.size = 0\n\t\t\t\t\t\tbundledStrings.position = extStart\n\t\t\t\t\t}\n\t\t\t\t\tlet twoByte = hasNonLatin.test(value)\n\t\t\t\t\tbundledStrings[twoByte ? 0 : 1] += value\n\t\t\t\t\ttarget[position++] = twoByte ? 0xce : 0xcf\n\t\t\t\t\tencode(strLength);\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tlet headerSize\n\t\t\t\t// first we estimate the header size, so we can write to the correct location\n\t\t\t\tif (strLength < 0x20) {\n\t\t\t\t\theaderSize = 1\n\t\t\t\t} else if (strLength < 0x100) {\n\t\t\t\t\theaderSize = 2\n\t\t\t\t} else if (strLength < 0x10000) {\n\t\t\t\t\theaderSize = 3\n\t\t\t\t} else {\n\t\t\t\t\theaderSize = 5\n\t\t\t\t}\n\t\t\t\tlet maxBytes = strLength * 3\n\t\t\t\tif (position + maxBytes > safeEnd)\n\t\t\t\t\ttarget = makeRoom(position + maxBytes)\n\n\t\t\t\tif (strLength < 0x40 || !encodeUtf8) {\n\t\t\t\t\tlet i, c1, c2, strPosition = position + headerSize\n\t\t\t\t\tfor (i = 0; i < strLength; i++) {\n\t\t\t\t\t\tc1 = value.charCodeAt(i)\n\t\t\t\t\t\tif (c1 < 0x80) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1\n\t\t\t\t\t\t} else if (c1 < 0x800) {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 | 0xc0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\t(c1 & 0xfc00) === 0xd800 &&\n\t\t\t\t\t\t\t((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tc1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff)\n\t\t\t\t\t\t\ti++\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 18 | 0xf0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 12 | 0xe0\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 >> 6 & 0x3f | 0x80\n\t\t\t\t\t\t\ttarget[strPosition++] = c1 & 0x3f | 0x80\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlength = strPosition - position - headerSize\n\t\t\t\t} else {\n\t\t\t\t\tlength = encodeUtf8(value, position + headerSize, maxBytes)\n\t\t\t\t}\n\n\t\t\t\tif (length < 0x18) {\n\t\t\t\t\ttarget[position++] = 0x60 | length\n\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\tif (headerSize < 2) {\n\t\t\t\t\t\ttarget.copyWithin(position + 2, position + 1, position + 1 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x78\n\t\t\t\t\ttarget[position++] = length\n\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\tif (headerSize < 3) {\n\t\t\t\t\t\ttarget.copyWithin(position + 3, position + 2, position + 2 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x79\n\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t} else {\n\t\t\t\t\tif (headerSize < 5) {\n\t\t\t\t\t\ttarget.copyWithin(position + 5, position + 3, position + 3 + length)\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0x7a\n\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\tposition += 4\n\t\t\t\t}\n\t\t\t\tposition += length\n\t\t\t} else if (type === 'number') {\n\t\t\t\tif (!this.alwaysUseFloat && value >>> 0 === value) {// positive integer, 32-bit or less\n\t\t\t\t\t// positive uint\n\t\t\t\t\tif (value < 0x18) {\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x100) {\n\t\t\t\t\t\ttarget[position++] = 0x18\n\t\t\t\t\t\ttarget[position++] = value\n\t\t\t\t\t} else if (value < 0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0x19\n\t\t\t\t\t\ttarget[position++] = value >> 8\n\t\t\t\t\t\ttarget[position++] = value & 0xff\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0x1a\n\t\t\t\t\t\ttargetView.setUint32(position, value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else if (!this.alwaysUseFloat && value >> 0 === value) { // negative integer\n\t\t\t\t\tif (value >= -0x18) {\n\t\t\t\t\t\ttarget[position++] = 0x1f - value\n\t\t\t\t\t} else if (value >= -0x100) {\n\t\t\t\t\t\ttarget[position++] = 0x38\n\t\t\t\t\t\ttarget[position++] = ~value\n\t\t\t\t\t} else if (value >= -0x10000) {\n\t\t\t\t\t\ttarget[position++] = 0x39\n\t\t\t\t\t\ttargetView.setUint16(position, ~value)\n\t\t\t\t\t\tposition += 2\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget[position++] = 0x3a\n\t\t\t\t\t\ttargetView.setUint32(position, ~value)\n\t\t\t\t\t\tposition += 4\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlet useFloat32\n\t\t\t\t\tif ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) {\n\t\t\t\t\t\ttarget[position++] = 0xfa\n\t\t\t\t\t\ttargetView.setFloat32(position, value)\n\t\t\t\t\t\tlet xShifted\n\t\t\t\t\t\tif (useFloat32 < 4 ||\n\t\t\t\t\t\t\t\t// this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved\n\t\t\t\t\t\t\t\t((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) {\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tposition-- // move back into position for writing a double\n\t\t\t\t\t}\n\t\t\t\t\ttarget[position++] = 0xfb\n\t\t\t\t\ttargetView.setFloat64(position, value)\n\t\t\t\t\tposition += 8\n\t\t\t\t}\n\t\t\t} else if (type === 'object') {\n\t\t\t\tif (!value)\n\t\t\t\t\ttarget[position++] = 0xf6\n\t\t\t\telse {\n\t\t\t\t\tif (referenceMap) {\n\t\t\t\t\t\tlet referee = referenceMap.get(value)\n\t\t\t\t\t\tif (referee) {\n\t\t\t\t\t\t\ttarget[position++] = 0xd8\n\t\t\t\t\t\t\ttarget[position++] = 29 // http://cbor.schmorp.de/value-sharing\n\t\t\t\t\t\t\ttarget[position++] = 0x19 // 16-bit uint\n\t\t\t\t\t\t\tif (!referee.references) {\n\t\t\t\t\t\t\t\tlet idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = [])\n\t\t\t\t\t\t\t\treferee.references = []\n\t\t\t\t\t\t\t\tidsToInsert.push(referee)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treferee.references.push(position - start)\n\t\t\t\t\t\t\tposition += 2 // TODO: also support 32-bit\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t} else \n\t\t\t\t\t\t\treferenceMap.set(value, { offset: position - start })\n\t\t\t\t\t}\n\t\t\t\t\tlet constructor = value.constructor\n\t\t\t\t\tif (constructor === Object) {\n\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t} else if (constructor === Array) {\n\t\t\t\t\t\tlength = value.length\n\t\t\t\t\t\tif (length < 0x18) {\n\t\t\t\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\twriteArrayHeader(length)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\t\t\tencode(value[i])\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (constructor === Map) {\n\t\t\t\t\t\tif (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) {\n\t\t\t\t\t\t\t// use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way\n\t\t\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\t\t\ttarget[position++] = 1\n\t\t\t\t\t\t\ttarget[position++] = 3\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlength = value.size\n\t\t\t\t\t\tif (length < 0x18) {\n\t\t\t\t\t\t\ttarget[position++] = 0xa0 | length\n\t\t\t\t\t\t} else if (length < 0x100) {\n\t\t\t\t\t\t\ttarget[position++] = 0xb8\n\t\t\t\t\t\t\ttarget[position++] = length\n\t\t\t\t\t\t} else if (length < 0x10000) {\n\t\t\t\t\t\t\ttarget[position++] = 0xb9\n\t\t\t\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttarget[position++] = 0xba\n\t\t\t\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (encoder.keyMap) { \n\t\t\t\t\t\t\tfor (let [ key, entryValue ] of value) {\n\t\t\t\t\t\t\t\tencode(encoder.encodeKey(key))\n\t\t\t\t\t\t\t\tencode(entryValue)\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t} else { \n\t\t\t\t\t\t\tfor (let [ key, entryValue ] of value) {\n\t\t\t\t\t\t\t\tencode(key) \n\t\t\t\t\t\t\t\tencode(entryValue)\n\t\t\t\t\t\t\t} \t\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (let i = 0, l = extensions.length; i < l; i++) {\n\t\t\t\t\t\t\tlet extensionClass = extensionClasses[i]\n\t\t\t\t\t\t\tif (value instanceof extensionClass) {\n\t\t\t\t\t\t\t\tlet extension = extensions[i]\n\t\t\t\t\t\t\t\tlet tag = extension.tag\n\t\t\t\t\t\t\t\tif (tag == undefined)\n\t\t\t\t\t\t\t\t\ttag = extension.getTag && extension.getTag.call(this, value)\n\t\t\t\t\t\t\t\tif (tag < 0x18) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xc0 | tag\n\t\t\t\t\t\t\t\t} else if (tag < 0x100) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd8\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag\n\t\t\t\t\t\t\t\t} else if (tag < 0x10000) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag >> 8\n\t\t\t\t\t\t\t\t\ttarget[position++] = tag & 0xff\n\t\t\t\t\t\t\t\t} else if (tag > -1) {\n\t\t\t\t\t\t\t\t\ttarget[position++] = 0xda\n\t\t\t\t\t\t\t\t\ttargetView.setUint32(position, tag)\n\t\t\t\t\t\t\t\t\tposition += 4\n\t\t\t\t\t\t\t\t} // else undefined, don't write tag\n\t\t\t\t\t\t\t\textension.encode.call(this, value, encode, makeRoom)\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value[Symbol.iterator]) {\n\t\t\t\t\t\t\tif (throwOnIterable) {\n\t\t\t\t\t\t\t\tlet error = new Error('Iterable should be serialized as iterator')\n\t\t\t\t\t\t\t\terror.iteratorNotHandled = true;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0x9f // indefinite length array\n\t\t\t\t\t\t\tfor (let entry of value) {\n\t\t\t\t\t\t\t\tencode(entry)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttarget[position++] = 0xff // stop-code\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (value[Symbol.asyncIterator] || isBlob(value)) {\n\t\t\t\t\t\t\tlet error = new Error('Iterable/blob should be serialized as iterator')\n\t\t\t\t\t\t\terror.iteratorNotHandled = true;\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (this.useToJSON && value.toJSON) {\n\t\t\t\t\t\t\tconst json = value.toJSON()\n\t\t\t\t\t\t\t// if for some reason value.toJSON returns itself it'll loop forever\n\t\t\t\t\t\t\tif (json !== value)\n\t\t\t\t\t\t\t\treturn encode(json)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// no extension found, write as a plain object\n\t\t\t\t\t\twriteObject(value)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (type === 'boolean') {\n\t\t\t\ttarget[position++] = value ? 0xf5 : 0xf4\n\t\t\t} else if (type === 'bigint') {\n\t\t\t\tif (value < (BigInt(1)<<BigInt(64)) && value >= 0) {\n\t\t\t\t\t// use an unsigned int as long as it fits\n\t\t\t\t\ttarget[position++] = 0x1b\n\t\t\t\t\ttargetView.setBigUint64(position, value)\n\t\t\t\t} else if (value > -(BigInt(1)<<BigInt(64)) && value < 0) {\n\t\t\t\t\t// if we can fit an unsigned int, use that\n\t\t\t\t\ttarget[position++] = 0x3b\n\t\t\t\t\ttargetView.setBigUint64(position, -value - BigInt(1))\n\t\t\t\t} else {\n\t\t\t\t\t// overflow\n\t\t\t\t\tif (this.largeBigIntToFloat) {\n\t\t\t\t\t\ttarget[position++] = 0xfb\n\t\t\t\t\t\ttargetView.setFloat64(position, Number(value))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (value >= BigInt(0))\n\t\t\t\t\t\t\ttarget[position++] = 0xc2 // tag 2\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\ttarget[position++] = 0xc3 // tag 2\n\t\t\t\t\t\t\tvalue = BigInt(-1) - value;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet bytes = [];\n\t\t\t\t\t\twhile (value) {\n\t\t\t\t\t\t\tbytes.push(Number(value & BigInt(0xff)));\n\t\t\t\t\t\t\tvalue >>= BigInt(8);\n\t\t\t\t\t\t}\n\t\t\t\t\t\twriteBuffer(new Uint8Array(bytes.reverse()), makeRoom);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tposition += 8\n\t\t\t} else if (type === 'undefined') {\n\t\t\t\ttarget[position++] = 0xf7\n\t\t\t} else {\n\t\t\t\tthrow new Error('Unknown type: ' + type)\n\t\t\t}\n\t\t}\n\n\t\tconst writeObject = this.useRecords === false ? this.variableMapSize ? (object) => {\n\t\t\t// this method is slightly slower, but generates \"preferred serialization\" (optimally small for smaller objects)\n\t\t\tlet keys = Object.keys(object)\n\t\t\tlet vals = Object.values(object)\n\t\t\tlet length = keys.length\n\t\t\tif (length < 0x18) {\n\t\t\t\ttarget[position++] = 0xa0 | length\n\t\t\t} else if (length < 0x100) {\n\t\t\t\ttarget[position++] = 0xb8\n\t\t\t\ttarget[position++] = length\n\t\t\t} else if (length < 0x10000) {\n\t\t\t\ttarget[position++] = 0xb9\n\t\t\t\ttarget[position++] = length >> 8\n\t\t\t\ttarget[position++] = length & 0xff\n\t\t\t} else {\n\t\t\t\ttarget[position++] = 0xba\n\t\t\t\ttargetView.setUint32(position, length)\n\t\t\t\tposition += 4\n\t\t\t}\n\t\t\tlet key\n\t\t\tif (encoder.keyMap) { \n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tencode(encoder.encodeKey(keys[i]))\n\t\t\t\t\tencode(vals[i])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tencode(keys[i])\n\t\t\t\t\tencode(vals[i])\n\t\t\t\t}\n\t\t\t}\n\t\t} :\n\t\t(object) => {\n\t\t\ttarget[position++] = 0xb9 // always use map 16, so we can preallocate and set the length afterwards\n\t\t\tlet objectOffset = position - start\n\t\t\tposition += 2\n\t\t\tlet size = 0\n\t\t\tif (encoder.keyMap) {\n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tencode(encoder.encodeKey(key))\n\t\t\t\t\tencode(object[key])\n\t\t\t\t\tsize++\n\t\t\t\t}\n\t\t\t} else { \n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\t\tencode(key)\n\t\t\t\t\t\tencode(object[key])\n\t\t\t\t\tsize++\n\t\t\t\t}\n\t\t\t}\n\t\t\ttarget[objectOffset++ + start] = size >> 8\n\t\t\ttarget[objectOffset + start] = size & 0xff\n\t\t} :\n\t\t(object, skipValues) => {\n\t\t\tlet nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null))\n\t\t\tlet newTransitions = 0\n\t\t\tlet length = 0\n\t\t\tlet parentRecordId\n\t\t\tlet keys\n\t\t\tif (this.keyMap) {\n\t\t\t\tkeys = Object.keys(object).map(k => this.encodeKey(k))\n\t\t\t\tlength = keys.length\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tlet key = keys[i]\n\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\tnewTransitions++\n\t\t\t\t\t}\n\t\t\t\t\ttransition = nextTransition\n\t\t\t\t}\t\t\t\t\n\t\t\t} else {\n\t\t\t\tfor (let key in object) if (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key)) {\n\t\t\t\t\tnextTransition = transition[key]\n\t\t\t\t\tif (!nextTransition) {\n\t\t\t\t\t\tif (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it\n\t\t\t\t\t\t\tparentRecordId = transition[RECORD_SYMBOL] & 0xffff\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnextTransition = transition[key] = Object.create(null)\n\t\t\t\t\t\tnewTransitions++\n\t\t\t\t\t}\n\t\t\t\t\ttransition = nextTransition\n\t\t\t\t\tlength++\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet recordId = transition[RECORD_SYMBOL]\n\t\t\tif (recordId !== undefined) {\n\t\t\t\trecordId &= 0xffff\n\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\ttarget[position++] = (recordId >> 8) | 0xe0\n\t\t\t\ttarget[position++] = recordId & 0xff\n\t\t\t} else {\n\t\t\t\tif (!keys)\n\t\t\t\t\tkeys = transition.__keys__ || (transition.__keys__ = Object.keys(object))\n\t\t\t\tif (parentRecordId === undefined) {\n\t\t\t\t\trecordId = structures.nextId++\n\t\t\t\t\tif (!recordId) {\n\t\t\t\t\t\trecordId = 0\n\t\t\t\t\t\tstructures.nextId = 1\n\t\t\t\t\t}\n\t\t\t\t\tif (recordId >= MAX_STRUCTURES) {// cycle back around\n\t\t\t\t\t\tstructures.nextId = (recordId = maxSharedStructures) + 1\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trecordId = parentRecordId\n\t\t\t\t}\n\t\t\t\tstructures[recordId] = keys\n\t\t\t\tif (recordId < maxSharedStructures) {\n\t\t\t\t\ttarget[position++] = 0xd9\n\t\t\t\t\ttarget[position++] = (recordId >> 8) | 0xe0\n\t\t\t\t\ttarget[position++] = recordId & 0xff\n\t\t\t\t\ttransition = structures.transitions\n\t\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\t\tif (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000))\n\t\t\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId\n\t\t\t\t\t\ttransition = transition[keys[i]]\n\t\t\t\t\t}\n\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId | 0x100000 // indicates it is a extendable terminal\n\t\t\t\t\thasSharedUpdate = true\n\t\t\t\t} else {\n\t\t\t\t\ttransition[RECORD_SYMBOL] = recordId\n\t\t\t\t\ttargetView.setUint32(position, 0xd9dfff00) // tag two byte, then record definition id\n\t\t\t\t\tposition += 3\n\t\t\t\t\tif (newTransitions)\n\t\t\t\t\t\ttransitionsCount += serializationsSinceTransitionRebuild * newTransitions\n\t\t\t\t\t// record the removal of the id, we can maintain our shared structure\n\t\t\t\t\tif (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures)\n\t\t\t\t\t\trecordIdsToRemove.shift()[RECORD_SYMBOL] = undefined // we are cycling back through, and have to remove old ones\n\t\t\t\t\trecordIdsToRemove.push(transition)\n\t\t\t\t\twriteArrayHeader(length + 2)\n\t\t\t\t\tencode(0xe000 + recordId)\n\t\t\t\t\tencode(keys)\n\t\t\t\t\tif (skipValues) return; // special exit for iterator\n\t\t\t\t\tfor (let key in object)\n\t\t\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))\n\t\t\t\t\t\t\tencode(object[key])\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (length < 0x18) { // write the array header\n\t\t\t\ttarget[position++] = 0x80 | length\n\t\t\t} else {\n\t\t\t\twriteArrayHeader(length)\n\t\t\t}\n\t\t\tif (skipValues) return; // special exit for iterator\n\t\t\tfor (let key in object)\n\t\t\t\tif (typeof object.hasOwnProperty !== 'function' || object.hasOwnProperty(key))\n\t\t\t\t\tencode(object[key])\n\t\t}\n\t\tconst makeRoom = (end) => {\n\t\t\tlet newSize\n\t\t\tif (end > 0x1000000) {\n\t\t\t\t// special handling for really large buffers\n\t\t\t\tif ((end - start) > MAX_BUFFER_SIZE)\n\t\t\t\t\tthrow new Error('Encoded buffer would be larger than maximum buffer size')\n\t\t\t\tnewSize = Math.min(MAX_BUFFER_SIZE,\n\t\t\t\t\tMath.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000)\n\t\t\t} else // faster handling for smaller buffers\n\t\t\t\tnewSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12\n\t\t\tlet newBuffer = new ByteArrayAllocate(newSize)\n\t\t\ttargetView = new DataView(newBuffer.buffer, 0, newSize)\n\t\t\tif (target.copy)\n\t\t\t\ttarget.copy(newBuffer, 0, start, end)\n\t\t\telse\n\t\t\t\tnewBuffer.set(target.slice(start, end))\n\t\t\tposition -= start\n\t\t\tstart = 0\n\t\t\tsafeEnd = newBuffer.length - 10\n\t\t\treturn target = newBuffer\n\t\t}\n\t\tlet chunkThreshold = 100;\n\t\tlet continuedChunkThreshold = 1000;\n\t\tthis.encodeAsIterable = function(value, options) {\n\t\t\treturn startEncoding(value, options, encodeObjectAsIterable);\n\t\t}\n\t\tthis.encodeAsAsyncIterable = function(value, options) {\n\t\t\treturn startEncoding(value, options, encodeObjectAsAsyncIterable);\n\t\t}\n\n\t\tfunction* encodeObjectAsIterable(object, iterateProperties, finalIterable) {\n\t\t\tlet constructor = object.constructor;\n\t\t\tif (constructor === Object) {\n\t\t\t\tlet useRecords = encoder.useRecords !== false;\n\t\t\t\tif (useRecords)\n\t\t\t\t\twriteObject(object, true); // write the record identifier\n\t\t\t\telse\n\t\t\t\t\twriteEntityLength(Object.keys(object).length, 0xa0);\n\t\t\t\tfor (let key in object) {\n\t\t\t\t\tlet value = object[key];\n\t\t\t\t\tif (!useRecords) encode(key);\n\t\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\t\tif (iterateProperties[key])\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties[key]);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, key);\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t} else if (constructor === Array) {\n\t\t\t\tlet length = object.length;\n\t\t\t\twriteArrayHeader(length);\n\t\t\t\tfor (let i = 0; i < length; i++) {\n\t\t\t\t\tlet value = object[i];\n\t\t\t\t\tif (value && (typeof value === 'object' || position - start > chunkThreshold)) {\n\t\t\t\t\t\tif (iterateProperties.element)\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties.element);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, 'element');\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t} else if (object[Symbol.iterator] && !object.buffer) { // iterator, but exclude typed arrays\n\t\t\t\ttarget[position++] = 0x9f; // start indefinite array\n\t\t\t\tfor (let value of object) {\n\t\t\t\t\tif (value && (typeof value === 'object' || position - start > chunkThreshold)) {\n\t\t\t\t\t\tif (iterateProperties.element)\n\t\t\t\t\t\t\tyield* encodeObjectAsIterable(value, iterateProperties.element);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tyield* tryEncode(value, iterateProperties, 'element');\n\t\t\t\t\t} else encode(value);\n\t\t\t\t}\n\t\t\t\ttarget[position++] = 0xff; // stop byte\n\t\t\t} else if (isBlob(object)){\n\t\t\t\twriteEntityLength(object.size, 0x40); // encode as binary data\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\tyield object; // directly return blobs, they have to be encoded asynchronously\n\t\t\t\trestartEncoding();\n\t\t\t} else if (object[Symbol.asyncIterator]) {\n\t\t\t\ttarget[position++] = 0x9f; // start indefinite array\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\tyield object; // directly return async iterators, they have to be encoded asynchronously\n\t\t\t\trestartEncoding();\n\t\t\t\ttarget[position++] = 0xff; // stop byte\n\t\t\t} else {\n\t\t\t\tencode(object);\n\t\t\t}\n\t\t\tif (finalIterable && position > start) yield target.subarray(start, position);\n\t\t\telse if (position - start > chunkThreshold) {\n\t\t\t\tyield target.subarray(start, position);\n\t\t\t\trestartEncoding();\n\t\t\t}\n\t\t}\n\t\tfunction* tryEncode(value, iterateProperties, key) {\n\t\t\tlet restart = position - start;\n\t\t\ttry {\n\t\t\t\tencode(value);\n\t\t\t\tif (position - start > chunkThreshold) {\n\t\t\t\t\tyield target.subarray(start, position);\n\t\t\t\t\trestartEncoding();\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error.iteratorNotHandled) {\n\t\t\t\t\titerateProperties[key] = {};\n\t\t\t\t\tposition = start + restart; // restart our position so we don't have partial data from last encode\n\t\t\t\t\tyield* encodeObjectAsIterable.call(this, value, iterateProperties[key]);\n\t\t\t\t} else throw error;\n\t\t\t}\n\t\t}\n\t\tfunction restartEncoding() {\n\t\t\tchunkThreshold = continuedChunkThreshold;\n\t\t\tencoder.encode(null, THROW_ON_ITERABLE); // restart encoding\n\t\t}\n\t\tfunction startEncoding(value, options, encodeIterable) {\n\t\t\tif (options && options.chunkThreshold) // explicitly specified chunk sizes\n\t\t\t\tchunkThreshold = continuedChunkThreshold = options.chunkThreshold;\n\t\t\telse // we start with a smaller threshold to get initial bytes sent quickly\n\t\t\t\tchunkThreshold = 100;\n\t\t\tif (value && typeof value === 'object') {\n\t\t\t\tencoder.encode(null, THROW_ON_ITERABLE); // start encoding\n\t\t\t\treturn encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true);\n\t\t\t}\n\t\t\treturn [encoder.encode(value)];\n\t\t}\n\n\t\tasync function* encodeObjectAsAsyncIterable(value, iterateProperties) {\n\t\t\tfor (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) {\n\t\t\t\tlet constructor = encodedValue.constructor;\n\t\t\t\tif (constructor === ByteArray || constructor === Uint8Array)\n\t\t\t\t\tyield encodedValue;\n\t\t\t\telse if (isBlob(encodedValue)) {\n\t\t\t\t\tlet reader = encodedValue.stream().getReader();\n\t\t\t\t\tlet next;\n\t\t\t\t\twhile (!(next = await reader.read()).done) {\n\t\t\t\t\t\tyield next.value;\n\t\t\t\t\t}\n\t\t\t\t} else if (encodedValue[Symbol.asyncIterator]) {\n\t\t\t\t\tfor await (let asyncValue of encodedValue) {\n\t\t\t\t\t\trestartEncoding();\n\t\t\t\t\t\tif (asyncValue)\n\t\t\t\t\t\t\tyield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {}));\n\t\t\t\t\t\telse yield encoder.encode(asyncValue);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tyield encodedValue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tuseBuffer(buffer) {\n\t\t// this means we are finished using our own buffer and we can write over it safely\n\t\ttarget = buffer\n\t\ttargetView = new DataView(target.buffer, target.byteOffset, target.byteLength)\n\t\tposition = 0\n\t}\n\tclearSharedData() {\n\t\tif (this.structures)\n\t\t\tthis.structures = []\n\t\tif (this.sharedValues)\n\t\t\tthis.sharedValues = undefined\n\t}\n\tupdateSharedData() {\n\t\tlet lastVersion = this.sharedVersion || 0\n\t\tthis.sharedVersion = lastVersion + 1\n\t\tlet structuresCopy = this.structures.slice(0)\n\t\tlet sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion)\n\t\tlet saveResults = this.saveShared(sharedData,\n\t\t\t\texistingShared => (existingShared && existingShared.version || 0) == lastVersion)\n\t\tif (saveResults === false) {\n\t\t\t// get updated structures and try again if the update failed\n\t\t\tsharedData = this.getShared() || {}\n\t\t\tthis.structures = sharedData.structures || []\n\t\t\tthis.sharedValues = sharedData.packedValues\n\t\t\tthis.sharedVersion = sharedData.version\n\t\t\tthis.structures.nextId = this.structures.length\n\t\t} else {\n\t\t\t// restore structures\n\t\t\tstructuresCopy.forEach((structure, i) => this.structures[i] = structure)\n\t\t}\n\t\t// saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data\n\t\treturn saveResults\n\t}\n}\nfunction writeEntityLength(length, majorValue) {\n\tif (length < 0x18)\n\t\ttarget[position++] = majorValue | length\n\telse if (length < 0x100) {\n\t\ttarget[position++] = majorValue | 0x18\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = majorValue | 0x19\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = majorValue | 0x1a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n\n}\nclass SharedData {\n\tconstructor(structures, values, version) {\n\t\tthis.structures = structures\n\t\tthis.packedValues = values\n\t\tthis.version = version\n\t}\n}\n\nfunction writeArrayHeader(length) {\n\tif (length < 0x18)\n\t\ttarget[position++] = 0x80 | length\n\telse if (length < 0x100) {\n\t\ttarget[position++] = 0x98\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = 0x99\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = 0x9a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n}\n\nconst BlobConstructor = typeof Blob === 'undefined' ? function(){} : Blob;\nfunction isBlob(object) {\n\tif (object instanceof BlobConstructor)\n\t\treturn true;\n\tlet tag = object[Symbol.toStringTag];\n\treturn tag === 'Blob' || tag === 'File';\n}\nfunction findRepetitiveStrings(value, packedValues) {\n\tswitch(typeof value) {\n\t\tcase 'string':\n\t\t\tif (value.length > 3) {\n\t\t\t\tif (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues)\n\t\t\t\t\treturn\n\t\t\t\tlet packedStatus = packedValues.get(value)\n\t\t\t\tif (packedStatus) {\n\t\t\t\t\tif (++packedStatus.count == 2) {\n\t\t\t\t\t\tpackedValues.values.push(value)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpackedValues.set(value, {\n\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t})\n\t\t\t\t\tif (packedValues.samplingPackedValues) {\n\t\t\t\t\t\tlet status = packedValues.samplingPackedValues.get(value)\n\t\t\t\t\t\tif (status)\n\t\t\t\t\t\t\tstatus.count++\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tpackedValues.samplingPackedValues.set(value, {\n\t\t\t\t\t\t\t\tcount: 1,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'object':\n\t\t\tif (value) {\n\t\t\t\tif (value instanceof Array) {\n\t\t\t\t\tfor (let i = 0, l = value.length; i < l; i++) {\n\t\t\t\t\t\tfindRepetitiveStrings(value[i], packedValues)\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tlet includeKeys = !packedValues.encoder.useRecords\n\t\t\t\t\tfor (var key in value) {\n\t\t\t\t\t\tif (value.hasOwnProperty(key)) {\n\t\t\t\t\t\t\tif (includeKeys)\n\t\t\t\t\t\t\t\tfindRepetitiveStrings(key, packedValues)\n\t\t\t\t\t\t\tfindRepetitiveStrings(value[key], packedValues)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase 'function': console.log(value)\n\t}\n}\nconst isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1\nextensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer,\n\tUint8Array, Uint8ClampedArray, Uint16Array, Uint32Array,\n\ttypeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array,\n\ttypeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array,\n\tFloat32Array, Float64Array, SharedData ]\n\n//Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/\nextensions = [{ // Date\n\ttag: 1,\n\tencode(date, encode) {\n\t\tlet seconds = date.getTime() / 1000\n\t\tif ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) {\n\t\t\t// Timestamp 32\n\t\t\ttarget[position++] = 0x1a\n\t\t\ttargetView.setUint32(position, seconds)\n\t\t\tposition += 4\n\t\t} else {\n\t\t\t// Timestamp float64\n\t\t\ttarget[position++] = 0xfb\n\t\t\ttargetView.setFloat64(position, seconds)\n\t\t\tposition += 8\n\t\t}\n\t}\n}, { // Set\n\ttag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md\n\tencode(set, encode) {\n\t\tlet array = Array.from(set)\n\t\tencode(array)\n\t}\n}, { // Error\n\ttag: 27, // http://cbor.schmorp.de/generic-object\n\tencode(error, encode) {\n\t\tencode([ error.name, error.message ])\n\t}\n}, { // RegExp\n\ttag: 27, // http://cbor.schmorp.de/generic-object\n\tencode(regex, encode) {\n\t\tencode([ 'RegExp', regex.source, regex.flags ])\n\t}\n}, { // Tag\n\tgetTag(tag) {\n\t\treturn tag.tag\n\t},\n\tencode(tag, encode) {\n\t\tencode(tag.value)\n\t}\n}, { // ArrayBuffer\n\tencode(arrayBuffer, encode, makeRoom) {\n\t\twriteBuffer(arrayBuffer, makeRoom)\n\t}\n}, { // Uint8Array\n\tgetTag(typedArray) {\n\t\tif (typedArray.constructor === Uint8Array) {\n\t\t\tif (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false)\n\t\t\t\treturn 64;\n\t\t} // else no tag\n\t},\n\tencode(typedArray, encode, makeRoom) {\n\t\twriteBuffer(typedArray, makeRoom)\n\t}\n},\n\ttypedArrayEncoder(68, 1),\n\ttypedArrayEncoder(69, 2),\n\ttypedArrayEncoder(70, 4),\n\ttypedArrayEncoder(71, 8),\n\ttypedArrayEncoder(72, 1),\n\ttypedArrayEncoder(77, 2),\n\ttypedArrayEncoder(78, 4),\n\ttypedArrayEncoder(79, 8),\n\ttypedArrayEncoder(85, 4),\n\ttypedArrayEncoder(86, 8),\n{\n\tencode(sharedData, encode) { // write SharedData\n\t\tlet packedValues = sharedData.packedValues || []\n\t\tlet sharedStructures = sharedData.structures || []\n\t\tif (packedValues.values.length > 0) {\n\t\t\ttarget[position++] = 0xd8 // one-byte tag\n\t\t\ttarget[position++] = 51 // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt\n\t\t\twriteArrayHeader(4)\n\t\t\tlet valuesArray = packedValues.values\n\t\t\tencode(valuesArray)\n\t\t\twriteArrayHeader(0) // prefixes\n\t\t\twriteArrayHeader(0) // suffixes\n\t\t\tpackedObjectMap = Object.create(sharedPackedObjectMap || null)\n\t\t\tfor (let i = 0, l = valuesArray.length; i < l; i++) {\n\t\t\t\tpackedObjectMap[valuesArray[i]] = i\n\t\t\t}\n\t\t}\n\t\tif (sharedStructures) {\n\t\t\ttargetView.setUint32(position, 0xd9dffe00)\n\t\t\tposition += 3\n\t\t\tlet definitions = sharedStructures.slice(0)\n\t\t\tdefinitions.unshift(0xe000)\n\t\t\tdefinitions.push(new Tag(sharedData.version, 0x53687264))\n\t\t\tencode(definitions)\n\t\t} else\n\t\t\tencode(new Tag(sharedData.version, 0x53687264))\n\t\t}\n\t}]\nfunction typedArrayEncoder(tag, size) {\n\tif (!isLittleEndianMachine && size > 1)\n\t\ttag -= 4 // the big endian equivalents are 4 less\n\treturn {\n\t\ttag: tag,\n\t\tencode: function writeExtBuffer(typedArray, encode) {\n\t\t\tlet length = typedArray.byteLength\n\t\t\tlet offset = typedArray.byteOffset || 0\n\t\t\tlet buffer = typedArray.buffer || typedArray\n\t\t\tencode(hasNodeBuffer ? Buffer.from(buffer, offset, length) :\n\t\t\t\tnew Uint8Array(buffer, offset, length))\n\t\t}\n\t}\n}\nfunction writeBuffer(buffer, makeRoom) {\n\tlet length = buffer.byteLength\n\tif (length < 0x18) {\n\t\ttarget[position++] = 0x40 + length\n\t} else if (length < 0x100) {\n\t\ttarget[position++] = 0x58\n\t\ttarget[position++] = length\n\t} else if (length < 0x10000) {\n\t\ttarget[position++] = 0x59\n\t\ttarget[position++] = length >> 8\n\t\ttarget[position++] = length & 0xff\n\t} else {\n\t\ttarget[position++] = 0x5a\n\t\ttargetView.setUint32(position, length)\n\t\tposition += 4\n\t}\n\tif (position + length >= target.length) {\n\t\tmakeRoom(position + length)\n\t}\n\t// if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself,\n\t// must wrap it to set it.\n\ttarget.set(buffer.buffer ? buffer : new Uint8Array(buffer), position)\n\tposition += length\n}\n\nfunction insertIds(serialized, idsToInsert) {\n\t// insert the ids that need to be referenced for structured clones\n\tlet nextId\n\tlet distanceToMove = idsToInsert.length * 2\n\tlet lastEnd = serialized.length - distanceToMove\n\tidsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1)\n\tfor (let id = 0; id < idsToInsert.length; id++) {\n\t\tlet referee = idsToInsert[id]\n\t\treferee.id = id\n\t\tfor (let position of referee.references) {\n\t\t\tserialized[position++] = id >> 8\n\t\t\tserialized[position] = id & 0xff\n\t\t}\n\t}\n\twhile (nextId = idsToInsert.pop()) {\n\t\tlet offset = nextId.offset\n\t\tserialized.copyWithin(offset + distanceToMove, offset, lastEnd)\n\t\tdistanceToMove -= 2\n\t\tlet position = offset + distanceToMove\n\t\tserialized[position++] = 0xd8\n\t\tserialized[position++] = 28 // http://cbor.schmorp.de/value-sharing\n\t\tlastEnd = offset\n\t}\n\treturn serialized\n}\nfunction writeBundles(start, encode) {\n\ttargetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1) // the offset to bundle\n\tlet writeStrings = bundledStrings\n\tbundledStrings = null\n\tencode(writeStrings[0])\n\tencode(writeStrings[1])\n}\n\nexport function addExtension(extension) {\n\tif (extension.Class) {\n\t\tif (!extension.encode)\n\t\t\tthrow new Error('Extension has no encode function')\n\t\textensionClasses.unshift(extension.Class)\n\t\textensions.unshift(extension)\n\t}\n\tdecodeAddExtension(extension)\n}\nlet defaultEncoder = new Encoder({ useRecords: false })\nexport const encode = defaultEncoder.encode\nexport const encodeAsIterable = defaultEncoder.encodeAsIterable\nexport const encodeAsAsyncIterable = defaultEncoder.encodeAsAsyncIterable\nexport { FLOAT32_OPTIONS } from './decode.js'\nimport { FLOAT32_OPTIONS } from './decode.js'\nexport const { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS\nexport const REUSE_BUFFER_MODE = 512\nexport const RESET_BUFFER_MODE = 1024\nexport const THROW_ON_ITERABLE = 2048\n\n\n", "import * as Automerge from \"@automerge/automerge/slim\";\nimport { encodeHeads, decodeHeads } from \"../AutomergeUrl.js\";\nimport { KIND } from \"./types.js\";\nimport { isSegment, isPattern } from \"./guards.js\";\nimport { matchesPattern } from \"./utils.js\";\nimport { isCursorMarker } from \"./guards.js\";\nimport { stringifyRefUrl } from \"./parser.js\";\nimport { MutableText } from \"./mutable-text.js\";\n/**\n * FinalizationRegistry for automatic cleanup of Ref instances.\n * This ensures subscriptions are cleaned up when Refs are garbage collected,\n * even if dispose() is never called.\n */\nconst refCleanupRegistry = new FinalizationRegistry(cleanup => cleanup());\n/**\n * Internal implementation of the Ref interface.\n *\n * Refs are stable by default - they track objects by ID, not position.\n *\n * Cleanup: Refs automatically clean up their subscriptions when garbage collected.\n *\n * @internal Use DocHandle.ref() to create refs, not this class directly.\n */\nexport class RefImpl {\n docHandle;\n path;\n range;\n #onChangeCallbacks = new Set();\n #updateHandler;\n constructor(docHandle, segments) {\n this.docHandle = docHandle;\n const doc = docHandle.doc();\n const { path, range } = this.#normalizePath(doc, segments);\n this.path = path;\n this.range = range;\n this.#updateHandler = () => {\n const currentDoc = this.docHandle.doc();\n this.#updateProps(currentDoc);\n };\n this.docHandle.on(\"change\", this.#updateHandler);\n // Register for automatic cleanup when this Ref is garbage collected\n refCleanupRegistry.register(this, () => this.#cleanup(), this);\n }\n #cleanup() {\n this.docHandle.off(\"change\", this.#updateHandler);\n for (const callback of this.#onChangeCallbacks) {\n this.docHandle.off(\"change\", callback);\n }\n this.#onChangeCallbacks.clear();\n }\n get rangePositions() {\n if (!this.range)\n return undefined;\n const propPath = this.#getPropPath();\n if (!propPath)\n return undefined;\n const doc = this.doc();\n return this.#getRangePositions(doc, propPath, this.range);\n }\n viewAt(heads) {\n const viewHandle = this.docHandle.view(encodeHeads(heads));\n return viewHandle.ref(...this.path);\n }\n value() {\n const doc = this.doc();\n const propPath = this.#getPropPath();\n if (!propPath)\n return undefined;\n const value = this.#getValueAt(doc, propPath);\n return (this.range ? this.#extractRange(doc, propPath, value, this.range) : value);\n }\n doc() {\n return this.docHandle.doc();\n }\n change(fnOrValue) {\n if (this.docHandle.isReadOnly()) {\n throw new Error(\"Cannot change a Ref on a read-only handle\");\n }\n // Convert direct value to function form\n const fn = typeof fnOrValue === \"function\"\n ? fnOrValue\n : () => fnOrValue;\n this.docHandle.change((doc) => {\n if (this.path.length === 0 && !this.range) {\n fn(doc);\n return;\n }\n const propPath = this.#getPropPath();\n if (!propPath)\n throw new Error(\"Cannot resolve path\");\n let current;\n if (this.range) {\n const parent = this.#getValueAt(doc, propPath);\n if (typeof parent !== \"string\") {\n throw new Error(\"Range refs can only be used on string values\");\n }\n current = this.#extractRange(doc, propPath, parent, this.range);\n }\n else {\n current = this.#getValueAt(doc, propPath);\n }\n // If current is a string, wrap it in MutableText\n const valueToPass = typeof current === \"string\"\n ? MutableText(doc, propPath, current)\n : current;\n const newValue = fn(valueToPass);\n if (newValue === undefined)\n return;\n // Warn if non-primitive value is returned (should mutate instead)\n if (!(newValue === null ||\n typeof newValue === \"string\" ||\n typeof newValue === \"number\" ||\n typeof newValue === \"boolean\" ||\n typeof newValue === \"bigint\")) {\n console.warn(\"Ref.change() returned a non-primitive value. For objects and arrays, \" +\n \"you should mutate them in place rather than returning a new instance. \" +\n \"Returning new instances loses granular change tracking.\");\n }\n if (this.range) {\n this.#spliceRange(doc, propPath, this.range, newValue);\n }\n else {\n this.#setValueAt(doc, propPath, newValue);\n }\n });\n }\n remove() {\n if (this.docHandle.isReadOnly()) {\n throw new Error(\"Cannot remove from a Ref on a read-only handle\");\n }\n if (this.path.length === 0 && !this.range) {\n throw new Error(\"Cannot remove the root document\");\n }\n this.docHandle.change((doc) => {\n const propPath = this.#getPropPath();\n if (!propPath || propPath.length === 0) {\n throw new Error(\"Cannot resolve path for removal\");\n }\n // Handle range refs - delete the text within the range\n if (this.range) {\n this.#spliceRange(doc, propPath, this.range, \"\");\n return;\n }\n const parentPath = propPath.slice(0, -1);\n const key = propPath[propPath.length - 1];\n const parent = parentPath.length === 0 ? doc : this.#getValueAt(doc, parentPath);\n if (parent == null) {\n throw new Error(\"Cannot remove: parent is null or undefined\");\n }\n if (Array.isArray(parent)) {\n if (typeof key !== \"number\") {\n throw new Error(\"Cannot remove from array: key is not a number\");\n }\n parent.splice(key, 1);\n }\n else {\n delete parent[key];\n }\n });\n }\n onChange(callback) {\n const wrappedCallback = (payload) => {\n if (this.#patchAffectsRef(payload.patches)) {\n const value = this.value();\n callback(value, payload);\n }\n };\n this.docHandle.on(\"change\", wrappedCallback);\n // Track this callback so it can be cleaned up in dispose()\n this.#onChangeCallbacks.add(wrappedCallback);\n const unsubscribe = () => {\n this.docHandle.off(\"change\", wrappedCallback);\n this.#onChangeCallbacks.delete(wrappedCallback);\n };\n return unsubscribe;\n }\n get url() {\n const allSegments = this.range\n ? [...this.path, this.range]\n : this.path;\n // Include heads in URL only for read-only (time-traveled) handles\n const heads = this.docHandle.isReadOnly()\n ? decodeHeads(this.docHandle.heads())\n : undefined;\n return stringifyRefUrl(this.docHandle.documentId, allSegments, heads);\n }\n equals(other) {\n return this.url === other.url;\n }\n contains(other) {\n // Must be same document\n if (this.docHandle.documentId !== other.docHandle.documentId) {\n return false;\n }\n // Must have same heads (compare handle URLs which include heads for read-only handles)\n if (this.docHandle.url !== other.docHandle.url) {\n return false;\n }\n // This path must be a prefix of other's path\n if (this.path.length >= other.path.length) {\n return false;\n }\n // Check if all segments match\n for (let i = 0; i < this.path.length; i++) {\n if (!this.#segmentsEqual(this.path[i], other.path[i])) {\n return false;\n }\n }\n return true;\n }\n isChildOf(parent) {\n // Must be same document\n if (this.docHandle.documentId !== parent.docHandle.documentId) {\n return false;\n }\n // Must have same heads (compare handle URLs which include heads for read-only handles)\n if (this.docHandle.url !== parent.docHandle.url) {\n return false;\n }\n // Check if paths match up to parent's length\n if (this.path.length < parent.path.length) {\n return false;\n }\n // All of parent's path segments must match\n for (let i = 0; i < parent.path.length; i++) {\n if (!this.#segmentsEqual(this.path[i], parent.path[i])) {\n return false;\n }\n }\n // Case 1: Same path length - only valid if this has a range and parent doesn't\n // (this is a range child of text)\n if (this.path.length === parent.path.length) {\n return this.range !== undefined && parent.range === undefined;\n }\n // Case 2: Path is exactly one segment longer (direct child)\n if (this.path.length === parent.path.length + 1) {\n return true;\n }\n // Case 3: Path is more than one segment longer (not a direct child)\n return false;\n }\n overlaps(other) {\n // Must be same document\n if (this.docHandle.documentId !== other.docHandle.documentId) {\n return false;\n }\n // Must have same heads (compare handle URLs which include heads for read-only handles)\n if (this.docHandle.url !== other.docHandle.url) {\n return false;\n }\n // Both must have ranges\n if (!this.range || !other.range) {\n return false;\n }\n // Paths must be identical (same parent location)\n if (this.path.length !== other.path.length) {\n return false;\n }\n for (let i = 0; i < this.path.length; i++) {\n if (!this.#segmentsEqual(this.path[i], other.path[i])) {\n return false;\n }\n }\n // Check if ranges overlap\n // Get the numeric positions for both ranges\n const doc = this.doc();\n const propPath = this.#getPropPath();\n if (!propPath)\n return false;\n const thisPositions = this.#getRangePositions(doc, propPath, this.range);\n const otherPositions = this.#getRangePositions(doc, propPath, other.range);\n if (!thisPositions || !otherPositions)\n return false;\n const [thisStart, thisEnd] = thisPositions;\n const [otherStart, otherEnd] = otherPositions;\n // Ranges overlap if: thisStart < otherEnd && otherStart < thisEnd\n return thisStart < otherEnd && otherStart < thisEnd;\n }\n isEquivalent(other) {\n // Fast path: identity check\n if (this === other) {\n return true;\n }\n // Different documents can't be equivalent\n if (this.docHandle.documentId !== other.docHandle.documentId) {\n return false;\n }\n // Check heads equivalence\n // undefined heads means \"current document state\"\n // If one has undefined and other has explicit heads, check if they match current\n if (!this.#headsEquivalent(other)) {\n return false;\n }\n // Different path lengths can't be equivalent\n if (this.path.length !== other.path.length) {\n return false;\n }\n // Check range presence mismatch\n if ((this.range === undefined) !== (other.range === undefined)) {\n return false;\n }\n // Fast path: if segments are structurally equal, they're equivalent\n let segmentsEqual = true;\n for (let i = 0; i < this.path.length; i++) {\n if (!this.#segmentsEqual(this.path[i], other.path[i])) {\n segmentsEqual = false;\n break;\n }\n }\n if (segmentsEqual) {\n // Same path structure, now check ranges\n if (!this.range && !other.range) {\n return true;\n }\n // Both have ranges (checked above), compare them\n return (this.range.start === other.range.start &&\n this.range.end === other.range.end);\n }\n // Segments differ structurally - check if they resolve to the same prop path\n // Note: we access other.path[i].prop directly (public) instead of calling\n // private methods on other, since other may be from a different bundle\n for (let i = 0; i < this.path.length; i++) {\n const thisProp = this.path[i].prop;\n const otherProp = other.path[i].prop;\n // If either can't be resolved, they're not equivalent\n if (thisProp === undefined || otherProp === undefined) {\n return false;\n }\n if (thisProp !== otherProp) {\n return false;\n }\n }\n // Prop paths match, now check ranges\n if (!this.range && !other.range) {\n return true;\n }\n // Both have ranges - compare cursor values\n return (this.range.start === other.range.start &&\n this.range.end === other.range.end);\n }\n valueOf() {\n return this.url;\n }\n toString() {\n return this.url;\n }\n /**\n * Check if this ref's heads are equivalent to another ref's heads.\n * A ref on a non-read-only handle represents \"current document state\",\n * so it's equivalent to a ref on a read-only handle with heads matching the current document.\n */\n #headsEquivalent(other) {\n // If both handles have the same URL (including heads for read-only handles), they're equivalent\n if (this.docHandle.url === other.docHandle.url) {\n return true;\n }\n // Get effective heads for each - use handle's heads (which is current for non-read-only)\n const thisHeadsStr = this.docHandle.heads().join(\",\");\n const otherHeadsStr = other.docHandle.heads().join(\",\");\n return thisHeadsStr === otherHeadsStr;\n }\n /**\n * Normalize path inputs and extract stable IDs where possible.\n */\n #normalizePath(doc, inputs) {\n const pathSegments = [];\n const propPath = [];\n let current = doc;\n let rangeSegment;\n for (let i = 0; i < inputs.length; i++) {\n const input = inputs[i];\n // Handle cursor() marker - creates cursor-based range\n if (isCursorMarker(input)) {\n // cursor() must be the last segment\n if (i < inputs.length - 1) {\n throw new Error(\"cursor() must be the last segment in a ref path. \" +\n \"Segments after cursor() are not allowed.\");\n }\n rangeSegment = this.#createCursorRange(doc, propPath, current, input);\n break;\n }\n const segment = isSegment(input)\n ? this.#ensureSegmentResolved(current, input)\n : this.#normalizeInput(current, input);\n if (segment[KIND] === \"cursors\") {\n // Cursor range from URL parsing - must also be last\n if (i < inputs.length - 1) {\n throw new Error(\"Cursor range must be the last segment in a ref path. \" +\n \"Segments after cursor range are not allowed.\");\n }\n rangeSegment = segment;\n break;\n }\n pathSegments.push(segment);\n if (segment.prop !== undefined &&\n current !== undefined &&\n current !== null) {\n propPath.push(segment.prop);\n current = current[segment.prop];\n }\n }\n return { path: pathSegments, range: rangeSegment };\n }\n /** Ensure a segment has its prop set */\n #ensureSegmentResolved(container, segment) {\n const prop = this.#resolveSegmentProp(container, segment);\n return { ...segment, prop };\n }\n /**\n * Resolve a path segment to its Automerge prop.\n * Returns undefined if the segment cannot be resolved.\n */\n #resolveSegmentProp(container, segment) {\n if (container === undefined || container === null)\n return undefined;\n switch (segment[KIND]) {\n case \"key\":\n return segment.key;\n case \"index\":\n return segment.index;\n case \"match\": {\n if (!Array.isArray(container))\n return undefined;\n const matchIndex = container.findIndex(item => matchesPattern(item, segment.match));\n return matchIndex !== -1 ? matchIndex : undefined;\n }\n case \"cursors\":\n return undefined;\n default:\n segment;\n return undefined;\n }\n }\n /** Update resolved props for all path segments based on current document state */\n #updateProps(doc) {\n let current = doc;\n for (const segment of this.path) {\n const prop = this.#resolveSegmentProp(current, segment);\n // Internal mutation: Update cached prop for efficient path resolution.\n // Safe because segments are owned by this Ref instance.\n segment.prop = prop;\n if (prop !== undefined && current !== undefined && current !== null) {\n current = current[prop];\n }\n else {\n break;\n }\n }\n }\n /**\n * Check if two PathSegments are equal.\n * Used by `contains` and `overlaps` methods.\n */\n #segmentsEqual(a, b) {\n if (a[KIND] !== b[KIND]) {\n return false;\n }\n switch (a[KIND]) {\n case \"key\":\n return a.key === b.key;\n case \"index\":\n return a.index === b.index;\n case \"match\": {\n const aKeys = Object.keys(a.match);\n const bKeys = Object.keys(b.match);\n if (aKeys.length !== bKeys.length)\n return false;\n return aKeys.every(key => a.match[key] === b.match[key]);\n }\n default:\n a;\n return false;\n }\n }\n #normalizeInput(container, input) {\n if (typeof input === \"string\") {\n return { [KIND]: \"key\", key: input, prop: input };\n }\n if (typeof input === \"number\") {\n return { [KIND]: \"index\", index: input, prop: input };\n }\n if (isPattern(input)) {\n if (!Array.isArray(container)) {\n return { [KIND]: \"match\", match: input, prop: undefined };\n }\n const index = container.findIndex(obj => matchesPattern(obj, input));\n return {\n [KIND]: \"match\",\n match: input,\n prop: index !== -1 ? index : undefined,\n };\n }\n throw new Error(`Unsupported path input type: ${typeof input}. ` +\n `Expected string, number, or plain object.`);\n }\n /** Create a cursor-based range from a CursorMarker */\n #createCursorRange(doc, propPath, container, marker) {\n const { start, end } = marker;\n if (typeof container !== \"string\") {\n throw new Error(`cursor() can only be used on string values, got ${typeof container}`);\n }\n const startCursor = Automerge.getCursor(doc, propPath, start);\n const endCursor = Automerge.getCursor(doc, propPath, end);\n if (!startCursor || !endCursor) {\n throw new Error(`Failed to create cursors at positions ${start}-${end}.`);\n }\n return { [KIND]: \"cursors\", start: startCursor, end: endCursor };\n }\n /** Extract cached navigation path from segments */\n #getPropPath() {\n const props = [];\n for (const segment of this.path) {\n if (segment.prop === undefined)\n return undefined;\n props.push(segment.prop);\n }\n return props;\n }\n /** Navigate to a value by following a prop path */\n #getValueAt(container, propPath) {\n let current = container;\n for (const prop of propPath) {\n if (current == null)\n return undefined;\n current = current[prop];\n }\n return current;\n }\n /** Extract substring from a text value using a range */\n #extractRange(doc, propPath, text, range) {\n const positions = this.#getRangePositions(doc, propPath, range);\n if (!positions)\n return undefined;\n return text.slice(positions[0], positions[1]);\n }\n /** Set a value at a prop path (change-only: mutates the doc proxy) */\n #setValueAt(container, propPath, value) {\n if (propPath.length === 0) {\n throw new Error(\"Internal error: #setValueAt called with empty path. \" +\n \"Root document changes should be handled by the caller.\");\n }\n const parent = this.#getValueAt(container, propPath.slice(0, -1));\n if (parent == null) {\n throw new Error(\"Cannot set value: parent is null or undefined\");\n }\n parent[propPath[propPath.length - 1]] = value;\n }\n /** Replace a substring at a range using Automerge.splice (change-only: mutates the doc proxy) */\n #spliceRange(doc, propPath, range, newValue) {\n const positions = this.#getRangePositions(doc, propPath, range);\n if (!positions) {\n throw new Error(\"Cannot resolve range positions\");\n }\n const [start, end] = positions;\n Automerge.splice(doc, propPath, start, end - start, newValue);\n }\n /** Convert cursor positions to numeric [start, end] positions */\n #getRangePositions(doc, propPath, range) {\n const start = Automerge.getCursorPosition(doc, propPath, range.start);\n const end = Automerge.getCursorPosition(doc, propPath, range.end);\n return start !== undefined && end !== undefined ? [start, end] : undefined;\n }\n #patchAffectsRef(patches) {\n const refPropPath = [];\n for (const segment of this.path) {\n if (segment.prop === undefined)\n break;\n refPropPath.push(segment.prop);\n }\n // If we couldn't resolve any part, ref was never valid - don't fire\n if (refPropPath.length === 0)\n return false;\n return patches.some(patch => this.#pathsOverlap(patch.path, refPropPath));\n }\n #pathsOverlap(patchPath, refPropPath) {\n const minLength = Math.min(patchPath.length, refPropPath.length);\n return patchPath\n .slice(0, minLength)\n .every((prop, i) => prop === refPropPath[i]);\n }\n}\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "/**\n * Bridge that allows Subduction to use `automerge-repo` network adapters.\n *\n * Implements the full {@link HandshakeConnection} interface (which extends\n * {@link Connection}) so that a single {@link NetworkAdapterConnection} can be\n * used for both the cryptographic handshake phase (`sendBytes`/`recvBytes`)\n * and the subsequent sync phase (`send`/`recv`).\n *\n * All frames travel through the same `NetworkAdapter` `data` field with a\n * one-byte tag prefix to distinguish handshake bytes from post-handshake\n * structured messages:\n *\n * - `0x00` — handshake frame (raw `Uint8Array`, used during `sendBytes`/`recvBytes`)\n * - `0x01` — message frame (a serialised Subduction `Message`, used during `send`/`recv`)\n *\n * Both peers must use this adapter (or an equivalent that speaks the same\n * tagging convention) for the connection to succeed.\n */\nimport debug from \"debug\";\n/**\n * A connection that wraps an `automerge-repo` `NetworkAdapter` to implement\n * Subduction's `HandshakeConnection` interface.\n *\n * This allows Subduction to communicate over any automerge-repo network adapter\n * (`BroadcastChannel`, `MessageChannel`, etc.) by encoding Subduction frames\n * within the adapter's message format, and decoding them on the other end.\n *\n * Note that both ends of the connection must be able to understand the\n * tag-prefixed transport framing.\n */\nexport class NetworkAdapterTransport {\n #adapter;\n #localPeerId;\n #remotePeerId;\n // --- Post-handshake message queue (Phase 2) ---\n #messageQueue = [];\n #messageWaiters = [];\n #log;\n #disconnectCallback = null;\n #disconnected = false;\n /**\n * Create a new NetworkAdapterConnection.\n *\n * @param adapter - The automerge-repo network adapter to wrap.\n * @param remotePeerId - The remote peer's automerge-repo PeerId.\n */\n constructor(adapter, localPeerId, remotePeerId) {\n this.#adapter = adapter;\n this.#localPeerId = localPeerId;\n this.#remotePeerId = remotePeerId;\n this.#log = debug(`automerge-repo:subduction:network:${localPeerId}-${remotePeerId}`);\n adapter.on(\"message\", this.#handleMessage);\n adapter.on(\"peer-disconnected\", this.#handlePeerDisconnected);\n }\n onDisconnect(callback) {\n this.#disconnectCallback = callback;\n }\n // -----------------------------------------------------------------------\n // Internal event handlers\n // -----------------------------------------------------------------------\n #handleMessage = (msg) => {\n this.#log(\"handling message\", msg);\n if (msg.targetId != this.#localPeerId) {\n this.#log(\"message targetId mismatch\", msg.targetId, this.#localPeerId);\n return;\n }\n // Filter by sender so that on shared adapters (e.g. a server adapter\n // handling multiple clients) each transport only sees messages from its\n // specific remote peer.\n if (msg.senderId != this.#remotePeerId) {\n this.#log(\"message senderId mismatch\", msg.senderId, this.#remotePeerId);\n return;\n }\n // Only process our custom message type.\n if (msg.type !== SUBDUCTION_MESSAGE_TYPE) {\n this.#log(\"message type mismatch\", msg.type, SUBDUCTION_MESSAGE_TYPE);\n return;\n }\n const payload = msg.data;\n if (!payload || payload.length === 0) {\n this.#log(\"ignoring message with no data\");\n return;\n }\n // Otherwise enqueue for recv().\n const waiter = this.#messageWaiters.shift();\n if (waiter) {\n waiter(payload);\n }\n else {\n this.#messageQueue.push(payload);\n }\n };\n #handlePeerDisconnected = ({ peerId }) => {\n if (peerId === this.#remotePeerId.toString()) {\n this.#teardown();\n }\n };\n /** Send a tagged frame over the adapter. */\n #sendFrame(data) {\n this.#adapter.send({\n type: SUBDUCTION_MESSAGE_TYPE,\n senderId: this.#localPeerId.toString(),\n targetId: this.#remotePeerId.toString(),\n data,\n });\n }\n /** Clean up all waiters and pending calls with the given error. */\n #teardown({ fireDisconnectCallback, } = {}) {\n this.#adapter.off(\"message\", this.#handleMessage);\n this.#adapter.off(\"peer-disconnected\", this.#handlePeerDisconnected);\n this.#disconnected = true;\n if (fireDisconnectCallback && this.#disconnectCallback) {\n this.#disconnectCallback();\n }\n }\n /**\n * Send raw bytes during the handshake phase.\n *\n * The bytes are tagged with `TAG_HANDSHAKE` (`0x00`) so that the remote\n * peer routes them to its own `recvBytes` queue.\n */\n async sendBytes(bytes) {\n if (this.#disconnected) {\n return Promise.reject(new Error(\"Connection is disconnected\"));\n }\n this.#sendFrame(bytes);\n }\n /**\n * Receive raw bytes during the handshake phase.\n *\n * Returns the next `TAG_HANDSHAKE`-tagged payload, waiting if none is\n * available yet.\n */\n recvBytes() {\n if (this.#disconnected) {\n return Promise.reject(new Error(\"Connection is disconnected\"));\n }\n // Drain any message that arrived before this call.\n const queued = this.#messageQueue.shift();\n if (queued)\n return Promise.resolve(queued);\n return new Promise((resolve, reject) => {\n if (this.#disconnected) {\n reject(new Error(\"Connection is disconnected\"));\n return;\n }\n this.#messageWaiters.push(resolve);\n });\n }\n /**\n * Disconnect from the peer.\n *\n * This does *not* close the underlying adapter (which may be shared with\n * other connections). It only unsubscribes this connection's listeners.\n */\n async disconnect() {\n this.#teardown({ fireDisconnectCallback: false });\n }\n}\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n/**\n * The `type` value used on automerge-repo messages that carry Subduction\n * frames. Both handshake and post-handshake frames share this type; the\n * tag byte inside `data` distinguishes them.\n */\nexport const SUBDUCTION_MESSAGE_TYPE = \"subduction-connection\";\nconst log = debug(\"automerge-repo:subduction:network\");\n", "(function (root, factory) {\n // Hack to make all exports of this module sha256 function object properties.\n var exports = {};\n factory(exports);\n var sha256 = exports[\"default\"];\n for (var k in exports) {\n sha256[k] = exports[k];\n }\n \n if (typeof module === 'object' && typeof module.exports === 'object') {\n module.exports = sha256;\n } else if (typeof define === 'function' && define.amd) {\n define(function() { return sha256; }); \n } else {\n root.sha256 = sha256;\n }\n})(this, function(exports) {\n\"use strict\";\nexports.__esModule = true;\n// SHA-256 (+ HMAC and PBKDF2) for JavaScript.\n//\n// Written in 2014-2016 by Dmitry Chestnykh.\n// Public domain, no warranty.\n//\n// Functions (accept and return Uint8Arrays):\n//\n// sha256(message) -> hash\n// sha256.hmac(key, message) -> mac\n// sha256.pbkdf2(password, salt, rounds, dkLen) -> dk\n//\n// Classes:\n//\n// new sha256.Hash()\n// new sha256.HMAC(key)\n//\nexports.digestLength = 32;\nexports.blockSize = 64;\n// SHA-256 constants\nvar K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\nfunction hashBlocks(w, v, p, pos, len) {\n var a, b, c, d, e, f, g, h, u, i, j, t1, t2;\n while (len >= 64) {\n a = v[0];\n b = v[1];\n c = v[2];\n d = v[3];\n e = v[4];\n f = v[5];\n g = v[6];\n h = v[7];\n for (i = 0; i < 16; i++) {\n j = pos + i * 4;\n w[i] = (((p[j] & 0xff) << 24) | ((p[j + 1] & 0xff) << 16) |\n ((p[j + 2] & 0xff) << 8) | (p[j + 3] & 0xff));\n }\n for (i = 16; i < 64; i++) {\n u = w[i - 2];\n t1 = (u >>> 17 | u << (32 - 17)) ^ (u >>> 19 | u << (32 - 19)) ^ (u >>> 10);\n u = w[i - 15];\n t2 = (u >>> 7 | u << (32 - 7)) ^ (u >>> 18 | u << (32 - 18)) ^ (u >>> 3);\n w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);\n }\n for (i = 0; i < 64; i++) {\n t1 = (((((e >>> 6 | e << (32 - 6)) ^ (e >>> 11 | e << (32 - 11)) ^\n (e >>> 25 | e << (32 - 25))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n t2 = (((a >>> 2 | a << (32 - 2)) ^ (a >>> 13 | a << (32 - 13)) ^\n (a >>> 22 | a << (32 - 22))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n v[0] += a;\n v[1] += b;\n v[2] += c;\n v[3] += d;\n v[4] += e;\n v[5] += f;\n v[6] += g;\n v[7] += h;\n pos += 64;\n len -= 64;\n }\n return pos;\n}\n// Hash implements SHA256 hash algorithm.\nvar Hash = /** @class */ (function () {\n function Hash() {\n this.digestLength = exports.digestLength;\n this.blockSize = exports.blockSize;\n // Note: Int32Array is used instead of Uint32Array for performance reasons.\n this.state = new Int32Array(8); // hash state\n this.temp = new Int32Array(64); // temporary state\n this.buffer = new Uint8Array(128); // buffer for data to hash\n this.bufferLength = 0; // number of bytes in buffer\n this.bytesHashed = 0; // number of total bytes hashed\n this.finished = false; // indicates whether the hash was finalized\n this.reset();\n }\n // Resets hash state making it possible\n // to re-use this instance to hash other data.\n Hash.prototype.reset = function () {\n this.state[0] = 0x6a09e667;\n this.state[1] = 0xbb67ae85;\n this.state[2] = 0x3c6ef372;\n this.state[3] = 0xa54ff53a;\n this.state[4] = 0x510e527f;\n this.state[5] = 0x9b05688c;\n this.state[6] = 0x1f83d9ab;\n this.state[7] = 0x5be0cd19;\n this.bufferLength = 0;\n this.bytesHashed = 0;\n this.finished = false;\n return this;\n };\n // Cleans internal buffers and re-initializes hash state.\n Hash.prototype.clean = function () {\n for (var i = 0; i < this.buffer.length; i++) {\n this.buffer[i] = 0;\n }\n for (var i = 0; i < this.temp.length; i++) {\n this.temp[i] = 0;\n }\n this.reset();\n };\n // Updates hash state with the given data.\n //\n // Optionally, length of the data can be specified to hash\n // fewer bytes than data.length.\n //\n // Throws error when trying to update already finalized hash:\n // instance must be reset to use it again.\n Hash.prototype.update = function (data, dataLength) {\n if (dataLength === void 0) { dataLength = data.length; }\n if (this.finished) {\n throw new Error(\"SHA256: can't update because hash was finished.\");\n }\n var dataPos = 0;\n this.bytesHashed += dataLength;\n if (this.bufferLength > 0) {\n while (this.bufferLength < 64 && dataLength > 0) {\n this.buffer[this.bufferLength++] = data[dataPos++];\n dataLength--;\n }\n if (this.bufferLength === 64) {\n hashBlocks(this.temp, this.state, this.buffer, 0, 64);\n this.bufferLength = 0;\n }\n }\n if (dataLength >= 64) {\n dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);\n dataLength %= 64;\n }\n while (dataLength > 0) {\n this.buffer[this.bufferLength++] = data[dataPos++];\n dataLength--;\n }\n return this;\n };\n // Finalizes hash state and puts hash into out.\n //\n // If hash was already finalized, puts the same value.\n Hash.prototype.finish = function (out) {\n if (!this.finished) {\n var bytesHashed = this.bytesHashed;\n var left = this.bufferLength;\n var bitLenHi = (bytesHashed / 0x20000000) | 0;\n var bitLenLo = bytesHashed << 3;\n var padLength = (bytesHashed % 64 < 56) ? 64 : 128;\n this.buffer[left] = 0x80;\n for (var i = left + 1; i < padLength - 8; i++) {\n this.buffer[i] = 0;\n }\n this.buffer[padLength - 8] = (bitLenHi >>> 24) & 0xff;\n this.buffer[padLength - 7] = (bitLenHi >>> 16) & 0xff;\n this.buffer[padLength - 6] = (bitLenHi >>> 8) & 0xff;\n this.buffer[padLength - 5] = (bitLenHi >>> 0) & 0xff;\n this.buffer[padLength - 4] = (bitLenLo >>> 24) & 0xff;\n this.buffer[padLength - 3] = (bitLenLo >>> 16) & 0xff;\n this.buffer[padLength - 2] = (bitLenLo >>> 8) & 0xff;\n this.buffer[padLength - 1] = (bitLenLo >>> 0) & 0xff;\n hashBlocks(this.temp, this.state, this.buffer, 0, padLength);\n this.finished = true;\n }\n for (var i = 0; i < 8; i++) {\n out[i * 4 + 0] = (this.state[i] >>> 24) & 0xff;\n out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;\n out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;\n out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;\n }\n return this;\n };\n // Returns the final hash digest.\n Hash.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n // Internal function for use in HMAC for optimization.\n Hash.prototype._saveState = function (out) {\n for (var i = 0; i < this.state.length; i++) {\n out[i] = this.state[i];\n }\n };\n // Internal function for use in HMAC for optimization.\n Hash.prototype._restoreState = function (from, bytesHashed) {\n for (var i = 0; i < this.state.length; i++) {\n this.state[i] = from[i];\n }\n this.bytesHashed = bytesHashed;\n this.finished = false;\n this.bufferLength = 0;\n };\n return Hash;\n}());\nexports.Hash = Hash;\n// HMAC implements HMAC-SHA256 message authentication algorithm.\nvar HMAC = /** @class */ (function () {\n function HMAC(key) {\n this.inner = new Hash();\n this.outer = new Hash();\n this.blockSize = this.inner.blockSize;\n this.digestLength = this.inner.digestLength;\n var pad = new Uint8Array(this.blockSize);\n if (key.length > this.blockSize) {\n (new Hash()).update(key).finish(pad).clean();\n }\n else {\n for (var i = 0; i < key.length; i++) {\n pad[i] = key[i];\n }\n }\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36;\n }\n this.inner.update(pad);\n for (var i = 0; i < pad.length; i++) {\n pad[i] ^= 0x36 ^ 0x5c;\n }\n this.outer.update(pad);\n this.istate = new Uint32Array(8);\n this.ostate = new Uint32Array(8);\n this.inner._saveState(this.istate);\n this.outer._saveState(this.ostate);\n for (var i = 0; i < pad.length; i++) {\n pad[i] = 0;\n }\n }\n // Returns HMAC state to the state initialized with key\n // to make it possible to run HMAC over the other data with the same\n // key without creating a new instance.\n HMAC.prototype.reset = function () {\n this.inner._restoreState(this.istate, this.inner.blockSize);\n this.outer._restoreState(this.ostate, this.outer.blockSize);\n return this;\n };\n // Cleans HMAC state.\n HMAC.prototype.clean = function () {\n for (var i = 0; i < this.istate.length; i++) {\n this.ostate[i] = this.istate[i] = 0;\n }\n this.inner.clean();\n this.outer.clean();\n };\n // Updates state with provided data.\n HMAC.prototype.update = function (data) {\n this.inner.update(data);\n return this;\n };\n // Finalizes HMAC and puts the result in out.\n HMAC.prototype.finish = function (out) {\n if (this.outer.finished) {\n this.outer.finish(out);\n }\n else {\n this.inner.finish(out);\n this.outer.update(out, this.digestLength).finish(out);\n }\n return this;\n };\n // Returns message authentication code.\n HMAC.prototype.digest = function () {\n var out = new Uint8Array(this.digestLength);\n this.finish(out);\n return out;\n };\n return HMAC;\n}());\nexports.HMAC = HMAC;\n// Returns SHA256 hash of data.\nfunction hash(data) {\n var h = (new Hash()).update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hash = hash;\n// Function hash is both available as module.hash and as default export.\nexports[\"default\"] = hash;\n// Returns HMAC-SHA256 of data under the key.\nfunction hmac(key, data) {\n var h = (new HMAC(key)).update(data);\n var digest = h.digest();\n h.clean();\n return digest;\n}\nexports.hmac = hmac;\n// Fills hkdf buffer like this:\n// T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)\nfunction fillBuffer(buffer, hmac, info, counter) {\n // Counter is a byte value: check if it overflowed.\n var num = counter[0];\n if (num === 0) {\n throw new Error(\"hkdf: cannot expand more\");\n }\n // Prepare HMAC instance for new data with old key.\n hmac.reset();\n // Hash in previous output if it was generated\n // (i.e. counter is greater than 1).\n if (num > 1) {\n hmac.update(buffer);\n }\n // Hash in info if it exists.\n if (info) {\n hmac.update(info);\n }\n // Hash in the counter.\n hmac.update(counter);\n // Output result to buffer and clean HMAC instance.\n hmac.finish(buffer);\n // Increment counter inside typed array, this works properly.\n counter[0]++;\n}\nvar hkdfSalt = new Uint8Array(exports.digestLength); // Filled with zeroes.\nfunction hkdf(key, salt, info, length) {\n if (salt === void 0) { salt = hkdfSalt; }\n if (length === void 0) { length = 32; }\n var counter = new Uint8Array([1]);\n // HKDF-Extract uses salt as HMAC key, and key as data.\n var okm = hmac(salt, key);\n // Initialize HMAC for expanding with extracted key.\n // Ensure no collisions with `hmac` function.\n var hmac_ = new HMAC(okm);\n // Allocate buffer.\n var buffer = new Uint8Array(hmac_.digestLength);\n var bufpos = buffer.length;\n var out = new Uint8Array(length);\n for (var i = 0; i < length; i++) {\n if (bufpos === buffer.length) {\n fillBuffer(buffer, hmac_, info, counter);\n bufpos = 0;\n }\n out[i] = buffer[bufpos++];\n }\n hmac_.clean();\n buffer.fill(0);\n counter.fill(0);\n return out;\n}\nexports.hkdf = hkdf;\n// Derives a key from password and salt using PBKDF2-HMAC-SHA256\n// with the given number of iterations.\n//\n// The number of bytes returned is equal to dkLen.\n//\n// (For better security, avoid dkLen greater than hash length - 32 bytes).\nfunction pbkdf2(password, salt, iterations, dkLen) {\n var prf = new HMAC(password);\n var len = prf.digestLength;\n var ctr = new Uint8Array(4);\n var t = new Uint8Array(len);\n var u = new Uint8Array(len);\n var dk = new Uint8Array(dkLen);\n for (var i = 0; i * len < dkLen; i++) {\n var c = i + 1;\n ctr[0] = (c >>> 24) & 0xff;\n ctr[1] = (c >>> 16) & 0xff;\n ctr[2] = (c >>> 8) & 0xff;\n ctr[3] = (c >>> 0) & 0xff;\n prf.reset();\n prf.update(salt);\n prf.update(ctr);\n prf.finish(u);\n for (var j = 0; j < len; j++) {\n t[j] = u[j];\n }\n for (var j = 2; j <= iterations; j++) {\n prf.reset();\n prf.update(u).finish(u);\n for (var k = 0; k < len; k++) {\n t[k] ^= u[k];\n }\n }\n for (var j = 0; j < len && i * len + j < dkLen; j++) {\n dk[i * len + j] = t[j];\n }\n }\n for (var i = 0; i < len; i++) {\n t[i] = u[i] = 0;\n }\n for (var i = 0; i < 4; i++) {\n ctr[i] = 0;\n }\n prf.clean();\n return dk;\n}\nexports.pbkdf2 = pbkdf2;\n});\n", "import debug from \"debug\";\nimport { EventEmitter } from \"eventemitter3\";\nimport { parseAutomergeUrl } from \"../AutomergeUrl.js\";\nimport { DocSynchronizer } from \"./DocSynchronizer.js\";\nconst log = debug(\"automerge-repo:collectionsync\");\n/**\n * CollectionSynchronizer manages the lifecycle of per-document synchronizers\n * and routes incoming messages to the correct DocSynchronizer.\n */\nexport class CollectionSynchronizer extends EventEmitter {\n #peers = new Set();\n #docSynchronizers = {};\n #denylist;\n #config;\n #networkReady;\n constructor(config, denylist = []) {\n super();\n this.#networkReady = config.networkReady;\n this.#config = config;\n this.#denylist = denylist.map(url => parseAutomergeUrl(url).documentId);\n }\n /** Expose doc synchronizers for Repo access (e.g. metrics) */\n get docSynchronizers() {\n return this.#docSynchronizers;\n }\n // DOCUMENT SOURCE INTERFACE\n /**\n * Register a document for syncing ({@link DocumentSource.attach}). If the\n * document is already registered this is a no-op.\n */\n attach(query) {\n if (this.#docSynchronizers[query.documentId])\n return;\n const docSync = this.#initDocSynchronizer(query.handle, query);\n this.#docSynchronizers[query.documentId] = docSync;\n for (const peerId of this.#peers) {\n this.#addPeerToDoc(peerId, docSync, []);\n }\n }\n /** {@link DocumentSource.detach} — removes a document and stops syncing. */\n detach(documentId) {\n log(`removing document ${documentId}`);\n const docSync = this.#docSynchronizers[documentId];\n if (docSync) {\n for (const peerId of this.peers) {\n docSync.removePeer(peerId);\n }\n }\n delete this.#docSynchronizers[documentId];\n }\n // PEER MANAGEMENT\n addPeer(peerId) {\n log(`adding ${peerId} & synchronizing with them`);\n if (this.#peers.has(peerId))\n return;\n this.#peers.add(peerId);\n for (const docSync of Object.values(this.#docSynchronizers)) {\n this.#addPeerToDoc(peerId, docSync, []);\n }\n }\n removePeer(peerId) {\n log(`removing peer ${peerId}`);\n this.#peers.delete(peerId);\n for (const docSync of Object.values(this.#docSynchronizers)) {\n docSync.removePeer(peerId);\n }\n }\n get peers() {\n return Array.from(this.#peers);\n }\n // MESSAGE HANDLING\n receiveMessage(message) {\n log(`onSyncMessage: ${message.senderId}, ${message.documentId}, ${\"data\" in message ? message.data.byteLength + \"bytes\" : \"\"}`);\n const documentId = message.documentId;\n if (!documentId) {\n throw new Error(\"received a message with an invalid documentId\");\n }\n if (this.#denylist.includes(documentId)) {\n this.emit(\"metrics\", { type: \"doc-denied\", documentId });\n this.emit(\"message\", {\n type: \"doc-unavailable\",\n documentId,\n targetId: message.senderId,\n });\n return;\n }\n // Ensure we have a DocSynchronizer for this document.\n // ensureHandle calls this.attach which no-ops if already registered.\n let docSync = this.#docSynchronizers[documentId];\n if (!docSync) {\n this.#config.ensureHandle(documentId);\n // ensureHandle should have synchronously registered a DocSynchronizer via\n // this.attach so it should now be present in this.#docSynchronizers\n docSync = this.#docSynchronizers[documentId];\n }\n // Ephemeral and doc-unavailable messages may have a senderId that is\n // not a direct network peer (e.g. relayed ephemeral messages preserve\n // the original author's senderId). Route them directly to the\n // DocSynchronizer without trying to register the sender as a peer.\n if (message.type === \"ephemeral\" || message.type === \"doc-unavailable\") {\n docSync.receiveMessage(message);\n return;\n }\n // For sync/request messages, ensure the sender is a peer on this doc\n // synchronizer. The incoming message is passed to addPeerToDoc so it is\n // queued and processed after persisted sync state loads, preserving\n // in-order delivery.\n if (!docSync.hasPeer(message.senderId)) {\n this.#addPeerToDoc(message.senderId, docSync, [message]);\n }\n else {\n docSync.receiveMessage(message);\n }\n }\n // SHARE POLICY\n shareConfigChanged() {\n for (const docSync of Object.values(this.#docSynchronizers)) {\n docSync.reevaluateSharePolicy();\n }\n }\n metrics() {\n return Object.fromEntries(Object.entries(this.#docSynchronizers).map(([documentId, synchronizer]) => {\n return [documentId, synchronizer.metrics()];\n }));\n }\n // PRIVATE\n #initDocSynchronizer(handle, query) {\n const docSync = new DocSynchronizer({\n handle,\n query,\n networkReady: this.#networkReady,\n shareConfig: this.#config.shareConfig,\n });\n docSync.on(\"message\", event => this.emit(\"message\", event));\n docSync.on(\"open-doc\", event => this.emit(\"open-doc\", event));\n docSync.on(\"sync-state\", event => this.emit(\"sync-state\", event));\n docSync.on(\"metrics\", event => this.emit(\"metrics\", event));\n return docSync;\n }\n #addPeerToDoc(peerId, docSync, messages) {\n const documentId = docSync.documentId;\n docSync.addPeer(peerId, this.#loadSyncStateFor(documentId, peerId), {\n messages,\n });\n }\n #loadSyncStateFor(documentId, peerId) {\n return (this.#config.loadSyncState?.(documentId, peerId) ??\n Promise.resolve(undefined));\n }\n}\n", "// https://github.com/maxogden/websocket-stream/blob/48dc3ddf943e5ada668c31ccd94e9186f02fafbd/ws-fallback.js\n\nvar ws = null\n\nif (typeof WebSocket !== 'undefined') {\n ws = WebSocket\n} else if (typeof MozWebSocket !== 'undefined') {\n ws = MozWebSocket\n} else if (typeof global !== 'undefined') {\n ws = global.WebSocket || global.MozWebSocket\n} else if (typeof window !== 'undefined') {\n ws = window.WebSocket || window.MozWebSocket\n} else if (typeof self !== 'undefined') {\n ws = self.WebSocket || self.MozWebSocket\n}\n\nexport default ws\n", "import WebSocket from \"isomorphic-ws\";\nimport debug from \"debug\";\nconst log = debug(\"automerge-repo:subduction:ws-transport\");\n/**\n * Wraps a WebSocket connection as a subduction {@link Transport}.\n *\n * Works in both Node.js (via `ws`) and the browser (via native `WebSocket`)\n * through `isomorphic-ws`.\n */\nexport class WebSocketTransport {\n #ws;\n #messageQueue = [];\n #waiters = [];\n #errorWaiters = [];\n #isClosed = false;\n #closedResolve;\n #closedPromise;\n #disconnectCallback = null;\n constructor(ws) {\n this.#ws = ws;\n this.#closedPromise = new Promise(r => {\n this.#closedResolve = r;\n });\n ws.binaryType = \"arraybuffer\";\n ws.addEventListener(\"message\", (event) => {\n const raw = event.data;\n const bytes = raw instanceof ArrayBuffer\n ? new Uint8Array(raw)\n : new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);\n const waiter = this.#waiters.shift();\n if (waiter) {\n this.#errorWaiters.shift();\n waiter(bytes);\n }\n else {\n this.#messageQueue.push(bytes);\n }\n });\n ws.addEventListener(\"close\", () => {\n this.#isClosed = true;\n this.#closedResolve();\n const err = new Error(\"WebSocket closed\");\n for (const ew of this.#errorWaiters)\n ew(err);\n this.#errorWaiters = [];\n this.#waiters = [];\n });\n ws.addEventListener(\"error\", (event) => {\n log(\"ws error: %O\", event);\n this.#isClosed = true;\n this.#closedResolve();\n const err = \"error\" in event && event.error instanceof Error\n ? event.error\n : new Error(\"WebSocket error\");\n for (const ew of this.#errorWaiters)\n ew(err);\n this.#errorWaiters = [];\n this.#waiters = [];\n });\n }\n onDisconnect(callback) {\n this.#disconnectCallback = callback;\n }\n /**\n * Open a WebSocket connection and return a transport wrapping it.\n * Resolves once the connection is open.\n */\n static connect(url) {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(url);\n const onOpen = () => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onError);\n resolve(new WebSocketTransport(ws));\n };\n const onError = (event) => {\n ws.removeEventListener(\"open\", onOpen);\n ws.removeEventListener(\"error\", onError);\n const err = \"error\" in event && event.error instanceof Error\n ? event.error\n : new Error(\"WebSocket connection failed\");\n reject(err);\n };\n ws.addEventListener(\"open\", onOpen);\n ws.addEventListener(\"error\", onError);\n });\n }\n async sendBytes(bytes) {\n if (this.#isClosed)\n throw new Error(\"WebSocket closed\");\n this.#ws.send(bytes.slice());\n }\n recvBytes() {\n const queued = this.#messageQueue.shift();\n if (queued)\n return Promise.resolve(queued);\n if (this.#isClosed)\n return Promise.reject(new Error(\"WebSocket closed\"));\n return new Promise((resolve, reject) => {\n this.#waiters.push(resolve);\n this.#errorWaiters.push(reject);\n });\n }\n async disconnect() {\n this.#teardown({ fireDisconnectCallback: false });\n }\n /** Resolves when the underlying WebSocket closes (for any reason). */\n closed() {\n return this.#closedPromise;\n }\n #teardown({ fireDisconnectCallback, } = {}) {\n this.#isClosed = true;\n this.#closedResolve();\n this.#ws.close();\n if (fireDisconnectCallback && this.#disconnectCallback)\n this.#disconnectCallback();\n }\n}\n", "export const DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000;\nexport const DEFAULT_PEER_TTL_MS = 3 * DEFAULT_HEARTBEAT_INTERVAL_MS;\nexport const PRESENCE_MESSAGE_MARKER = \"__presence\";\n", "export function unique(items) {\n return Array.from(new Set(items));\n}\n", "import { unique } from \"../helpers/array.js\";\nexport class PeerStateView {\n value;\n constructor(value) {\n this.value = value;\n }\n /** All distinct users across peers. */\n get users() {\n const userIds = unique(Object.values(this.value).map(peerState => peerState.userId));\n return userIds.map(u => this.getUserState(u));\n }\n /** All distinct devices across peers. */\n get devices() {\n const deviceIds = unique(Object.values(this.value).map(peerState => peerState.deviceId));\n return deviceIds.map(d => this.getDeviceState(d));\n }\n /** All peer states. */\n get peers() {\n return Object.values(this.value);\n }\n /** Peer IDs belonging to a given user. */\n getUserPeers(userId) {\n return Object.values(this.value)\n .filter(peerState => peerState.userId === userId)\n .map(peerState => peerState.peerId);\n }\n /** Peer IDs belonging to a given device. */\n getDevicePeers(deviceId) {\n return Object.values(this.value)\n .filter(peerState => peerState.deviceId === deviceId)\n .map(peerState => peerState.peerId);\n }\n /** Most recently seen peer from a set of peer IDs. */\n getLastSeenPeer(peers) {\n let freshestLastSeenAt;\n return peers.reduce((freshest, curr) => {\n const lastSeenAt = this.value[curr]?.lastUpdateAt;\n if (!lastSeenAt) {\n return freshest;\n }\n if (!freshest || lastSeenAt > freshestLastSeenAt) {\n freshestLastSeenAt = lastSeenAt;\n return curr;\n }\n return freshest;\n }, undefined);\n }\n /** Peer from a set that most recently sent a state update. */\n getLastActivePeer(peers) {\n let freshestLastActiveAt;\n return peers.reduce((freshest, curr) => {\n const lastActiveAt = this.value[curr]?.lastActiveAt;\n if (!lastActiveAt) {\n return freshest;\n }\n if (!freshest || lastActiveAt > freshestLastActiveAt) {\n freshestLastActiveAt = lastActiveAt;\n return curr;\n }\n return freshest;\n }, undefined);\n }\n /** State of the most recently active peer for a user. */\n getUserState(userId) {\n const peers = this.getUserPeers(userId);\n if (!peers)\n return undefined;\n const peer = this.getLastActivePeer(peers);\n if (!peer)\n return undefined;\n return this.value[peer];\n }\n /** State of the most recently active peer for a device. */\n getDeviceState(deviceId) {\n const peers = this.getDevicePeers(deviceId);\n if (!peers)\n return undefined;\n const peer = this.getLastActivePeer(peers);\n if (!peer)\n return undefined;\n return this.value[peer];\n }\n}\n", "import { PeerStateView } from \"./PeerStateView.js\";\nexport class PeerPresenceInfo {\n ttl;\n #peerStates = new PeerStateView({});\n /**\n * Build a new peer presence state.\n *\n * @param ttl in milliseconds - peers with no activity within this timeframe\n * are forgotten when {@link prune} is called.\n */\n constructor(ttl) {\n this.ttl = ttl;\n }\n has(peerId) {\n return peerId in this.#peerStates.value;\n }\n /**\n * Record that we've seen the given peer recently.\n */\n markSeen(peerId) {\n this.#peerStates = new PeerStateView({\n ...this.#peerStates.value,\n [peerId]: {\n ...this.#peerStates.value[peerId],\n lastUpdateAt: Date.now(),\n },\n });\n }\n /**\n * Record a state update for the given peer. Note that existing state is not\n * overwritten.\n */\n update({ peerId, deviceId, userId, value, }) {\n const peerState = this.#peerStates.value[peerId];\n const existingState = peerState?.value ?? {};\n const now = Date.now();\n this.#peerStates = new PeerStateView({\n ...this.#peerStates.value,\n [peerId]: {\n peerId,\n deviceId,\n userId,\n lastActiveAt: now,\n lastUpdateAt: now,\n value: {\n ...existingState,\n ...value,\n },\n },\n });\n }\n /**\n * Forget the given peer.\n */\n delete(peerId) {\n this.#peerStates = new PeerStateView(Object.fromEntries(Object.entries(this.#peerStates.value).filter(([existingId]) => {\n return existingId != peerId;\n })));\n }\n /**\n * Prune all peers that have not been active since the configured ttl has\n * elapsed.\n */\n prune() {\n const threshold = Date.now() - this.ttl;\n this.#peerStates = new PeerStateView(Object.fromEntries(Object.entries(this.#peerStates.value).filter(([, state]) => {\n return state.lastActiveAt >= threshold;\n })));\n }\n /**\n * Get a snapshot of the current peer states\n */\n get states() {\n return this.#peerStates;\n }\n}\n", "import { EventEmitter } from \"eventemitter3\";\nimport { DEFAULT_HEARTBEAT_INTERVAL_MS, DEFAULT_PEER_TTL_MS, PRESENCE_MESSAGE_MARKER, } from \"./constants.js\";\nimport { PeerPresenceInfo } from \"./PeerPresenceInfo.js\";\n/**\n * Presence encapsulates ephemeral state communication for a specific doc\n * handle. It tracks caller-provided local state and broadcasts that state to\n * all peers. It sends periodic heartbeats when there are no state updates.\n *\n * It also tracks ephemeral state broadcast by peers and emits events when peers\n * send ephemeral state updates (see {@link PresenceEvents}).\n *\n * Presence starts out in an inactive state. Call {@link start} and {@link stop}\n * to activate and deactivate it.\n */\nexport class Presence extends EventEmitter {\n #handle;\n deviceId;\n userId;\n #peers;\n #localState;\n #heartbeatMs;\n #handleEphemeralMessage;\n #heartbeatInterval;\n #pruningInterval;\n #hellos = [];\n #running = false;\n /**\n * Create a new Presence to share ephemeral state with peers.\n *\n * @param config see {@link PresenceConfig}\n * @returns\n */\n constructor({ handle, deviceId, userId, }) {\n super();\n this.#handle = handle;\n this.#peers = new PeerPresenceInfo(DEFAULT_PEER_TTL_MS);\n this.#localState = {};\n this.deviceId = deviceId;\n this.userId = userId;\n }\n /**\n * Start listening to ephemeral messages on the handle, broadcast initial\n * state to peers, and start sending heartbeats.\n */\n start({ initialState, heartbeatMs, peerTtlMs }) {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#heartbeatMs = heartbeatMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;\n this.#peers = new PeerPresenceInfo(peerTtlMs ?? DEFAULT_PEER_TTL_MS);\n this.#localState = initialState;\n // N.B.: We can't use a regular member function here since member functions\n // of two distinct objects are identical, and we need to be able to stop\n // listening to the handle for just this Presence instance in stop()\n this.#handleEphemeralMessage = (e) => {\n const peerId = e.senderId;\n const envelope = e.message;\n if (!(PRESENCE_MESSAGE_MARKER in envelope)) {\n return;\n }\n const message = envelope[PRESENCE_MESSAGE_MARKER];\n const { deviceId, userId } = message;\n if (!this.#peers.has(peerId)) {\n this.announce();\n }\n switch (message.type) {\n case \"heartbeat\":\n this.#peers.markSeen(peerId);\n this.emit(\"heartbeat\", { type: \"heartbeat\", peerId });\n break;\n case \"goodbye\":\n this.#peers.delete(peerId);\n this.emit(\"goodbye\", { type: \"goodbye\", peerId });\n break;\n case \"update\":\n this.#peers.update({\n peerId,\n deviceId,\n userId,\n value: { [message.channel]: message.value },\n });\n this.emit(\"update\", {\n type: \"update\",\n peerId,\n deviceId,\n userId,\n channel: message.channel,\n value: message.value,\n });\n break;\n case \"snapshot\":\n this.#peers.update({\n peerId,\n deviceId,\n userId,\n value: message.state,\n });\n this.emit(\"snapshot\", {\n type: \"snapshot\",\n peerId,\n deviceId,\n userId,\n state: message.state,\n });\n break;\n }\n };\n this.#handle.on(\"ephemeral-message\", this.#handleEphemeralMessage);\n this.broadcastLocalState(); // also starts heartbeats\n this.startPruningPeers();\n }\n /**\n * Return a view of current peer states.\n */\n getPeerStates() {\n return this.#peers.states;\n }\n /**\n * Return a view of current local state.\n */\n getLocalState() {\n return this.#localState;\n }\n /**\n * Update state for the specific channel, and broadcast new state to all\n * peers.\n *\n * @param channel\n * @param value\n */\n broadcast(channel, value) {\n this.#localState = Object.assign({}, this.#localState, {\n [channel]: value,\n });\n this.broadcastChannelState(channel);\n }\n /**\n * Whether this Presence is currently active. See\n * {@link start} and {@link stop}.\n */\n get running() {\n return this.#running;\n }\n /**\n * Stop this Presence: broadcast a \"goodbye\" message (when received, other\n * peers will immediately forget the sender), stop sending heartbeats, and\n * stop listening to ephemeral-messages broadcast from peers.\n *\n * This can be used with browser events like\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event | \"pagehide\"}\n * or\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event | \"visibilitychange\"}\n * to stop sending and receiving updates when not active.\n */\n stop() {\n if (!this.#running) {\n return;\n }\n this.#hellos.forEach(timeoutId => {\n clearTimeout(timeoutId);\n });\n this.#hellos = [];\n this.#handle.off(\"ephemeral-message\", this.#handleEphemeralMessage);\n this.stopHeartbeats();\n this.stopPruningPeers();\n this.send({ type: \"goodbye\" });\n this.#running = false;\n }\n announce() {\n // Broadcast our current state whenever we see new peers\n // TODO: We currently need to wait for the peer to be ready, but waiting\n // some arbitrary amount of time is brittle\n const helloId = setTimeout(() => {\n this.broadcastLocalState();\n this.#hellos = this.#hellos.filter(id => id !== helloId);\n }, 500);\n this.#hellos.push(helloId);\n }\n broadcastLocalState() {\n this.doBroadcast(\"snapshot\", { state: this.#localState });\n this.resetHeartbeats();\n }\n broadcastChannelState(channel) {\n const value = this.#localState[channel];\n this.doBroadcast(\"update\", { channel, value });\n this.resetHeartbeats();\n }\n resetHeartbeats() {\n // Reset heartbeats every time we broadcast a message to avoid sending\n // unnecessary heartbeats when there is plenty of actual update activity\n // happening.\n this.stopHeartbeats();\n this.startHeartbeats();\n }\n doBroadcast(type, extra) {\n this.send({\n userId: this.userId,\n deviceId: this.deviceId,\n type,\n ...extra,\n });\n }\n send(message) {\n if (!this.#running) {\n return;\n }\n this.#handle.broadcast({\n [PRESENCE_MESSAGE_MARKER]: message,\n });\n }\n startHeartbeats() {\n if (this.#heartbeatInterval !== undefined) {\n return;\n }\n this.#heartbeatInterval = setInterval(() => {\n this.send({ type: \"heartbeat\" });\n }, this.#heartbeatMs);\n }\n stopHeartbeats() {\n if (this.#heartbeatInterval === undefined) {\n return;\n }\n clearInterval(this.#heartbeatInterval);\n this.#heartbeatInterval = undefined;\n }\n startPruningPeers() {\n if (this.#pruningInterval !== undefined) {\n return;\n }\n // Pruning happens at the heartbeat frequency, not on a peer ttl frequency,\n // to minimize variance between peer expiration, since the heartbeat frequency\n // is expected to be several times higher.\n this.#pruningInterval = setInterval(() => {\n const before = Object.keys(this.#peers.states.value).length;\n this.#peers.prune();\n const after = Object.keys(this.#peers.states.value).length;\n if (after < before) {\n this.emit(\"pruned\");\n }\n }, this.#heartbeatMs);\n }\n stopPruningPeers() {\n if (this.#pruningInterval === undefined) {\n return;\n }\n clearInterval(this.#pruningInterval);\n this.#pruningInterval = undefined;\n }\n}\n", "import { useCallback, useEffect, useRef, useState } from \"react\"\n\nimport {\n Presence,\n PresenceConfig,\n DocHandle,\n PeerStateView,\n PresenceState,\n} from \"@automerge/automerge-repo/slim\"\n\nexport type UsePresenceConfig<State extends PresenceState> =\n PresenceConfig<State> & {\n handle: DocHandle<unknown>\n }\n\nexport type UsePresenceResult<State extends PresenceState> = {\n /**\n * Presence view of our peers.\n */\n peerStates: PeerStateView<State>\n /**\n * Our own presence state, as last set by `update` or the initial value.\n */\n localState: State | undefined\n /**\n * Update our presence state for the given channel and broadcast\n * it to our peers.\n *\n * @param channel\n * @param value\n */\n update: <Channel extends keyof State>(\n channel: Channel,\n value: State[Channel]\n ) => void\n /**\n * Resume presence broadcasting and listening to peer presence.\n *\n * Note that this only needs to be called after `stop` has been called:\n * usePresence starts running immediately.\n */\n start: (config?: Partial<PresenceConfig<State>>) => void\n /**\n * Stop broadcasting presence state and listening to peer presence.\n */\n stop: () => void\n}\n\n/**\n * This hook encapsulates ephemeral state communication for a specific doc\n * handle. It tracks caller-provided local state and broadcasts that state to\n * all peers. It sends periodic heartbeats when there are no state updates.\n *\n * It also tracks ephemeral state broadcast by peers and forces a re-render when\n * the state of a peer changes.\n *\n * It cleans up (stops sending heartbeats and processing ephemeral messages)\n * when it unmounts.\n *\n * It is implemented using {@link Presence}.\n *\n * @param config - see {@link UsePresenceConfig}. Note that initialState only\n * determines the initial value. Updates to this param will not trigger a\n * re-render of the hook.\n *\n * @returns see {@link UsePresenceResult}\n */\nexport function usePresence<State extends PresenceState>({\n handle,\n initialState,\n heartbeatMs,\n peerTtlMs,\n}: UsePresenceConfig<State>): UsePresenceResult<State> {\n const [localState, setLocalState] = useState<State>(initialState)\n const [peerStates, setPeerStates] = useState(new PeerStateView<State>({}))\n // Don't re-render based on changes to these: they are not expected to\n // change but may be passed in as object literals\n const firstOpts = useRef({\n heartbeatMs,\n peerTtlMs,\n })\n const firstInitialState = useRef(initialState)\n const [presence] = useState(() => new Presence<State>({ handle }))\n\n useEffect(() => {\n presence.start({\n initialState: firstInitialState.current,\n ...firstOpts.current,\n })\n presence.on(\"heartbeat\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"snapshot\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"update\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"goodbye\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"pruned\", () => setPeerStates(presence.getPeerStates()))\n\n return () => {\n presence.stop()\n }\n }, [presence, firstInitialState, firstOpts])\n\n const start = useCallback(\n (config?: Partial<PresenceConfig<State>>) => {\n // Fall back to the last state if not provided when restarting\n const initialState = config?.initialState ?? presence.getLocalState()\n const opts = {\n ...firstOpts.current,\n ...config,\n initialState,\n }\n presence.start(opts)\n },\n [presence, firstOpts]\n )\n const stop = useCallback(() => {\n presence.stop()\n }, [presence])\n\n const update = useCallback(\n <Channel extends keyof State>(channel: Channel, msg: State[Channel]) => {\n presence.broadcast(channel, msg)\n const updated = presence.getLocalState()\n setLocalState(updated)\n },\n [presence]\n )\n\n return {\n peerStates,\n localState,\n update,\n start,\n stop,\n }\n}\n", "export * from \"@automerge/automerge-repo-react-hooks\";\nexport { BroadcastChannelNetworkAdapter } from \"@automerge/automerge-repo-network-broadcastchannel\";\nexport { MessageChannelNetworkAdapter } from \"@automerge/automerge-repo-network-messagechannel\";\nexport { WebSocketClientAdapter } from \"@automerge/automerge-repo-network-websocket\";\nexport { IndexedDBStorageAdapter } from \"@automerge/automerge-repo-storage-indexeddb\";\n", "import {\n type TLAnyShapeUtilConstructor,\n type TLRecord,\n type TLStoreWithStatus,\n createTLStore,\n defaultShapeUtils,\n type HistoryEntry,\n getUserPreferences,\n setUserPreferences,\n defaultUserPreferences,\n createPresenceStateDerivation,\n InstancePresenceRecordType,\n computed,\n react,\n type TLStoreSnapshot,\n type TLInstancePresence,\n sortById,\n useEditor,\n} from \"@tldraw/tldraw\";\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n type DocHandle,\n type DocHandleChangePayload,\n} from \"@automerge/automerge-repo/slim\";\nimport { usePresence } from \"@automerge/automerge-repo-react-hooks\";\n\nimport { applyAutomergePatchesToTLStore } from \"./AutomergeToTLStore.js\";\nimport { applyTLStoreChangesToAutomerge } from \"./TLStoreToAutomerge.js\";\n\nexport function useAutomergeStore({\n handle,\n shapeUtils = [],\n readOnly = false,\n}: {\n handle: DocHandle<TLStoreSnapshot>;\n userId: string;\n shapeUtils?: TLAnyShapeUtilConstructor[];\n readOnly?: boolean;\n}): TLStoreWithStatus {\n const [store] = useState(() => {\n const store = createTLStore({\n shapeUtils: [...defaultShapeUtils, ...shapeUtils],\n });\n return store;\n });\n\n const [storeWithStatus, setStoreWithStatus] = useState<TLStoreWithStatus>({\n status: \"loading\",\n });\n\n // Read through a ref inside the write-back listener so a mid-session flip\n // (see `useIsHandleReadOnly`) doesn't re-run the store effect below \u2014 that\n // would re-load the snapshot and clear session records (camera, selection).\n const readOnlyRef = useRef(readOnly);\n readOnlyRef.current = readOnly;\n\n /* -------------------- TLDraw <--> Automerge -------------------- */\n useEffect(() => {\n const unsubs: (() => void)[] = [];\n\n // A hacky workaround to prevent local changes from being applied twice\n // once into the automerge doc and then back again.\n let preventPatchApplications = false;\n\n /* TLDraw to Automerge */\n function syncStoreChangesToAutomergeDoc({\n changes,\n }: HistoryEntry<TLRecord>) {\n // A read-only (history-pinned) handle is at fixed heads and rejects\n // `handle.change`, so never forward store edits back to Automerge.\n if (readOnlyRef.current) return;\n preventPatchApplications = true;\n handle.change((doc) => {\n applyTLStoreChangesToAutomerge(doc, changes);\n });\n preventPatchApplications = false;\n }\n\n unsubs.push(\n store.listen(syncStoreChangesToAutomergeDoc, {\n source: \"user\",\n scope: \"document\",\n })\n );\n\n /* Automerge to TLDraw */\n const syncAutomergeDocChangesToStore = ({\n patches,\n scopeReplaced,\n doc,\n }: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (preventPatchApplications) return;\n\n // A wholesale scope replacement (e.g. the draft overlay re-pointing\n // this handle at a different clone) carries no patch stream connecting\n // the old doc to the new one. Diff the new doc's *document*-scope\n // records into the store rather than `loadStoreSnapshot`: that would\n // `clear()` the session-scope records too (camera/zoom, current page,\n // selection), which should survive a draft switch. Drafts are forks of\n // each other, so most records are identical and `put` skips them.\n if (scopeReplaced) {\n const swapped = handle.doc();\n if (!swapped?.store) return;\n const migrated = store.schema.migrateStoreSnapshot({\n store: JSON.parse(JSON.stringify(swapped.store)),\n schema: JSON.parse(JSON.stringify(swapped.schema)),\n });\n if (migrated.type === \"error\") {\n console.error(\n \"[tldraw4] failed to migrate swapped-in snapshot:\",\n migrated.reason\n );\n return;\n }\n const next = migrated.value;\n store.mergeRemoteChanges(() => {\n const toRemove = store\n .allRecords()\n .filter(\n (record) =>\n store.scopedTypes.document.has(record.typeName) &&\n !(record.id in next)\n )\n .map((record) => record.id);\n if (toRemove.length) store.remove(toRemove);\n store.put(Object.values(next));\n });\n return;\n }\n\n applyAutomergePatchesToTLStore(patches, store, doc ?? handle.doc());\n };\n\n handle.on(\"change\", syncAutomergeDocChangesToStore);\n unsubs.push(() => handle.off(\"change\", syncAutomergeDocChangesToStore));\n\n /* Load the initial document snapshot into the store. */\n // TODO: need to think through the various status possibilities here and how they map\n const doc = handle.doc();\n if (!doc) throw new Error(\"Document not found\");\n if (!doc.store) throw new Error(\"Document store not initialized\");\n\n store.mergeRemoteChanges(() => {\n store.loadStoreSnapshot({\n store: structuredClone(doc.store),\n schema: structuredClone(doc.schema),\n });\n });\n\n setStoreWithStatus({\n store,\n status: \"synced-remote\",\n connectionStatus: \"online\",\n });\n\n return () => {\n unsubs.forEach((fn) => fn());\n unsubs.length = 0;\n };\n }, [handle, store]);\n\n return storeWithStatus;\n}\n\n// A handle's read-only state (`isReadOnly()`, true at fixed heads) can flip in\n// place: its backing may be swapped without the handle identity changing (a\n// `change` event with `scopeReplaced: true`). Track it as state re-read on\n// every swap rather than sampling it once per mount.\nexport function useIsHandleReadOnly(\n handle: DocHandle<TLStoreSnapshot>\n): boolean {\n const [readOnly, setReadOnly] = useState(() => handle.isReadOnly());\n\n useEffect(() => {\n setReadOnly(handle.isReadOnly());\n const onChange = (payload: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (payload.scopeReplaced) setReadOnly(handle.isReadOnly());\n };\n handle.on(\"change\", onChange);\n return () => void handle.off(\"change\", onChange);\n }, [handle]);\n\n return readOnly;\n}\n\n// A scope swap (a `change` event with `scopeReplaced: true` -- the draft\n// overlay re-pointing this handle at a different clone when scrubbing history\n// or switching drafts) invalidates the undo stack: its entries describe a\n// different timeline. The swapped-in records themselves are applied via\n// `mergeRemoteChanges` in `useAutomergeStore` above (so they are never\n// recorded); clearing the stale stack is all that's left to do.\n//\n// This can't live in `useAutomergeStore` directly: undo history is not a\n// store concern -- the `HistoryManager` belongs to the `Editor`, which tldraw\n// only creates internally once `<Tldraw store={...}>` mounts. The store hook\n// runs outside `<Tldraw>`, before any editor exists, so the history-clearing\n// half of the swap handling has to be a separate hook rendered *inside*\n// `<Tldraw>`, where `useEditor()` can reach the editor.\nexport function useClearHistoryOnScopeSwap(handle: DocHandle<TLStoreSnapshot>) {\n const editor = useEditor();\n\n useEffect(() => {\n if (!editor) return;\n const onChange = (payload: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (payload.scopeReplaced) editor.clearHistory();\n };\n handle.on(\"change\", onChange);\n return () => void handle.off(\"change\", onChange);\n }, [editor, handle]);\n}\n\n// Ephemeral state shared with peers: our tldraw presence record, or null if window is not focused\ntype PresenceChannels = { presence: TLInstancePresence | null };\n\nexport function useAutomergePresence({\n handle,\n store,\n userMetadata,\n element,\n}: {\n handle: DocHandle<TLStoreSnapshot>;\n store: TLStoreWithStatus;\n userMetadata: any;\n element: HTMLElement;\n}) {\n const innerStore = store?.store;\n\n const { userId, name, color } = userMetadata;\n\n const isCursorActive = useIsCursorActive(element);\n\n const { peerStates, update, stop } = usePresence<PresenceChannels>({\n handle,\n initialState: { presence: null },\n });\n\n useEffect(() => {\n if (!innerStore) return;\n\n // Records are keyed by peerId so multiple sessions of the same user stay distinct.\n const toPut: TLRecord[] = peerStates.peers\n .filter((peer) => peer.value?.presence)\n .map((peer) => ({\n ...peer.value.presence!,\n id: InstancePresenceRecordType.createId(peer.peerId),\n }));\n\n const toRemove = innerStore.query\n .records(\"instance_presence\")\n .get()\n .sort(sortById)\n .map((record) => record.id)\n .filter((id) => !toPut.find((record) => record.id === id));\n\n if (toRemove.length) innerStore.remove(toRemove);\n if (toPut.length) innerStore.put(toPut);\n }, [innerStore, peerStates]);\n\n useEffect(() => {\n if (!innerStore) return;\n setUserPreferences({ id: userId, color, name });\n\n const userPreferences = computed<{\n id: string;\n color: string;\n name: string;\n }>(\"userPreferences\", () => {\n const user = getUserPreferences();\n return {\n id: user.id,\n color: user.color ?? defaultUserPreferences.color,\n name: user.name ?? defaultUserPreferences.name,\n };\n });\n\n const presenceDerivation =\n createPresenceStateDerivation(userPreferences)(innerStore);\n\n // Closing the page sends a goodbye, which removes our record from peers.\n window.addEventListener(\"pagehide\", stop);\n\n let cancelled = false;\n let dispose: (() => void) | undefined;\n\n if (isCursorActive) {\n dispose = react(\"broadcast presence\", () => {\n const presence = presenceDerivation.get();\n // rAF throttles broadcasts to frame rate.\n requestAnimationFrame(() => {\n if (cancelled) return;\n // Stamp activity so becoming active again shows the cursor without\n // waiting for a pointer move to refresh the store's stale timestamp.\n update(\n \"presence\",\n presence ? { ...presence, lastActivityTimestamp: Date.now() } : null\n );\n });\n });\n } else {\n // Keep the record but clear the cursor when blurred or pointer leaves\n const presence = presenceDerivation.get();\n update(\"presence\", presence ? { ...presence, cursor: null } : null);\n }\n\n return () => {\n // Invalidate pending rAF broadcasts so stale updates don't overwrite deactivated cursors.\n cancelled = true;\n dispose?.();\n window.removeEventListener(\"pagehide\", stop);\n };\n }, [innerStore, userId, name, color, update, stop, isCursorActive]);\n}\n\n// The local cursor is active only when the window is focused and the pointer is over this tool.\nfunction useIsCursorActive(element: HTMLElement) {\n const [isFocused, setIsFocused] = useState(() => document.hasFocus());\n const [isPointerOver, setIsPointerOver] = useState(() =>\n element.matches(\":hover\")\n );\n\n useEffect(() => {\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n const onEnter = () => setIsPointerOver(true);\n const onLeave = () => setIsPointerOver(false);\n window.addEventListener(\"focus\", onFocus);\n window.addEventListener(\"blur\", onBlur);\n element.addEventListener(\"mouseenter\", onEnter);\n element.addEventListener(\"mouseleave\", onLeave);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n window.removeEventListener(\"blur\", onBlur);\n element.removeEventListener(\"mouseenter\", onEnter);\n element.removeEventListener(\"mouseleave\", onLeave);\n };\n }, [element]);\n\n return isFocused && isPointerOver;\n}\n", "type Status = \"pending\" | \"success\" | \"error\"\n\nexport type PromiseWrapper<T> = {\n promise: Promise<T>\n read(): T\n}\n\nexport function wrapPromise<T>(promise: Promise<T>): PromiseWrapper<T> {\n let status: Status = \"pending\"\n let result: T\n let error: Error\n\n const suspender = promise.then(\n data => {\n status = \"success\"\n result = data\n },\n err => {\n status = \"error\"\n error = err\n }\n )\n\n return {\n promise,\n read(): T {\n switch (status) {\n case \"pending\":\n throw suspender\n case \"error\":\n throw error\n case \"success\":\n return result\n }\n },\n }\n}\n", "import { Repo } from \"@automerge/automerge-repo/slim\"\nimport { createContext, useContext } from \"react\"\n\n/** A [React context](https://react.dev/learn/passing-data-deeply-with-context) which provides access to an Automerge repo. */\nexport const RepoContext = createContext<Repo | null>(null)\n\n/** A [React hook](https://reactjs.org/docs/hooks-intro.html) which returns the Automerge repo from {@link RepoContext}. */\nexport function useRepo(): Repo {\n const repo = useContext(RepoContext)\n if (!repo) throw new Error(\"Repo was not found on RepoContext.\")\n return repo\n}\n", "export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\n", "import REGEX from './regex.js';\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\nexport default validate;\n", "import validate from './validate.js';\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff);\n}\nexport default parse;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map", "// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n", "import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n", "'use strict';\nimport base58 from 'bs58';\nexport default function (checksumFn) {\n // Encode a buffer as a base58-check encoded string\n function encode(payload) {\n var payloadU8 = Uint8Array.from(payload);\n var checksum = checksumFn(payloadU8);\n var length = payloadU8.length + 4;\n var both = new Uint8Array(length);\n both.set(payloadU8, 0);\n both.set(checksum.subarray(0, 4), payloadU8.length);\n return base58.encode(both);\n }\n function decodeRaw(buffer) {\n var payload = buffer.slice(0, -4);\n var checksum = buffer.slice(-4);\n var newChecksum = checksumFn(payload);\n // eslint-disable-next-line\n if (checksum[0] ^ newChecksum[0] |\n checksum[1] ^ newChecksum[1] |\n checksum[2] ^ newChecksum[2] |\n checksum[3] ^ newChecksum[3])\n return;\n return payload;\n }\n // Decode a base58-check encoded string to a buffer, no result if checksum is wrong\n function decodeUnsafe(str) {\n var buffer = base58.decodeUnsafe(str);\n if (buffer == null)\n return;\n return decodeRaw(buffer);\n }\n function decode(str) {\n var buffer = base58.decode(str);\n var payload = decodeRaw(buffer);\n if (payload == null)\n throw new Error('Invalid checksum');\n return payload;\n }\n return {\n encode: encode,\n decode: decode,\n decodeUnsafe: decodeUnsafe\n };\n}\n", "'use strict';\nimport { sha256 } from '@noble/hashes/sha256';\nimport bs58checkBase from './base.js';\n// SHA256(SHA256(buffer))\nfunction sha256x2(buffer) {\n return sha256(sha256(buffer));\n}\nexport default bs58checkBase(sha256x2);\n", "export const uint8ArrayFromHexString = (hexString) => {\n if (hexString.length % 2 !== 0) {\n throw new Error(\"Hex string must have an even length\");\n }\n const bytes = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n bytes[i >> 1] = parseInt(hexString.slice(i, i + 2), 16);\n }\n return bytes;\n};\nexport const uint8ArrayToHexString = (data) => {\n return Array.from(data, byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n};\n//# sourceMappingURL=bufferFromHex.js.map", "/**\n * Symbol used as discriminator for segments to avoid collision with user data.\n * Users might have objects with a 'kind' property in id patterns.\n */\nexport const KIND = \"AUTOMERGE_REF_KIND\";\n/**\n * Symbol to mark a cursor request for stabilization during sub-handle creation.\n */\nexport const CURSOR_MARKER = \"AUTOMERGE_REF_CURSOR_MARKER\";\n//# sourceMappingURL=types.js.map", "import { KIND } from \"./types.js\";\n/**\n * # Path Segment Encoding Scheme\n *\n * | Type | Format | Example | Notes |\n * |---------|---------------------|----------------------------|---------------------------------|\n * | Key | string | `foo`, `my%2Fkey` | Default, URL-encoded |\n * | Index | `@` + number | `@0`, `@42` | Array index |\n * | Match | `{...}` | `{\"id\":\"alice\"}` | JSON object pattern (URL-encoded) |\n * | Cursors | `[start-end]` | `[2@abc-5@def]` | Cursor range |\n * | Cursors | `[cursor]` | `[2@abc]` | Collapsed (start === end) |\n *\n * ## Escape Rule\n * If a key starts with `@`, `{`, `[`, or `\\`, prefix with `\\` (URL-encoded as `%5C`):\n * - `\\@at` → key \"@at\" (appears as `%5C%40at` in URL)\n * - `\\{brace` → key \"{brace\" (appears as `%5C%7Bbrace` in URL)\n * - `\\\\backslash` → key \"\\backslash\" (appears as `%5C%5Cbackslash` in URL)\n *\n * ## Parsing Priority (first match wins)\n * 1. Index: `@` + digits\n * 2. Match: `{...}` or URL-encoded `%7B...`\n * 3. Cursors: `[...]`\n * 4. Key: `\\...` (escaped, URL-encoded as `%5C...`) or anything else\n */\n/** The escape character (backslash) */\nconst ESCAPE_CHAR = \"\\\\\";\n/** URL-encoded form of the escape character for matching in URLs */\nconst ESCAPE_PREFIX = \"%5C\";\nconst INDEX_PREFIX = \"@\";\nconst CURSOR_OPEN = \"[\";\nconst CURSOR_CLOSE = \"]\";\nconst CURSOR_SEPARATOR = \"-\";\n/** Characters that trigger escaping when at the start of a key */\nconst ESCAPE_TRIGGERS = [ESCAPE_CHAR, INDEX_PREFIX, \"{\", CURSOR_OPEN];\nconst INDEX_PATTERN = /^@(\\d+)$/;\nconst indexCodec = {\n kind: \"index\",\n match: s => INDEX_PATTERN.test(s),\n parse: s => {\n const m = s.match(INDEX_PATTERN);\n if (!m)\n throw new Error(`Invalid index: ${s}`);\n return { [KIND]: \"index\", index: parseInt(m[1], 10) };\n },\n serialize: seg => `${INDEX_PREFIX}${seg.index}`,\n};\nconst matchCodec = {\n kind: \"match\",\n // Match both raw JSON and URL-encoded JSON\n match: s => s.startsWith(\"{\") || s.startsWith(\"%7B\"),\n parse: s => {\n try {\n // Decode URL encoding first, then parse JSON\n // This handles both URL-encoded and raw JSON formats\n const decoded = decodeURIComponent(s);\n const parsed = JSON.parse(decoded);\n if (typeof parsed !== \"object\" ||\n parsed === null ||\n Array.isArray(parsed)) {\n throw new Error(\"Match pattern must be a plain object\");\n }\n return { [KIND]: \"match\", match: parsed };\n }\n catch (e) {\n throw new Error(`Invalid match pattern: ${s}. ${e instanceof Error ? e.message : \"\"}`);\n }\n },\n // Serialize with sorted keys so `{a:1,b:2}` and `{b:2,a:1}` produce\n // identical URLs (they're semantically the same pattern). Also URL-\n // encode the JSON to protect `/` and other path-significant chars.\n serialize: seg => encodeURIComponent(JSON.stringify(Object.fromEntries(Object.keys(seg.match)\n .sort()\n .map(k => [k, seg.match[k]])))),\n};\nconst cursorsCodec = {\n kind: \"cursors\",\n match: s => s.startsWith(CURSOR_OPEN) && s.endsWith(CURSOR_CLOSE),\n parse: s => {\n const inner = s.slice(1, -1);\n if (!inner) {\n throw new Error(\"Invalid cursor range: empty brackets\");\n }\n const sepIndex = inner.indexOf(CURSOR_SEPARATOR);\n if (sepIndex === -1) {\n const cursor = inner;\n return { [KIND]: \"cursors\", start: cursor, end: cursor };\n }\n const start = inner.slice(0, sepIndex);\n const end = inner.slice(sepIndex + 1);\n if (!start || !end) {\n throw new Error(`Invalid cursor range: ${s}. Expected format: [cursor] or [start-end]`);\n }\n return { [KIND]: \"cursors\", start, end };\n },\n serialize: seg => {\n if (seg.start === seg.end) {\n return `${CURSOR_OPEN}${seg.start}${CURSOR_CLOSE}`;\n }\n return `${CURSOR_OPEN}${seg.start}${CURSOR_SEPARATOR}${seg.end}${CURSOR_CLOSE}`;\n },\n};\nconst keyCodec = {\n kind: \"key\",\n match: s => {\n // Escaped keys start with backslash (URL-encoded as %5C)\n if (s.startsWith(ESCAPE_PREFIX) || s.startsWith(ESCAPE_CHAR)) {\n return true;\n }\n // Regular keys don't start with special prefixes\n // We need to check both raw and URL-decoded forms\n const decoded = safeDecodeURIComponent(s);\n return !ESCAPE_TRIGGERS.some(p => s.startsWith(p) || decoded.startsWith(p));\n },\n parse: s => {\n // Check for URL-encoded escape prefix (%5C) or literal backslash\n if (s.startsWith(ESCAPE_PREFIX)) {\n return {\n [KIND]: \"key\",\n key: decodeURIComponent(s.slice(ESCAPE_PREFIX.length)),\n };\n }\n if (s.startsWith(ESCAPE_CHAR)) {\n return {\n [KIND]: \"key\",\n key: decodeURIComponent(s.slice(ESCAPE_CHAR.length)),\n };\n }\n return { [KIND]: \"key\", key: decodeURIComponent(s) };\n },\n serialize: seg => {\n // Empty keys don't round-trip through a slash-delimited URL path.\n if (seg.key === \"\") {\n throw new Error(\"Path keys cannot be empty strings\");\n }\n // Check if key starts with any character that needs escaping\n const needsEscape = ESCAPE_TRIGGERS.some(p => seg.key.startsWith(p));\n const encoded = encodeURIComponent(seg.key);\n // Prefix with URL-encoded backslash (%5C) if escape needed\n return needsEscape ? `${ESCAPE_PREFIX}${encoded}` : encoded;\n },\n};\n/** Safely decode URI component, returning original string on error */\nfunction safeDecodeURIComponent(s) {\n try {\n return decodeURIComponent(s);\n }\n catch {\n return s;\n }\n}\n/**\n * Codecs in priority order. First matching codec wins for parsing.\n * Order: index → match → cursors → key (key is catch-all, must be last)\n */\nconst SEGMENT_CODECS = [indexCodec, matchCodec, cursorsCodec, keyCodec];\nexport function parseSegment(segment) {\n for (const codec of SEGMENT_CODECS) {\n if (codec.match(segment)) {\n return codec.parse(segment);\n }\n }\n throw new Error(`Invalid segment: \"${segment}\"`);\n}\n// ⇧ Parse --- Serialize ⇩\nexport function serializeSegment(segment) {\n for (const codec of SEGMENT_CODECS) {\n if (segment[KIND] === codec.kind) {\n return codec.serialize(segment);\n }\n }\n throw new Error(`No codec found for segment kind: ${segment[KIND]}`);\n}\nexport function parsePath(path) {\n if (!path)\n return [];\n const trimmed = path.replace(/^\\/+|\\/+$/g, \"\");\n if (!trimmed) {\n throw new Error(\"Invalid path: path cannot be empty or consist only of slashes\");\n }\n if (trimmed.includes(\"//\")) {\n throw new Error(\"Invalid path: contains empty segment (double slash)\");\n }\n return trimmed.split(\"/\").map(parseSegment);\n}\n// ⇧ Parse --- Serialize ⇩\nexport function serializePath(segments) {\n return segments.map(serializeSegment).join(\"/\");\n}\n//# sourceMappingURL=parser.js.map", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "import debug from \"debug\";\n// `.debug` is routed through the `debug` package for namespace-based filtering\n// via `DEBUG=automerge-repo:*`; the rest go straight to `console`.\nconst defaultFactory = namespace => {\n const trace = debug(namespace);\n const prefix = `[${namespace}]`;\n return {\n debug: (message, ...args) => trace(message, ...args),\n info: (message, ...args) => console.info(prefix, message, ...args),\n warn: (message, ...args) => console.warn(prefix, message, ...args),\n error: (message, ...args) => console.error(prefix, message, ...args),\n };\n};\nlet factory = defaultFactory;\n/**\n * Replace the global logger factory. All subsequent {@link makeLogger} calls use it.\n *\n * Call once at startup to route automerge-repo output through your own logger.\n * The factory receives a namespace such as `automerge-repo:repo` or\n * `automerge-repo:docsync:abc12` for each subsystem instance.\n *\n * @example\n * ```ts\n * import { setLoggerFactory } from \"@automerge/automerge-repo\"\n * import winston from \"winston\"\n *\n * const logger = winston.createLogger({ ... })\n *\n * setLoggerFactory(namespace => ({\n * debug: (msg, ...args) => logger.debug(msg, { namespace, args }),\n * info: (msg, ...args) => logger.info(msg, { namespace, args }),\n * warn: (msg, ...args) => logger.warn(msg, { namespace, args }),\n * error: (msg, ...args) => logger.error(msg, { namespace, args }),\n * }))\n * ```\n */\nexport function setLoggerFactory(f) {\n factory = f;\n}\n/** Restore the built-in logger factory (mainly for tests). */\nexport function resetLoggerFactory() {\n factory = defaultFactory;\n}\n/**\n * Returns a {@link Logger} for `namespace` that delegates to whichever factory\n * is current at the time each method is called. The factory is consulted on\n * every call so that consumers can replace it (via {@link setLoggerFactory})\n * after the library's modules have already been imported.\n */\nexport function makeLogger(namespace) {\n return {\n debug: (message, ...args) => factory(namespace).debug(message, ...args),\n info: (message, ...args) => factory(namespace).info(message, ...args),\n warn: (message, ...args) => factory(namespace).warn(message, ...args),\n error: (message, ...args) => factory(namespace).error(message, ...args),\n };\n}\n//# sourceMappingURL=Logger.js.map", "import * as Uuid from \"uuid\";\nimport bs58check from \"bs58check\";\nimport { uint8ArrayFromHexString, uint8ArrayToHexString, } from \"./helpers/bufferFromHex.js\";\nimport { parsePath, serializePath } from \"./subdoc-handles/parser.js\";\nimport { makeLogger } from \"./Logger.js\";\nconst log = makeLogger(\"automerge-repo:url\");\nexport const urlPrefix = \"automerge:\";\n/**\n * Parse an Automerge URL.\n *\n * Supported shapes:\n * - `automerge:<docId>`\n * - `automerge:<docId>#<heads>` (heads `|`-joined)\n * - `automerge:<docId>/<path>` (path `/`-joined segments)\n * - `automerge:<docId>/<path>#<heads>`\n *\n * `segments` is undefined when no path is present; otherwise it's the\n * parsed `Segment[]`.\n */\nexport const parseAutomergeUrl = (url) => {\n const [baseUrl, headsSection, ...rest] = url.split(\"#\");\n if (rest.length > 0) {\n throw new Error(\"Invalid URL: contains multiple heads sections\");\n }\n const match = baseUrl.match(new RegExp(`^${urlPrefix}([^/]+)(?:\\\\/(.*))?$`));\n if (!match)\n throw new Error(\"Invalid document URL: \" + url);\n const [, docMatch, pathStr] = match;\n const documentId = docMatch;\n const binaryDocumentId = documentIdToBinary(documentId);\n if (!binaryDocumentId)\n throw new Error(\"Invalid document URL: \" + url);\n const segments = pathStr !== undefined && pathStr.length > 0 ? parsePath(pathStr) : undefined;\n if (headsSection === undefined) {\n return segments\n ? { binaryDocumentId, documentId, segments }\n : { binaryDocumentId, documentId };\n }\n const heads = (headsSection === \"\" ? [] : headsSection.split(\"|\"));\n const hexHeads = heads.map(head => {\n try {\n return uint8ArrayToHexString(bs58check.decode(head));\n }\n catch (e) {\n throw new Error(`Invalid head in URL: ${head}`);\n }\n });\n return segments\n ? { binaryDocumentId, hexHeads, documentId, heads, segments }\n : { binaryDocumentId, hexHeads, documentId, heads };\n};\n/**\n * Given a documentId in either binary or base58check-encoded form, returns\n * an Automerge URL. Optionally accepts `segments` to construct a sub-tree\n * URL (`automerge:<docId>/seg/seg/...`) and `heads` to pin the URL to a\n * point in time. Throws on invalid input.\n */\nexport const stringifyAutomergeUrl = (arg) => {\n if (arg instanceof Uint8Array || typeof arg === \"string\") {\n return (urlPrefix +\n (arg instanceof Uint8Array\n ? binaryToDocumentId(arg)\n : arg));\n }\n const { documentId, heads = undefined, segments = undefined } = arg;\n if (documentId === undefined)\n throw new Error(\"Invalid documentId: \" + documentId);\n const encodedDocumentId = documentId instanceof Uint8Array\n ? binaryToDocumentId(documentId)\n : documentId;\n let url = `${urlPrefix}${encodedDocumentId}`;\n if (segments !== undefined && segments.length > 0) {\n url += \"/\" + serializePath(segments);\n }\n if (heads !== undefined) {\n heads.forEach(head => {\n try {\n bs58check.decode(head);\n }\n catch (e) {\n throw new Error(`Invalid head: ${head}`);\n }\n });\n // Sort so two heads arrays with the same content in different\n // orders produce identical URLs.\n url += \"#\" + [...heads].sort().join(\"|\");\n }\n return url;\n};\n/** Helper to extract just the heads from a URL if they exist */\nexport const getHeadsFromUrl = (url) => {\n const { heads } = parseAutomergeUrl(url);\n return heads;\n};\nexport const anyDocumentIdToAutomergeUrl = (id) => isValidAutomergeUrl(id)\n ? id\n : isValidDocumentId(id)\n ? stringifyAutomergeUrl({ documentId: id })\n : isValidUuid(id)\n ? parseLegacyUUID(id)\n : undefined;\n/**\n * Given a string, returns true if it is a valid Automerge URL. This function also acts as a type\n * discriminator in Typescript.\n */\nexport const isValidAutomergeUrl = (str) => {\n if (typeof str !== \"string\" || !str || !str.startsWith(urlPrefix))\n return false;\n try {\n const { documentId, heads } = parseAutomergeUrl(str);\n if (!isValidDocumentId(documentId))\n return false;\n if (heads &&\n !heads.every(head => {\n try {\n bs58check.decode(head);\n return true;\n }\n catch {\n return false;\n }\n }))\n return false;\n return true;\n }\n catch {\n return false;\n }\n};\nexport const isValidDocumentId = (str) => {\n if (typeof str !== \"string\")\n return false;\n // try to decode from base58\n const binaryDocumentID = documentIdToBinary(str);\n return binaryDocumentID !== undefined;\n};\nexport const isValidUuid = (str) => typeof str === \"string\" && Uuid.validate(str);\n/**\n * Returns a new Automerge URL with a random UUID documentId. Called by Repo.create(), and also used by tests.\n */\nexport const generateAutomergeUrl = () => {\n const documentId = Uuid.v4(undefined, new Uint8Array(16));\n return stringifyAutomergeUrl({ documentId });\n};\nexport const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId);\nexport const binaryToDocumentId = (docId) => bs58check.encode(docId);\nexport const encodeHeads = (heads) => heads.map(h => bs58check.encode(uint8ArrayFromHexString(h)));\nexport const decodeHeads = (heads) => heads.map(h => uint8ArrayToHexString(bs58check.decode(h)));\nexport const parseLegacyUUID = (str) => {\n if (!Uuid.validate(str))\n return undefined;\n const documentId = Uuid.parse(str);\n return stringifyAutomergeUrl({ documentId });\n};\n/**\n * Given any valid expression of a document ID, returns a DocumentId in base58check-encoded form.\n *\n * Currently supports:\n * - base58check-encoded DocumentId\n * - Automerge URL\n * - legacy UUID\n * - binary DocumentId\n *\n * Throws on invalid input.\n */\nexport const interpretAsDocumentId = (id) => {\n // binary\n if (id instanceof Uint8Array)\n return binaryToDocumentId(id);\n // url\n if (isValidAutomergeUrl(id))\n return parseAutomergeUrl(id).documentId;\n // base58check\n if (isValidDocumentId(id))\n return id;\n // legacy UUID\n if (isValidUuid(id)) {\n log.warn(\"Future versions will not support UUIDs as document IDs; use Automerge URLs instead.\");\n const binaryDocumentID = Uuid.parse(id);\n return binaryToDocumentId(binaryDocumentID);\n }\n // none of the above\n throw new Error(`Invalid AutomergeUrl: '${id}'`);\n};\n//# sourceMappingURL=AutomergeUrl.js.map", "import { AnyDocumentId, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { useRepo } from \"./useRepo.js\"\nimport { useEffect, useRef, useState } from \"react\"\nimport { anyDocumentIdToAutomergeUrl } from \"../../automerge-repo/dist/AutomergeUrl.js\"\n\n// Shared with useDocHandles\nexport const wrapperCache = new Map<\n AnyDocumentId,\n PromiseWrapper<DocHandle<any>>\n>()\n// NB: this is a global cache that isn't keyed on the Repo\n// so if your app uses the same documents in two Repos\n// this could cause problems. please let me know if you do.\n\nexport interface UseDocHandleSuspendingParams {\n suspense: true\n}\nexport interface UseDocHandleSynchronousParams {\n suspense: false\n}\n\ntype UseDocHandleParams =\n | UseDocHandleSuspendingParams\n | UseDocHandleSynchronousParams\n\nexport function useDocHandle<T>(\n id: AnyDocumentId,\n params: UseDocHandleSuspendingParams\n): DocHandle<T>\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocHandleSynchronousParams\n): DocHandle<T> | undefined\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n { suspense }: UseDocHandleParams = { suspense: false }\n): DocHandle<T> | undefined {\n const repo = useRepo()\n const controllerRef = useRef<AbortController | undefined>(undefined)\n const [handle, setHandle] = useState<DocHandle<T> | undefined>()\n\n let currentHandle: DocHandle<T> | undefined =\n // make sure the handle matches the id\n id && handle && handle.url === anyDocumentIdToAutomergeUrl(id)\n ? handle\n : undefined\n\n if (id && !currentHandle) {\n // if we haven't saved a handle yet, check if one is immediately available\n const progress = repo.findWithProgress<T>(id)\n const state = progress.peek()\n if (state.state === \"ready\") {\n currentHandle = state.handle\n }\n }\n\n let wrapper = id ? wrapperCache.get(id) : undefined\n if (!wrapper && id) {\n controllerRef.current?.abort()\n controllerRef.current = new AbortController()\n\n const promise = repo.find<T>(id, { signal: controllerRef.current.signal })\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n }\n\n /* From here we split into two paths: suspense and not.\n * In the suspense path, we return the wrapper directly.\n * In the non-suspense path, we wait for the promise to resolve\n * and then set the handle via setState. Suspense relies on\n * re-running this function until it succeeds, whereas the synchronous\n * form uses a setState to track the value. */\n useEffect(() => {\n if (currentHandle || suspense || !wrapper) {\n return\n }\n // Stays true until this effect run is torn down (unmount or id change); a\n // result that arrives after that must not setState for a stale id.\n let active = true\n wrapper.promise\n .then(handle => {\n if (active) setHandle(handle as DocHandle<T>)\n })\n .catch(() => {\n // Drop the failed wrapper so a later render retries instead of reusing\n // the rejection.\n if (id && wrapperCache.get(id) === wrapper) {\n wrapperCache.delete(id)\n }\n if (active) setHandle(undefined)\n })\n return () => {\n active = false\n }\n }, [currentHandle, suspense, wrapper, id])\n\n if (currentHandle || !suspense || !wrapper) {\n return currentHandle\n }\n\n return wrapper.read() as DocHandle<T>\n}\n", "import { AnyDocumentId } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandle } from \"./useDocHandle.js\"\n\n/**\n * A hook which returns a document and a function to change it.\n * Uses React Suspense for loading states, returning a tuple matching useState pattern.\n *\n * @example\n * ```tsx\n * function Counter() {\n * const [doc, changeDoc] = useDocument<{ count: number }>(docUrl)\n * return (\n * <button onClick={() => changeDoc(d => d.count++)}>\n * Count: {doc.count}\n * </button>\n * )\n * }\n *\n * // Must be wrapped in Suspense boundary\n * <Suspense fallback={<Loading />}>\n * <Counter />\n * </Suspense>\n * ```\n */\n\nexport interface UseDocumentSuspendingParams {\n suspense: true\n}\nexport interface UseDocumentSynchronousParams {\n suspense: false\n}\n\ntype UseDocumentParams =\n | UseDocumentSuspendingParams\n | UseDocumentSynchronousParams\n\nexport type UseDocumentReturn<T> = [\n Doc<T>,\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => void,\n]\n\nexport function useDocument<T>(\n id: AnyDocumentId,\n params: UseDocumentSuspendingParams\n): UseDocumentReturn<T>\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocumentSynchronousParams\n): UseDocumentReturn<T> | [undefined, () => void]\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params: UseDocumentParams = { suspense: false }\n): UseDocumentReturn<T> | [undefined, () => void] {\n // @ts-expect-error -- typescript doesn't realize we're discriminating these types the same way in both functions\n const handle = useDocHandle<T>(id, params)\n // Initialize with current doc state\n const [doc, setDoc] = useState<Doc<T> | undefined>(() => handle?.doc())\n const [deleteError, setDeleteError] = useState<Error>()\n\n // Reinitialize doc when handle changes\n useEffect(() => {\n setDoc(handle?.doc())\n }, [handle])\n\n useEffect(() => {\n if (!handle) {\n return\n }\n const onChange = () => setDoc(handle.doc())\n const onDelete = () => {\n setDeleteError(new Error(`Document ${id} was deleted`))\n }\n\n handle.on(\"change\", onChange)\n handle.on(\"delete\", onDelete)\n\n return () => {\n handle.removeListener(\"change\", onChange)\n handle.removeListener(\"delete\", onDelete)\n }\n }, [handle, id])\n\n const changeDoc = useCallback(\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n handle!.change(changeFn, options)\n },\n [handle]\n )\n\n if (deleteError) {\n throw deleteError\n }\n\n if (!doc) {\n return [undefined, () => {}]\n }\n return [doc, changeDoc]\n}\n", "import { useEffect, useState } from \"react\"\n\nexport function useSet<T>(items: T[]): Set<T> {\n const [set, setSet] = useState<Set<T>>(() => {\n return new Set<T>(items)\n })\n useEffect(() => {\n const newSet = new Set(items)\n if (identical(set, newSet)) {\n return\n }\n setSet(newSet)\n }, [set, items])\n return set\n}\n\nfunction identical<T>(s1: Set<T>, s2: Set<T>) {\n return s1.size === s2.size && Array.from(s1).every(v => s2.has(v))\n}\n", "import { AutomergeUrl, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { useState, useEffect } from \"react\"\nimport { useRepo } from \"./useRepo.js\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { wrapperCache } from \"./useDocHandle.js\"\nimport { useSet } from \"./helpers/useSet.js\"\n\nexport interface UseDocHandlesParams {\n suspense?: boolean\n}\n\nexport type DocHandleMap<T> = Map<AutomergeUrl, DocHandle<T> | undefined>\n\nexport function useDocHandles<T>(\n ids: AutomergeUrl[],\n { suspense = false }: UseDocHandlesParams = {}\n): DocHandleMap<T> {\n const idSet = useSet(ids)\n const repo = useRepo()\n const [handleMap, setHandleMap] = useState<DocHandleMap<T>>(() => {\n const map = new Map()\n\n // Initialize the map with any handles that are ready\n for (const id of idSet.values()) {\n let progress\n try {\n progress = repo.findWithProgress<T>(id)\n } catch (e) {\n continue\n }\n\n const state = progress.peek()\n if (state.state === \"ready\") {\n map.set(id, state.handle)\n }\n }\n\n return map\n })\n\n const pendingPromises: PromiseWrapper<DocHandle<T>>[] = []\n const nextHandleMap = new Map<AutomergeUrl, DocHandle<T> | undefined>()\n\n // Check if we need any new wrappers\n for (const id of idSet.values()) {\n let handle = handleMap.get(id)\n let wrapper = wrapperCache.get(id)\n if (!wrapper) {\n try {\n const promise = repo.find<T>(id)\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n } catch (e) {\n continue\n }\n }\n\n // Try to read each wrapper.\n // Update handleMap with any available handles,\n // and collect any pending promises\n try {\n handle ??= wrapper.read() as DocHandle<T>\n nextHandleMap.set(id, handle)\n } catch (e) {\n if (e instanceof Promise) {\n pendingPromises.push(wrapper as PromiseWrapper<DocHandle<T>>)\n } else {\n nextHandleMap.set(id, undefined)\n }\n }\n }\n\n // Suspense is handled quasi-synchronously below by throwing if we still have\n // unresolved promises.\n useEffect(() => {\n // Stays true until this effect run is torn down; if idSet changes (or we\n // unmount) before these finds settle, the now-stale map must not overwrite\n // a newer one.\n let active = true\n if (pendingPromises.length > 0) {\n void Promise.allSettled(pendingPromises.map(p => p.promise)).then(\n handles => {\n if (!active) return\n handles.forEach(r => {\n if (r.status === \"fulfilled\") {\n const h = r.value as DocHandle<T>\n nextHandleMap.set(h.url, h)\n }\n })\n setHandleMap(nextHandleMap)\n }\n )\n } else {\n setHandleMap(nextHandleMap)\n }\n return () => {\n active = false\n }\n }, [suspense, idSet])\n\n // If any promises are pending, suspend with Promise.all\n // Note that this behaviour is different from the synchronous\n // form where we get gradual load-in of child documents.\n // I couldn't find an obvious way of incremental loading with\n // a single hook for suspense.\n // (But maybe with suspense this hook is less useful?)\n if (suspense && pendingPromises.length > 0) {\n throw Promise.all(pendingPromises.map(p => p.promise))\n }\n\n return handleMap\n}\n", "import { AutomergeUrl } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandles } from \"./useDocHandles.js\"\n\nexport type DocMap<T> = Map<AutomergeUrl, Doc<T>>\nexport type ChangeDocFn<T> = (\n id: AutomergeUrl,\n changeFn: ChangeFn<T>,\n options?: ChangeOptions<T>\n) => void\n\nexport interface UseDocumentsOptions {\n suspense?: boolean\n}\n\nexport function useDocuments<T>(\n ids: AutomergeUrl[],\n { suspense = true }: UseDocumentsOptions = {}\n): [DocMap<T>, ChangeDocFn<T>] {\n const handleMap = useDocHandles<T>(ids, { suspense })\n const [docMap, setDocMap] = useState<DocMap<T>>(() => {\n const docs: DocMap<T> = new Map()\n handleMap.forEach(handle => {\n const url = handle?.url\n if (url) {\n docs.set(url, handle?.doc() as Doc<T>)\n }\n })\n return docs\n })\n\n useEffect(() => {\n const listeners = new Map<AutomergeUrl, () => void>()\n\n handleMap.forEach((handle, id) => {\n if (handle) {\n const onChange = () => {\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc() as Doc<T>)\n return next\n })\n }\n\n // Initial state\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc() as Doc<T>)\n return next\n })\n\n handle.on(\"change\", onChange)\n listeners.set(id, onChange)\n }\n })\n\n // Clear docs that are no longer in handleMap\n setDocMap(prev => {\n const next = new Map(prev)\n for (const [id] of next) {\n if (!handleMap.has(id)) {\n next.delete(id)\n }\n }\n return next\n })\n\n return () => {\n handleMap.forEach((handle, id) => {\n const listener = listeners.get(id)\n if (handle && listener) {\n handle.removeListener(\"change\", listener)\n }\n })\n }\n }, [handleMap])\n\n const changeDoc = useCallback(\n (id: AutomergeUrl, changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n const handle = handleMap.get(id)\n if (handle) {\n handle.change(changeFn, options)\n }\n },\n [handleMap]\n )\n\n return [docMap, changeDoc]\n}\n", "import {\n type Dispatch,\n type MutableRefObject,\n type SetStateAction,\n useCallback,\n useRef,\n useState,\n} from \"react\"\n\n/**\n * Like `useState`, but also returns a ref whose `.current` is updated\n * synchronously inside the setter — so callbacks can read the latest value\n * without waiting for a re-render.\n *\n * @privateRemarks\n * Not idiomatic — a stale-closure workaround, inlined (ESM) to replace the\n * CommonJS `react-usestateref` dependency, which does not bundle cleanly for\n * ESM/browser consumers. Used only by the two `@deprecated` awareness hooks\n * (`useLocalAwareness`/`useRemoteAwareness`); the replacement `usePresence` hook\n * does not use it. Prefer eliminating it: rewrite those hooks to use functional\n * state updaters for read-modify-write updates, and a plain ref synced in an\n * effect (or `useEffectEvent`) for reads inside long-lived callbacks — then\n * delete this helper.\n */\nexport function useStateRef<S>(\n initialState: S | (() => S)\n): [S, Dispatch<SetStateAction<S>>, MutableRefObject<S>] {\n const [state, setState] = useState(initialState)\n const ref = useRef(state)\n const dispatch = useCallback<Dispatch<SetStateAction<S>>>(setStateAction => {\n ref.current =\n typeof setStateAction === \"function\"\n ? (setStateAction as (prev: S) => S)(ref.current)\n : setStateAction\n setState(ref.current)\n }, [])\n return [state, dispatch, ref]\n}\n\nexport default useStateRef\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "import {\n DocHandle,\n DocHandleEphemeralMessagePayload,\n} from \"@automerge/automerge-repo/slim\"\nimport { useEffect } from \"react\"\nimport useStateRef from \"./useStateRef.js\"\nimport { EventEmitter } from \"eventemitter3\"\n\n// Emits new_peer event when a new peer is seen\nexport const peerEvents = new EventEmitter()\n\nexport interface UseRemoteAwarenessProps<T> {\n /** The handle to receive ephemeral state on */\n handle?: DocHandle<T>\n /** Our user ID */\n localUserId?: string\n /** How long to wait (in ms) before marking a peer as offline */\n offlineTimeout?: number\n /** Function to provide current epoch time */\n getTime?: () => number\n}\n\n/** A map from peer ID to their state */\nexport type PeerStates = Record<string, any>\n/** A map from peer ID to their last heartbeat timestamp */\nexport type Heartbeats = Record<string, number>\n\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook returns read-only state for remote clients.\n * It also returns their heartbeat status.\n * It is intended to be used alongside useLocalAwareness.\n *\n * @returns [ peerStates: { [userId]: state, ... }, { [userId]: heartbeatEpochTime, ...} ]\n */\nexport const useRemoteAwareness = <T>({\n handle,\n localUserId,\n offlineTimeout = 30000,\n getTime = () => new Date().getTime(),\n}: UseRemoteAwarenessProps<T>): [PeerStates, Heartbeats] => {\n // TODO: You should be able to use multiple instances of this hook on the same handle (write test)\n // TODO: This should support some kind of caching or memoization when switching between channelIDs\n const [peerStates, setPeerStates, peerStatesRef] = useStateRef<PeerStates>({})\n const [heartbeats, setHeartbeats, heartbeatsRef] = useStateRef<Heartbeats>({})\n useEffect(() => {\n if (!handle) {\n return\n }\n\n // Receive incoming message\n const handleIncomingUpdate = (\n event: DocHandleEphemeralMessagePayload<T>\n ) => {\n const [userId, state] = event.message as [string, unknown]\n if (userId === localUserId) return\n if (!heartbeatsRef.current[userId]) peerEvents.emit(\"new_peer\", event) // Let useLocalAwareness know we've seen a new peer\n setPeerStates({\n ...peerStatesRef.current,\n [userId]: state,\n })\n setHeartbeats({\n ...heartbeatsRef.current,\n [userId]: getTime(),\n })\n }\n // Remove peers we haven't seen recently\n const pruneOfflinePeers = () => {\n const peerStates = { ...peerStatesRef.current }\n const heartbeats = { ...heartbeatsRef.current }\n const time = getTime()\n let hasChanges = false\n for (const key in heartbeats) {\n if (time - heartbeats[key] > offlineTimeout) {\n delete peerStates[key]\n delete heartbeats[key]\n hasChanges = true\n }\n }\n if (hasChanges) {\n setPeerStates(peerStates)\n setHeartbeats(heartbeats)\n }\n }\n handle.on(\"ephemeral-message\", handleIncomingUpdate)\n // Check for offline peers every `offlineTimeout` ms\n const pruneOfflinePeersIntervalId = setInterval(\n pruneOfflinePeers,\n offlineTimeout\n )\n return () => {\n handle.removeListener(\"ephemeral-message\", handleIncomingUpdate)\n clearInterval(pruneOfflinePeersIntervalId)\n }\n }, [handle, localUserId, offlineTimeout, getTime])\n\n return [peerStates, heartbeats]\n}\n", "import { useEffect } from \"react\"\nimport useStateRef from \"./useStateRef.js\"\nimport { peerEvents } from \"./useRemoteAwareness.js\"\nimport { DocHandle } from \"@automerge/automerge-repo/slim\"\n\nexport interface UseLocalAwarenessProps {\n /** The document handle to send ephemeral state on */\n handle?: DocHandle<unknown>\n /** Our user ID **/\n userId: string\n /** The initial state object/primitive we should advertise */\n initialState: any\n /** How frequently to send heartbeats */\n heartbeatTime?: number\n}\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook maintains state for the local client.\n * Like React.useState, it returns a [state, setState] array.\n * It is intended to be used alongside useRemoteAwareness.\n *\n * When state is changed it is broadcast to all clients.\n * It also broadcasts a heartbeat to let other clients know it is online.\n *\n * Note that userIds aren't secure (yet). Any client can lie about theirs.\n *\n * @returns [state, setState]\n */\nexport const useLocalAwareness = ({\n handle,\n userId,\n initialState,\n heartbeatTime = 15000,\n}: UseLocalAwarenessProps) => {\n const [localState, setLocalState, localStateRef] = useStateRef(initialState)\n\n const setState = (stateOrUpdater: any) => {\n const state =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(localStateRef.current)\n : stateOrUpdater\n setLocalState(state)\n // TODO: Send deltas instead of entire state\n if (handle) {\n handle.broadcast([userId, state])\n }\n }\n\n useEffect(() => {\n // Don't broadcast if userId or handle isn't set: this avoids bogus broadcasts\n // during the loading of a userId document or handle.\n if (!userId || !handle) {\n return\n }\n\n // Send periodic heartbeats\n const heartbeat = () =>\n void handle.broadcast([userId, localStateRef.current])\n heartbeat() // Initial heartbeat\n // TODO: we don't need to send a heartbeat if we've changed state recently; use recursive setTimeout instead of setInterval\n const heartbeatIntervalId = setInterval(heartbeat, heartbeatTime)\n return () => void clearInterval(heartbeatIntervalId)\n }, [handle, userId, heartbeatTime])\n\n useEffect(() => {\n // Send entire state to new peers\n if (!handle || !userId) {\n return\n }\n\n let broadcastTimeoutId: ReturnType<typeof setTimeout>\n const newPeerEvents = peerEvents.on(\"new_peer\", () => {\n broadcastTimeoutId = setTimeout(\n () => handle.broadcast([userId, localStateRef.current]),\n 500 // Wait for the peer to be ready\n )\n })\n return () => {\n newPeerEvents.off(\"new_peer\")\n broadcastTimeoutId && clearTimeout(broadcastTimeoutId)\n }\n }, [handle, userId, peerEvents])\n\n // TODO: Send an \"offline\" message on unmount\n // useEffect(\n // () => () => void handle.broadcast(null), // Same as Yjs awareness\n // []\n // );\n\n return [localState, setState]\n}\n", "import { useCallback, useEffect, useRef, useState } from \"react\"\n\nimport {\n Presence,\n PresenceConfig,\n DocHandle,\n PeerStateView,\n PresenceState,\n} from \"@automerge/automerge-repo/slim\"\n\nexport type UsePresenceConfig<State extends PresenceState> =\n PresenceConfig<State> & {\n handle: DocHandle<unknown>\n }\n\nexport type UsePresenceResult<State extends PresenceState> = {\n /**\n * Presence view of our peers.\n */\n peerStates: PeerStateView<State>\n /**\n * Our own presence state, as last set by `update` or the initial value.\n */\n localState: State | undefined\n /**\n * Update our presence state for the given channel and broadcast\n * it to our peers.\n *\n * @param channel\n * @param value\n */\n update: <Channel extends keyof State>(\n channel: Channel,\n value: State[Channel]\n ) => void\n /**\n * Resume presence broadcasting and listening to peer presence.\n *\n * Note that this only needs to be called after `stop` has been called:\n * usePresence starts running immediately.\n */\n start: (config?: Partial<PresenceConfig<State>>) => void\n /**\n * Stop broadcasting presence state and listening to peer presence.\n */\n stop: () => void\n}\n\n/**\n * This hook encapsulates ephemeral state communication for a specific doc\n * handle. It tracks caller-provided local state and broadcasts that state to\n * all peers. It sends periodic heartbeats when there are no state updates.\n *\n * It also tracks ephemeral state broadcast by peers and forces a re-render when\n * the state of a peer changes.\n *\n * It cleans up (stops sending heartbeats and processing ephemeral messages)\n * when it unmounts.\n *\n * It is implemented using {@link Presence}.\n *\n * @param config - see {@link UsePresenceConfig}. Note that initialState only\n * determines the initial value. Updates to this param will not trigger a\n * re-render of the hook.\n *\n * @returns see {@link UsePresenceResult}\n */\nexport function usePresence<State extends PresenceState>({\n handle,\n initialState,\n heartbeatMs,\n peerTtlMs,\n}: UsePresenceConfig<State>): UsePresenceResult<State> {\n const [localState, setLocalState] = useState<State>(initialState)\n const [peerStates, setPeerStates] = useState(new PeerStateView<State>({}))\n // Don't re-render based on changes to these: they are not expected to\n // change but may be passed in as object literals\n const firstOpts = useRef({\n heartbeatMs,\n peerTtlMs,\n })\n const firstInitialState = useRef(initialState)\n const [presence] = useState(() => new Presence<State>({ handle }))\n\n useEffect(() => {\n presence.start({\n initialState: firstInitialState.current,\n ...firstOpts.current,\n })\n presence.on(\"heartbeat\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"snapshot\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"update\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"goodbye\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"pruned\", () => setPeerStates(presence.getPeerStates()))\n\n return () => {\n presence.stop()\n }\n }, [presence, firstInitialState, firstOpts])\n\n const start = useCallback(\n (config?: Partial<PresenceConfig<State>>) => {\n // Fall back to the last state if not provided when restarting\n const initialState = config?.initialState ?? presence.getLocalState()\n const opts = {\n ...firstOpts.current,\n ...config,\n initialState,\n }\n presence.start(opts)\n },\n [presence, firstOpts]\n )\n const stop = useCallback(() => {\n presence.stop()\n }, [presence])\n\n const update = useCallback(\n <Channel extends keyof State>(channel: Channel, msg: State[Channel]) => {\n presence.broadcast(channel, msg)\n const updated = presence.getLocalState()\n setLocalState(updated)\n },\n [presence]\n )\n\n return {\n peerStates,\n localState,\n update,\n start,\n stop,\n }\n}\n", "import type { TLRecord, TLStore } from \"@tldraw/tldraw\";\nimport * as Automerge from \"@automerge/automerge/slim\";\n\n/**\n * Sync automerge doc changes into the tldraw store.\n *\n * The patches are only used to find out *which* records changed; the record\n * contents are rebuilt wholesale from the doc. Replaying patch mechanics\n * against store records would require modeling every patch shape automerge\n * can emit (nested `del`, `splice`, `conflict`, ...) and any gap silently\n * diverges the view from the doc until reload. Rebuilding from the doc makes\n * the doc the single source of truth: after every change the store record is\n * exactly what the doc says, regardless of what the patches looked like.\n * tldraw records are small, so the per-record rebuild cost is negligible.\n */\nexport function applyAutomergePatchesToTLStore(\n patches: Automerge.Patch[],\n store: TLStore,\n doc: { store: Record<string, unknown> }\n) {\n const changedIds = new Set<string>();\n for (const patch of patches) {\n if (patch.path[0] === \"store\" && patch.path.length > 1) {\n changedIds.add(`${patch.path[1]}`);\n }\n }\n\n const toRemove: TLRecord[\"id\"][] = [];\n const toPut: TLRecord[] = [];\n for (const id of changedIds) {\n const record = doc.store[id];\n if (record === undefined) {\n toRemove.push(id as TLRecord[\"id\"]);\n } else {\n toPut.push(structuredClone(record) as TLRecord);\n }\n }\n\n store.mergeRemoteChanges(() => {\n if (toRemove.length) store.remove(toRemove);\n if (toPut.length) store.put(toPut);\n });\n}\n", "import { useEffect, useState } from \"react\";\nimport { useDocument, useDocHandle } from \"@automerge/automerge-repo-react-hooks\";\nimport * as Providers from \"@inkandswitch/patchwork-providers\";\n/**\n * Generic reactive request hook. Resolves the first value a provider emits for\n * `selector` (via the one-shot `request` helper) and returns it once it\n * arrives (and whenever `element`/`selector` change). `T` is the response type.\n */\nexport function useRequest(element, selector) {\n const [value, setValue] = useState(undefined);\n const key = JSON.stringify(selector);\n useEffect(() => {\n let canceled = false;\n Providers.request(element, selector).then((v) => {\n if (canceled || v == null)\n return;\n setValue(() => v);\n });\n return () => {\n canceled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, key]);\n return value;\n}\nexport function useSubscribe(element, selector, initialValue) {\n const [value, setValue] = useState(initialValue);\n const key = JSON.stringify(selector);\n useEffect(() => {\n const unsubscribe = Providers.subscribe(element, selector, (v) => {\n setValue(() => v);\n });\n return unsubscribe;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, key]);\n return value;\n}\n/**\n * Handle-specialized subscription hook. Use when the answering provider emits\n * an `AutomergeUrl`. The handle is recovered locally from the global repo, so\n * it stays fully live. Returns `[doc, handle]` matching the shape of\n * `useDocument`; both read `undefined` until the first url arrives. `T` is the\n * doc shape inside the handle.\n */\nexport function useSubscribeDoc(element, selector) {\n const url = useSubscribe(element, selector);\n const [doc] = useDocument(url);\n const handle = useDocHandle(url);\n return [doc, handle];\n}\n", "import * as Automerge from \"@automerge/automerge/slim\";\nimport { isEqual } from \"lodash\";\nimport type { TLRecord, TLShapeId } from \"@tldraw/tldraw\";\nimport type { TLDrawDoc } from \"./datatype.ts\";\n\n// A record-level diff of the tldraw store between a baseline version and the\n// current one. Modelled on how `codemirror-base` diffs text: we view the doc\n// at the baseline heads and compare it against the live doc. The granularity\n// here is whole records (shapes) rather than text spans.\nexport type ShapeDiff = {\n added: Set<TLShapeId>;\n changed: Set<TLShapeId>;\n // Deleted shapes no longer exist in the live store, so we keep a plain\n // clone of the baseline record to re-render it as a ghost.\n deleted: TLRecord[];\n};\n\nconst isShapeId = (id: string): id is TLShapeId => id.startsWith(\"shape:\");\n\n// Compute which shapes were added / changed / deleted between the doc at\n// `headsBefore` and its current state. Only `shape:*` records are considered\n// \u2014 the store also holds `camera:`, `instance:`, `pointer:` and\n// `instance_presence:` records (presence is written live by every peer) which\n// must not show up as diffs.\nexport function diffStore(\n doc: TLDrawDoc,\n headsBefore: Automerge.Heads\n): ShapeDiff {\n const before = Automerge.view<TLDrawDoc>(doc, headsBefore);\n const beforeStore = (before.store ?? {}) as Record<string, TLRecord>;\n const afterStore = (doc.store ?? {}) as Record<string, TLRecord>;\n\n const added = new Set<TLShapeId>();\n const changed = new Set<TLShapeId>();\n const deleted: TLRecord[] = [];\n\n for (const id in afterStore) {\n if (!isShapeId(id)) continue;\n if (!(id in beforeStore)) {\n added.add(id);\n } else if (!isEqual(beforeStore[id], afterStore[id])) {\n changed.add(id);\n }\n }\n\n for (const id in beforeStore) {\n if (!isShapeId(id)) continue;\n if (!(id in afterStore)) {\n // Clone via JSON so the record survives outside the Automerge doc and\n // carries no proxies (matches how the store snapshot is loaded).\n deleted.push(JSON.parse(JSON.stringify(beforeStore[id])) as TLRecord);\n }\n }\n\n return { added, changed, deleted };\n}\n\nexport const hasDiff = (d: ShapeDiff | null | undefined): d is ShapeDiff =>\n !!d && (d.added.size > 0 || d.changed.size > 0 || d.deleted.length > 0);\n", "import { createContext, forwardRef, useContext } from \"react\";\nimport {\n DefaultShapeWrapper,\n useValue,\n type Atom,\n type TLShapeId,\n type TLShapeWrapperProps,\n} from \"@tldraw/tldraw\";\n\nexport type DiffStatus = \"added\" | \"changed\" | \"deleted\";\n\n// Per-tool atom mapping each shape id to its diff status. It lives in a tldraw\n// `atom` (not React state) so the wrapper can read it via `useValue` and only\n// the shapes whose status actually changed re-render. It reaches the wrapper\n// through context because tldraw instantiates `ShapeWrapper` internally \u2014 props\n// can't be passed to it, but context (which flows down from `<Tldraw>`) can.\nexport type DiffStatusAtom = Atom<Map<TLShapeId, DiffStatus>>;\n\nexport const DiffStatusContext = createContext<DiffStatusAtom | null>(null);\n\n// Wraps every shape's DOM and tags it with a `tl-diff-*` class so a CSS\n// `drop-shadow` glow can hug the shape outline (added / changed) or fade it out\n// (deleted ghosts). Re-uses `DefaultShapeWrapper` so all default behaviour is\n// preserved.\nexport const DiffShapeWrapper = forwardRef<HTMLDivElement, TLShapeWrapperProps>(\n function DiffShapeWrapper({ children, shape, isBackground }, ref) {\n const statusAtom = useContext(DiffStatusContext);\n const status = useValue(\n \"diff status\",\n () => statusAtom?.get().get(shape.id),\n [statusAtom, shape.id]\n );\n return (\n <DefaultShapeWrapper\n ref={ref}\n shape={shape}\n isBackground={isBackground}\n className={status ? `tl-diff-${status}` : undefined}\n >\n {children}\n </DefaultShapeWrapper>\n );\n }\n);\n", "import {\n Geometry2d,\n HTMLContainer,\n Rectangle2d,\n ShapeUtil,\n T,\n createShapeId,\n resizeBox,\n useEditor,\n useValue,\n type RecordProps,\n type TLResizeInfo,\n type TLShape,\n type TLShapeId,\n} from \"@tldraw/tldraw\";\nimport { useEffect, useRef } from \"react\";\nimport { getSupportedToolsForType } from \"@inkandswitch/patchwork-plugins\";\nimport type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport { useDocument } from \"@automerge/react\";\nimport { automergeUrlToServiceWorkerUrl } from \"@inkandswitch/patchwork-filesystem\";\n\n// A tldraw shape embedding another Patchwork document via the shared \"embed\"\n// tool (<patchwork-view tool-id=\"embed\">), which draws the chrome and nests\n// the content view. The doc reference lives in the shape props, so it syncs\n// like any other shape.\n\nexport const PATCHWORK_DOC_SHAPE_TYPE = \"patchwork-doc\" as const;\n\ndeclare module \"@tldraw/tldraw\" {\n export interface TLGlobalShapePropsMap {\n [PATCHWORK_DOC_SHAPE_TYPE]: {\n w: number;\n h: number;\n docUrl: string;\n docName: string;\n docType: string;\n toolId: string;\n };\n }\n}\n\nexport type PatchworkDocShape = TLShape<typeof PATCHWORK_DOC_SHAPE_TYPE>;\n\n// Deterministic shape id derived from the doc url, so remote peers that create\n// a shape for the same document converge on a single shape instead of dupes.\nexport function makeShapeId(docUrl: string): TLShapeId {\n return createShapeId(docUrl.replace(/[^a-zA-Z0-9]/g, \"_\"));\n}\n\nexport class PatchworkDocShapeUtil extends ShapeUtil<PatchworkDocShape> {\n static override type = PATCHWORK_DOC_SHAPE_TYPE;\n\n static override props: RecordProps<PatchworkDocShape> = {\n w: T.number,\n h: T.number,\n docUrl: T.string,\n docName: T.string,\n docType: T.string,\n toolId: T.string,\n };\n\n getDefaultProps(): PatchworkDocShape[\"props\"] {\n return {\n w: 640,\n h: 480,\n docUrl: \"\",\n docName: \"Untitled\",\n docType: \"\",\n toolId: \"\",\n };\n }\n\n getGeometry(shape: PatchworkDocShape): Geometry2d {\n return new Rectangle2d({\n width: shape.props.w,\n height: shape.props.h,\n isFilled: true,\n });\n }\n\n override canResize() {\n return true;\n }\n override canEdit() {\n return true;\n }\n override isAspectRatioLocked() {\n return false;\n }\n override hideRotateHandle() {\n return true;\n }\n\n override onResize(shape: PatchworkDocShape, info: TLResizeInfo<PatchworkDocShape>) {\n return resizeBox(shape, info);\n }\n\n component(shape: PatchworkDocShape) {\n return <PatchworkDocComponent shape={shape} />;\n }\n\n indicator(shape: PatchworkDocShape) {\n return <rect width={shape.props.w} height={shape.props.h} />;\n }\n}\n\n// Best default tool for a datatype: prefer a tool that explicitly lists the\n// datatype over a wildcard (\"*\") tool; fall back to the first available.\nexport function getDefaultToolId(datatypeId: string): string {\n if (!datatypeId) return \"\";\n try {\n const tools = getSupportedToolsForType(datatypeId).filter(\n (t) => !(t as { unlisted?: boolean }).unlisted,\n );\n const specific = tools.find((t) => {\n const supported = (t as { supportedDatatypes?: unknown }).supportedDatatypes;\n return Array.isArray(supported) && supported.includes(datatypeId);\n });\n return (specific ?? tools[0])?.id ?? \"\";\n } catch {\n return \"\";\n }\n}\n\nfunction useIsImage(docUrl: string): boolean {\n const [doc] = useDocument<{ \"@patchwork\"?: { type?: string }; mimeType?: string }>(\n docUrl ? (docUrl as AutomergeUrl) : undefined,\n );\n return doc?.[\"@patchwork\"]?.type === \"file\" && !!doc?.mimeType?.startsWith(\"image/\");\n}\n\nfunction PatchworkDocComponent({ shape }: { shape: PatchworkDocShape }) {\n const { docUrl, docName, toolId } = shape.props;\n const editor = useEditor();\n const isImage = useIsImage(docUrl);\n\n const isEditingShape = useValue(\n \"is editing shape\",\n () => editor.getEditingShapeId() === shape.id,\n [editor, shape.id],\n );\n const isFocused = isEditingShape;\n\n const containerRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n\n // While the embedded content is focused, stop tldraw from swallowing\n // keyboard / wheel / pointer events so the inner tool stays interactive.\n useEffect(() => {\n if (!isFocused) return;\n const el = contentRef.current;\n if (!el) return;\n\n const stopKey = (e: KeyboardEvent) => e.stopPropagation();\n const stopWheel = (e: WheelEvent) => {\n if (!e.ctrlKey) e.stopPropagation();\n };\n const stopPointer = (e: PointerEvent) => e.stopPropagation();\n\n el.addEventListener(\"keydown\", stopKey);\n el.addEventListener(\"keyup\", stopKey);\n el.addEventListener(\"keypress\", stopKey);\n el.addEventListener(\"wheel\", stopWheel);\n el.addEventListener(\"pointerdown\", stopPointer, true);\n el.addEventListener(\"pointermove\", stopPointer, true);\n el.addEventListener(\"pointerup\", stopPointer, true);\n return () => {\n el.removeEventListener(\"keydown\", stopKey);\n el.removeEventListener(\"keyup\", stopKey);\n el.removeEventListener(\"keypress\", stopKey);\n el.removeEventListener(\"wheel\", stopWheel);\n el.removeEventListener(\"pointerdown\", stopPointer, true);\n el.removeEventListener(\"pointermove\", stopPointer, true);\n el.removeEventListener(\"pointerup\", stopPointer, true);\n };\n }, [isFocused]);\n\n // Persist tool picks from the embed frame into the shape props.\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n const onToolChanged = (e: Event) => {\n // Stop propagation so nested embeds don't also change the outer embed.\n e.stopPropagation();\n const newToolId = (e as CustomEvent<{ toolId?: string }>).detail?.toolId;\n if (!newToolId) return;\n editor.updateShape({\n id: shape.id,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: { toolId: newToolId },\n });\n };\n el.addEventListener(\"patchwork:embed-tool-changed\", onToolChanged);\n return () =>\n el.removeEventListener(\"patchwork:embed-tool-changed\", onToolChanged);\n }, [editor, shape.id]);\n\n return (\n <HTMLContainer>\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n flexDirection: \"column\",\n overflow: \"hidden\",\n border: \"1px solid var(--color-panel-contrast, #e5e7eb)\",\n borderRadius: \"8px\",\n background: \"var(--color-panel, #ffffff)\",\n boxShadow: \"0 1px 4px rgba(0,0,0,0.10)\",\n pointerEvents: \"all\",\n }}\n >\n {/* Interactive only while editing (double-click); otherwise pointer\n events fall through so tldraw can select and drag the shape. */}\n <div\n ref={contentRef}\n style={{\n flex: 1,\n minHeight: 0,\n overflow: \"hidden\",\n position: \"relative\",\n pointerEvents: isFocused ? \"auto\" : \"none\",\n userSelect: isFocused ? \"text\" : \"none\",\n cursor: isFocused ? \"auto\" : undefined,\n }}\n >\n {docUrl && isImage ? (\n <img\n src={automergeUrlToServiceWorkerUrl(docUrl as AutomergeUrl)}\n alt={docName}\n style={{ width: \"100%\", height: \"100%\", objectFit: \"contain\" }}\n />\n ) : docUrl ? (\n // @ts-expect-error Custom element from @inkandswitch/patchwork-elements\n <patchwork-view\n doc-url={docUrl}\n tool-id=\"embed\"\n {...(toolId ? { \"embed-tool-id\": toolId } : {})}\n key={toolId || \"default\"}\n style={{ display: \"block\", width: \"100%\", height: \"100%\" }}\n />\n ) : (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n color: \"var(--color-text-3, #9ca3af)\",\n fontSize: \"12px\",\n }}\n >\n No document\n </div>\n )}\n </div>\n </div>\n </HTMLContainer>\n );\n}\n", "/**\n * NewDocTool \u2014 a tldraw tool that lets the user draw a box to create a new\n * embedded Patchwork document of a chosen datatype.\n *\n * Exports:\n * - NewDocShapeTool \u2014 pass to Tldraw `tools`\n * - newDocUiOverrides \u2014 spread into Tldraw `overrides`\n * - NewDocToolbar \u2014 pass as Tldraw `components.Toolbar`\n * - setNewDocToolContext() \u2014 call once per editor when it's ready\n */\n\nimport {\n DefaultToolbar,\n DefaultToolbarContent,\n StateNode,\n createShapeId,\n useEditor,\n useValue,\n type Editor,\n type TLPointerEventInfo,\n type TLUiOverrides,\n type TLUiToolsContextType,\n} from \"@tldraw/tldraw\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { Repo } from \"@automerge/automerge-repo/slim\";\nimport {\n createDocOfDatatype2,\n getRegistry,\n type DatatypeDescription,\n type LoadedDatatype,\n} from \"@inkandswitch/patchwork-plugins\";\nimport { PATCHWORK_DOC_SHAPE_TYPE, makeShapeId } from \"./PatchworkDocShape.tsx\";\n\n// Per-editor context, keyed by editor instance, so a nested canvas embedded in\n// another canvas doesn't clobber the outer one's repo reference.\ninterface NewDocContext {\n repo: Repo;\n}\n\nconst _contextByEditor = new WeakMap<Editor, NewDocContext>();\nlet _selectedDatatypeId = \"\";\n\nexport function setNewDocToolContext(repo: Repo, editor: Editor) {\n _contextByEditor.set(editor, { repo });\n}\n\nexport function setSelectedDatatypeId(id: string) {\n _selectedDatatypeId = id;\n}\n\nfunction getListedDatatypeDescriptions(): DatatypeDescription[] {\n try {\n const registry = getRegistry<DatatypeDescription>(\"patchwork:datatype\");\n return registry.filter((d) => !(d as DatatypeDescription).unlisted) as unknown as DatatypeDescription[];\n } catch {\n return [];\n }\n}\n\nasync function loadDatatype(id: string): Promise<LoadedDatatype | undefined> {\n try {\n const registry = getRegistry<DatatypeDescription>(\"patchwork:datatype\");\n return (await registry.load(id)) as unknown as LoadedDatatype | undefined;\n } catch {\n return undefined;\n }\n}\n\nexport class NewDocShapeTool extends StateNode {\n static override id = \"new-doc\";\n\n private startPoint = { x: 0, y: 0 };\n private previewId: ReturnType<typeof createShapeId> | null = null;\n\n override onPointerDown(_info: TLPointerEventInfo) {\n const { currentPagePoint } = this.editor.inputs;\n this.startPoint = { x: currentPagePoint.x, y: currentPagePoint.y };\n\n this.previewId = createShapeId();\n this.editor.createShape({\n id: this.previewId,\n type: \"geo\",\n x: currentPagePoint.x,\n y: currentPagePoint.y,\n parentId: this.editor.getCurrentPageId(),\n props: { w: 1, h: 1, geo: \"rectangle\", dash: \"dashed\", fill: \"none\" },\n });\n }\n\n override onPointerMove(_info: TLPointerEventInfo) {\n if (!this.previewId) return;\n const { currentPagePoint } = this.editor.inputs;\n const x = Math.min(this.startPoint.x, currentPagePoint.x);\n const y = Math.min(this.startPoint.y, currentPagePoint.y);\n const w = Math.max(1, Math.abs(currentPagePoint.x - this.startPoint.x));\n const h = Math.max(1, Math.abs(currentPagePoint.y - this.startPoint.y));\n this.editor.updateShape({ id: this.previewId, type: \"geo\", x, y, props: { w, h } });\n }\n\n override onCancel() {\n this.cleanup();\n this.editor.setCurrentTool(\"select\");\n }\n\n override onInterrupt() {\n this.cleanup();\n }\n\n private cleanup() {\n if (this.previewId) {\n if (this.editor.getShape(this.previewId)) {\n this.editor.deleteShapes([this.previewId]);\n }\n this.previewId = null;\n }\n }\n\n override onPointerUp(_info: TLPointerEventInfo) {\n if (!this.previewId) return;\n\n const preview = this.editor.getShape(this.previewId);\n this.editor.deleteShapes([this.previewId]);\n this.previewId = null;\n\n if (!preview) {\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const px = (preview as { x: number }).x;\n const py = (preview as { y: number }).y;\n const pw = (preview as { props: { w: number } }).props.w;\n const ph = (preview as { props: { h: number } }).props.h;\n\n const finalW = Math.max(pw, 240);\n const finalH = Math.max(ph, 180);\n\n const ctx = _contextByEditor.get(this.editor);\n if (!ctx) {\n console.warn(\"[tldraw4] NewDocTool: context not set for this editor\");\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const datatypeId = _selectedDatatypeId;\n if (!datatypeId) {\n console.warn(\"[tldraw4] NewDocTool: no datatype selected\");\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const editor = this.editor;\n const repo = ctx.repo;\n const placeholderId = createShapeId();\n\n editor.createShape({\n id: placeholderId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: px,\n y: py,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: finalW,\n h: finalH,\n docUrl: \"\",\n docName: \"Creating\\u2026\",\n docType: datatypeId,\n toolId: \"\",\n },\n });\n\n editor.setCurrentTool(\"select\");\n editor.setSelectedShapes([placeholderId]);\n\n void (async () => {\n try {\n const datatype = await loadDatatype(datatypeId);\n if (!datatype) throw new Error(`Could not load datatype: ${datatypeId}`);\n\n // `createDocOfDatatype2` in the installed plugins package is typed\n // against an older @automerge/automerge-repo Repo; cast to bridge the\n // version skew (same pattern used by the space / llm-canvas tools).\n const docHandle = await (\n createDocOfDatatype2 as (d: LoadedDatatype, r: unknown) => Promise<{ url: string }>\n )(datatype, repo);\n const docUrl = docHandle.url;\n const deterministicId = makeShapeId(docUrl);\n\n const tempShape = editor.getShape(placeholderId) as\n | { x: number; y: number; props: { w: number; h: number } }\n | undefined;\n const sx = tempShape?.x ?? px;\n const sy = tempShape?.y ?? py;\n const sw = tempShape?.props?.w ?? finalW;\n const sh = tempShape?.props?.h ?? finalH;\n\n if (editor.getShape(placeholderId)) {\n editor.deleteShapes([placeholderId]);\n }\n\n if (editor.getShape(deterministicId)) {\n editor.updateShape({\n id: deterministicId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: {\n docUrl,\n docName: datatype.name ?? datatypeId,\n docType: datatypeId,\n toolId: \"\",\n },\n });\n } else {\n editor.createShape({\n id: deterministicId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: sx,\n y: sy,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: sw,\n h: sh,\n docUrl,\n docName: datatype.name ?? datatypeId,\n docType: datatypeId,\n toolId: \"\",\n },\n });\n }\n\n editor.setSelectedShapes([deterministicId]);\n } catch (err) {\n console.error(\"[tldraw4] new doc creation failed:\", err);\n if (editor.getShape(placeholderId)) {\n editor.updateShape({\n id: placeholderId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: { docName: `Error creating ${datatypeId}` },\n });\n }\n }\n })();\n }\n}\n\nexport const newDocUiOverrides: TLUiOverrides = {\n tools(editor: Editor, tools: TLUiToolsContextType) {\n tools[\"new-doc\"] = {\n id: \"new-doc\",\n icon: \"plus\",\n label: \"New document\",\n kbd: \"c\",\n onSelect() {\n editor.setCurrentTool(\"new-doc\");\n },\n };\n return tools;\n },\n};\n\nexport function NewDocToolbar() {\n const editor = useEditor();\n const isActive = useValue(\"new-doc active\", () => editor.getCurrentToolId() === \"new-doc\", [\n editor,\n ]);\n\n const [datatypes, setDatatypes] = useState<DatatypeDescription[]>([]);\n const [menuOpen, setMenuOpen] = useState(false);\n const [selectedId, setSelectedId] = useState(_selectedDatatypeId);\n const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const dt = getListedDatatypeDescriptions();\n setDatatypes(dt);\n if (dt.length > 0 && !_selectedDatatypeId) {\n setSelectedDatatypeId(dt[0].id);\n setSelectedId(dt[0].id);\n }\n }, []);\n\n useEffect(() => {\n if (!menuOpen) return;\n const handler = (e: PointerEvent) => {\n const t = e.target as Node;\n if (buttonRef.current?.contains(t) || menuRef.current?.contains(t)) return;\n setMenuOpen(false);\n };\n document.addEventListener(\"pointerdown\", handler, true);\n return () => document.removeEventListener(\"pointerdown\", handler, true);\n }, [menuOpen]);\n\n const openMenu = useCallback(() => {\n if (buttonRef.current) {\n const rect = buttonRef.current.getBoundingClientRect();\n setMenuPos({ x: rect.left + rect.width / 2, y: rect.top });\n }\n setDatatypes(getListedDatatypeDescriptions());\n setMenuOpen(true);\n }, []);\n\n const handlePlusClick = useCallback(() => {\n if (datatypes.length > 0 && !_selectedDatatypeId) {\n setSelectedDatatypeId(datatypes[0].id);\n setSelectedId(datatypes[0].id);\n }\n editor.setCurrentTool(\"new-doc\");\n if (datatypes.length > 1) {\n if (menuOpen) setMenuOpen(false);\n else requestAnimationFrame(openMenu);\n }\n }, [datatypes, editor, menuOpen, openMenu]);\n\n const handlePick = useCallback(\n (id: string) => {\n setSelectedDatatypeId(id);\n setSelectedId(id);\n setMenuOpen(false);\n editor.setCurrentTool(\"new-doc\");\n },\n [editor],\n );\n\n if (datatypes.length === 0) {\n return (\n <DefaultToolbar>\n <DefaultToolbarContent />\n </DefaultToolbar>\n );\n }\n\n const selectedName = datatypes.find((d) => d.id === selectedId)?.name ?? \"document\";\n\n return (\n <DefaultToolbar>\n <DefaultToolbarContent />\n\n <div style={{ width: \"1px\", height: \"20px\", background: \"#ddd\", margin: \"0 4px\", flexShrink: 0 }} />\n\n <div\n style={{\n position: \"relative\",\n display: \"inline-flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n }}\n >\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={handlePlusClick}\n title={`New document (${selectedName})`}\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: \"32px\",\n height: \"32px\",\n border: \"none\",\n borderRadius: \"6px\",\n background: isActive || menuOpen ? \"var(--color-selected, #e8f0fe)\" : \"transparent\",\n cursor: \"pointer\",\n color: isActive || menuOpen ? \"var(--color-selected-contrast, #2f80ed)\" : \"currentColor\",\n flexShrink: 0,\n }}\n >\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path d=\"M8 2v12M2 8h12\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n </svg>\n </button>\n\n {menuOpen &&\n menuPos &&\n datatypes.length > 1 &&\n createPortal(\n <div\n ref={menuRef}\n style={{\n position: \"fixed\",\n left: menuPos.x,\n top: menuPos.y,\n transform: \"translate(-50%, -100%)\",\n marginTop: \"-8px\",\n background: \"#fff\",\n border: \"1px solid #ddd\",\n borderRadius: \"8px\",\n boxShadow: \"0 4px 12px rgba(0,0,0,0.12)\",\n padding: \"4px\",\n minWidth: \"160px\",\n zIndex: 100000,\n }}\n >\n {datatypes.map((dt) => (\n <button\n key={dt.id}\n type=\"button\"\n onPointerDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n handlePick(dt.id);\n }}\n style={{\n display: \"block\",\n width: \"100%\",\n padding: \"6px 10px\",\n border: \"none\",\n borderRadius: \"4px\",\n background: dt.id === selectedId ? \"#e8f0fe\" : \"transparent\",\n cursor: \"pointer\",\n fontSize: \"13px\",\n fontFamily: \"system-ui, -apple-system, sans-serif\",\n color: \"#333\",\n textAlign: \"left\",\n whiteSpace: \"nowrap\",\n }}\n >\n {dt.name}\n </button>\n ))}\n </div>,\n document.body,\n )}\n </div>\n </DefaultToolbar>\n );\n}\n", "/**\n * Patchwork drag-and-drop payload parsing.\n *\n * Patchwork document drags (from the folder-tree-view / sideboard and most\n * tools) carry these DataTransfer formats:\n * - `text/x-patchwork-urls` \u2014 JSON `AutomergeUrl[]` (the detection hook)\n * - `text/x-patchwork-dnd` \u2014 JSON `{ source, items: [{ id, url, type, name }] }`\n * - `text/uri-list` / `text/plain` \u2014 one Patchwork web link per line\n *\n * Only `text/x-patchwork-urls` is guaranteed; the richer `-dnd` payload, when\n * present, gives us the datatype id and display name without a repo lookup.\n */\n\nimport {\n isValidAutomergeUrl,\n parseAutomergeUrl,\n stringifyAutomergeUrl,\n type AutomergeUrl,\n type DocumentId,\n} from \"@automerge/automerge-repo/slim\";\n\nexport const PATCHWORK_URLS_MIME = \"text/x-patchwork-urls\" as const;\nexport const PATCHWORK_DND_MIME = \"text/x-patchwork-dnd\" as const;\n\nexport interface DroppedDoc {\n url: AutomergeUrl;\n /** Datatype id (from the `-dnd` payload), if known. */\n type?: string;\n /** Display name (from the `-dnd` payload), if known. */\n name?: string;\n}\n\n/** True when the drag carries Patchwork document URLs. */\nexport function isPatchworkDrag(types: readonly string[]): boolean {\n return types.includes(PATCHWORK_URLS_MIME);\n}\n\ntype DndItem = { url?: unknown; type?: unknown; name?: unknown };\ntype DndPayload = { items?: DndItem[] };\n\n/** Extract the dropped documents, preferring the richest payload available. */\nexport function parseDroppedDocs(dt: DataTransfer | null): DroppedDoc[] {\n if (!dt) return [];\n\n // 1. Structured payload with datatype + name.\n const dnd = dt.getData(PATCHWORK_DND_MIME);\n if (dnd) {\n try {\n const parsed = JSON.parse(dnd) as DndPayload;\n const items = (parsed.items ?? [])\n .map((it): DroppedDoc | null => {\n const url = typeof it.url === \"string\" ? it.url : undefined;\n if (!url || !isValidAutomergeUrl(url)) return null;\n return {\n url,\n type: typeof it.type === \"string\" ? it.type : undefined,\n name: typeof it.name === \"string\" ? it.name : undefined,\n };\n })\n .filter((it): it is DroppedDoc => it !== null);\n if (items.length > 0) return dedupe(items);\n } catch {\n // fall through\n }\n }\n\n // 2. Bare URL list.\n const urls = dt.getData(PATCHWORK_URLS_MIME);\n if (urls) {\n try {\n const parsed: unknown = JSON.parse(urls);\n const items = (Array.isArray(parsed) ? parsed : [])\n .filter((u): u is AutomergeUrl => typeof u === \"string\" && isValidAutomergeUrl(u))\n .map((url) => ({ url }));\n if (items.length > 0) return dedupe(items);\n } catch {\n // fall through\n }\n }\n\n // 3. Plain-text / uri-list fallback (external links, \"#doc=<id>\" form).\n const text = dt.getData(\"text/uri-list\") || dt.getData(\"text/plain\");\n if (text) {\n const items = text\n .split(/\\r?\\n/)\n .map(urlFromText)\n .filter((url): url is AutomergeUrl => url !== null)\n .map((url) => ({ url }));\n if (items.length > 0) return dedupe(items);\n }\n\n return [];\n}\n\nfunction dedupe(items: DroppedDoc[]): DroppedDoc[] {\n const seen = new Set<string>();\n const out: DroppedDoc[] = [];\n for (const it of items) {\n if (seen.has(it.url)) continue;\n seen.add(it.url);\n out.push(it);\n }\n return out;\n}\n\n// Accept `automerge:\u2026` directly, or a Patchwork web link containing\n// `#doc=<documentId>` / `?doc=<documentId>`.\nfunction urlFromText(line: string): AutomergeUrl | null {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) return null;\n if (isValidAutomergeUrl(trimmed)) return trimmed;\n\n const match = trimmed.match(/[#?&]doc=([^&\\s]+)/);\n if (match) {\n const raw = decodeURIComponent(match[1]);\n if (isValidAutomergeUrl(raw)) return raw;\n try {\n const url = stringifyAutomergeUrl({ documentId: raw as DocumentId });\n // Round-trip to reject malformed ids.\n parseAutomergeUrl(url);\n return url;\n } catch {\n return null;\n }\n }\n return null;\n}\n", "import type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport type { TLCursorProps } from \"@tldraw/tldraw\";\n\n// Parses a userId of the form `${contactUrl}-${peerId}` to recover contactUrl\n// and actorId (see useContactInfo in tool.tsx for why userIds are composed).\nexport function splitPresenceUserId(userId: string): {\n contactUrl?: AutomergeUrl;\n actorId?: string;\n} {\n if (!userId.startsWith(\"automerge:\")) return { actorId: userId };\n const i = userId.indexOf(\"-\");\n if (i === -1) return { contactUrl: userId as AutomergeUrl };\n return {\n contactUrl: userId.slice(0, i) as AutomergeUrl,\n actorId: userId.slice(i + 1),\n };\n}\n\n/**\n * Collaborator cursor override: tldraw's default arrow, but the nametag is\n * replaced by the shared \"contact-cursor\" token (rendered live from the\n * peer's contact doc), so remote cursors look the same on canvases as in\n * text editors. The arrow paths are copied from tldraw's own cursor SVG --\n * the shared symbol DefaultCursor references has a runtime-generated id we\n * can't reach from here.\n */\nexport function ContactCollaboratorCursor({\n className,\n point,\n zoom,\n color,\n name,\n userId,\n}: TLCursorProps) {\n if (!point) return null;\n const { contactUrl } = splitPresenceUserId(userId);\n return (\n <div\n className={\n className ? `tl-overlays__item ${className}` : \"tl-overlays__item\"\n }\n style={{\n transform: `translate(${point.x}px, ${point.y}px) scale(${1 / zoom})`,\n }}\n >\n <svg\n className=\"tl-cursor\"\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 32 32\"\n fill=\"none\"\n aria-hidden=\"true\"\n >\n {/* translate(-12,-12) puts the arrow tip at the presence point (the\n shadow copy sits 1px off), matching tldraw's CursorDef -- and\n keeps the arrow clear of the nametag slot below. */}\n <g fill=\"rgba(0,0,0,.2)\" transform=\"translate(-11,-11)\">\n <path d=\"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z\" />\n <path d=\"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z\" />\n </g>\n <g style={{ color }} transform=\"translate(-12,-12)\">\n <path\n d=\"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z\"\n fill=\"white\"\n />\n <path\n d=\"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z\"\n fill=\"white\"\n />\n <path\n d=\"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z\"\n fill=\"currentColor\"\n />\n <path\n d=\"m13 10.814v11.188l2.969-2.866.428-.139h4.768z\"\n fill=\"currentColor\"\n />\n </g>\n </svg>\n {contactUrl ? (\n // Same offset as tldraw's .tl-nametag so the token hangs off the\n // arrow tip.\n <div style={{ position: \"absolute\", top: 16, left: 13 }}>\n {/* @ts-expect-error Custom element from @inkandswitch/patchwork-elements */}\n <patchwork-view doc-url={contactUrl} tool-id=\"contact-cursor\" />\n </div>\n ) : (\n name && (\n <div className=\"tl-nametag\" style={{ backgroundColor: color }}>\n {name}\n </div>\n )\n )}\n </div>\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,mBAAkC;;;ACD3C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qCAAc;;;;ACOP,SAAS,YAAe,SAAwC;AACrE,MAAI,SAAiB;AACrB,MAAI;AACJ,MAAI;AAEJ,QAAM,YAAY,QAAQ;IACxB,CAAA,S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,SAAS;AAAA,kBACT,QAAQ,iBAAiB,UAAU;AAAA,gBACrC;AAAA,cACF,CAAC;AAAA,YACH,SAAS,KAAK;AACZ,sBAAQ,MAAM,2CAA2C,GAAG;AAAA,YAC9D;AAAA,UACF,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAED,aAAO,kBAAkB,UAAU;AAAA,IACrC;AAEA,YAAQ,iBAAiB,aAAa,WAAW,EAAE,SAAS,KAAK,CAAC;AAClE,YAAQ,iBAAiB,YAAY,WAAW,EAAE,SAAS,KAAK,CAAC;AACjE,YAAQ,iBAAiB,QAAQ,YAAY,EAAE,SAAS,KAAK,CAAC;AAC9D,WAAO,MAAM;AACX,cAAQ,oBAAoB,aAAa,WAAW,EAAE,SAAS,KAAK,CAAC;AACrE,cAAQ,oBAAoB,YAAY,WAAW,EAAE,SAAS,KAAK,CAAC;AACpE,cAAQ,oBAAoB,QAAQ,YAAY,EAAE,SAAS,KAAK,CAAC;AAAA,IACnE;AAAA,EACF,GAAG,CAAC,QAAQ,MAAM,OAAO,CAAC;AAC5B;AAEO,SAAS,OAAO,QAAa,SAAc;AAChD,QAAM,WAAO,0BAAW,OAAO;AAC/B,OAAK;AAAA,IACH,6CAAC,YAAY,UAAZ,EAAqB,OAAO,QAAQ,MACnC,uDAAC,cAAW,QAAQ,OAAO,KAAK,SAAkB,GACpD;AAAA,EACF;AACA,SAAO,MAAM,KAAK,QAAQ;AAC5B;",
6
- "names": ["crypto", "isBytes", "abytes", "aexists", "aoutput", "clean", "createView", "rotr", "utf8ToBytes", "toBytes", "createHasher", "require$$0", "Hash", "setBigUint64", "Chi", "Maj", "view", "HashMD", "dataView", "require$$1", "require$$2", "SHA256_K", "SHA256_W", "SHA256", "sha256", "base", "i", "j", "src", "sha256x2", "bs58check", "Uuid.validate", "Uuid.parse", "handle", "useStateRef", "EventEmitter", "peerStates", "heartbeats", "position", "bundledStrings", "i", "structure", "read", "target", "isLittleEndianMachine", "Buffer", "referenceMap", "packedObjectMap", "sharedPackedObjectMap", "sharedValues", "packedValues", "options", "maxBytes", "parse", "ms", "require$$0", "debug", "sha256", "this", "Hash", "HMAC", "hmac", "initialState", "import_react", "RepoContext", "view", "dataView", "sha256", "sha256n", "base", "basex", "base58", "bs58checkBase", "parse", "ms", "debug", "peerEvents", "__toESM", "EventEmitter", "usePresence", "PeerStateView", "Presence", "initialState", "store", "doc", "usePresence", "import_react", "automergeUrlToServiceWorkerUrl", "import_react", "import_react", "DiffShapeWrapper", "import_react", "import_jsx_runtime", "import_react", "import_react", "import_jsx_runtime", "isValidAutomergeUrl", "parseAutomergeUrl", "stringifyAutomergeUrl", "import_jsx_runtime", "import_jsx_runtime", "automergeUrlToServiceWorkerUrl"]
3
+ "sources": ["../src/tool.tsx", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/wrapPromise.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useRepo.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/regex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/validate.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/uuid@14.0.0/node_modules/uuid/dist/parse.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/base-x@5.0.1/node_modules/base-x/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58@6.0.0/node_modules/bs58/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/base.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/bs58check@4.0.0/node_modules/bs58check/src/esm/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/helpers/bufferFromHex.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/subdoc-handles/types.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/subdoc-handles/parser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/Logger.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo/dist/AutomergeUrl.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandle.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocument.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/helpers/useSet.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocHandles.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useDocuments.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useStateRef.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.js", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/node_modules/.pnpm/eventemitter3@5.0.4/node_modules/eventemitter3/index.mjs", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useRemoteAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/useLocalAwareness.ts", "../node_modules/.pnpm/@automerge+automerge-repo-react-hooks@2.6.0-subduction.46_react-dom@18.3.1_react@18.3.1_4b92195feb6ea50576810c4c883087b2/node_modules/@automerge/automerge-repo-react-hooks/src/usePresence.ts", "../src/lith/useAutomergeStore.ts", "../src/lith/AutomergeToTLStore.ts", "../node_modules/.pnpm/@inkandswitch+patchwork-providers-react@0.2.6_@automerge+automerge-repo-react-hooks@2.6_80ffcbcf3e158b4c39ecf6aef28824ac/node_modules/@inkandswitch/patchwork-providers-react/dist/index.js", "../src/diff.ts", "../src/DiffShapeWrapper.tsx", "../src/PatchworkDocShape.tsx", "../src/NewDocTool.tsx", "../src/dnd.ts", "../src/CollaboratorCursor.tsx"],
4
+ "sourcesContent": ["import type { AutomergeUrl, DocHandle } from \"@automerge/automerge-repo/slim\";\nimport { decodeHeads, type UrlHeads } from \"@automerge/automerge-repo/slim\";\nimport {\n RepoContext,\n useDocHandle,\n useDocument,\n useRepo,\n} from \"@automerge/automerge-repo-react-hooks\";\nimport {\n Tldraw,\n useEditor,\n getMediaAssetInfoPartial,\n atom,\n createShapeId,\n type VecLike,\n type TLContent,\n type TLAssetId,\n type TLAsset,\n type TLComponents,\n type TLRecord,\n type TLShapeId,\n type TLStoreWithStatus,\n} from \"@tldraw/tldraw\";\nimport {\n useAutomergeStore,\n useAutomergePresence,\n useClearHistoryOnScopeSwap,\n useIsHandleReadOnly,\n} from \"./lith/useAutomergeStore.ts\";\nimport type { TLDrawDoc } from \"./datatype.ts\";\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { UnixFileEntry } from \"@inkandswitch/patchwork-filesystem\";\nimport { automergeUrlToServiceWorkerUrl } from \"@inkandswitch/patchwork-filesystem\";\nimport { useSubscribe } from \"@inkandswitch/patchwork-providers-react\";\nimport { createRoot } from \"react-dom/client\";\nimport { diffStore, type ShapeDiff } from \"./diff.ts\";\nimport {\n DiffShapeWrapper,\n DiffStatusContext,\n type DiffStatus,\n type DiffStatusAtom,\n} from \"./DiffShapeWrapper.tsx\";\nimport {\n PatchworkDocShapeUtil,\n PATCHWORK_DOC_SHAPE_TYPE,\n getDefaultToolId,\n} from \"./PatchworkDocShape.tsx\";\nimport {\n NewDocShapeTool,\n NewDocToolbar,\n newDocUiOverrides,\n setNewDocToolContext,\n} from \"./NewDocTool.tsx\";\nimport { isPatchworkDrag, parseDroppedDocs } from \"./dnd.ts\";\nimport { ContactCollaboratorCursor } from \"./CollaboratorCursor.tsx\";\n\nexport { splitPresenceUserId } from \"./CollaboratorCursor.tsx\";\n\n// Custom shapes / tools that let a tldraw canvas embed other Patchwork\n// documents. These must be registered both on the Automerge-backed store (so\n// the shape type persists) and on the <Tldraw> component (so it renders).\nconst customShapeUtils = [PatchworkDocShapeUtil];\nconst customTools = [NewDocShapeTool];\n\n// Diff baseline (fork-point heads) served by the draft overlay\n// (`draft:baseline`). `heads` is `null` when there is no baseline and no\n// diff is rendered (e.g. on \"main\"). It is `null` rather than optional so the\n// value is a valid structured-cloneable `JSONValue` crossing the provider\n// channel.\ntype Baseline = { heads: UrlHeads | null };\n\nconst MIME_TO_EXT: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"image/bmp\": \"bmp\",\n \"image/tiff\": \"tiff\",\n \"image/avif\": \"avif\",\n \"video/mp4\": \"mp4\",\n \"video/webm\": \"webm\",\n \"video/quicktime\": \"mov\",\n};\n\nfunction extensionForMimeType(mimeType: string): string {\n return MIME_TO_EXT[mimeType] || mimeType.split(\"/\")[1] || \"bin\";\n}\n\ninterface ContactDoc {\n type: string;\n name?: string;\n color?: string;\n}\n\nfunction useContactInfo() {\n const repo = useRepo();\n const [contactUrl, setContactUrl] = useState<AutomergeUrl | undefined>();\n\n useEffect(() => {\n const accountDocHandle = (window as any).accountDocHandle as\n | DocHandle<{ contactUrl: AutomergeUrl }>\n | undefined;\n if (!accountDocHandle) return;\n const doc = accountDocHandle.doc();\n if (doc?.contactUrl) {\n setContactUrl(doc.contactUrl);\n }\n }, []);\n\n const [contactDoc] = useDocument<ContactDoc>(contactUrl);\n\n return {\n // Compose userId as `${contactUrl}-${repo.peerId}` to uniquely identify a session;\n // this prevents tldraw from hiding local cursors across multiple sessions under the same account.\n userId: contactUrl ? `${contactUrl}-${repo.peerId}` : repo.peerId,\n name: contactDoc?.name ?? \"Anonymous\",\n // The color chosen in the account picker; it rides along in our presence\n // record, so the cursor arrow always matches the contact-cursor token.\n color: contactDoc?.color,\n };\n}\n\nexport function TldrawTool({\n docUrl,\n element,\n}: {\n docUrl: AutomergeUrl;\n element: HTMLElement;\n}) {\n const handle = useDocHandle<TLDrawDoc>(docUrl, { suspense: true });\n // A history-pinned handle is at fixed heads and rejects writes, so the whole\n // tool renders read-only. Tracked live: it flips in place when the handle's\n // backing is swapped.\n const readOnly = useIsHandleReadOnly(handle);\n const contactInfo = useContactInfo();\n const store = useAutomergeStore({\n handle,\n userId: contactInfo.userId,\n readOnly,\n shapeUtils: customShapeUtils,\n });\n\n useAutomergePresence({\n handle: handle as DocHandle<any>,\n store,\n userMetadata: contactInfo,\n element,\n });\n\n const baseline = useSubscribe<Baseline>(\n element,\n { type: \"draft:baseline\", url: docUrl },\n { heads: null }\n );\n const diff = useShapeDiff(handle, baseline.heads ?? undefined);\n\n // Per-tool atom feeding `DiffShapeWrapper` (read via `useValue`). Created once\n // per mount so multiple tldraw tools don't share styling state.\n const [statusAtom] = useState<DiffStatusAtom>(() =>\n atom(\"diff status\", new Map<TLShapeId, DiffStatus>())\n );\n useEffect(() => {\n statusAtom.set(buildStatusMap(diff));\n }, [diff, statusAtom]);\n\n // Deleted shapes are gone from the live store, so re-insert them as locked\n // ghosts (styled `tl-diff-deleted`). They never reach Automerge \u2014 see\n // `useDeletedGhosts`.\n useDeletedGhosts(store, handle, diff);\n\n const components = useMemo<TLComponents>(\n () => ({\n ShapeWrapper: DiffShapeWrapper,\n Toolbar: NewDocToolbar,\n CollaboratorCursor: ContactCollaboratorCursor,\n }),\n []\n );\n\n return (\n <DiffStatusContext.Provider value={statusAtom}>\n <Tldraw\n inferDarkMode\n autoFocus\n store={store}\n shapeUtils={customShapeUtils}\n tools={customTools}\n overrides={newDocUiOverrides}\n components={components}\n >\n <TldrawInner docUrl={docUrl} element={element} readOnly={readOnly} />\n </Tldraw>\n </DiffStatusContext.Provider>\n );\n}\n\n// Recomputes the diff against `heads` on every doc change. `baseline.heads`\n// only moves when the draft is forked (copy-on-write), so without listening to\n// the handle the diff would freeze after the first computation. The bump is\n// deferred to a microtask so we never recompute synchronously from inside the\n// sync layer's own `handle.change` callback.\nfunction useShapeDiff(\n handle: DocHandle<TLDrawDoc>,\n heads: UrlHeads | undefined\n): ShapeDiff | null {\n const [tick, setTick] = useState(0);\n\n useEffect(() => {\n let scheduled = false;\n const onChange = () => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n setTick((t) => t + 1);\n });\n };\n handle.on(\"change\", onChange);\n return () => {\n handle.off(\"change\", onChange);\n };\n }, [handle]);\n\n return useMemo(() => {\n if (!heads) return null;\n const doc = handle.doc();\n if (!doc) return null;\n try {\n return diffStore(doc, decodeHeads(heads));\n } catch (error) {\n console.warn(\"[tldraw4/diff] failed to compute diff\", error);\n return null;\n }\n // `tick` is intentionally a dependency: it forces recompute on doc change.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [handle, heads, tick]);\n}\n\nfunction buildStatusMap(diff: ShapeDiff | null): Map<TLShapeId, DiffStatus> {\n const map = new Map<TLShapeId, DiffStatus>();\n if (!diff) return map;\n for (const id of diff.added) map.set(id, \"added\");\n for (const id of diff.changed) map.set(id, \"changed\");\n for (const record of diff.deleted) map.set(record.id as TLShapeId, \"deleted\");\n return map;\n}\n\n// Renders deleted shapes by putting their baseline records back into the\n// *tldraw* store as locked ghosts. These are applied via `mergeRemoteChanges`\n// (source: \"remote\"), and the only TLStore->Automerge sync path listens for\n// source: \"user\" \u2014 so ghosts never sync back to the doc. `diffStore` reads the\n// Automerge doc (not the tldraw store), so ghosts also never re-enter the diff.\nfunction useDeletedGhosts(\n store: TLStoreWithStatus,\n handle: DocHandle<TLDrawDoc>,\n diff: ShapeDiff | null\n) {\n const ghostIds = useRef<Set<TLShapeId>>(new Set());\n\n useEffect(() => {\n const inner = store.store;\n if (!inner) return;\n\n const desired = new Map<TLShapeId, TLRecord>();\n if (diff) {\n for (const record of diff.deleted) {\n desired.set(record.id as TLShapeId, record);\n }\n }\n\n // A ghost is only safe to remove if it isn't currently a real record in the\n // doc: if a deleted shape was re-added upstream, the sync layer puts the\n // real record back at the same id, and removing it then would drop the real\n // shape from the view.\n const liveStore = (handle.doc()?.store ?? {}) as Record<string, unknown>;\n const toRemove = [...ghostIds.current].filter(\n (id) => !desired.has(id) && !(id in liveStore)\n );\n const toAdd: TLRecord[] = [];\n for (const [id, record] of desired) {\n if (!ghostIds.current.has(id)) {\n // Fade the ghost via tldraw's first-class `opacity` prop. tldraw writes\n // `opacity` as an inline style on the shape element (Shape.tsx), so a CSS\n // class (`.tl-diff-deleted`) can't override it \u2014 the fade has to live on\n // the record itself. The red \"removed\" glow stays in CSS as a `filter`.\n toAdd.push({ ...record, isLocked: true, opacity: 0.1 } as TLRecord);\n }\n }\n\n if (toRemove.length === 0 && toAdd.length === 0) return;\n\n inner.mergeRemoteChanges(() => {\n if (toRemove.length) inner.remove(toRemove);\n if (toAdd.length) inner.put(toAdd);\n });\n\n for (const id of toRemove) ghostIds.current.delete(id);\n for (const record of toAdd) ghostIds.current.add(record.id as TLShapeId);\n }, [store, handle, diff]);\n}\n\nfunction TldrawInner(props: {\n docUrl: AutomergeUrl;\n element: HTMLElement;\n readOnly: boolean;\n}) {\n const key = useMemo(() => `${props.docUrl}-camera`, [props.docUrl]);\n\n const editor = useEditor();\n const repo = useRepo();\n const handle = useDocHandle<TLDrawDoc>(props.docUrl, { suspense: true });\n\n usePatchworkDrop(props.element);\n useClearHistoryOnScopeSwap(handle);\n\n const onChange = useCallback(() => {\n if (!editor) return;\n const camstate = editor.getCameraState();\n if (camstate == \"moving\") {\n // todo debounce?\n localStorage.setItem(key, JSON.stringify(editor.getCamera()));\n }\n }, []);\n\n useEffect(() => {\n if (!editor) return;\n\n // History-pinned views block all canvas editing (the store write-back is\n // also disabled in useAutomergeStore).\n editor.updateInstanceState({ isReadonly: props.readOnly });\n\n // Give the NewDocTool the repo it needs to create embedded documents.\n setNewDocToolContext(repo, editor);\n\n // Handle pasted/dropped files (images, videos) by storing them as\n // UnixFileEntry automerge docs and referencing them via service-worker URLs.\n editor.registerExternalAssetHandler(\"file\", async ({ file, assetId }) => {\n const isImage = file.type.startsWith(\"image/\");\n const isVideo = file.type.startsWith(\"video/\");\n\n // Create a stable asset ID if one wasn't provided\n const id = assetId ?? (`asset:${crypto.randomUUID()}` as TLAssetId);\n\n // Read the file bytes\n const bytes = new Uint8Array(await file.arrayBuffer());\n\n // Determine extension and name\n const ext = extensionForMimeType(file.type);\n const name =\n file.name && file.name !== \"image.png\"\n ? file.name\n : `Pasted image on ${new Date().toLocaleDateString()}.${ext}`;\n\n // Create an automerge doc for the file\n const fileHandle = repo.create<UnixFileEntry>();\n fileHandle.change((doc) => {\n doc.content = bytes;\n doc.extension = ext;\n doc.mimeType = file.type;\n doc.name = name;\n });\n\n // Build the asset using tldraw's helper to get dimensions etc.\n const asset = await getMediaAssetInfoPartial(file, id, isImage, isVideo);\n\n // Point the asset's src at the service-worker URL for this doc\n asset.props.src = automergeUrlToServiceWorkerUrl(fileHandle.url);\n\n return asset as TLAsset;\n });\n\n // Override the tldraw paste handler to avoid \"could not migrate content\"\n // errors when pasting from newer tldraw versions (e.g. tldraw.com may\n // run a canary build whose schema sequence versions are ahead of ours).\n editor.registerExternalContentHandler(\n \"tldraw\",\n ({ point, content }: { point?: VecLike; content: TLContent }) => {\n editor.run(() => {\n const selectionBoundsBefore = editor.getSelectionPageBounds();\n editor.markHistoryStoppingPoint(\"paste\");\n\n for (const shape of content.shapes) {\n if (content.rootShapeIds.includes(shape.id)) {\n shape.isLocked = false;\n }\n }\n\n // Replace the pasted content's schema with ours so that\n // migrateStoreSnapshot sees matching versions and skips migration\n // rather than failing on unknown future sequence versions.\n content.schema = editor.store.schema.serialize();\n\n editor.putContentOntoCurrentPage(content, {\n point,\n select: true,\n });\n\n const selectedBoundsAfter = editor.getSelectionPageBounds();\n if (\n selectionBoundsBefore &&\n selectedBoundsAfter &&\n selectionBoundsBefore.collides(selectedBoundsAfter)\n ) {\n editor.updateInstanceState({ isChangingStyle: true });\n }\n });\n }\n );\n\n const existing = localStorage.getItem(key);\n if (existing) {\n try {\n const cam = JSON.parse(existing);\n editor.setCamera(cam);\n } catch {\n localStorage.removeItem(key);\n }\n }\n editor.on(\"change\", onChange);\n return () => void editor.off(\"change\", onChange);\n }, [editor, props.readOnly]);\n return null;\n}\n\n// Accept documents dragged in from the folder-tree-view / sideboard and other\n// Patchwork tools, embedding each as a `patchwork-doc` shape at the drop point.\nfunction usePatchworkDrop(element: HTMLElement) {\n const editor = useEditor();\n const repo = useRepo();\n\n useEffect(() => {\n if (!editor || !element) return;\n\n // If the drop lands inside an already-embedded <patchwork-view>, let that\n // inner tool handle it instead of creating a nested embed. The outer\n // <patchwork-view> hosting this canvas appears at/after `element` in the\n // path, so we stop the walk once we reach `element`.\n const isInsideEmbeddedPatchworkView = (e: DragEvent) => {\n for (const el of e.composedPath()) {\n if (el === element) break;\n if ((el as Element).tagName?.toLowerCase() === \"patchwork-view\")\n return true;\n }\n return false;\n };\n\n const allowDrop = (e: DragEvent) => {\n if (e.dataTransfer && isPatchworkDrag(e.dataTransfer.types)) {\n e.preventDefault();\n // Dropping embeds a *reference* to the same automerge doc, not a copy.\n e.dataTransfer.dropEffect = \"link\";\n }\n };\n\n const handleDrop = (e: DragEvent) => {\n if (!e.dataTransfer || !isPatchworkDrag(e.dataTransfer.types)) return;\n e.preventDefault();\n if (isInsideEmbeddedPatchworkView(e)) return;\n e.stopImmediatePropagation();\n\n const docs = parseDroppedDocs(e.dataTransfer);\n if (docs.length === 0) return;\n\n const dropPoint = editor.screenToPage({ x: e.clientX, y: e.clientY });\n const STAGGER = 24;\n const createdIds: TLShapeId[] = [];\n\n docs.forEach((item, i) => {\n // Random id (not derived from the doc url) so the same document can be\n // embedded on the canvas any number of times.\n const shapeId = createShapeId();\n createdIds.push(shapeId);\n\n const knownType = item.type ?? \"\";\n editor.createShape({\n id: shapeId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: dropPoint.x + i * STAGGER,\n y: dropPoint.y + i * STAGGER,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: 640,\n h: 480,\n docUrl: item.url,\n docName: item.name ?? \"Loading\\u2026\",\n docType: knownType,\n toolId: getDefaultToolId(knownType),\n },\n });\n\n // Resolve datatype/name from the doc when the drag payload didn't\n // include them (e.g. bare-URL drags).\n if (!item.type || !item.name) {\n void (async () => {\n try {\n const handle = await repo.find<{\n \"@patchwork\"?: { type?: string };\n }>(item.url);\n const doc = handle.doc();\n const datatypeId = doc?.[\"@patchwork\"]?.type ?? knownType;\n if (!editor.getShape(shapeId)) return;\n editor.updateShape({\n id: shapeId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: {\n docName: item.name ?? datatypeId ?? item.url,\n docType: datatypeId,\n toolId: getDefaultToolId(datatypeId),\n },\n });\n } catch (err) {\n console.error(\"[tldraw4] failed to resolve dropped doc\", err);\n }\n })();\n }\n });\n\n editor.setSelectedShapes(createdIds);\n };\n\n element.addEventListener(\"dragenter\", allowDrop, { capture: true });\n element.addEventListener(\"dragover\", allowDrop, { capture: true });\n element.addEventListener(\"drop\", handleDrop, { capture: true });\n return () => {\n element.removeEventListener(\"dragenter\", allowDrop, { capture: true });\n element.removeEventListener(\"dragover\", allowDrop, { capture: true });\n element.removeEventListener(\"drop\", handleDrop, { capture: true });\n };\n }, [editor, repo, element]);\n}\n\nexport function render(handle: any, element: any) {\n const root = createRoot(element);\n root.render(\n <RepoContext.Provider value={element.repo}>\n <TldrawTool docUrl={handle.url} element={element} />\n </RepoContext.Provider>\n );\n return () => root.unmount();\n}\n", "type Status = \"pending\" | \"success\" | \"error\"\n\nexport type PromiseWrapper<T> = {\n promise: Promise<T>\n read(): T\n}\n\nexport function wrapPromise<T>(promise: Promise<T>): PromiseWrapper<T> {\n let status: Status = \"pending\"\n let result: T\n let error: Error\n\n const suspender = promise.then(\n data => {\n status = \"success\"\n result = data\n },\n err => {\n status = \"error\"\n error = err\n }\n )\n\n return {\n promise,\n read(): T {\n switch (status) {\n case \"pending\":\n throw suspender\n case \"error\":\n throw error\n case \"success\":\n return result\n }\n },\n }\n}\n", "import { Repo } from \"@automerge/automerge-repo/slim\"\nimport { createContext, useContext } from \"react\"\n\n/** A [React context](https://react.dev/learn/passing-data-deeply-with-context) which provides access to an Automerge repo. */\nexport const RepoContext = createContext<Repo | null>(null)\n\n/** A [React hook](https://reactjs.org/docs/hooks-intro.html) which returns the Automerge repo from {@link RepoContext}. */\nexport function useRepo(): Repo {\n const repo = useContext(RepoContext)\n if (!repo) throw new Error(\"Repo was not found on RepoContext.\")\n return repo\n}\n", "export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;\n", "import REGEX from './regex.js';\nfunction validate(uuid) {\n return typeof uuid === 'string' && REGEX.test(uuid);\n}\nexport default validate;\n", "import validate from './validate.js';\nfunction parse(uuid) {\n if (!validate(uuid)) {\n throw TypeError('Invalid UUID');\n }\n let v;\n return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff);\n}\nexport default parse;\n", "/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor(outputLen = 32) {\n super(64, outputLen, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\nexport class SHA224 extends SHA256 {\n constructor() {\n super(28);\n this.A = SHA224_IV[0] | 0;\n this.B = SHA224_IV[1] | 0;\n this.C = SHA224_IV[2] | 0;\n this.D = SHA224_IV[3] | 0;\n this.E = SHA224_IV[4] | 0;\n this.F = SHA224_IV[5] | 0;\n this.G = SHA224_IV[6] | 0;\n this.H = SHA224_IV[7] | 0;\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor(outputLen = 64) {\n super(128, outputLen, 16, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = SHA512_IV[0] | 0;\n this.Al = SHA512_IV[1] | 0;\n this.Bh = SHA512_IV[2] | 0;\n this.Bl = SHA512_IV[3] | 0;\n this.Ch = SHA512_IV[4] | 0;\n this.Cl = SHA512_IV[5] | 0;\n this.Dh = SHA512_IV[6] | 0;\n this.Dl = SHA512_IV[7] | 0;\n this.Eh = SHA512_IV[8] | 0;\n this.El = SHA512_IV[9] | 0;\n this.Fh = SHA512_IV[10] | 0;\n this.Fl = SHA512_IV[11] | 0;\n this.Gh = SHA512_IV[12] | 0;\n this.Gl = SHA512_IV[13] | 0;\n this.Hh = SHA512_IV[14] | 0;\n this.Hl = SHA512_IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super(48);\n this.Ah = SHA384_IV[0] | 0;\n this.Al = SHA384_IV[1] | 0;\n this.Bh = SHA384_IV[2] | 0;\n this.Bl = SHA384_IV[3] | 0;\n this.Ch = SHA384_IV[4] | 0;\n this.Cl = SHA384_IV[5] | 0;\n this.Dh = SHA384_IV[6] | 0;\n this.Dl = SHA384_IV[7] | 0;\n this.Eh = SHA384_IV[8] | 0;\n this.El = SHA384_IV[9] | 0;\n this.Fh = SHA384_IV[10] | 0;\n this.Fl = SHA384_IV[11] | 0;\n this.Gh = SHA384_IV[12] | 0;\n this.Gl = SHA384_IV[13] | 0;\n this.Hh = SHA384_IV[14] | 0;\n this.Hl = SHA384_IV[15] | 0;\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super(28);\n this.Ah = T224_IV[0] | 0;\n this.Al = T224_IV[1] | 0;\n this.Bh = T224_IV[2] | 0;\n this.Bl = T224_IV[3] | 0;\n this.Ch = T224_IV[4] | 0;\n this.Cl = T224_IV[5] | 0;\n this.Dh = T224_IV[6] | 0;\n this.Dl = T224_IV[7] | 0;\n this.Eh = T224_IV[8] | 0;\n this.El = T224_IV[9] | 0;\n this.Fh = T224_IV[10] | 0;\n this.Fl = T224_IV[11] | 0;\n this.Gh = T224_IV[12] | 0;\n this.Gl = T224_IV[13] | 0;\n this.Hh = T224_IV[14] | 0;\n this.Hl = T224_IV[15] | 0;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super(32);\n this.Ah = T256_IV[0] | 0;\n this.Al = T256_IV[1] | 0;\n this.Bh = T256_IV[2] | 0;\n this.Bl = T256_IV[3] | 0;\n this.Ch = T256_IV[4] | 0;\n this.Cl = T256_IV[5] | 0;\n this.Dh = T256_IV[6] | 0;\n this.Dl = T256_IV[7] | 0;\n this.Eh = T256_IV[8] | 0;\n this.El = T256_IV[9] | 0;\n this.Fh = T256_IV[10] | 0;\n this.Fl = T256_IV[11] | 0;\n this.Gh = T256_IV[12] | 0;\n this.Gl = T256_IV[13] | 0;\n this.Hh = T256_IV[14] | 0;\n this.Hl = T256_IV[15] | 0;\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map", "/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n * @deprecated\n */\nimport { SHA224 as SHA224n, sha224 as sha224n, SHA256 as SHA256n, sha256 as sha256n, } from \"./sha2.js\";\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA256 = SHA256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha256 = sha256n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const SHA224 = SHA224n;\n/** @deprecated Use import from `noble/hashes/sha2` module */\nexport const sha224 = sha224n;\n//# sourceMappingURL=sha256.js.map", "// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n", "import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n", "'use strict';\nimport base58 from 'bs58';\nexport default function (checksumFn) {\n // Encode a buffer as a base58-check encoded string\n function encode(payload) {\n var payloadU8 = Uint8Array.from(payload);\n var checksum = checksumFn(payloadU8);\n var length = payloadU8.length + 4;\n var both = new Uint8Array(length);\n both.set(payloadU8, 0);\n both.set(checksum.subarray(0, 4), payloadU8.length);\n return base58.encode(both);\n }\n function decodeRaw(buffer) {\n var payload = buffer.slice(0, -4);\n var checksum = buffer.slice(-4);\n var newChecksum = checksumFn(payload);\n // eslint-disable-next-line\n if (checksum[0] ^ newChecksum[0] |\n checksum[1] ^ newChecksum[1] |\n checksum[2] ^ newChecksum[2] |\n checksum[3] ^ newChecksum[3])\n return;\n return payload;\n }\n // Decode a base58-check encoded string to a buffer, no result if checksum is wrong\n function decodeUnsafe(str) {\n var buffer = base58.decodeUnsafe(str);\n if (buffer == null)\n return;\n return decodeRaw(buffer);\n }\n function decode(str) {\n var buffer = base58.decode(str);\n var payload = decodeRaw(buffer);\n if (payload == null)\n throw new Error('Invalid checksum');\n return payload;\n }\n return {\n encode: encode,\n decode: decode,\n decodeUnsafe: decodeUnsafe\n };\n}\n", "'use strict';\nimport { sha256 } from '@noble/hashes/sha256';\nimport bs58checkBase from './base.js';\n// SHA256(SHA256(buffer))\nfunction sha256x2(buffer) {\n return sha256(sha256(buffer));\n}\nexport default bs58checkBase(sha256x2);\n", "export const uint8ArrayFromHexString = (hexString) => {\n if (hexString.length % 2 !== 0) {\n throw new Error(\"Hex string must have an even length\");\n }\n const bytes = new Uint8Array(hexString.length / 2);\n for (let i = 0; i < hexString.length; i += 2) {\n bytes[i >> 1] = parseInt(hexString.slice(i, i + 2), 16);\n }\n return bytes;\n};\nexport const uint8ArrayToHexString = (data) => {\n return Array.from(data, byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n};\n//# sourceMappingURL=bufferFromHex.js.map", "/**\n * Symbol used as discriminator for segments to avoid collision with user data.\n * Users might have objects with a 'kind' property in id patterns.\n */\nexport const KIND = \"AUTOMERGE_REF_KIND\";\n/**\n * Symbol to mark a cursor request for stabilization during sub-handle creation.\n */\nexport const CURSOR_MARKER = \"AUTOMERGE_REF_CURSOR_MARKER\";\n//# sourceMappingURL=types.js.map", "import { KIND } from \"./types.js\";\n/**\n * # Path Segment Encoding Scheme\n *\n * | Type | Format | Example | Notes |\n * |---------|---------------------|----------------------------|---------------------------------|\n * | Key | string | `foo`, `my%2Fkey` | Default, URL-encoded |\n * | Index | `@` + number | `@0`, `@42` | Array index |\n * | Match | `{...}` | `{\"id\":\"alice\"}` | JSON object pattern (URL-encoded) |\n * | Cursors | `[start-end]` | `[2@abc-5@def]` | Cursor range |\n * | Cursors | `[cursor]` | `[2@abc]` | Collapsed (start === end) |\n *\n * ## Escape Rule\n * If a key starts with `@`, `{`, `[`, or `\\`, prefix with `\\` (URL-encoded as `%5C`):\n * - `\\@at` → key \"@at\" (appears as `%5C%40at` in URL)\n * - `\\{brace` → key \"{brace\" (appears as `%5C%7Bbrace` in URL)\n * - `\\\\backslash` → key \"\\backslash\" (appears as `%5C%5Cbackslash` in URL)\n *\n * ## Parsing Priority (first match wins)\n * 1. Index: `@` + digits\n * 2. Match: `{...}` or URL-encoded `%7B...`\n * 3. Cursors: `[...]`\n * 4. Key: `\\...` (escaped, URL-encoded as `%5C...`) or anything else\n */\n/** The escape character (backslash) */\nconst ESCAPE_CHAR = \"\\\\\";\n/** URL-encoded form of the escape character for matching in URLs */\nconst ESCAPE_PREFIX = \"%5C\";\nconst INDEX_PREFIX = \"@\";\nconst CURSOR_OPEN = \"[\";\nconst CURSOR_CLOSE = \"]\";\nconst CURSOR_SEPARATOR = \"-\";\n/** Characters that trigger escaping when at the start of a key */\nconst ESCAPE_TRIGGERS = [ESCAPE_CHAR, INDEX_PREFIX, \"{\", CURSOR_OPEN];\nconst INDEX_PATTERN = /^@(\\d+)$/;\nconst indexCodec = {\n kind: \"index\",\n match: s => INDEX_PATTERN.test(s),\n parse: s => {\n const m = s.match(INDEX_PATTERN);\n if (!m)\n throw new Error(`Invalid index: ${s}`);\n return { [KIND]: \"index\", index: parseInt(m[1], 10) };\n },\n serialize: seg => `${INDEX_PREFIX}${seg.index}`,\n};\nconst matchCodec = {\n kind: \"match\",\n // Match both raw JSON and URL-encoded JSON\n match: s => s.startsWith(\"{\") || s.startsWith(\"%7B\"),\n parse: s => {\n try {\n // Decode URL encoding first, then parse JSON\n // This handles both URL-encoded and raw JSON formats\n const decoded = decodeURIComponent(s);\n const parsed = JSON.parse(decoded);\n if (typeof parsed !== \"object\" ||\n parsed === null ||\n Array.isArray(parsed)) {\n throw new Error(\"Match pattern must be a plain object\");\n }\n return { [KIND]: \"match\", match: parsed };\n }\n catch (e) {\n throw new Error(`Invalid match pattern: ${s}. ${e instanceof Error ? e.message : \"\"}`);\n }\n },\n // Serialize with sorted keys so `{a:1,b:2}` and `{b:2,a:1}` produce\n // identical URLs (they're semantically the same pattern). Also URL-\n // encode the JSON to protect `/` and other path-significant chars.\n serialize: seg => encodeURIComponent(JSON.stringify(Object.fromEntries(Object.keys(seg.match)\n .sort()\n .map(k => [k, seg.match[k]])))),\n};\nconst cursorsCodec = {\n kind: \"cursors\",\n match: s => s.startsWith(CURSOR_OPEN) && s.endsWith(CURSOR_CLOSE),\n parse: s => {\n const inner = s.slice(1, -1);\n if (!inner) {\n throw new Error(\"Invalid cursor range: empty brackets\");\n }\n const sepIndex = inner.indexOf(CURSOR_SEPARATOR);\n if (sepIndex === -1) {\n const cursor = inner;\n return { [KIND]: \"cursors\", start: cursor, end: cursor };\n }\n const start = inner.slice(0, sepIndex);\n const end = inner.slice(sepIndex + 1);\n if (!start || !end) {\n throw new Error(`Invalid cursor range: ${s}. Expected format: [cursor] or [start-end]`);\n }\n return { [KIND]: \"cursors\", start, end };\n },\n serialize: seg => {\n if (seg.start === seg.end) {\n return `${CURSOR_OPEN}${seg.start}${CURSOR_CLOSE}`;\n }\n return `${CURSOR_OPEN}${seg.start}${CURSOR_SEPARATOR}${seg.end}${CURSOR_CLOSE}`;\n },\n};\nconst keyCodec = {\n kind: \"key\",\n match: s => {\n // Escaped keys start with backslash (URL-encoded as %5C)\n if (s.startsWith(ESCAPE_PREFIX) || s.startsWith(ESCAPE_CHAR)) {\n return true;\n }\n // Regular keys don't start with special prefixes\n // We need to check both raw and URL-decoded forms\n const decoded = safeDecodeURIComponent(s);\n return !ESCAPE_TRIGGERS.some(p => s.startsWith(p) || decoded.startsWith(p));\n },\n parse: s => {\n // Check for URL-encoded escape prefix (%5C) or literal backslash\n if (s.startsWith(ESCAPE_PREFIX)) {\n return {\n [KIND]: \"key\",\n key: decodeURIComponent(s.slice(ESCAPE_PREFIX.length)),\n };\n }\n if (s.startsWith(ESCAPE_CHAR)) {\n return {\n [KIND]: \"key\",\n key: decodeURIComponent(s.slice(ESCAPE_CHAR.length)),\n };\n }\n return { [KIND]: \"key\", key: decodeURIComponent(s) };\n },\n serialize: seg => {\n // Empty keys don't round-trip through a slash-delimited URL path.\n if (seg.key === \"\") {\n throw new Error(\"Path keys cannot be empty strings\");\n }\n // Check if key starts with any character that needs escaping\n const needsEscape = ESCAPE_TRIGGERS.some(p => seg.key.startsWith(p));\n const encoded = encodeURIComponent(seg.key);\n // Prefix with URL-encoded backslash (%5C) if escape needed\n return needsEscape ? `${ESCAPE_PREFIX}${encoded}` : encoded;\n },\n};\n/** Safely decode URI component, returning original string on error */\nfunction safeDecodeURIComponent(s) {\n try {\n return decodeURIComponent(s);\n }\n catch {\n return s;\n }\n}\n/**\n * Codecs in priority order. First matching codec wins for parsing.\n * Order: index → match → cursors → key (key is catch-all, must be last)\n */\nconst SEGMENT_CODECS = [indexCodec, matchCodec, cursorsCodec, keyCodec];\nexport function parseSegment(segment) {\n for (const codec of SEGMENT_CODECS) {\n if (codec.match(segment)) {\n return codec.parse(segment);\n }\n }\n throw new Error(`Invalid segment: \"${segment}\"`);\n}\n// ⇧ Parse --- Serialize ⇩\nexport function serializeSegment(segment) {\n for (const codec of SEGMENT_CODECS) {\n if (segment[KIND] === codec.kind) {\n return codec.serialize(segment);\n }\n }\n throw new Error(`No codec found for segment kind: ${segment[KIND]}`);\n}\nexport function parsePath(path) {\n if (!path)\n return [];\n const trimmed = path.replace(/^\\/+|\\/+$/g, \"\");\n if (!trimmed) {\n throw new Error(\"Invalid path: path cannot be empty or consist only of slashes\");\n }\n if (trimmed.includes(\"//\")) {\n throw new Error(\"Invalid path: contains empty segment (double slash)\");\n }\n return trimmed.split(\"/\").map(parseSegment);\n}\n// ⇧ Parse --- Serialize ⇩\nexport function serializePath(segments) {\n return segments.map(serializeSegment).join(\"/\");\n}\n//# sourceMappingURL=parser.js.map", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n", "/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n", "import debug from \"debug\";\n// `.debug` is routed through the `debug` package for namespace-based filtering\n// via `DEBUG=automerge-repo:*`; the rest go straight to `console`.\nconst defaultFactory = namespace => {\n const trace = debug(namespace);\n const prefix = `[${namespace}]`;\n return {\n debug: (message, ...args) => trace(message, ...args),\n info: (message, ...args) => console.info(prefix, message, ...args),\n warn: (message, ...args) => console.warn(prefix, message, ...args),\n error: (message, ...args) => console.error(prefix, message, ...args),\n };\n};\nlet factory = defaultFactory;\n/**\n * Replace the global logger factory. All subsequent {@link makeLogger} calls use it.\n *\n * Call once at startup to route automerge-repo output through your own logger.\n * The factory receives a namespace such as `automerge-repo:repo` or\n * `automerge-repo:docsync:abc12` for each subsystem instance.\n *\n * @example\n * ```ts\n * import { setLoggerFactory } from \"@automerge/automerge-repo\"\n * import winston from \"winston\"\n *\n * const logger = winston.createLogger({ ... })\n *\n * setLoggerFactory(namespace => ({\n * debug: (msg, ...args) => logger.debug(msg, { namespace, args }),\n * info: (msg, ...args) => logger.info(msg, { namespace, args }),\n * warn: (msg, ...args) => logger.warn(msg, { namespace, args }),\n * error: (msg, ...args) => logger.error(msg, { namespace, args }),\n * }))\n * ```\n */\nexport function setLoggerFactory(f) {\n factory = f;\n}\n/** Restore the built-in logger factory (mainly for tests). */\nexport function resetLoggerFactory() {\n factory = defaultFactory;\n}\n/**\n * Returns a {@link Logger} for `namespace` that delegates to whichever factory\n * is current at the time each method is called. The factory is consulted on\n * every call so that consumers can replace it (via {@link setLoggerFactory})\n * after the library's modules have already been imported.\n */\nexport function makeLogger(namespace) {\n return {\n debug: (message, ...args) => factory(namespace).debug(message, ...args),\n info: (message, ...args) => factory(namespace).info(message, ...args),\n warn: (message, ...args) => factory(namespace).warn(message, ...args),\n error: (message, ...args) => factory(namespace).error(message, ...args),\n };\n}\n//# sourceMappingURL=Logger.js.map", "import * as Uuid from \"uuid\";\nimport bs58check from \"bs58check\";\nimport { uint8ArrayFromHexString, uint8ArrayToHexString, } from \"./helpers/bufferFromHex.js\";\nimport { parsePath, serializePath } from \"./subdoc-handles/parser.js\";\nimport { makeLogger } from \"./Logger.js\";\nconst log = makeLogger(\"automerge-repo:url\");\nexport const urlPrefix = \"automerge:\";\n/**\n * Parse an Automerge URL.\n *\n * Supported shapes:\n * - `automerge:<docId>`\n * - `automerge:<docId>#<heads>` (heads `|`-joined)\n * - `automerge:<docId>/<path>` (path `/`-joined segments)\n * - `automerge:<docId>/<path>#<heads>`\n *\n * `segments` is undefined when no path is present; otherwise it's the\n * parsed `Segment[]`.\n */\nexport const parseAutomergeUrl = (url) => {\n const [baseUrl, headsSection, ...rest] = url.split(\"#\");\n if (rest.length > 0) {\n throw new Error(\"Invalid URL: contains multiple heads sections\");\n }\n const match = baseUrl.match(new RegExp(`^${urlPrefix}([^/]+)(?:\\\\/(.*))?$`));\n if (!match)\n throw new Error(\"Invalid document URL: \" + url);\n const [, docMatch, pathStr] = match;\n const documentId = docMatch;\n const binaryDocumentId = documentIdToBinary(documentId);\n if (!binaryDocumentId)\n throw new Error(\"Invalid document URL: \" + url);\n const segments = pathStr !== undefined && pathStr.length > 0 ? parsePath(pathStr) : undefined;\n if (headsSection === undefined) {\n return segments\n ? { binaryDocumentId, documentId, segments }\n : { binaryDocumentId, documentId };\n }\n const heads = (headsSection === \"\" ? [] : headsSection.split(\"|\"));\n const hexHeads = heads.map(head => {\n try {\n return uint8ArrayToHexString(bs58check.decode(head));\n }\n catch (e) {\n throw new Error(`Invalid head in URL: ${head}`);\n }\n });\n return segments\n ? { binaryDocumentId, hexHeads, documentId, heads, segments }\n : { binaryDocumentId, hexHeads, documentId, heads };\n};\n/**\n * Given a documentId in either binary or base58check-encoded form, returns\n * an Automerge URL. Optionally accepts `segments` to construct a sub-tree\n * URL (`automerge:<docId>/seg/seg/...`) and `heads` to pin the URL to a\n * point in time. Throws on invalid input.\n */\nexport const stringifyAutomergeUrl = (arg) => {\n if (arg instanceof Uint8Array || typeof arg === \"string\") {\n return (urlPrefix +\n (arg instanceof Uint8Array\n ? binaryToDocumentId(arg)\n : arg));\n }\n const { documentId, heads = undefined, segments = undefined } = arg;\n if (documentId === undefined)\n throw new Error(\"Invalid documentId: \" + documentId);\n const encodedDocumentId = documentId instanceof Uint8Array\n ? binaryToDocumentId(documentId)\n : documentId;\n let url = `${urlPrefix}${encodedDocumentId}`;\n if (segments !== undefined && segments.length > 0) {\n url += \"/\" + serializePath(segments);\n }\n if (heads !== undefined) {\n heads.forEach(head => {\n try {\n bs58check.decode(head);\n }\n catch (e) {\n throw new Error(`Invalid head: ${head}`);\n }\n });\n // Sort so two heads arrays with the same content in different\n // orders produce identical URLs.\n url += \"#\" + [...heads].sort().join(\"|\");\n }\n return url;\n};\n/** Helper to extract just the heads from a URL if they exist */\nexport const getHeadsFromUrl = (url) => {\n const { heads } = parseAutomergeUrl(url);\n return heads;\n};\nexport const anyDocumentIdToAutomergeUrl = (id) => isValidAutomergeUrl(id)\n ? id\n : isValidDocumentId(id)\n ? stringifyAutomergeUrl({ documentId: id })\n : isValidUuid(id)\n ? parseLegacyUUID(id)\n : undefined;\n/**\n * Given a string, returns true if it is a valid Automerge URL. This function also acts as a type\n * discriminator in Typescript.\n */\nexport const isValidAutomergeUrl = (str) => {\n if (typeof str !== \"string\" || !str || !str.startsWith(urlPrefix))\n return false;\n try {\n const { documentId, heads } = parseAutomergeUrl(str);\n if (!isValidDocumentId(documentId))\n return false;\n if (heads &&\n !heads.every(head => {\n try {\n bs58check.decode(head);\n return true;\n }\n catch {\n return false;\n }\n }))\n return false;\n return true;\n }\n catch {\n return false;\n }\n};\nexport const isValidDocumentId = (str) => {\n if (typeof str !== \"string\")\n return false;\n // try to decode from base58\n const binaryDocumentID = documentIdToBinary(str);\n return binaryDocumentID !== undefined;\n};\nexport const isValidUuid = (str) => typeof str === \"string\" && Uuid.validate(str);\n/**\n * Returns a new Automerge URL with a random UUID documentId. Called by Repo.create(), and also used by tests.\n */\nexport const generateAutomergeUrl = () => {\n const documentId = Uuid.v4(undefined, new Uint8Array(16));\n return stringifyAutomergeUrl({ documentId });\n};\nexport const documentIdToBinary = (docId) => bs58check.decodeUnsafe(docId);\nexport const binaryToDocumentId = (docId) => bs58check.encode(docId);\nexport const encodeHeads = (heads) => heads.map(h => bs58check.encode(uint8ArrayFromHexString(h)));\nexport const decodeHeads = (heads) => heads.map(h => uint8ArrayToHexString(bs58check.decode(h)));\nexport const parseLegacyUUID = (str) => {\n if (!Uuid.validate(str))\n return undefined;\n const documentId = Uuid.parse(str);\n return stringifyAutomergeUrl({ documentId });\n};\n/**\n * Given any valid expression of a document ID, returns a DocumentId in base58check-encoded form.\n *\n * Currently supports:\n * - base58check-encoded DocumentId\n * - Automerge URL\n * - legacy UUID\n * - binary DocumentId\n *\n * Throws on invalid input.\n */\nexport const interpretAsDocumentId = (id) => {\n // binary\n if (id instanceof Uint8Array)\n return binaryToDocumentId(id);\n // url\n if (isValidAutomergeUrl(id))\n return parseAutomergeUrl(id).documentId;\n // base58check\n if (isValidDocumentId(id))\n return id;\n // legacy UUID\n if (isValidUuid(id)) {\n log.warn(\"Future versions will not support UUIDs as document IDs; use Automerge URLs instead.\");\n const binaryDocumentID = Uuid.parse(id);\n return binaryToDocumentId(binaryDocumentID);\n }\n // none of the above\n throw new Error(`Invalid AutomergeUrl: '${id}'`);\n};\n//# sourceMappingURL=AutomergeUrl.js.map", "import { AnyDocumentId, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { useRepo } from \"./useRepo.js\"\nimport { useEffect, useRef, useState } from \"react\"\nimport { anyDocumentIdToAutomergeUrl } from \"../../automerge-repo/dist/AutomergeUrl.js\"\n\n// Shared with useDocHandles\nexport const wrapperCache = new Map<\n AnyDocumentId,\n PromiseWrapper<DocHandle<any>>\n>()\n// NB: this is a global cache that isn't keyed on the Repo\n// so if your app uses the same documents in two Repos\n// this could cause problems. please let me know if you do.\n\nexport interface UseDocHandleSuspendingParams {\n suspense: true\n}\nexport interface UseDocHandleSynchronousParams {\n suspense: false\n}\n\ntype UseDocHandleParams =\n | UseDocHandleSuspendingParams\n | UseDocHandleSynchronousParams\n\nexport function useDocHandle<T>(\n id: AnyDocumentId,\n params: UseDocHandleSuspendingParams\n): DocHandle<T>\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocHandleSynchronousParams\n): DocHandle<T> | undefined\nexport function useDocHandle<T>(\n id: AnyDocumentId | undefined,\n { suspense }: UseDocHandleParams = { suspense: false }\n): DocHandle<T> | undefined {\n const repo = useRepo()\n const controllerRef = useRef<AbortController | undefined>(undefined)\n const [handle, setHandle] = useState<DocHandle<T> | undefined>()\n\n let currentHandle: DocHandle<T> | undefined =\n // make sure the handle matches the id\n id && handle && handle.url === anyDocumentIdToAutomergeUrl(id)\n ? handle\n : undefined\n\n if (id && !currentHandle) {\n // if we haven't saved a handle yet, check if one is immediately available\n const progress = repo.findWithProgress<T>(id)\n const state = progress.peek()\n if (state.state === \"ready\") {\n currentHandle = state.handle\n }\n }\n\n let wrapper = id ? wrapperCache.get(id) : undefined\n if (!wrapper && id) {\n controllerRef.current?.abort()\n controllerRef.current = new AbortController()\n\n const promise = repo.find<T>(id, { signal: controllerRef.current.signal })\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n }\n\n /* From here we split into two paths: suspense and not.\n * In the suspense path, we return the wrapper directly.\n * In the non-suspense path, we wait for the promise to resolve\n * and then set the handle via setState. Suspense relies on\n * re-running this function until it succeeds, whereas the synchronous\n * form uses a setState to track the value. */\n useEffect(() => {\n if (currentHandle || suspense || !wrapper) {\n return\n }\n // Stays true until this effect run is torn down (unmount or id change); a\n // result that arrives after that must not setState for a stale id.\n let active = true\n wrapper.promise\n .then(handle => {\n if (active) setHandle(handle as DocHandle<T>)\n })\n .catch(() => {\n // Drop the failed wrapper so a later render retries instead of reusing\n // the rejection.\n if (id && wrapperCache.get(id) === wrapper) {\n wrapperCache.delete(id)\n }\n if (active) setHandle(undefined)\n })\n return () => {\n active = false\n }\n }, [currentHandle, suspense, wrapper, id])\n\n if (currentHandle || !suspense || !wrapper) {\n return currentHandle\n }\n\n return wrapper.read() as DocHandle<T>\n}\n", "import { AnyDocumentId } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandle } from \"./useDocHandle.js\"\n\n/**\n * A hook which returns a document and a function to change it.\n * Uses React Suspense for loading states, returning a tuple matching useState pattern.\n *\n * @example\n * ```tsx\n * function Counter() {\n * const [doc, changeDoc] = useDocument<{ count: number }>(docUrl)\n * return (\n * <button onClick={() => changeDoc(d => d.count++)}>\n * Count: {doc.count}\n * </button>\n * )\n * }\n *\n * // Must be wrapped in Suspense boundary\n * <Suspense fallback={<Loading />}>\n * <Counter />\n * </Suspense>\n * ```\n */\n\nexport interface UseDocumentSuspendingParams {\n suspense: true\n}\nexport interface UseDocumentSynchronousParams {\n suspense: false\n}\n\ntype UseDocumentParams =\n | UseDocumentSuspendingParams\n | UseDocumentSynchronousParams\n\nexport type UseDocumentReturn<T> = [\n Doc<T>,\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => void,\n]\n\nexport function useDocument<T>(\n id: AnyDocumentId,\n params: UseDocumentSuspendingParams\n): UseDocumentReturn<T>\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params?: UseDocumentSynchronousParams\n): UseDocumentReturn<T> | [undefined, () => void]\nexport function useDocument<T>(\n id: AnyDocumentId | undefined,\n params: UseDocumentParams = { suspense: false }\n): UseDocumentReturn<T> | [undefined, () => void] {\n // @ts-expect-error -- typescript doesn't realize we're discriminating these types the same way in both functions\n const handle = useDocHandle<T>(id, params)\n // Initialize with current doc state\n const [doc, setDoc] = useState<Doc<T> | undefined>(() => handle?.doc())\n const [deleteError, setDeleteError] = useState<Error>()\n\n // Reinitialize doc when handle changes\n useEffect(() => {\n setDoc(handle?.doc())\n }, [handle])\n\n useEffect(() => {\n if (!handle) {\n return\n }\n const onChange = () => setDoc(handle.doc())\n const onDelete = () => {\n setDeleteError(new Error(`Document ${id} was deleted`))\n }\n\n handle.on(\"change\", onChange)\n handle.on(\"delete\", onDelete)\n\n return () => {\n handle.removeListener(\"change\", onChange)\n handle.removeListener(\"delete\", onDelete)\n }\n }, [handle, id])\n\n const changeDoc = useCallback(\n (changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n handle!.change(changeFn, options)\n },\n [handle]\n )\n\n if (deleteError) {\n throw deleteError\n }\n\n if (!doc) {\n return [undefined, () => {}]\n }\n return [doc, changeDoc]\n}\n", "import { useEffect, useState } from \"react\"\n\nexport function useSet<T>(items: T[]): Set<T> {\n const [set, setSet] = useState<Set<T>>(() => {\n return new Set<T>(items)\n })\n useEffect(() => {\n const newSet = new Set(items)\n if (identical(set, newSet)) {\n return\n }\n setSet(newSet)\n }, [set, items])\n return set\n}\n\nfunction identical<T>(s1: Set<T>, s2: Set<T>) {\n return s1.size === s2.size && Array.from(s1).every(v => s2.has(v))\n}\n", "import { AutomergeUrl, DocHandle } from \"@automerge/automerge-repo/slim\"\nimport { useState, useEffect } from \"react\"\nimport { useRepo } from \"./useRepo.js\"\nimport { PromiseWrapper, wrapPromise } from \"./wrapPromise.js\"\nimport { wrapperCache } from \"./useDocHandle.js\"\nimport { useSet } from \"./helpers/useSet.js\"\n\nexport interface UseDocHandlesParams {\n suspense?: boolean\n}\n\nexport type DocHandleMap<T> = Map<AutomergeUrl, DocHandle<T> | undefined>\n\nexport function useDocHandles<T>(\n ids: AutomergeUrl[],\n { suspense = false }: UseDocHandlesParams = {}\n): DocHandleMap<T> {\n const idSet = useSet(ids)\n const repo = useRepo()\n const [handleMap, setHandleMap] = useState<DocHandleMap<T>>(() => {\n const map = new Map()\n\n // Initialize the map with any handles that are ready\n for (const id of idSet.values()) {\n let progress\n try {\n progress = repo.findWithProgress<T>(id)\n } catch (e) {\n continue\n }\n\n const state = progress.peek()\n if (state.state === \"ready\") {\n map.set(id, state.handle)\n }\n }\n\n return map\n })\n\n const pendingPromises: PromiseWrapper<DocHandle<T>>[] = []\n const nextHandleMap = new Map<AutomergeUrl, DocHandle<T> | undefined>()\n\n // Check if we need any new wrappers\n for (const id of idSet.values()) {\n let handle = handleMap.get(id)\n let wrapper = wrapperCache.get(id)\n if (!wrapper) {\n try {\n const promise = repo.find<T>(id)\n wrapper = wrapPromise(promise)\n wrapperCache.set(id, wrapper)\n } catch (e) {\n continue\n }\n }\n\n // Try to read each wrapper.\n // Update handleMap with any available handles,\n // and collect any pending promises\n try {\n handle ??= wrapper.read() as DocHandle<T>\n nextHandleMap.set(id, handle)\n } catch (e) {\n if (e instanceof Promise) {\n pendingPromises.push(wrapper as PromiseWrapper<DocHandle<T>>)\n } else {\n nextHandleMap.set(id, undefined)\n }\n }\n }\n\n // Suspense is handled quasi-synchronously below by throwing if we still have\n // unresolved promises.\n useEffect(() => {\n // Stays true until this effect run is torn down; if idSet changes (or we\n // unmount) before these finds settle, the now-stale map must not overwrite\n // a newer one.\n let active = true\n if (pendingPromises.length > 0) {\n void Promise.allSettled(pendingPromises.map(p => p.promise)).then(\n handles => {\n if (!active) return\n handles.forEach(r => {\n if (r.status === \"fulfilled\") {\n const h = r.value as DocHandle<T>\n nextHandleMap.set(h.url, h)\n }\n })\n setHandleMap(nextHandleMap)\n }\n )\n } else {\n setHandleMap(nextHandleMap)\n }\n return () => {\n active = false\n }\n }, [suspense, idSet])\n\n // If any promises are pending, suspend with Promise.all\n // Note that this behaviour is different from the synchronous\n // form where we get gradual load-in of child documents.\n // I couldn't find an obvious way of incremental loading with\n // a single hook for suspense.\n // (But maybe with suspense this hook is less useful?)\n if (suspense && pendingPromises.length > 0) {\n throw Promise.all(pendingPromises.map(p => p.promise))\n }\n\n return handleMap\n}\n", "import { AutomergeUrl } from \"@automerge/automerge-repo/slim\"\nimport { ChangeFn, ChangeOptions, Doc } from \"@automerge/automerge/slim\"\nimport { useCallback, useEffect, useState } from \"react\"\nimport { useDocHandles } from \"./useDocHandles.js\"\n\nexport type DocMap<T> = Map<AutomergeUrl, Doc<T>>\nexport type ChangeDocFn<T> = (\n id: AutomergeUrl,\n changeFn: ChangeFn<T>,\n options?: ChangeOptions<T>\n) => void\n\nexport interface UseDocumentsOptions {\n suspense?: boolean\n}\n\nexport function useDocuments<T>(\n ids: AutomergeUrl[],\n { suspense = true }: UseDocumentsOptions = {}\n): [DocMap<T>, ChangeDocFn<T>] {\n const handleMap = useDocHandles<T>(ids, { suspense })\n const [docMap, setDocMap] = useState<DocMap<T>>(() => {\n const docs: DocMap<T> = new Map()\n handleMap.forEach(handle => {\n const url = handle?.url\n if (url) {\n docs.set(url, handle?.doc() as Doc<T>)\n }\n })\n return docs\n })\n\n useEffect(() => {\n const listeners = new Map<AutomergeUrl, () => void>()\n\n handleMap.forEach((handle, id) => {\n if (handle) {\n const onChange = () => {\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc() as Doc<T>)\n return next\n })\n }\n\n // Initial state\n setDocMap(prev => {\n const next = new Map(prev)\n next.set(id, handle.doc() as Doc<T>)\n return next\n })\n\n handle.on(\"change\", onChange)\n listeners.set(id, onChange)\n }\n })\n\n // Clear docs that are no longer in handleMap\n setDocMap(prev => {\n const next = new Map(prev)\n for (const [id] of next) {\n if (!handleMap.has(id)) {\n next.delete(id)\n }\n }\n return next\n })\n\n return () => {\n handleMap.forEach((handle, id) => {\n const listener = listeners.get(id)\n if (handle && listener) {\n handle.removeListener(\"change\", listener)\n }\n })\n }\n }, [handleMap])\n\n const changeDoc = useCallback(\n (id: AutomergeUrl, changeFn: ChangeFn<T>, options?: ChangeOptions<T>) => {\n const handle = handleMap.get(id)\n if (handle) {\n handle.change(changeFn, options)\n }\n },\n [handleMap]\n )\n\n return [docMap, changeDoc]\n}\n", "import {\n type Dispatch,\n type MutableRefObject,\n type SetStateAction,\n useCallback,\n useRef,\n useState,\n} from \"react\"\n\n/**\n * Like `useState`, but also returns a ref whose `.current` is updated\n * synchronously inside the setter — so callbacks can read the latest value\n * without waiting for a re-render.\n *\n * @privateRemarks\n * Not idiomatic — a stale-closure workaround, inlined (ESM) to replace the\n * CommonJS `react-usestateref` dependency, which does not bundle cleanly for\n * ESM/browser consumers. Used only by the two `@deprecated` awareness hooks\n * (`useLocalAwareness`/`useRemoteAwareness`); the replacement `usePresence` hook\n * does not use it. Prefer eliminating it: rewrite those hooks to use functional\n * state updaters for read-modify-write updates, and a plain ref synced in an\n * effect (or `useEffectEvent`) for reads inside long-lived callbacks — then\n * delete this helper.\n */\nexport function useStateRef<S>(\n initialState: S | (() => S)\n): [S, Dispatch<SetStateAction<S>>, MutableRefObject<S>] {\n const [state, setState] = useState(initialState)\n const ref = useRef(state)\n const dispatch = useCallback<Dispatch<SetStateAction<S>>>(setStateAction => {\n ref.current =\n typeof setStateAction === \"function\"\n ? (setStateAction as (prev: S) => S)(ref.current)\n : setStateAction\n setState(ref.current)\n }, [])\n return [state, dispatch, ref]\n}\n\nexport default useStateRef\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n", "import EventEmitter from './index.js'\n\nexport { EventEmitter }\nexport default EventEmitter\n", "import {\n DocHandle,\n DocHandleEphemeralMessagePayload,\n} from \"@automerge/automerge-repo/slim\"\nimport { useEffect } from \"react\"\nimport useStateRef from \"./useStateRef.js\"\nimport { EventEmitter } from \"eventemitter3\"\n\n// Emits new_peer event when a new peer is seen\nexport const peerEvents = new EventEmitter()\n\nexport interface UseRemoteAwarenessProps<T> {\n /** The handle to receive ephemeral state on */\n handle?: DocHandle<T>\n /** Our user ID */\n localUserId?: string\n /** How long to wait (in ms) before marking a peer as offline */\n offlineTimeout?: number\n /** Function to provide current epoch time */\n getTime?: () => number\n}\n\n/** A map from peer ID to their state */\nexport type PeerStates = Record<string, any>\n/** A map from peer ID to their last heartbeat timestamp */\nexport type Heartbeats = Record<string, number>\n\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook returns read-only state for remote clients.\n * It also returns their heartbeat status.\n * It is intended to be used alongside useLocalAwareness.\n *\n * @returns [ peerStates: { [userId]: state, ... }, { [userId]: heartbeatEpochTime, ...} ]\n */\nexport const useRemoteAwareness = <T>({\n handle,\n localUserId,\n offlineTimeout = 30000,\n getTime = () => new Date().getTime(),\n}: UseRemoteAwarenessProps<T>): [PeerStates, Heartbeats] => {\n // TODO: You should be able to use multiple instances of this hook on the same handle (write test)\n // TODO: This should support some kind of caching or memoization when switching between channelIDs\n const [peerStates, setPeerStates, peerStatesRef] = useStateRef<PeerStates>({})\n const [heartbeats, setHeartbeats, heartbeatsRef] = useStateRef<Heartbeats>({})\n useEffect(() => {\n if (!handle) {\n return\n }\n\n // Receive incoming message\n const handleIncomingUpdate = (\n event: DocHandleEphemeralMessagePayload<T>\n ) => {\n const [userId, state] = event.message as [string, unknown]\n if (userId === localUserId) return\n if (!heartbeatsRef.current[userId]) peerEvents.emit(\"new_peer\", event) // Let useLocalAwareness know we've seen a new peer\n setPeerStates({\n ...peerStatesRef.current,\n [userId]: state,\n })\n setHeartbeats({\n ...heartbeatsRef.current,\n [userId]: getTime(),\n })\n }\n // Remove peers we haven't seen recently\n const pruneOfflinePeers = () => {\n const peerStates = { ...peerStatesRef.current }\n const heartbeats = { ...heartbeatsRef.current }\n const time = getTime()\n let hasChanges = false\n for (const key in heartbeats) {\n if (time - heartbeats[key] > offlineTimeout) {\n delete peerStates[key]\n delete heartbeats[key]\n hasChanges = true\n }\n }\n if (hasChanges) {\n setPeerStates(peerStates)\n setHeartbeats(heartbeats)\n }\n }\n handle.on(\"ephemeral-message\", handleIncomingUpdate)\n // Check for offline peers every `offlineTimeout` ms\n const pruneOfflinePeersIntervalId = setInterval(\n pruneOfflinePeers,\n offlineTimeout\n )\n return () => {\n handle.removeListener(\"ephemeral-message\", handleIncomingUpdate)\n clearInterval(pruneOfflinePeersIntervalId)\n }\n }, [handle, localUserId, offlineTimeout, getTime])\n\n return [peerStates, heartbeats]\n}\n", "import { useEffect } from \"react\"\nimport useStateRef from \"./useStateRef.js\"\nimport { peerEvents } from \"./useRemoteAwareness.js\"\nimport { DocHandle } from \"@automerge/automerge-repo/slim\"\n\nexport interface UseLocalAwarenessProps {\n /** The document handle to send ephemeral state on */\n handle?: DocHandle<unknown>\n /** Our user ID **/\n userId: string\n /** The initial state object/primitive we should advertise */\n initialState: any\n /** How frequently to send heartbeats */\n heartbeatTime?: number\n}\n/**\n * @deprecated use the usePresence hook instead\n *\n * This hook maintains state for the local client.\n * Like React.useState, it returns a [state, setState] array.\n * It is intended to be used alongside useRemoteAwareness.\n *\n * When state is changed it is broadcast to all clients.\n * It also broadcasts a heartbeat to let other clients know it is online.\n *\n * Note that userIds aren't secure (yet). Any client can lie about theirs.\n *\n * @returns [state, setState]\n */\nexport const useLocalAwareness = ({\n handle,\n userId,\n initialState,\n heartbeatTime = 15000,\n}: UseLocalAwarenessProps) => {\n const [localState, setLocalState, localStateRef] = useStateRef(initialState)\n\n const setState = (stateOrUpdater: any) => {\n const state =\n typeof stateOrUpdater === \"function\"\n ? stateOrUpdater(localStateRef.current)\n : stateOrUpdater\n setLocalState(state)\n // TODO: Send deltas instead of entire state\n if (handle) {\n handle.broadcast([userId, state])\n }\n }\n\n useEffect(() => {\n // Don't broadcast if userId or handle isn't set: this avoids bogus broadcasts\n // during the loading of a userId document or handle.\n if (!userId || !handle) {\n return\n }\n\n // Send periodic heartbeats\n const heartbeat = () =>\n void handle.broadcast([userId, localStateRef.current])\n heartbeat() // Initial heartbeat\n // TODO: we don't need to send a heartbeat if we've changed state recently; use recursive setTimeout instead of setInterval\n const heartbeatIntervalId = setInterval(heartbeat, heartbeatTime)\n return () => void clearInterval(heartbeatIntervalId)\n }, [handle, userId, heartbeatTime])\n\n useEffect(() => {\n // Send entire state to new peers\n if (!handle || !userId) {\n return\n }\n\n let broadcastTimeoutId: ReturnType<typeof setTimeout>\n const newPeerEvents = peerEvents.on(\"new_peer\", () => {\n broadcastTimeoutId = setTimeout(\n () => handle.broadcast([userId, localStateRef.current]),\n 500 // Wait for the peer to be ready\n )\n })\n return () => {\n newPeerEvents.off(\"new_peer\")\n broadcastTimeoutId && clearTimeout(broadcastTimeoutId)\n }\n }, [handle, userId, peerEvents])\n\n // TODO: Send an \"offline\" message on unmount\n // useEffect(\n // () => () => void handle.broadcast(null), // Same as Yjs awareness\n // []\n // );\n\n return [localState, setState]\n}\n", "import { useCallback, useEffect, useRef, useState } from \"react\"\n\nimport {\n Presence,\n PresenceConfig,\n DocHandle,\n PeerStateView,\n PresenceState,\n} from \"@automerge/automerge-repo/slim\"\n\nexport type UsePresenceConfig<State extends PresenceState> =\n PresenceConfig<State> & {\n handle: DocHandle<unknown>\n }\n\nexport type UsePresenceResult<State extends PresenceState> = {\n /**\n * Presence view of our peers.\n */\n peerStates: PeerStateView<State>\n /**\n * Our own presence state, as last set by `update` or the initial value.\n */\n localState: State | undefined\n /**\n * Update our presence state for the given channel and broadcast\n * it to our peers.\n *\n * @param channel\n * @param value\n */\n update: <Channel extends keyof State>(\n channel: Channel,\n value: State[Channel]\n ) => void\n /**\n * Resume presence broadcasting and listening to peer presence.\n *\n * Note that this only needs to be called after `stop` has been called:\n * usePresence starts running immediately.\n */\n start: (config?: Partial<PresenceConfig<State>>) => void\n /**\n * Stop broadcasting presence state and listening to peer presence.\n */\n stop: () => void\n}\n\n/**\n * This hook encapsulates ephemeral state communication for a specific doc\n * handle. It tracks caller-provided local state and broadcasts that state to\n * all peers. It sends periodic heartbeats when there are no state updates.\n *\n * It also tracks ephemeral state broadcast by peers and forces a re-render when\n * the state of a peer changes.\n *\n * It cleans up (stops sending heartbeats and processing ephemeral messages)\n * when it unmounts.\n *\n * It is implemented using {@link Presence}.\n *\n * @param config - see {@link UsePresenceConfig}. Note that initialState only\n * determines the initial value. Updates to this param will not trigger a\n * re-render of the hook.\n *\n * @returns see {@link UsePresenceResult}\n */\nexport function usePresence<State extends PresenceState>({\n handle,\n initialState,\n heartbeatMs,\n peerTtlMs,\n}: UsePresenceConfig<State>): UsePresenceResult<State> {\n const [localState, setLocalState] = useState<State>(initialState)\n const [peerStates, setPeerStates] = useState(new PeerStateView<State>({}))\n // Don't re-render based on changes to these: they are not expected to\n // change but may be passed in as object literals\n const firstOpts = useRef({\n heartbeatMs,\n peerTtlMs,\n })\n const firstInitialState = useRef(initialState)\n const [presence] = useState(() => new Presence<State>({ handle }))\n\n useEffect(() => {\n presence.start({\n initialState: firstInitialState.current,\n ...firstOpts.current,\n })\n presence.on(\"heartbeat\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"snapshot\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"update\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"goodbye\", () => setPeerStates(presence.getPeerStates()))\n presence.on(\"pruned\", () => setPeerStates(presence.getPeerStates()))\n\n return () => {\n presence.stop()\n }\n }, [presence, firstInitialState, firstOpts])\n\n const start = useCallback(\n (config?: Partial<PresenceConfig<State>>) => {\n // Fall back to the last state if not provided when restarting\n const initialState = config?.initialState ?? presence.getLocalState()\n const opts = {\n ...firstOpts.current,\n ...config,\n initialState,\n }\n presence.start(opts)\n },\n [presence, firstOpts]\n )\n const stop = useCallback(() => {\n presence.stop()\n }, [presence])\n\n const update = useCallback(\n <Channel extends keyof State>(channel: Channel, msg: State[Channel]) => {\n presence.broadcast(channel, msg)\n const updated = presence.getLocalState()\n setLocalState(updated)\n },\n [presence]\n )\n\n return {\n peerStates,\n localState,\n update,\n start,\n stop,\n }\n}\n", "import {\n type TLAnyShapeUtilConstructor,\n type TLRecord,\n type TLStoreWithStatus,\n createTLStore,\n defaultShapeUtils,\n type HistoryEntry,\n getUserPreferences,\n setUserPreferences,\n defaultUserPreferences,\n createPresenceStateDerivation,\n InstancePresenceRecordType,\n computed,\n react,\n type TLStoreSnapshot,\n type TLInstancePresence,\n sortById,\n useEditor,\n} from \"@tldraw/tldraw\";\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n type DocHandle,\n type DocHandleChangePayload,\n} from \"@automerge/automerge-repo/slim\";\nimport { usePresence } from \"@automerge/automerge-repo-react-hooks\";\n\nimport { applyAutomergePatchesToTLStore } from \"./AutomergeToTLStore.js\";\nimport { applyTLStoreChangesToAutomerge } from \"./TLStoreToAutomerge.js\";\n\nexport function useAutomergeStore({\n handle,\n shapeUtils = [],\n readOnly = false,\n}: {\n handle: DocHandle<TLStoreSnapshot>;\n userId: string;\n shapeUtils?: TLAnyShapeUtilConstructor[];\n readOnly?: boolean;\n}): TLStoreWithStatus {\n const [store] = useState(() => {\n const store = createTLStore({\n shapeUtils: [...defaultShapeUtils, ...shapeUtils],\n });\n return store;\n });\n\n const [storeWithStatus, setStoreWithStatus] = useState<TLStoreWithStatus>({\n status: \"loading\",\n });\n\n // Read through a ref inside the write-back listener so a mid-session flip\n // (see `useIsHandleReadOnly`) doesn't re-run the store effect below \u2014 that\n // would re-load the snapshot and clear session records (camera, selection).\n const readOnlyRef = useRef(readOnly);\n readOnlyRef.current = readOnly;\n\n /* -------------------- TLDraw <--> Automerge -------------------- */\n useEffect(() => {\n const unsubs: (() => void)[] = [];\n\n // A hacky workaround to prevent local changes from being applied twice\n // once into the automerge doc and then back again.\n let preventPatchApplications = false;\n\n /* TLDraw to Automerge */\n function syncStoreChangesToAutomergeDoc({\n changes,\n }: HistoryEntry<TLRecord>) {\n // A read-only (history-pinned) handle is at fixed heads and rejects\n // `handle.change`, so never forward store edits back to Automerge.\n if (readOnlyRef.current) return;\n preventPatchApplications = true;\n handle.change((doc) => {\n applyTLStoreChangesToAutomerge(doc, changes);\n });\n preventPatchApplications = false;\n }\n\n unsubs.push(\n store.listen(syncStoreChangesToAutomergeDoc, {\n source: \"user\",\n scope: \"document\",\n })\n );\n\n /* Automerge to TLDraw */\n const syncAutomergeDocChangesToStore = ({\n patches,\n scopeReplaced,\n doc,\n }: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (preventPatchApplications) return;\n\n // A wholesale scope replacement (e.g. the draft overlay re-pointing\n // this handle at a different clone) carries no patch stream connecting\n // the old doc to the new one. Diff the new doc's *document*-scope\n // records into the store rather than `loadStoreSnapshot`: that would\n // `clear()` the session-scope records too (camera/zoom, current page,\n // selection), which should survive a draft switch. Drafts are forks of\n // each other, so most records are identical and `put` skips them.\n if (scopeReplaced) {\n const swapped = handle.doc();\n if (!swapped?.store) return;\n const migrated = store.schema.migrateStoreSnapshot({\n store: JSON.parse(JSON.stringify(swapped.store)),\n schema: JSON.parse(JSON.stringify(swapped.schema)),\n });\n if (migrated.type === \"error\") {\n console.error(\n \"[tldraw4] failed to migrate swapped-in snapshot:\",\n migrated.reason\n );\n return;\n }\n const next = migrated.value;\n store.mergeRemoteChanges(() => {\n const toRemove = store\n .allRecords()\n .filter(\n (record) =>\n store.scopedTypes.document.has(record.typeName) &&\n !(record.id in next)\n )\n .map((record) => record.id);\n if (toRemove.length) store.remove(toRemove);\n store.put(Object.values(next));\n });\n return;\n }\n\n applyAutomergePatchesToTLStore(patches, store, doc ?? handle.doc());\n };\n\n handle.on(\"change\", syncAutomergeDocChangesToStore);\n unsubs.push(() => handle.off(\"change\", syncAutomergeDocChangesToStore));\n\n /* Load the initial document snapshot into the store. */\n // TODO: need to think through the various status possibilities here and how they map\n const doc = handle.doc();\n if (!doc) throw new Error(\"Document not found\");\n if (!doc.store) throw new Error(\"Document store not initialized\");\n\n store.mergeRemoteChanges(() => {\n store.loadStoreSnapshot({\n store: structuredClone(doc.store),\n schema: structuredClone(doc.schema),\n });\n });\n\n setStoreWithStatus({\n store,\n status: \"synced-remote\",\n connectionStatus: \"online\",\n });\n\n return () => {\n unsubs.forEach((fn) => fn());\n unsubs.length = 0;\n };\n }, [handle, store]);\n\n return storeWithStatus;\n}\n\n// A handle's read-only state (`isReadOnly()`, true at fixed heads) can flip in\n// place: its backing may be swapped without the handle identity changing (a\n// `change` event with `scopeReplaced: true`). Track it as state re-read on\n// every swap rather than sampling it once per mount.\nexport function useIsHandleReadOnly(\n handle: DocHandle<TLStoreSnapshot>\n): boolean {\n const [readOnly, setReadOnly] = useState(() => handle.isReadOnly());\n\n useEffect(() => {\n setReadOnly(handle.isReadOnly());\n const onChange = (payload: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (payload.scopeReplaced) setReadOnly(handle.isReadOnly());\n };\n handle.on(\"change\", onChange);\n return () => void handle.off(\"change\", onChange);\n }, [handle]);\n\n return readOnly;\n}\n\n// A scope swap (a `change` event with `scopeReplaced: true` -- the draft\n// overlay re-pointing this handle at a different clone when scrubbing history\n// or switching drafts) invalidates the undo stack: its entries describe a\n// different timeline. The swapped-in records themselves are applied via\n// `mergeRemoteChanges` in `useAutomergeStore` above (so they are never\n// recorded); clearing the stale stack is all that's left to do.\n//\n// This can't live in `useAutomergeStore` directly: undo history is not a\n// store concern -- the `HistoryManager` belongs to the `Editor`, which tldraw\n// only creates internally once `<Tldraw store={...}>` mounts. The store hook\n// runs outside `<Tldraw>`, before any editor exists, so the history-clearing\n// half of the swap handling has to be a separate hook rendered *inside*\n// `<Tldraw>`, where `useEditor()` can reach the editor.\nexport function useClearHistoryOnScopeSwap(handle: DocHandle<TLStoreSnapshot>) {\n const editor = useEditor();\n\n useEffect(() => {\n if (!editor) return;\n const onChange = (payload: DocHandleChangePayload<TLStoreSnapshot>) => {\n if (payload.scopeReplaced) editor.clearHistory();\n };\n handle.on(\"change\", onChange);\n return () => void handle.off(\"change\", onChange);\n }, [editor, handle]);\n}\n\n// Ephemeral state shared with peers: our tldraw presence record, or null if window is not focused\ntype PresenceChannels = { presence: TLInstancePresence | null };\n\nexport function useAutomergePresence({\n handle,\n store,\n userMetadata,\n element,\n}: {\n handle: DocHandle<TLStoreSnapshot>;\n store: TLStoreWithStatus;\n userMetadata: any;\n element: HTMLElement;\n}) {\n const innerStore = store?.store;\n\n const { userId, name, color } = userMetadata;\n\n const isCursorActive = useIsCursorActive(element);\n\n const { peerStates, update, stop } = usePresence<PresenceChannels>({\n handle,\n initialState: { presence: null },\n });\n\n useEffect(() => {\n if (!innerStore) return;\n\n // Records are keyed by peerId so multiple sessions of the same user stay distinct.\n const toPut: TLRecord[] = peerStates.peers\n .filter((peer) => peer.value?.presence)\n .map((peer) => ({\n ...peer.value.presence!,\n id: InstancePresenceRecordType.createId(peer.peerId),\n }));\n\n const toRemove = innerStore.query\n .records(\"instance_presence\")\n .get()\n .sort(sortById)\n .map((record) => record.id)\n .filter((id) => !toPut.find((record) => record.id === id));\n\n if (toRemove.length) innerStore.remove(toRemove);\n if (toPut.length) innerStore.put(toPut);\n }, [innerStore, peerStates]);\n\n useEffect(() => {\n if (!innerStore) return;\n setUserPreferences({ id: userId, color, name });\n\n const userPreferences = computed<{\n id: string;\n color: string;\n name: string;\n }>(\"userPreferences\", () => {\n const user = getUserPreferences();\n return {\n id: user.id,\n color: user.color ?? defaultUserPreferences.color,\n name: user.name ?? defaultUserPreferences.name,\n };\n });\n\n const presenceDerivation =\n createPresenceStateDerivation(userPreferences)(innerStore);\n\n // Closing the page sends a goodbye, which removes our record from peers.\n window.addEventListener(\"pagehide\", stop);\n\n let cancelled = false;\n let dispose: (() => void) | undefined;\n\n if (isCursorActive) {\n dispose = react(\"broadcast presence\", () => {\n const presence = presenceDerivation.get();\n // rAF throttles broadcasts to frame rate.\n requestAnimationFrame(() => {\n if (cancelled) return;\n // Stamp activity so becoming active again shows the cursor without\n // waiting for a pointer move to refresh the store's stale timestamp.\n update(\n \"presence\",\n presence ? { ...presence, lastActivityTimestamp: Date.now() } : null\n );\n });\n });\n } else {\n // Keep the record but clear the cursor when blurred or pointer leaves\n const presence = presenceDerivation.get();\n update(\"presence\", presence ? { ...presence, cursor: null } : null);\n }\n\n return () => {\n // Invalidate pending rAF broadcasts so stale updates don't overwrite deactivated cursors.\n cancelled = true;\n dispose?.();\n window.removeEventListener(\"pagehide\", stop);\n };\n }, [innerStore, userId, name, color, update, stop, isCursorActive]);\n}\n\n// The local cursor is active only when the window is focused and the pointer is over this tool.\nfunction useIsCursorActive(element: HTMLElement) {\n const [isFocused, setIsFocused] = useState(() => document.hasFocus());\n const [isPointerOver, setIsPointerOver] = useState(() =>\n element.matches(\":hover\")\n );\n\n useEffect(() => {\n const onFocus = () => setIsFocused(true);\n const onBlur = () => setIsFocused(false);\n const onEnter = () => setIsPointerOver(true);\n const onLeave = () => setIsPointerOver(false);\n window.addEventListener(\"focus\", onFocus);\n window.addEventListener(\"blur\", onBlur);\n element.addEventListener(\"mouseenter\", onEnter);\n element.addEventListener(\"mouseleave\", onLeave);\n return () => {\n window.removeEventListener(\"focus\", onFocus);\n window.removeEventListener(\"blur\", onBlur);\n element.removeEventListener(\"mouseenter\", onEnter);\n element.removeEventListener(\"mouseleave\", onLeave);\n };\n }, [element]);\n\n return isFocused && isPointerOver;\n}\n", "import type { TLRecord, TLStore } from \"@tldraw/tldraw\";\nimport * as Automerge from \"@automerge/automerge/slim\";\n\n/**\n * Sync automerge doc changes into the tldraw store.\n *\n * The patches are only used to find out *which* records changed; the record\n * contents are rebuilt wholesale from the doc. Replaying patch mechanics\n * against store records would require modeling every patch shape automerge\n * can emit (nested `del`, `splice`, `conflict`, ...) and any gap silently\n * diverges the view from the doc until reload. Rebuilding from the doc makes\n * the doc the single source of truth: after every change the store record is\n * exactly what the doc says, regardless of what the patches looked like.\n * tldraw records are small, so the per-record rebuild cost is negligible.\n */\nexport function applyAutomergePatchesToTLStore(\n patches: Automerge.Patch[],\n store: TLStore,\n doc: { store: Record<string, unknown> }\n) {\n const changedIds = new Set<string>();\n for (const patch of patches) {\n if (patch.path[0] === \"store\" && patch.path.length > 1) {\n changedIds.add(`${patch.path[1]}`);\n }\n }\n\n const toRemove: TLRecord[\"id\"][] = [];\n const toPut: TLRecord[] = [];\n for (const id of changedIds) {\n const record = doc.store[id];\n if (record === undefined) {\n toRemove.push(id as TLRecord[\"id\"]);\n } else {\n toPut.push(structuredClone(record) as TLRecord);\n }\n }\n\n store.mergeRemoteChanges(() => {\n if (toRemove.length) store.remove(toRemove);\n if (toPut.length) store.put(toPut);\n });\n}\n", "import { useEffect, useState } from \"react\";\nimport { useDocument, useDocHandle } from \"@automerge/automerge-repo-react-hooks\";\nimport * as Providers from \"@inkandswitch/patchwork-providers\";\n/**\n * Generic reactive request hook. Resolves the first value a provider emits for\n * `selector` (via the one-shot `request` helper) and returns it once it\n * arrives (and whenever `element`/`selector` change). `T` is the response type.\n */\nexport function useRequest(element, selector) {\n const [value, setValue] = useState(undefined);\n const key = JSON.stringify(selector);\n useEffect(() => {\n let canceled = false;\n Providers.request(element, selector).then((v) => {\n if (canceled || v == null)\n return;\n setValue(() => v);\n });\n return () => {\n canceled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, key]);\n return value;\n}\nexport function useSubscribe(element, selector, initialValue) {\n const [value, setValue] = useState(initialValue);\n const key = JSON.stringify(selector);\n useEffect(() => {\n const unsubscribe = Providers.subscribe(element, selector, (v) => {\n setValue(() => v);\n });\n return unsubscribe;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [element, key]);\n return value;\n}\n/**\n * Handle-specialized subscription hook. Use when the answering provider emits\n * an `AutomergeUrl`. The handle is recovered locally from the global repo, so\n * it stays fully live. Returns `[doc, handle]` matching the shape of\n * `useDocument`; both read `undefined` until the first url arrives. `T` is the\n * doc shape inside the handle.\n */\nexport function useSubscribeDoc(element, selector) {\n const url = useSubscribe(element, selector);\n const [doc] = useDocument(url);\n const handle = useDocHandle(url);\n return [doc, handle];\n}\n", "import * as Automerge from \"@automerge/automerge/slim\";\nimport { isEqual } from \"lodash\";\nimport type { TLRecord, TLShapeId } from \"@tldraw/tldraw\";\nimport type { TLDrawDoc } from \"./datatype.ts\";\n\n// A record-level diff of the tldraw store between a baseline version and the\n// current one. Modelled on how `codemirror-base` diffs text: we view the doc\n// at the baseline heads and compare it against the live doc. The granularity\n// here is whole records (shapes) rather than text spans.\nexport type ShapeDiff = {\n added: Set<TLShapeId>;\n changed: Set<TLShapeId>;\n // Deleted shapes no longer exist in the live store, so we keep a plain\n // clone of the baseline record to re-render it as a ghost.\n deleted: TLRecord[];\n};\n\nconst isShapeId = (id: string): id is TLShapeId => id.startsWith(\"shape:\");\n\n// Compute which shapes were added / changed / deleted between the doc at\n// `headsBefore` and its current state. Only `shape:*` records are considered\n// \u2014 the store also holds `camera:`, `instance:`, `pointer:` and\n// `instance_presence:` records (presence is written live by every peer) which\n// must not show up as diffs.\nexport function diffStore(\n doc: TLDrawDoc,\n headsBefore: Automerge.Heads\n): ShapeDiff {\n const before = Automerge.view<TLDrawDoc>(doc, headsBefore);\n const beforeStore = (before.store ?? {}) as Record<string, TLRecord>;\n const afterStore = (doc.store ?? {}) as Record<string, TLRecord>;\n\n const added = new Set<TLShapeId>();\n const changed = new Set<TLShapeId>();\n const deleted: TLRecord[] = [];\n\n for (const id in afterStore) {\n if (!isShapeId(id)) continue;\n if (!(id in beforeStore)) {\n added.add(id);\n } else if (!isEqual(beforeStore[id], afterStore[id])) {\n changed.add(id);\n }\n }\n\n for (const id in beforeStore) {\n if (!isShapeId(id)) continue;\n if (!(id in afterStore)) {\n // Clone via JSON so the record survives outside the Automerge doc and\n // carries no proxies (matches how the store snapshot is loaded).\n deleted.push(JSON.parse(JSON.stringify(beforeStore[id])) as TLRecord);\n }\n }\n\n return { added, changed, deleted };\n}\n\nexport const hasDiff = (d: ShapeDiff | null | undefined): d is ShapeDiff =>\n !!d && (d.added.size > 0 || d.changed.size > 0 || d.deleted.length > 0);\n", "import { createContext, forwardRef, useContext } from \"react\";\nimport {\n DefaultShapeWrapper,\n useValue,\n type Atom,\n type TLShapeId,\n type TLShapeWrapperProps,\n} from \"@tldraw/tldraw\";\n\nexport type DiffStatus = \"added\" | \"changed\" | \"deleted\";\n\n// Per-tool atom mapping each shape id to its diff status. It lives in a tldraw\n// `atom` (not React state) so the wrapper can read it via `useValue` and only\n// the shapes whose status actually changed re-render. It reaches the wrapper\n// through context because tldraw instantiates `ShapeWrapper` internally \u2014 props\n// can't be passed to it, but context (which flows down from `<Tldraw>`) can.\nexport type DiffStatusAtom = Atom<Map<TLShapeId, DiffStatus>>;\n\nexport const DiffStatusContext = createContext<DiffStatusAtom | null>(null);\n\n// Wraps every shape's DOM and tags it with a `tl-diff-*` class so a CSS\n// `drop-shadow` glow can hug the shape outline (added / changed) or fade it out\n// (deleted ghosts). Re-uses `DefaultShapeWrapper` so all default behaviour is\n// preserved.\nexport const DiffShapeWrapper = forwardRef<HTMLDivElement, TLShapeWrapperProps>(\n function DiffShapeWrapper({ children, shape, isBackground }, ref) {\n const statusAtom = useContext(DiffStatusContext);\n const status = useValue(\n \"diff status\",\n () => statusAtom?.get().get(shape.id),\n [statusAtom, shape.id]\n );\n return (\n <DefaultShapeWrapper\n ref={ref}\n shape={shape}\n isBackground={isBackground}\n className={status ? `tl-diff-${status}` : undefined}\n >\n {children}\n </DefaultShapeWrapper>\n );\n }\n);\n", "import {\n Geometry2d,\n HTMLContainer,\n Rectangle2d,\n ShapeUtil,\n T,\n createShapeId,\n resizeBox,\n useEditor,\n useValue,\n type RecordProps,\n type TLResizeInfo,\n type TLShape,\n type TLShapeId,\n} from \"@tldraw/tldraw\";\nimport { useEffect, useRef } from \"react\";\nimport { getSupportedToolsForType } from \"@inkandswitch/patchwork-plugins\";\nimport type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport { useDocument } from \"@automerge/automerge-repo-react-hooks\";\nimport { automergeUrlToServiceWorkerUrl } from \"@inkandswitch/patchwork-filesystem\";\n\n// A tldraw shape embedding another Patchwork document via the shared \"embed\"\n// tool (<patchwork-view tool-id=\"embed\">), which draws the chrome and nests\n// the content view. The doc reference lives in the shape props, so it syncs\n// like any other shape.\n\nexport const PATCHWORK_DOC_SHAPE_TYPE = \"patchwork-doc\" as const;\n\ndeclare module \"@tldraw/tldraw\" {\n export interface TLGlobalShapePropsMap {\n [PATCHWORK_DOC_SHAPE_TYPE]: {\n w: number;\n h: number;\n docUrl: string;\n docName: string;\n docType: string;\n toolId: string;\n };\n }\n}\n\nexport type PatchworkDocShape = TLShape<typeof PATCHWORK_DOC_SHAPE_TYPE>;\n\n// Deterministic shape id derived from the doc url, so remote peers that create\n// a shape for the same document converge on a single shape instead of dupes.\nexport function makeShapeId(docUrl: string): TLShapeId {\n return createShapeId(docUrl.replace(/[^a-zA-Z0-9]/g, \"_\"));\n}\n\nexport class PatchworkDocShapeUtil extends ShapeUtil<PatchworkDocShape> {\n static override type = PATCHWORK_DOC_SHAPE_TYPE;\n\n static override props: RecordProps<PatchworkDocShape> = {\n w: T.number,\n h: T.number,\n docUrl: T.string,\n docName: T.string,\n docType: T.string,\n toolId: T.string,\n };\n\n getDefaultProps(): PatchworkDocShape[\"props\"] {\n return {\n w: 640,\n h: 480,\n docUrl: \"\",\n docName: \"Untitled\",\n docType: \"\",\n toolId: \"\",\n };\n }\n\n getGeometry(shape: PatchworkDocShape): Geometry2d {\n return new Rectangle2d({\n width: shape.props.w,\n height: shape.props.h,\n isFilled: true,\n });\n }\n\n override canResize() {\n return true;\n }\n override canEdit() {\n return true;\n }\n override isAspectRatioLocked() {\n return false;\n }\n override hideRotateHandle() {\n return true;\n }\n\n override onResize(shape: PatchworkDocShape, info: TLResizeInfo<PatchworkDocShape>) {\n return resizeBox(shape, info);\n }\n\n component(shape: PatchworkDocShape) {\n return <PatchworkDocComponent shape={shape} />;\n }\n\n indicator(shape: PatchworkDocShape) {\n return <rect width={shape.props.w} height={shape.props.h} />;\n }\n}\n\n// Best default tool for a datatype: prefer a tool that explicitly lists the\n// datatype over a wildcard (\"*\") tool; fall back to the first available.\nexport function getDefaultToolId(datatypeId: string): string {\n if (!datatypeId) return \"\";\n try {\n const tools = getSupportedToolsForType(datatypeId).filter(\n (t) => !(t as { unlisted?: boolean }).unlisted,\n );\n const specific = tools.find((t) => {\n const supported = (t as { supportedDatatypes?: unknown }).supportedDatatypes;\n return Array.isArray(supported) && supported.includes(datatypeId);\n });\n return (specific ?? tools[0])?.id ?? \"\";\n } catch {\n return \"\";\n }\n}\n\nfunction useIsImage(docUrl: string): boolean {\n const [doc] = useDocument<{ \"@patchwork\"?: { type?: string }; mimeType?: string }>(\n docUrl ? (docUrl as AutomergeUrl) : undefined,\n );\n return doc?.[\"@patchwork\"]?.type === \"file\" && !!doc?.mimeType?.startsWith(\"image/\");\n}\n\nfunction PatchworkDocComponent({ shape }: { shape: PatchworkDocShape }) {\n const { docUrl, docName, toolId } = shape.props;\n const editor = useEditor();\n const isImage = useIsImage(docUrl);\n\n const isEditingShape = useValue(\n \"is editing shape\",\n () => editor.getEditingShapeId() === shape.id,\n [editor, shape.id],\n );\n const isFocused = isEditingShape;\n\n const containerRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n\n // While the embedded content is focused, stop tldraw from swallowing\n // keyboard / wheel / pointer events so the inner tool stays interactive.\n useEffect(() => {\n if (!isFocused) return;\n const el = contentRef.current;\n if (!el) return;\n\n const stopKey = (e: KeyboardEvent) => e.stopPropagation();\n const stopWheel = (e: WheelEvent) => {\n if (!e.ctrlKey) e.stopPropagation();\n };\n const stopPointer = (e: PointerEvent) => e.stopPropagation();\n\n el.addEventListener(\"keydown\", stopKey);\n el.addEventListener(\"keyup\", stopKey);\n el.addEventListener(\"keypress\", stopKey);\n el.addEventListener(\"wheel\", stopWheel);\n el.addEventListener(\"pointerdown\", stopPointer, true);\n el.addEventListener(\"pointermove\", stopPointer, true);\n el.addEventListener(\"pointerup\", stopPointer, true);\n return () => {\n el.removeEventListener(\"keydown\", stopKey);\n el.removeEventListener(\"keyup\", stopKey);\n el.removeEventListener(\"keypress\", stopKey);\n el.removeEventListener(\"wheel\", stopWheel);\n el.removeEventListener(\"pointerdown\", stopPointer, true);\n el.removeEventListener(\"pointermove\", stopPointer, true);\n el.removeEventListener(\"pointerup\", stopPointer, true);\n };\n }, [isFocused]);\n\n // Persist tool picks from the embed frame into the shape props.\n useEffect(() => {\n const el = containerRef.current;\n if (!el) return;\n const onToolChanged = (e: Event) => {\n // Stop propagation so nested embeds don't also change the outer embed.\n e.stopPropagation();\n const newToolId = (e as CustomEvent<{ toolId?: string }>).detail?.toolId;\n if (!newToolId) return;\n editor.updateShape({\n id: shape.id,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: { toolId: newToolId },\n });\n };\n el.addEventListener(\"patchwork:embed-tool-changed\", onToolChanged);\n return () =>\n el.removeEventListener(\"patchwork:embed-tool-changed\", onToolChanged);\n }, [editor, shape.id]);\n\n return (\n <HTMLContainer>\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: \"100%\",\n display: \"flex\",\n flexDirection: \"column\",\n overflow: \"hidden\",\n border: \"1px solid var(--color-panel-contrast, #e5e7eb)\",\n borderRadius: \"8px\",\n background: \"var(--color-panel, #ffffff)\",\n boxShadow: \"0 1px 4px rgba(0,0,0,0.10)\",\n pointerEvents: \"all\",\n }}\n >\n {/* Interactive only while editing (double-click); otherwise pointer\n events fall through so tldraw can select and drag the shape. */}\n <div\n ref={contentRef}\n style={{\n flex: 1,\n minHeight: 0,\n overflow: \"hidden\",\n position: \"relative\",\n pointerEvents: isFocused ? \"auto\" : \"none\",\n userSelect: isFocused ? \"text\" : \"none\",\n cursor: isFocused ? \"auto\" : undefined,\n }}\n >\n {docUrl && isImage ? (\n <img\n src={automergeUrlToServiceWorkerUrl(docUrl as AutomergeUrl)}\n alt={docName}\n style={{ width: \"100%\", height: \"100%\", objectFit: \"contain\" }}\n />\n ) : docUrl ? (\n // @ts-expect-error Custom element from @inkandswitch/patchwork-elements\n <patchwork-view\n doc-url={docUrl}\n tool-id=\"embed\"\n {...(toolId ? { \"embed-tool-id\": toolId } : {})}\n key={toolId || \"default\"}\n style={{ display: \"block\", width: \"100%\", height: \"100%\" }}\n />\n ) : (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n height: \"100%\",\n color: \"var(--color-text-3, #9ca3af)\",\n fontSize: \"12px\",\n }}\n >\n No document\n </div>\n )}\n </div>\n </div>\n </HTMLContainer>\n );\n}\n", "/**\n * NewDocTool \u2014 a tldraw tool that lets the user draw a box to create a new\n * embedded Patchwork document of a chosen datatype.\n *\n * Exports:\n * - NewDocShapeTool \u2014 pass to Tldraw `tools`\n * - newDocUiOverrides \u2014 spread into Tldraw `overrides`\n * - NewDocToolbar \u2014 pass as Tldraw `components.Toolbar`\n * - setNewDocToolContext() \u2014 call once per editor when it's ready\n */\n\nimport {\n DefaultToolbar,\n DefaultToolbarContent,\n StateNode,\n createShapeId,\n useEditor,\n useValue,\n type Editor,\n type TLPointerEventInfo,\n type TLUiOverrides,\n type TLUiToolsContextType,\n} from \"@tldraw/tldraw\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { Repo } from \"@automerge/automerge-repo/slim\";\nimport {\n createDocOfDatatype2,\n getRegistry,\n type DatatypeDescription,\n type LoadedDatatype,\n} from \"@inkandswitch/patchwork-plugins\";\nimport { PATCHWORK_DOC_SHAPE_TYPE, makeShapeId } from \"./PatchworkDocShape.tsx\";\n\n// Per-editor context, keyed by editor instance, so a nested canvas embedded in\n// another canvas doesn't clobber the outer one's repo reference.\ninterface NewDocContext {\n repo: Repo;\n}\n\nconst _contextByEditor = new WeakMap<Editor, NewDocContext>();\nlet _selectedDatatypeId = \"\";\n\nexport function setNewDocToolContext(repo: Repo, editor: Editor) {\n _contextByEditor.set(editor, { repo });\n}\n\nexport function setSelectedDatatypeId(id: string) {\n _selectedDatatypeId = id;\n}\n\nfunction getListedDatatypeDescriptions(): DatatypeDescription[] {\n try {\n const registry = getRegistry<DatatypeDescription>(\"patchwork:datatype\");\n return registry.filter((d) => !(d as DatatypeDescription).unlisted) as unknown as DatatypeDescription[];\n } catch {\n return [];\n }\n}\n\nasync function loadDatatype(id: string): Promise<LoadedDatatype | undefined> {\n try {\n const registry = getRegistry<DatatypeDescription>(\"patchwork:datatype\");\n return (await registry.load(id)) as unknown as LoadedDatatype | undefined;\n } catch {\n return undefined;\n }\n}\n\nexport class NewDocShapeTool extends StateNode {\n static override id = \"new-doc\";\n\n private startPoint = { x: 0, y: 0 };\n private previewId: ReturnType<typeof createShapeId> | null = null;\n\n override onPointerDown(_info: TLPointerEventInfo) {\n const { currentPagePoint } = this.editor.inputs;\n this.startPoint = { x: currentPagePoint.x, y: currentPagePoint.y };\n\n this.previewId = createShapeId();\n this.editor.createShape({\n id: this.previewId,\n type: \"geo\",\n x: currentPagePoint.x,\n y: currentPagePoint.y,\n parentId: this.editor.getCurrentPageId(),\n props: { w: 1, h: 1, geo: \"rectangle\", dash: \"dashed\", fill: \"none\" },\n });\n }\n\n override onPointerMove(_info: TLPointerEventInfo) {\n if (!this.previewId) return;\n const { currentPagePoint } = this.editor.inputs;\n const x = Math.min(this.startPoint.x, currentPagePoint.x);\n const y = Math.min(this.startPoint.y, currentPagePoint.y);\n const w = Math.max(1, Math.abs(currentPagePoint.x - this.startPoint.x));\n const h = Math.max(1, Math.abs(currentPagePoint.y - this.startPoint.y));\n this.editor.updateShape({ id: this.previewId, type: \"geo\", x, y, props: { w, h } });\n }\n\n override onCancel() {\n this.cleanup();\n this.editor.setCurrentTool(\"select\");\n }\n\n override onInterrupt() {\n this.cleanup();\n }\n\n private cleanup() {\n if (this.previewId) {\n if (this.editor.getShape(this.previewId)) {\n this.editor.deleteShapes([this.previewId]);\n }\n this.previewId = null;\n }\n }\n\n override onPointerUp(_info: TLPointerEventInfo) {\n if (!this.previewId) return;\n\n const preview = this.editor.getShape(this.previewId);\n this.editor.deleteShapes([this.previewId]);\n this.previewId = null;\n\n if (!preview) {\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const px = (preview as { x: number }).x;\n const py = (preview as { y: number }).y;\n const pw = (preview as { props: { w: number } }).props.w;\n const ph = (preview as { props: { h: number } }).props.h;\n\n const finalW = Math.max(pw, 240);\n const finalH = Math.max(ph, 180);\n\n const ctx = _contextByEditor.get(this.editor);\n if (!ctx) {\n console.warn(\"[tldraw4] NewDocTool: context not set for this editor\");\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const datatypeId = _selectedDatatypeId;\n if (!datatypeId) {\n console.warn(\"[tldraw4] NewDocTool: no datatype selected\");\n this.editor.setCurrentTool(\"select\");\n return;\n }\n\n const editor = this.editor;\n const repo = ctx.repo;\n const placeholderId = createShapeId();\n\n editor.createShape({\n id: placeholderId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: px,\n y: py,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: finalW,\n h: finalH,\n docUrl: \"\",\n docName: \"Creating\\u2026\",\n docType: datatypeId,\n toolId: \"\",\n },\n });\n\n editor.setCurrentTool(\"select\");\n editor.setSelectedShapes([placeholderId]);\n\n void (async () => {\n try {\n const datatype = await loadDatatype(datatypeId);\n if (!datatype) throw new Error(`Could not load datatype: ${datatypeId}`);\n\n // `createDocOfDatatype2` in the installed plugins package is typed\n // against an older @automerge/automerge-repo Repo; cast to bridge the\n // version skew (same pattern used by the space / llm-canvas tools).\n const docHandle = await (\n createDocOfDatatype2 as (d: LoadedDatatype, r: unknown) => Promise<{ url: string }>\n )(datatype, repo);\n const docUrl = docHandle.url;\n const deterministicId = makeShapeId(docUrl);\n\n const tempShape = editor.getShape(placeholderId) as\n | { x: number; y: number; props: { w: number; h: number } }\n | undefined;\n const sx = tempShape?.x ?? px;\n const sy = tempShape?.y ?? py;\n const sw = tempShape?.props?.w ?? finalW;\n const sh = tempShape?.props?.h ?? finalH;\n\n if (editor.getShape(placeholderId)) {\n editor.deleteShapes([placeholderId]);\n }\n\n if (editor.getShape(deterministicId)) {\n editor.updateShape({\n id: deterministicId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: {\n docUrl,\n docName: datatype.name ?? datatypeId,\n docType: datatypeId,\n toolId: \"\",\n },\n });\n } else {\n editor.createShape({\n id: deterministicId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n x: sx,\n y: sy,\n rotation: 0,\n parentId: editor.getCurrentPageId(),\n props: {\n w: sw,\n h: sh,\n docUrl,\n docName: datatype.name ?? datatypeId,\n docType: datatypeId,\n toolId: \"\",\n },\n });\n }\n\n editor.setSelectedShapes([deterministicId]);\n } catch (err) {\n console.error(\"[tldraw4] new doc creation failed:\", err);\n if (editor.getShape(placeholderId)) {\n editor.updateShape({\n id: placeholderId,\n type: PATCHWORK_DOC_SHAPE_TYPE,\n props: { docName: `Error creating ${datatypeId}` },\n });\n }\n }\n })();\n }\n}\n\nexport const newDocUiOverrides: TLUiOverrides = {\n tools(editor: Editor, tools: TLUiToolsContextType) {\n tools[\"new-doc\"] = {\n id: \"new-doc\",\n icon: \"plus\",\n label: \"New document\",\n kbd: \"c\",\n onSelect() {\n editor.setCurrentTool(\"new-doc\");\n },\n };\n return tools;\n },\n};\n\nexport function NewDocToolbar() {\n const editor = useEditor();\n const isActive = useValue(\"new-doc active\", () => editor.getCurrentToolId() === \"new-doc\", [\n editor,\n ]);\n\n const [datatypes, setDatatypes] = useState<DatatypeDescription[]>([]);\n const [menuOpen, setMenuOpen] = useState(false);\n const [selectedId, setSelectedId] = useState(_selectedDatatypeId);\n const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const dt = getListedDatatypeDescriptions();\n setDatatypes(dt);\n if (dt.length > 0 && !_selectedDatatypeId) {\n setSelectedDatatypeId(dt[0].id);\n setSelectedId(dt[0].id);\n }\n }, []);\n\n useEffect(() => {\n if (!menuOpen) return;\n const handler = (e: PointerEvent) => {\n const t = e.target as Node;\n if (buttonRef.current?.contains(t) || menuRef.current?.contains(t)) return;\n setMenuOpen(false);\n };\n document.addEventListener(\"pointerdown\", handler, true);\n return () => document.removeEventListener(\"pointerdown\", handler, true);\n }, [menuOpen]);\n\n const openMenu = useCallback(() => {\n if (buttonRef.current) {\n const rect = buttonRef.current.getBoundingClientRect();\n setMenuPos({ x: rect.left + rect.width / 2, y: rect.top });\n }\n setDatatypes(getListedDatatypeDescriptions());\n setMenuOpen(true);\n }, []);\n\n const handlePlusClick = useCallback(() => {\n if (datatypes.length > 0 && !_selectedDatatypeId) {\n setSelectedDatatypeId(datatypes[0].id);\n setSelectedId(datatypes[0].id);\n }\n editor.setCurrentTool(\"new-doc\");\n if (datatypes.length > 1) {\n if (menuOpen) setMenuOpen(false);\n else requestAnimationFrame(openMenu);\n }\n }, [datatypes, editor, menuOpen, openMenu]);\n\n const handlePick = useCallback(\n (id: string) => {\n setSelectedDatatypeId(id);\n setSelectedId(id);\n setMenuOpen(false);\n editor.setCurrentTool(\"new-doc\");\n },\n [editor],\n );\n\n if (datatypes.length === 0) {\n return (\n <DefaultToolbar>\n <DefaultToolbarContent />\n </DefaultToolbar>\n );\n }\n\n const selectedName = datatypes.find((d) => d.id === selectedId)?.name ?? \"document\";\n\n return (\n <DefaultToolbar>\n <DefaultToolbarContent />\n\n <div style={{ width: \"1px\", height: \"20px\", background: \"#ddd\", margin: \"0 4px\", flexShrink: 0 }} />\n\n <div\n style={{\n position: \"relative\",\n display: \"inline-flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n flexShrink: 0,\n }}\n >\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={handlePlusClick}\n title={`New document (${selectedName})`}\n style={{\n display: \"inline-flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: \"32px\",\n height: \"32px\",\n border: \"none\",\n borderRadius: \"6px\",\n background: isActive || menuOpen ? \"var(--color-selected, #e8f0fe)\" : \"transparent\",\n cursor: \"pointer\",\n color: isActive || menuOpen ? \"var(--color-selected-contrast, #2f80ed)\" : \"currentColor\",\n flexShrink: 0,\n }}\n >\n <svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\">\n <path d=\"M8 2v12M2 8h12\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n </svg>\n </button>\n\n {menuOpen &&\n menuPos &&\n datatypes.length > 1 &&\n createPortal(\n <div\n ref={menuRef}\n style={{\n position: \"fixed\",\n left: menuPos.x,\n top: menuPos.y,\n transform: \"translate(-50%, -100%)\",\n marginTop: \"-8px\",\n background: \"#fff\",\n border: \"1px solid #ddd\",\n borderRadius: \"8px\",\n boxShadow: \"0 4px 12px rgba(0,0,0,0.12)\",\n padding: \"4px\",\n minWidth: \"160px\",\n zIndex: 100000,\n }}\n >\n {datatypes.map((dt) => (\n <button\n key={dt.id}\n type=\"button\"\n onPointerDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n handlePick(dt.id);\n }}\n style={{\n display: \"block\",\n width: \"100%\",\n padding: \"6px 10px\",\n border: \"none\",\n borderRadius: \"4px\",\n background: dt.id === selectedId ? \"#e8f0fe\" : \"transparent\",\n cursor: \"pointer\",\n fontSize: \"13px\",\n fontFamily: \"system-ui, -apple-system, sans-serif\",\n color: \"#333\",\n textAlign: \"left\",\n whiteSpace: \"nowrap\",\n }}\n >\n {dt.name}\n </button>\n ))}\n </div>,\n document.body,\n )}\n </div>\n </DefaultToolbar>\n );\n}\n", "/**\n * Patchwork drag-and-drop payload parsing.\n *\n * Patchwork document drags (from the folder-tree-view / sideboard and most\n * tools) carry these DataTransfer formats:\n * - `text/x-patchwork-urls` \u2014 JSON `AutomergeUrl[]` (the detection hook)\n * - `text/x-patchwork-dnd` \u2014 JSON `{ source, items: [{ id, url, type, name }] }`\n * - `text/uri-list` / `text/plain` \u2014 one Patchwork web link per line\n *\n * Only `text/x-patchwork-urls` is guaranteed; the richer `-dnd` payload, when\n * present, gives us the datatype id and display name without a repo lookup.\n */\n\nimport {\n isValidAutomergeUrl,\n parseAutomergeUrl,\n stringifyAutomergeUrl,\n type AutomergeUrl,\n type DocumentId,\n} from \"@automerge/automerge-repo/slim\";\n\nexport const PATCHWORK_URLS_MIME = \"text/x-patchwork-urls\" as const;\nexport const PATCHWORK_DND_MIME = \"text/x-patchwork-dnd\" as const;\n\nexport interface DroppedDoc {\n url: AutomergeUrl;\n /** Datatype id (from the `-dnd` payload), if known. */\n type?: string;\n /** Display name (from the `-dnd` payload), if known. */\n name?: string;\n}\n\n/** True when the drag carries Patchwork document URLs. */\nexport function isPatchworkDrag(types: readonly string[]): boolean {\n return types.includes(PATCHWORK_URLS_MIME);\n}\n\ntype DndItem = { url?: unknown; type?: unknown; name?: unknown };\ntype DndPayload = { items?: DndItem[] };\n\n/** Extract the dropped documents, preferring the richest payload available. */\nexport function parseDroppedDocs(dt: DataTransfer | null): DroppedDoc[] {\n if (!dt) return [];\n\n // 1. Structured payload with datatype + name.\n const dnd = dt.getData(PATCHWORK_DND_MIME);\n if (dnd) {\n try {\n const parsed = JSON.parse(dnd) as DndPayload;\n const items = (parsed.items ?? [])\n .map((it): DroppedDoc | null => {\n const url = typeof it.url === \"string\" ? it.url : undefined;\n if (!url || !isValidAutomergeUrl(url)) return null;\n return {\n url,\n type: typeof it.type === \"string\" ? it.type : undefined,\n name: typeof it.name === \"string\" ? it.name : undefined,\n };\n })\n .filter((it): it is DroppedDoc => it !== null);\n if (items.length > 0) return dedupe(items);\n } catch {\n // fall through\n }\n }\n\n // 2. Bare URL list.\n const urls = dt.getData(PATCHWORK_URLS_MIME);\n if (urls) {\n try {\n const parsed: unknown = JSON.parse(urls);\n const items = (Array.isArray(parsed) ? parsed : [])\n .filter((u): u is AutomergeUrl => typeof u === \"string\" && isValidAutomergeUrl(u))\n .map((url) => ({ url }));\n if (items.length > 0) return dedupe(items);\n } catch {\n // fall through\n }\n }\n\n // 3. Plain-text / uri-list fallback (external links, \"#doc=<id>\" form).\n const text = dt.getData(\"text/uri-list\") || dt.getData(\"text/plain\");\n if (text) {\n const items = text\n .split(/\\r?\\n/)\n .map(urlFromText)\n .filter((url): url is AutomergeUrl => url !== null)\n .map((url) => ({ url }));\n if (items.length > 0) return dedupe(items);\n }\n\n return [];\n}\n\nfunction dedupe(items: DroppedDoc[]): DroppedDoc[] {\n const seen = new Set<string>();\n const out: DroppedDoc[] = [];\n for (const it of items) {\n if (seen.has(it.url)) continue;\n seen.add(it.url);\n out.push(it);\n }\n return out;\n}\n\n// Accept `automerge:\u2026` directly, or a Patchwork web link containing\n// `#doc=<documentId>` / `?doc=<documentId>`.\nfunction urlFromText(line: string): AutomergeUrl | null {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) return null;\n if (isValidAutomergeUrl(trimmed)) return trimmed;\n\n const match = trimmed.match(/[#?&]doc=([^&\\s]+)/);\n if (match) {\n const raw = decodeURIComponent(match[1]);\n if (isValidAutomergeUrl(raw)) return raw;\n try {\n const url = stringifyAutomergeUrl({ documentId: raw as DocumentId });\n // Round-trip to reject malformed ids.\n parseAutomergeUrl(url);\n return url;\n } catch {\n return null;\n }\n }\n return null;\n}\n", "import type { AutomergeUrl } from \"@automerge/automerge-repo/slim\";\nimport type { TLCursorProps } from \"@tldraw/tldraw\";\n\n// Parses a userId of the form `${contactUrl}-${peerId}` to recover contactUrl\n// and actorId (see useContactInfo in tool.tsx for why userIds are composed).\nexport function splitPresenceUserId(userId: string): {\n contactUrl?: AutomergeUrl;\n actorId?: string;\n} {\n if (!userId.startsWith(\"automerge:\")) return { actorId: userId };\n const i = userId.indexOf(\"-\");\n if (i === -1) return { contactUrl: userId as AutomergeUrl };\n return {\n contactUrl: userId.slice(0, i) as AutomergeUrl,\n actorId: userId.slice(i + 1),\n };\n}\n\n/**\n * Collaborator cursor override: tldraw's default arrow, but the nametag is\n * replaced by the shared \"contact-cursor\" token (rendered live from the\n * peer's contact doc), so remote cursors look the same on canvases as in\n * text editors. The arrow paths are copied from tldraw's own cursor SVG --\n * the shared symbol DefaultCursor references has a runtime-generated id we\n * can't reach from here.\n */\nexport function ContactCollaboratorCursor({\n className,\n point,\n zoom,\n color,\n name,\n userId,\n}: TLCursorProps) {\n if (!point) return null;\n const { contactUrl } = splitPresenceUserId(userId);\n return (\n <div\n className={\n className ? `tl-overlays__item ${className}` : \"tl-overlays__item\"\n }\n style={{\n transform: `translate(${point.x}px, ${point.y}px) scale(${1 / zoom})`,\n }}\n >\n <svg\n className=\"tl-cursor\"\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 32 32\"\n fill=\"none\"\n aria-hidden=\"true\"\n >\n {/* translate(-12,-12) puts the arrow tip at the presence point (the\n shadow copy sits 1px off), matching tldraw's CursorDef -- and\n keeps the arrow clear of the nametag slot below. */}\n <g fill=\"rgba(0,0,0,.2)\" transform=\"translate(-11,-11)\">\n <path d=\"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z\" />\n <path d=\"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z\" />\n </g>\n <g style={{ color }} transform=\"translate(-12,-12)\">\n <path\n d=\"m12 24.4219v-16.015l11.591 11.619h-6.781l-.411.124z\"\n fill=\"white\"\n />\n <path\n d=\"m21.0845 25.0962-3.605 1.535-4.682-11.089 3.686-1.553z\"\n fill=\"white\"\n />\n <path\n d=\"m19.751 24.4155-1.844.774-3.1-7.374 1.841-.775z\"\n fill=\"currentColor\"\n />\n <path\n d=\"m13 10.814v11.188l2.969-2.866.428-.139h4.768z\"\n fill=\"currentColor\"\n />\n </g>\n </svg>\n {contactUrl ? (\n // Same offset as tldraw's .tl-nametag so the token hangs off the\n // arrow tip.\n <div style={{ position: \"absolute\", top: 16, left: 13 }}>\n {/* @ts-expect-error Custom element from @inkandswitch/patchwork-elements */}\n <patchwork-view doc-url={contactUrl} tool-id=\"contact-cursor\" />\n </div>\n ) : (\n name && (\n <div className=\"tl-nametag\" style={{ backgroundColor: color }}>\n {name}\n </div>\n )\n )}\n </div>\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,mBAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;ACM3C,SAAgB,YAAe,SAAwC;AACrE,MAAI,SAAiB;AACrB,MAAI;AACJ,MAAI;AAEJ,QAAM,YAAY,QAAQ,KAAA,CACxB,SAAQ;AACN,aAAS;AACT,aAAS;EACX,GAAA,CACA,QAAO;AACL,aAAS;AACT,YAAQ;EACV,CACF;AAEA,SAAO;IACL;IACA,OAAU;AACR,cAAQ,QAAR;QACE,KAAK;AACH,gBAAM;QACR,KAAK;AACH,gBAAM;QACR,KAAK;AACH,iBAAO;MACX;IACF;EACF;AACF;AChCA,IAAa,kBAAc,4BAA2B,IAAI;AAG1D,SAAgB,UAAgB;AAC9B,QAAM,WAAO,yBAAW,WAAW;AACnC,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,oCAAoC;AAC/D,SAAO;AACT;ACXA,IAAA,gBAAe;ACCf,SAAS,SAAS,MAAM;AACpB,SAAO,OAAO,SAAS,YAAYA,cAAM,KAAK,IAAI;AACtD;ACFA,SAAS,MAAM,MAAM;AACjB,MAAI,CAAC,SAAS,IAAI,EACd,OAAM,UAAU,cAAc;AAElC,MAAI;AACJ,SAAO,WAAW,IAAI,IAAI,SAAS,KAAK,MAAM,GAAG,CAAC,GAAG,EAAE,OAAO,IAAK,MAAM,KAAM,KAAO,MAAM,IAAK,KAAM,IAAI,MAAO,IAAI,SAAS,KAAK,MAAM,GAAG,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,MAAO,IAAI,SAAS,KAAK,MAAM,IAAI,EAAE,GAAG,EAAE,OAAO,GAAG,IAAI,MAAO,IAAI,SAAS,KAAK,MAAM,IAA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A,IACrC;AAEA,YAAQ,iBAAiB,aAAa,WAAW,EAAE,SAAS,KAAK,CAAC;AAClE,YAAQ,iBAAiB,YAAY,WAAW,EAAE,SAAS,KAAK,CAAC;AACjE,YAAQ,iBAAiB,QAAQ,YAAY,EAAE,SAAS,KAAK,CAAC;AAC9D,WAAO,MAAM;AACX,cAAQ,oBAAoB,aAAa,WAAW,EAAE,SAAS,KAAK,CAAC;AACrE,cAAQ,oBAAoB,YAAY,WAAW,EAAE,SAAS,KAAK,CAAC;AACpE,cAAQ,oBAAoB,QAAQ,YAAY,EAAE,SAAS,KAAK,CAAC;AAAA,IACnE;AAAA,EACF,GAAG,CAAC,QAAQ,MAAM,OAAO,CAAC;AAC5B;AAEO,SAAS,OAAO,QAAa,SAAc;AAChD,QAAM,WAAO,0BAAW,OAAO;AAC/B,OAAK;AAAA,IACH,6CAAC,YAAY,UAAZ,EAAqB,OAAO,QAAQ,MACnC,uDAAC,cAAW,QAAQ,OAAO,KAAK,SAAkB,GACpD;AAAA,EACF;AACA,SAAO,MAAM,KAAK,QAAQ;AAC5B;",
6
+ "names": ["REGEX", "view", "sha256n", "basex", "base58", "bs58checkBase", "parse", "handle", "__toESM", "initialState", "import_react", "store", "doc", "import_react", "automergeUrlToServiceWorkerUrl", "import_react", "import_react", "DiffShapeWrapper", "import_react", "import_jsx_runtime", "import_react", "import_react", "import_jsx_runtime", "isValidAutomergeUrl", "parseAutomergeUrl", "stringifyAutomergeUrl", "import_jsx_runtime", "import_jsx_runtime", "automergeUrlToServiceWorkerUrl"]
7
7
  }