@aionbuilders/nabu 0.1.0-beta.0 → 0.1.1

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 (308) hide show
  1. package/CHANGELOG.md +531 -0
  2. package/LICENSE +21 -0
  3. package/README.md +72 -341
  4. package/dist/behaviors/text/RichText.svelte +24 -4
  5. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +3 -0
  6. package/dist/behaviors/text/markdown-shortcuts.extension.js +35 -10
  7. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  8. package/dist/behaviors/text/markdown-syntax.js +81 -0
  9. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  10. package/dist/behaviors/text/rich-text.extension.js +95 -38
  11. package/dist/behaviors/text/text.behavior.svelte.d.ts +195 -55
  12. package/dist/behaviors/text/text.behavior.svelte.js +531 -103
  13. package/dist/behaviors/text/typography.extension.d.ts +2 -1
  14. package/dist/behaviors/text/typography.extension.js +3 -2
  15. package/dist/blocks/BlockList.svelte +48 -0
  16. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  17. package/dist/blocks/Nabu.svelte +169 -25
  18. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  19. package/dist/blocks/block.extension.d.ts +3 -0
  20. package/dist/blocks/block.extension.js +4 -7
  21. package/dist/blocks/block.svelte.d.ts +350 -86
  22. package/dist/blocks/block.svelte.js +370 -59
  23. package/dist/blocks/blockquote/Blockquote.svelte +1 -2
  24. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -1
  25. package/dist/blocks/blockquote/blockquote.extension.js +14 -5
  26. package/dist/blocks/blockquote/blockquote.svelte.d.ts +19 -11
  27. package/dist/blocks/blockquote/blockquote.svelte.js +58 -13
  28. package/dist/blocks/callout/Callout.svelte +6 -8
  29. package/dist/blocks/callout/callout.extension.d.ts +4 -1
  30. package/dist/blocks/callout/callout.extension.js +19 -3
  31. package/dist/blocks/callout/callout.svelte.d.ts +5 -3
  32. package/dist/blocks/callout/callout.svelte.js +11 -6
  33. package/dist/blocks/chunks.d.ts +49 -0
  34. package/dist/blocks/chunks.js +90 -0
  35. package/dist/blocks/code/Code.svelte +7 -8
  36. package/dist/blocks/code/code.extension.d.ts +4 -1
  37. package/dist/blocks/code/code.extension.js +22 -2
  38. package/dist/blocks/code/code.svelte.d.ts +9 -2
  39. package/dist/blocks/code/code.svelte.js +49 -25
  40. package/dist/blocks/container.utils.d.ts +85 -13
  41. package/dist/blocks/container.utils.js +338 -178
  42. package/dist/blocks/dialogue/Dialogue.svelte +8 -4
  43. package/dist/blocks/dialogue/dialogue.svelte.d.ts +33 -2
  44. package/dist/blocks/dialogue/dialogue.svelte.js +58 -4
  45. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  46. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  47. package/dist/blocks/dialogue/index.d.ts +12 -1
  48. package/dist/blocks/dialogue/index.js +51 -35
  49. package/dist/blocks/divider/divider.extension.d.ts +23 -1
  50. package/dist/blocks/divider/divider.extension.js +85 -19
  51. package/dist/blocks/divider/divider.svelte.d.ts +7 -2
  52. package/dist/blocks/divider/divider.svelte.js +9 -4
  53. package/dist/blocks/file/File.svelte +13 -6
  54. package/dist/blocks/file/file.extension.d.ts +4 -1
  55. package/dist/blocks/file/file.extension.js +9 -1
  56. package/dist/blocks/file/file.svelte.d.ts +3 -3
  57. package/dist/blocks/file/file.svelte.js +20 -14
  58. package/dist/blocks/heading/Heading.svelte +1 -2
  59. package/dist/blocks/heading/heading.svelte.d.ts +23 -11
  60. package/dist/blocks/heading/heading.svelte.js +68 -13
  61. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  62. package/dist/blocks/heading/index.d.ts +2 -2
  63. package/dist/blocks/heading/index.js +33 -8
  64. package/dist/blocks/image/Image.svelte +5 -2
  65. package/dist/blocks/image/image.extension.d.ts +4 -1
  66. package/dist/blocks/image/image.extension.js +9 -1
  67. package/dist/blocks/image/image.svelte.d.ts +17 -6
  68. package/dist/blocks/image/image.svelte.js +33 -11
  69. package/dist/blocks/index.d.ts +1 -1
  70. package/dist/blocks/index.js +1 -1
  71. package/dist/blocks/list/List.svelte +1 -0
  72. package/dist/blocks/list/ListItem.svelte +1 -0
  73. package/dist/blocks/list/convert.d.ts +20 -0
  74. package/dist/blocks/list/convert.js +92 -0
  75. package/dist/blocks/list/hooks/onBeforeInput.hook.js +49 -28
  76. package/dist/blocks/list/html-flat.d.ts +78 -0
  77. package/dist/blocks/list/html-flat.js +244 -0
  78. package/dist/blocks/list/indent.d.ts +86 -0
  79. package/dist/blocks/list/indent.js +205 -0
  80. package/dist/blocks/list/index.d.ts +6 -3
  81. package/dist/blocks/list/index.js +42 -31
  82. package/dist/blocks/list/list-item.svelte.d.ts +32 -18
  83. package/dist/blocks/list/list-item.svelte.js +99 -100
  84. package/dist/blocks/list/list.behavior.svelte.d.ts +4 -1
  85. package/dist/blocks/list/list.behavior.svelte.js +6 -1
  86. package/dist/blocks/list/list.svelte.d.ts +89 -18
  87. package/dist/blocks/list/list.svelte.js +129 -125
  88. package/dist/blocks/list/markdown.d.ts +149 -0
  89. package/dist/blocks/list/markdown.js +442 -0
  90. package/dist/blocks/list/normalize.d.ts +11 -0
  91. package/dist/blocks/list/normalize.js +396 -0
  92. package/dist/blocks/list/paste.d.ts +45 -0
  93. package/dist/blocks/list/paste.js +242 -0
  94. package/dist/blocks/list/step-back.d.ts +24 -0
  95. package/dist/blocks/list/step-back.js +87 -0
  96. package/dist/blocks/list/to-list.d.ts +7 -0
  97. package/dist/blocks/list/to-list.js +44 -0
  98. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  99. package/dist/blocks/list/todos-toggle.js +48 -0
  100. package/dist/blocks/media/markdown.d.ts +12 -0
  101. package/dist/blocks/media/markdown.js +26 -0
  102. package/dist/blocks/media/media-block.svelte.d.ts +77 -2
  103. package/dist/blocks/media/media-block.svelte.js +124 -12
  104. package/dist/blocks/media/media.helpers.d.ts +6 -1
  105. package/dist/blocks/media/media.helpers.js +43 -6
  106. package/dist/blocks/megablock.svelte.d.ts +50 -19
  107. package/dist/blocks/megablock.svelte.js +114 -74
  108. package/dist/blocks/move.d.ts +23 -0
  109. package/dist/blocks/move.js +92 -0
  110. package/dist/blocks/nabu.svelte.d.ts +764 -71
  111. package/dist/blocks/nabu.svelte.js +1753 -189
  112. package/dist/blocks/paragraph/Paragraph.svelte +1 -2
  113. package/dist/blocks/paragraph/index.d.ts +2 -2
  114. package/dist/blocks/paragraph/index.js +35 -13
  115. package/dist/blocks/paragraph/paragraph.svelte.d.ts +46 -14
  116. package/dist/blocks/paragraph/paragraph.svelte.js +77 -16
  117. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  118. package/dist/blocks/paragraph/table.html.js +111 -0
  119. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  120. package/dist/blocks/paragraph/table.markdown.js +90 -0
  121. package/dist/blocks/region/Region.svelte +264 -0
  122. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  123. package/dist/blocks/region/actions.d.ts +135 -0
  124. package/dist/blocks/region/actions.js +402 -0
  125. package/dist/blocks/region/close.d.ts +35 -0
  126. package/dist/blocks/region/close.js +130 -0
  127. package/dist/blocks/region/commands.d.ts +6 -0
  128. package/dist/blocks/region/commands.js +277 -0
  129. package/dist/blocks/region/create.d.ts +72 -0
  130. package/dist/blocks/region/create.js +208 -0
  131. package/dist/blocks/region/end-marker.d.ts +35 -0
  132. package/dist/blocks/region/end-marker.js +51 -0
  133. package/dist/blocks/region/facts.d.ts +69 -0
  134. package/dist/blocks/region/facts.js +152 -0
  135. package/dist/blocks/region/format.d.ts +91 -0
  136. package/dist/blocks/region/format.js +260 -0
  137. package/dist/blocks/region/index.d.ts +14 -0
  138. package/dist/blocks/region/index.js +14 -0
  139. package/dist/blocks/region/insert.d.ts +59 -0
  140. package/dist/blocks/region/insert.js +102 -0
  141. package/dist/blocks/region/messages.d.ts +254 -0
  142. package/dist/blocks/region/messages.js +131 -0
  143. package/dist/blocks/region/normalize.d.ts +7 -0
  144. package/dist/blocks/region/normalize.js +170 -0
  145. package/dist/blocks/region/region.extension.d.ts +58 -0
  146. package/dist/blocks/region/region.extension.js +119 -0
  147. package/dist/blocks/region/region.svelte.d.ts +221 -0
  148. package/dist/blocks/region/region.svelte.js +582 -0
  149. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  150. package/dist/blocks/region/regions.svelte.js +276 -0
  151. package/dist/blocks/region/serialize.d.ts +57 -0
  152. package/dist/blocks/region/serialize.js +112 -0
  153. package/dist/blocks/region/types.d.ts +255 -0
  154. package/dist/blocks/region/types.js +204 -0
  155. package/dist/blocks/selection.svelte.d.ts +106 -8
  156. package/dist/blocks/selection.svelte.js +622 -74
  157. package/dist/blocks/subthread.d.ts +80 -0
  158. package/dist/blocks/subthread.js +167 -0
  159. package/dist/blocks/text-block.svelte.d.ts +35 -14
  160. package/dist/blocks/text-block.svelte.js +42 -8
  161. package/dist/blocks/toggle/Toggle.svelte +4 -15
  162. package/dist/blocks/toggle/markdown.d.ts +20 -0
  163. package/dist/blocks/toggle/markdown.js +112 -0
  164. package/dist/blocks/toggle/toggle.extension.d.ts +4 -1
  165. package/dist/blocks/toggle/toggle.extension.js +6 -0
  166. package/dist/blocks/toggle/toggle.svelte.d.ts +55 -8
  167. package/dist/blocks/toggle/toggle.svelte.js +134 -34
  168. package/dist/blocks/undo-selection.d.ts +175 -0
  169. package/dist/blocks/undo-selection.js +360 -0
  170. package/dist/blocks/video/Video.svelte +5 -2
  171. package/dist/blocks/video/video.extension.d.ts +4 -1
  172. package/dist/blocks/video/video.extension.js +9 -1
  173. package/dist/blocks/video/video.svelte.d.ts +6 -5
  174. package/dist/blocks/video/video.svelte.js +18 -9
  175. package/dist/extend.d.ts +55 -0
  176. package/dist/extend.js +88 -0
  177. package/dist/files/assets.clipboard.d.ts +77 -0
  178. package/dist/files/assets.clipboard.js +152 -0
  179. package/dist/files/files.svelte.d.ts +321 -19
  180. package/dist/files/files.svelte.js +847 -43
  181. package/dist/files/index.d.ts +3 -1
  182. package/dist/files/index.js +3 -1
  183. package/dist/files/outbox.d.ts +69 -0
  184. package/dist/files/outbox.js +48 -0
  185. package/dist/files/status.d.ts +65 -0
  186. package/dist/files/status.js +87 -0
  187. package/dist/files/store.d.ts +97 -0
  188. package/dist/files/store.js +65 -0
  189. package/dist/files/uploads.svelte.d.ts +174 -0
  190. package/dist/files/uploads.svelte.js +504 -0
  191. package/dist/index.d.ts +68 -9
  192. package/dist/index.js +117 -10
  193. package/dist/nabu-theme.css +21 -1
  194. package/dist/paste/html.paste.d.ts +74 -3
  195. package/dist/paste/html.paste.js +550 -86
  196. package/dist/paste/markdown-inline.d.ts +86 -0
  197. package/dist/paste/markdown-inline.js +528 -0
  198. package/dist/paste/markdown.paste.d.ts +2 -8
  199. package/dist/paste/markdown.paste.js +78 -94
  200. package/dist/paste/nabu.paste.d.ts +3 -0
  201. package/dist/paste/nabu.paste.js +29 -3
  202. package/dist/paste/plain-text.paste.d.ts +2 -2
  203. package/dist/paste/plain-text.paste.js +3 -3
  204. package/dist/persistence/asset-store.d.ts +51 -0
  205. package/dist/persistence/asset-store.js +103 -0
  206. package/dist/persistence/autosave.d.ts +53 -0
  207. package/dist/persistence/autosave.js +62 -0
  208. package/dist/persistence/compact.d.ts +162 -0
  209. package/dist/persistence/compact.js +141 -0
  210. package/dist/persistence/history.d.ts +77 -0
  211. package/dist/persistence/history.js +176 -0
  212. package/dist/persistence/indexeddb.d.ts +190 -4
  213. package/dist/persistence/indexeddb.js +333 -29
  214. package/dist/persistence/merge.d.ts +38 -0
  215. package/dist/persistence/merge.js +36 -0
  216. package/dist/persistence/outbox.d.ts +25 -0
  217. package/dist/persistence/outbox.js +40 -0
  218. package/dist/persistence/persistence.d.ts +70 -9
  219. package/dist/persistence/persistence.js +507 -35
  220. package/dist/persistence/recovery.d.ts +79 -0
  221. package/dist/persistence/recovery.js +79 -0
  222. package/dist/persistence/release.d.ts +34 -0
  223. package/dist/persistence/release.js +64 -0
  224. package/dist/persistence/state.svelte.d.ts +53 -0
  225. package/dist/persistence/state.svelte.js +48 -0
  226. package/dist/persistence/sync.d.ts +39 -0
  227. package/dist/persistence/sync.js +138 -0
  228. package/dist/persistence/tail.d.ts +42 -0
  229. package/dist/persistence/tail.js +103 -0
  230. package/dist/presets.d.ts +29 -26
  231. package/dist/presets.js +35 -13
  232. package/dist/themes/atelier.css +318 -0
  233. package/dist/ui/CommandChooser.svelte +153 -0
  234. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  235. package/dist/ui/CommandInvite.svelte +99 -0
  236. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  237. package/dist/ui/DragHandle.svelte +97 -21
  238. package/dist/ui/FloatingToolbar.svelte +75 -27
  239. package/dist/ui/FloatingToolbar.svelte.d.ts +10 -0
  240. package/dist/ui/SlashMenu.svelte +147 -15
  241. package/dist/ui/SlashMenu.svelte.d.ts +20 -0
  242. package/dist/ui/anchor.d.ts +112 -0
  243. package/dist/ui/anchor.js +136 -0
  244. package/dist/ui/index.d.ts +7 -1
  245. package/dist/ui/index.js +12 -1
  246. package/dist/ui/slash-menu.svelte.d.ts +79 -7
  247. package/dist/ui/slash-menu.svelte.js +85 -51
  248. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  249. package/dist/utils/command-confirm.svelte.js +673 -0
  250. package/dist/utils/commands.d.ts +328 -0
  251. package/dist/utils/commands.js +416 -0
  252. package/dist/utils/composition.d.ts +28 -0
  253. package/dist/utils/composition.js +51 -0
  254. package/dist/utils/dom-scope.d.ts +14 -0
  255. package/dist/utils/dom-scope.js +20 -0
  256. package/dist/utils/drop.d.ts +160 -0
  257. package/dist/utils/drop.js +305 -0
  258. package/dist/utils/extensions.d.ts +439 -45
  259. package/dist/utils/extensions.js +271 -29
  260. package/dist/utils/html.d.ts +44 -0
  261. package/dist/utils/html.js +183 -0
  262. package/dist/utils/index.d.ts +3 -0
  263. package/dist/utils/index.js +3 -0
  264. package/dist/utils/keys.d.ts +120 -0
  265. package/dist/utils/keys.js +248 -0
  266. package/dist/utils/links.d.ts +22 -0
  267. package/dist/utils/links.js +34 -0
  268. package/dist/utils/placeholders.d.ts +81 -3
  269. package/dist/utils/placeholders.js +73 -3
  270. package/dist/utils/selection.svelte.d.ts +48 -20
  271. package/dist/utils/selection.svelte.js +60 -10
  272. package/dist/utils/spellcheck.d.ts +9 -0
  273. package/dist/utils/spellcheck.js +17 -0
  274. package/dist/utils/tab.d.ts +31 -0
  275. package/dist/utils/tab.js +117 -0
  276. package/dist/utils/words.d.ts +42 -0
  277. package/dist/utils/words.js +147 -0
  278. package/dist/vite.d.ts +9 -3
  279. package/dist/vite.js +19 -8
  280. package/package.json +56 -20
  281. package/dist/blocks/variable.svelte.d.ts +0 -47
  282. package/dist/blocks/variable.svelte.js +0 -51
  283. package/dist/blocks/zone/TemplateEditor.svelte +0 -308
  284. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +0 -11
  285. package/dist/blocks/zone/Zone.svelte +0 -272
  286. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  287. package/dist/blocks/zone/ZoneEditor.svelte +0 -289
  288. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +0 -11
  289. package/dist/blocks/zone/ZoneTemplatesList.svelte +0 -188
  290. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +0 -11
  291. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +0 -3
  292. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +0 -30
  293. package/dist/blocks/zone/index.d.ts +0 -2
  294. package/dist/blocks/zone/index.js +0 -2
  295. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  296. package/dist/blocks/zone/zone.extension.js +0 -237
  297. package/dist/blocks/zone/zone.svelte.d.ts +0 -221
  298. package/dist/blocks/zone/zone.svelte.js +0 -608
  299. package/dist/overlays/context/Context.svelte +0 -182
  300. package/dist/overlays/context/Context.svelte.d.ts +0 -17
  301. package/dist/overlays/context/collect.d.ts +0 -17
  302. package/dist/overlays/context/collect.js +0 -33
  303. package/dist/overlays/context/context.extension.d.ts +0 -2
  304. package/dist/overlays/context/context.extension.js +0 -8
  305. package/dist/overlays/context/context.svelte.d.ts +0 -82
  306. package/dist/overlays/context/context.svelte.js +0 -159
  307. package/dist/overlays/context/index.d.ts +0 -3
  308. package/dist/overlays/context/index.js +0 -3
@@ -1,28 +1,138 @@
1
- import { LoroMap } from 'loro-crdt';
1
+ import { SvelteMap } from 'svelte/reactivity';
2
+ import { sanitizeUrl } from '../utils/html.js';
3
+ import { ASSET_PREFIX, PENDING_PREFIX, assetIdOf, isHashId, sha256Id, mapAssetBlocks, mapRemoteBlocks, remoteFileName, collectAssetIds, bytesToBase64, base64ToBytes } from './assets.clipboard.js';
4
+ import { MemoryAssetStore } from './store.js';
5
+ import { Uploads } from './uploads.svelte.js';
6
+ import { FileRejectedError, tooLarge, reasonOf } from './status.js';
7
+
8
+ /** @import { AssetStore, AssetMeta } from './store.js' */
9
+ /** @import { Outbox } from './outbox.js' */
10
+ /** @import { FileReason, FileStatus } from './status.js' */
11
+
12
+ export { FileRejectedError };
13
+
14
+ /** Origin of the commits that finish a paste in the background (ref swap): not undoable. See Nabu's UndoManager. */
15
+ export const SILENT_ORIGIN = 'nabu:silent:files';
16
+ /** Largest asset (bytes) turned into a `data:` URL in the `text/html` of a copy. */
17
+ export const HTML_INLINE_LIMIT = 1024 * 1024;
18
+ /** Upper bound (bytes) of the in-memory copy of the bytes kept to answer a (synchronous) copy / export. */
19
+ const EMBED_CACHE_BUDGET = 32 * 1024 * 1024;
20
+
21
+ /**
22
+ * An asset as carried by `application/x-nabu+json` (`assets: { [id]: EmbeddedAsset }`), `id` being the part of the ref
23
+ * after `nabu-asset:` (`sha256-<hex>`, or a beta `<uuid>`). An entry with `omitted: true` and no `data` says "this file
24
+ * exists but its bytes are NOT in this copy" (too large, or not loaded yet): the receiver shows the block as `missing`
25
+ * with the reason `not-embedded` (unless its own store already has the file).
26
+ * @typedef {Object} EmbeddedAsset
27
+ * @property {string} mime
28
+ * @property {string} name
29
+ * @property {number} size byte length
30
+ * @property {string} [data] base64 (absent when `omitted`)
31
+ * @property {boolean} [omitted]
32
+ */
2
33
 
3
34
  /**
4
35
  * @typedef {Object} FilesConfig
36
+ * @property {AssetStore} [store] Where the BYTES of the files live (ADR 014). Default: a `MemoryAssetStore`
37
+ * (`createPersistedEditor`: an `IndexedDBAssetStore` shared by all the documents of the origin). The document itself only
38
+ * holds `nabu-asset:sha256-<hex>` references and a metadata index (`assetIndex`).
5
39
  * @property {(file: File, ctx: { signal?: AbortSignal, onProgress?: (p: number) => void }) => Promise<{ ref: string } | void>} [onBeforePersist]
6
- * Intercept before default persistence. Return `{ ref }` to redirect to your own
7
- * storage (the bytes are NOT stored in Loro). Return nothing to fall back to default.
40
+ * Host storage (ADR 014 §3.4). The file is always written to the local store first and the block keeps its
41
+ * `nabu-asset:sha256-…` ref FOREVER; the upload then runs in the background (the block is `pending`, `block.progress` follows
42
+ * `onProgress(0..1)`). Return `{ ref }` (where the host keeps the file): it is recorded as `assetIndex[hash].url` and the
43
+ * block becomes `ready`. Throw to fail (`error`, the local copy is kept, `block.retry()` runs it again). `signal` fires when
44
+ * the upload is cancelled (`block.cancel()`) or when the last block that shows the file is deleted — honour it. The upload
45
+ * is retried from the local copy after a reload (it may therefore run more than once for one file: make it idempotent).
46
+ * @property {false | import('./uploads.svelte.js').AutoRetryConfig} [autoRetry] Retry on open (P-97), only meaningful with a host and a persisted editor:
47
+ * the uploads the outbox lists when the document is opened (interrupted, or failed earlier) are sent again by themselves, in the
48
+ * background, with a growing delay (`initialDelay` 2 s, doubling, `maxDelay` 60 s, `maxAttempts` 8 per session; the browser's `online`
49
+ * event grants a fresh series). A cancelled upload is never retried; failures of the current session are left to `block.retry()`.
50
+ * `false` turns it off.
51
+ * @property {number} [maxFileSize] Largest file (bytes) accepted; default none. A bigger file is REFUSED: the block that would
52
+ * have shown it is created with `status: 'rejected'`, no ref, and a readable `reason` (`too-large`).
53
+ * @property {Outbox} [outbox] Where the uploads still to do are listed (ADR 014 §3.4), scoped to this document. Default: in
54
+ * memory (`createPersistedEditor`: an `IndexedDBOutbox`, next to the asset store).
55
+ * @property {(ref: string) => void | Promise<void>} [onAssetReleased] Host mode, called with the host `url` (the `ref` your
56
+ * `onBeforePersist` returned) of a file that THIS document no longer references in any version it keeps: after a compaction
57
+ * (`history: { mode: 'compact' }` / `nabu.compact()`) released it, or when `clearPersistence()` deleted the document. Nabu NEVER
58
+ * deletes anything at the host: you decide (another document may still use the same host file). Awaited; an error is swallowed
59
+ * and reported with `nabu.warn`. Never called in the default `history: 'full'` mode (nothing is released).
60
+ * @property {number} [releaseGraceMs] Default 10 minutes. A release (compaction, `clearPersistence()`) never deletes from the shared store
61
+ * a file whose record is newer than this, nor one whose age is unknown: another tab may have just added it without having saved
62
+ * its references yet. Such a file is skipped and reconsidered at the next compaction / clear. `0` disables the grace period.
8
63
  * @property {(ref: string) => string} [resolve] Turn a stored ref into a display URL.
9
- * @property {number} [maxInlineSize] Byte threshold above which the default (Loro) mode warns. Default 2MB.
64
+ * @property {number} [maxInlineSize] Byte threshold for embedding files in a COPY / export (`application/x-nabu+json`,
65
+ * `serialize('json')`): above it (total, or for one file) the bytes are not embedded. Default 2MB.
66
+ * @property {boolean} [importRemote] Opt-in, default `false`. When `true`, a remote image / media (an `http(s)` URL) pasted
67
+ * from the HTML of a web page is fetched and stored in the local store (and sent to `onBeforePersist`, if any) instead of
68
+ * being hot-linked: the block shows the original URL meanwhile (`pending`) and gets its `nabu-asset:` ref when done. A fetch
69
+ * that fails (network, CORS, HTTP error) or a file over `maxFileSize` keeps the original URL.
10
70
  */
11
71
 
12
72
  /**
13
- * Document-level file/asset manager. Default mode stores bytes in a Loro `assets`
14
- * map (source of truth stays in Loro). Lazy: Files.get(nabu).
73
+ * @typedef {Object} EmbeddedBytes
74
+ * @property {Uint8Array} bytes @property {string} type @property {string} name
75
+ */
76
+
77
+ /**
78
+ * Document-level file/asset manager (ADR 014). The bytes of a file live in an {@link AssetStore}, the document only holds
79
+ * `nabu-asset:sha256-<hex>` references and a small `assetIndex` Loro map (`hash → { mime, name, size, url? }`).
80
+ * Lazy: Files.get(nabu).
15
81
  */
16
82
  export class Files {
17
83
  /** @type {import('../blocks/nabu.svelte.js').Nabu} */
18
84
  #nabu;
19
- /** @type {Map<string,string>} ref → objectURL cache for nabu-asset: refs */
20
- #urlCache = new Map();
85
+ /** @type {SvelteMap<string, string | null>} asset id → objectURL (or host URL) once loaded; `null` = no source has it (missing) */
86
+ #urls = new SvelteMap();
87
+ /** @type {Set<string>} ids being loaded from the store */
88
+ #loading = new Set();
89
+ /** @type {Map<string, number>} asset id → number of mounted blocks displaying it (see {@link Files#hold}) */
90
+ #holds = new Map();
91
+ /** @type {Map<string, { data: Uint8Array, type: string, name: string }>} id → bytes of the small files, for the synchronous copy / export */
92
+ #embed = new Map();
93
+ #embedBytes = 0;
94
+ /** @type {Set<string>} ids whose bytes are being read into the embed cache */
95
+ #warming = new Set();
96
+ /** @type {Map<string,string>} transient `nabu-pending:` ref → local objectURL (bytes being re-created by a paste) */
97
+ #pendingUrls = new Map();
98
+ /** @type {Map<string,string>} id of an asset pasted from ANOTHER document → the ref it got here (temporary until settled) */
99
+ #adopted = new Map();
100
+ /** @type {Map<string, Promise<void>>} hash → the background storage of bytes that arrived with a paste / import */
101
+ #inflight = new Map();
102
+ /** Background jobs (see {@link Files#whenIdle}). @type {Set<Promise<any>>} */
103
+ #jobs = new Set();
104
+ /** @type {Map<string, string>} beta uuid → hash id, for the assets migrated by THIS session */
105
+ #legacy = new Map();
106
+ /** @type {Map<string, string>} ref → objectURL of a beta asset whose bytes are still in the Loro `assets` map (migration pending) */
107
+ #legacyUrls = new Map();
108
+ /** The upload queue (host mode). @type {Uploads} */
109
+ #uploads;
110
+
111
+ /** Milliseconds an unused objectURL is kept before being revoked (a block that moves unmounts and remounts at once). */
112
+ revokeGraceMs = 1000;
21
113
 
22
114
  /** @param {import('../blocks/nabu.svelte.js').Nabu} nabu */
23
115
  constructor(nabu) {
24
116
  this.#nabu = nabu;
117
+ /** The local store of the bytes. @type {AssetStore} */
118
+ this.store = this.config.store ?? new MemoryAssetStore();
119
+ /** Beta format: bytes inside the document. Read-only legacy, emptied by the migration. */
25
120
  this.assets = nabu.doc.getMap('assets');
121
+ /** ADR 014 §3.2: `hash → { mime, name, size, url? }`, metadata only (never bytes). */
122
+ this.index = nabu.doc.getMap('assetIndex');
123
+ this.#uploads = new Uploads({
124
+ nabu,
125
+ store: this.store,
126
+ index: this.index,
127
+ config: () => this.config,
128
+ silent: (write) => this.#silent(write),
129
+ settled: async (hash) => { await this.#inflight.get(hash)?.catch(() => {}); },
130
+ forgetMissing: () => { for (const [key, value] of this.#urls) if (value === null) this.#urls.delete(key); },
131
+ track: (promise) => this.#track(promise),
132
+ });
133
+ nabu.doc.subscribe((event) => this.#uploads.onDocEvent(event));
134
+ if (this.assets.size > 0) this.#track(this.#migrate());
135
+ this.#preload();
26
136
  }
27
137
 
28
138
  /** @param {import('../blocks/nabu.svelte.js').Nabu} nabu @returns {Files} */
@@ -40,54 +150,748 @@ export class Files {
40
150
 
41
151
  get maxInlineSize() { return this.config.maxInlineSize ?? 2 * 1024 * 1024; }
42
152
 
153
+ /** `files.maxFileSize`, or `null` (no limit). @returns {number | null} */
154
+ get maxFileSize() {
155
+ const max = this.config.maxFileSize;
156
+ return typeof max === 'number' && max > 0 ? max : null;
157
+ }
158
+
159
+ /** Whether a host is configured (`files.onBeforePersist`): files are then uploaded in the background. @returns {boolean} */
160
+ get hosted() { return typeof this.config.onBeforePersist === 'function'; }
161
+
43
162
  /**
44
- * Persist a File → durable ref. Uses onBeforePersist if configured, else stores
45
- * the bytes in the Loro `assets` map.
46
- * @param {File} file
47
- * @param {{ signal?: AbortSignal, onProgress?: (p:number)=>void }} [ctx]
48
- * @returns {Promise<string>}
163
+ * Check a file size against `files.maxFileSize`.
164
+ * @param {number} size bytes @returns {FileReason | null} the reason it is refused, `null` when accepted
165
+ */
166
+ checkSize(size) {
167
+ const max = this.maxFileSize;
168
+ return max !== null && size > max ? tooLarge(size, max) : null;
169
+ }
170
+
171
+ // ── Background work ──────────────────────────────────────────────────────────────────────────
172
+
173
+ /**
174
+ * @template T
175
+ * @param {Promise<T>} promise @returns {Promise<T>}
176
+ */
177
+ #track(promise) {
178
+ const tracked = promise.finally(() => { this.#jobs.delete(tracked); });
179
+ this.#jobs.add(tracked);
180
+ return tracked;
181
+ }
182
+
183
+ /**
184
+ * Resolves when the background storage work started by a paste / import / migration is done (bytes verified and written
185
+ * to the store, index completed, missing files flagged). Uploads to a host (`onBeforePersist`) are NOT waited for.
186
+ * @returns {Promise<void>}
187
+ */
188
+ async whenIdle() {
189
+ while (this.#jobs.size) await Promise.allSettled([...this.#jobs]);
190
+ }
191
+
192
+ /**
193
+ * Run Loro writes as a silent commit (not an undo step). Whatever is pending in the open transaction is committed
194
+ * normally first, so that it does not end up swallowed by the silent origin.
195
+ * @param {() => void} write
196
+ */
197
+ async #silent(write) {
198
+ const nabu = this.#nabu;
199
+ for (let i = 0; i < 3 && nabu.doc.getUncommittedOpsAsJson(); i++) await nabu.commit();
200
+ write();
201
+ await nabu.commit({ origin: SILENT_ORIGIN });
202
+ }
203
+
204
+ // ── Storing ──────────────────────────────────────────────────────────────────────────────────
205
+
206
+ /** Ids (`sha256-<hex>`) of every file the document knows (its `assetIndex`): what a persisted document references. @returns {string[]} */
207
+ indexedHashes() { return Object.keys(this.index.toJSON()); }
208
+
209
+ /**
210
+ * The host location (`assetIndex[hash].url`) of each of `hashes` that has one (lot 3: what `onAssetReleased` receives).
211
+ * @param {Iterable<string>} hashes @returns {Map<string, string>}
49
212
  */
50
- async persist(file, ctx = {}) {
51
- const hook = this.config.onBeforePersist;
52
- if (hook) {
53
- const result = await hook(file, ctx);
54
- if (result && result.ref) return result.ref;
55
- // fell through → default
213
+ hostUrls(hashes) {
214
+ /** @type {Map<string, string>} */
215
+ const urls = new Map();
216
+ for (const hash of hashes) {
217
+ const url = /** @type {any} */ (this.index.get(hash))?.url;
218
+ if (typeof url === 'string' && url) urls.set(hash, url);
219
+ }
220
+ return urls;
221
+ }
222
+
223
+ /**
224
+ * How many uploads are still to do or running (the outbox of the document, plus any running job). A compaction refuses to run
225
+ * while this is not 0 (ADR 014 §3.6): the local copy is the only copy of such a file. Waits for the resume pass first.
226
+ * @returns {Promise<number>}
227
+ */
228
+ async pendingUploads() {
229
+ await this.#uploads.ready();
230
+ const entries = await this.#uploads.outbox.list().catch(() => []);
231
+ return entries.length || (this.#uploads.busy() ? 1 : 0);
232
+ }
233
+
234
+ /**
235
+ * Remove the index entries of files a compaction released (silent commit, not an undo step). The entries stay readable in the
236
+ * history that was archived / retained; only the live index forgets them.
237
+ * @param {Iterable<string>} hashes @returns {Promise<void>}
238
+ */
239
+ async releaseIndex(hashes) {
240
+ const ids = [...hashes].filter((id) => this.index.get(id) !== undefined);
241
+ if (!ids.length) return;
242
+ await this.#silent(() => { for (const id of ids) this.index.delete(id); });
243
+ for (const id of ids) {
244
+ const cached = this.#embed.get(id);
245
+ if (cached) { this.#embedBytes -= cached.data.length; this.#embed.delete(id); }
246
+ }
247
+ }
248
+
249
+ /** @param {string} id @param {AssetMeta} meta @returns {void} */
250
+ #setIndex(id, meta) {
251
+ if (!this.index.get(id)) this.index.set(id, { mime: meta.mime, name: meta.name, size: meta.size });
252
+ }
253
+
254
+ /** Remember the bytes of a small file for the synchronous copy / export (bounded; oldest forgotten first). @param {string} id @param {Uint8Array} bytes @param {AssetMeta} meta */
255
+ #remember(id, bytes, meta) {
256
+ if (bytes.length > this.maxInlineSize) return;
257
+ const previous = this.#embed.get(id);
258
+ if (previous) { this.#embedBytes -= previous.data.length; this.#embed.delete(id); }
259
+ this.#embed.set(id, { data: bytes, type: meta.mime, name: meta.name });
260
+ this.#embedBytes += bytes.length;
261
+ for (const [key, entry] of this.#embed) {
262
+ if (this.#embedBytes <= EMBED_CACHE_BUDGET || key === id) break;
263
+ this.#embed.delete(key);
264
+ this.#embedBytes -= entry.data.length;
56
265
  }
57
- if (file.size > this.maxInlineSize) {
58
- console.warn(`[Nabu] File "${file.name}" is ${(file.size / 1048576).toFixed(1)}MB — stored inline in the Loro document (default mode). For large media, configure files.onBeforePersist to upload to your own storage.`);
266
+ }
267
+
268
+ /** A file already in the store is used again: refresh its `savedAt` (release grace period, multi-tab safety). Never throws. @param {string} id */
269
+ async #touch(id) {
270
+ try { await this.store.touch?.(id); } catch { /* a stale savedAt only makes a release less cautious */ }
271
+ }
272
+
273
+ /**
274
+ * Write bytes (already verified) to the store, remember them and complete the index (silent commit).
275
+ * @param {string} id @param {Uint8Array} bytes @param {AssetMeta} meta
276
+ */
277
+ async #storeBytes(id, bytes, meta) {
278
+ await this.store.put(id, new Blob([/** @type {BlobPart} */ (bytes)], { type: meta.mime }), meta);
279
+ this.#remember(id, bytes, meta);
280
+ if (this.#urls.get(id) === null) this.#urls.delete(id); // it was reported missing a moment ago
281
+ await this.#silent(() => this.#setIndex(id, meta));
282
+ }
283
+
284
+ /**
285
+ * Hash a File and write it to the local store (deduplicated: the same bytes give the same id and one entry), then
286
+ * make sure the document's `assetIndex` knows it. This is step 1 of the lifecycle (ADR 014 §3.4).
287
+ * Throws {@link FileRejectedError} for a file over `files.maxFileSize`.
288
+ * @param {File} file
289
+ * @returns {Promise<{ id: string, ref: string, meta: AssetMeta }>}
290
+ */
291
+ async ingest(file) {
292
+ const rejection = this.checkSize(file.size);
293
+ if (rejection) throw new FileRejectedError(rejection);
294
+ const bytes = new Uint8Array(await file.arrayBuffer());
295
+ const id = await sha256Id(bytes);
296
+ const meta = { mime: file.type || 'application/octet-stream', name: file.name || '', size: bytes.length };
297
+ if (await this.store.has(id)) {
298
+ await this.#touch(id);
299
+ this.#remember(id, bytes, meta);
300
+ if (!this.index.get(id)) await this.#silent(() => this.#setIndex(id, meta));
301
+ } else {
302
+ await this.#storeBytes(id, bytes, meta);
59
303
  }
60
- const buf = new Uint8Array(await file.arrayBuffer());
61
- const id = (globalThis.crypto?.randomUUID?.() ?? String(Date.now()) + Math.random().toString(36).slice(2));
62
- const sub = this.assets.setContainer(id, new LoroMap());
63
- sub.set('data', buf);
64
- sub.set('type', file.type || 'application/octet-stream');
65
- sub.set('name', file.name || '');
66
- this.#nabu.doc.commit();
67
- return 'nabu-asset:' + id;
304
+ return { id, ref: ASSET_PREFIX + id, meta };
305
+ }
306
+
307
+ /**
308
+ * Store a File and hand it to the host: {@link Files#ingest}, then (with `onBeforePersist`) the upload starts in the
309
+ * background. Resolves with the `nabu-asset:sha256-…` ref as soon as the local copy is written — it never changes, the
310
+ * host location ends up in `assetIndex[hash].url`. Blocks do not call this: they use `ingest` and become `pending`, the
311
+ * upload queue does the rest. For programmatic use.
312
+ * @param {File} file
313
+ * @returns {Promise<string>}
314
+ */
315
+ async persist(file) {
316
+ const { id, ref } = await this.ingest(file);
317
+ if (this.hosted) this.#uploads.upload(id);
318
+ return ref;
319
+ }
320
+
321
+ // ── Upload state & controls (ADR 014 §3.5) ───────────────────────────────────────────────────
322
+
323
+ /** @param {string} ref @returns {string | null} the hash id of a `nabu-asset:sha256-…` ref */
324
+ #hashOf(ref) {
325
+ const raw = ref ? assetIdOf(ref) : null;
326
+ if (raw === null) return null;
327
+ const id = this.#canonical(raw);
328
+ return isHashId(id) ? id : null;
68
329
  }
69
330
 
70
331
  /**
71
- * Resolve a ref to a displayable URL. nabu-asset: refs → objectURL from Loro
72
- * bytes (cached); external URLs → config.resolve or identity.
332
+ * Progress (0–1) of the running upload of the file `ref` designates; `null` when none runs. Reactive.
333
+ * @param {string} ref @returns {number | null}
334
+ */
335
+ progress(ref) {
336
+ const id = this.#hashOf(ref);
337
+ return id === null ? null : this.#uploads.progress(id);
338
+ }
339
+
340
+ /** Whether the upload of the file `ref` designates is running. Reactive. @param {string} ref @returns {boolean} */
341
+ isUploading(ref) {
342
+ const id = this.#hashOf(ref);
343
+ return id !== null && this.#uploads.isUploading(id);
344
+ }
345
+
346
+ /**
347
+ * Run the upload of the file `ref` designates again, from its local copy. Resolves `true` when the file ended up at the host.
348
+ * @param {string} ref @returns {Promise<boolean>}
349
+ */
350
+ retry(ref) {
351
+ const id = this.#hashOf(ref);
352
+ return id === null ? Promise.resolve(false) : this.#uploads.retry(id);
353
+ }
354
+
355
+ /**
356
+ * Abort the running upload of the file `ref` designates (the host's `signal` fires). The blocks showing it become `error` with
357
+ * the reason `cancelled`; the local copy stays. Uploads are per file: every block with the same ref is affected.
358
+ * @param {string} ref @returns {boolean} whether an upload was running
359
+ */
360
+ cancel(ref) {
361
+ const id = this.#hashOf(ref);
362
+ return id !== null && this.#uploads.cancel(id);
363
+ }
364
+
365
+ /**
366
+ * The status a block showing the file `id` should start with: `pending` when a host still has to get it, else `ready`.
367
+ * @param {string} id @returns {'pending' | 'ready'}
368
+ */
369
+ initialStatus(id) { return this.#uploads.needsUpload(id) ? 'pending' : 'ready'; }
370
+
371
+ /** Stop the automatic upload retries (timers, `online` listener): the persistence of the editor was disposed. */
372
+ dispose() { this.#uploads.dispose(); }
373
+
374
+ /** Resolves when the first pass over the document (resuming the uploads of a reopened document) is done. @returns {Promise<void>} */
375
+ whenResumed() { return this.#uploads.ready(); }
376
+
377
+ /** Run an upload pass now (tests, or after changing the host config at runtime). @returns {Promise<void>} */
378
+ reconcileUploads() { return this.#uploads.reconcile(); }
379
+
380
+ // ── Display ──────────────────────────────────────────────────────────────────────────────────
381
+
382
+ /** The id a ref designates for the store: a hash id, or the hash a beta uuid was migrated to. @param {string} raw @returns {string} */
383
+ #canonical(raw) { return isHashId(raw) ? raw : (this.#legacy.get(raw) ?? raw); }
384
+
385
+ /**
386
+ * Resolve a ref to a displayable URL. `nabu-asset:` refs → objectURL made from the local store (loaded in the
387
+ * background: `''` until it is there, reactive), else the `url` of the document index (through `config.resolve`);
388
+ * external URLs → config.resolve or identity.
73
389
  * @param {string} ref @returns {string}
74
390
  */
75
391
  resolve(ref) {
76
392
  if (!ref) return '';
77
- if (ref.startsWith('nabu-asset:')) {
78
- const cached = this.#urlCache.get(ref);
79
- if (cached) return cached;
80
- const id = ref.slice('nabu-asset:'.length);
81
- const sub = /** @type {any} */ (this.assets.get(id));
82
- if (!sub || typeof sub.get !== 'function') return '';
83
- const data = sub.get('data');
84
- const type = sub.get('type') || 'application/octet-stream';
85
- if (!data) return '';
86
- const url = URL.createObjectURL(new Blob([data], { type }));
87
- this.#urlCache.set(ref, url);
88
- return url;
393
+ if (ref.startsWith(PENDING_PREFIX)) return this.#pendingUrls.get(ref) ?? '';
394
+ const raw = assetIdOf(ref);
395
+ if (raw !== null) {
396
+ const id = this.#canonical(raw);
397
+ return isHashId(id) ? (this.#entry(id) ?? '') : this.#legacyUrl(ref, raw);
89
398
  }
90
399
  if (this.config.resolve) return this.config.resolve(ref);
91
400
  return ref;
92
401
  }
402
+
403
+ /**
404
+ * What displaying `ref` would give right now: `loading` (being read from the store), `missing` (neither the local store
405
+ * nor the document index has it) or `ready`. Reactive. Refs that are not `nabu-asset:` are always `ready`.
406
+ * @param {string} ref @returns {'ready' | 'loading' | 'missing'}
407
+ */
408
+ state(ref) {
409
+ const raw = ref ? assetIdOf(ref) : null;
410
+ if (raw === null) return 'ready';
411
+ const id = this.#canonical(raw);
412
+ if (!isHashId(id)) return this.#legacyUrl(ref, raw) ? 'ready' : 'missing';
413
+ const entry = this.#entry(id);
414
+ return entry === undefined ? 'loading' : entry === null ? 'missing' : 'ready';
415
+ }
416
+
417
+ /** @param {string} id @returns {string | null | undefined} */
418
+ #entry(id) {
419
+ const entry = this.#urls.get(id);
420
+ if (entry === undefined) this.#load(id);
421
+ return entry;
422
+ }
423
+
424
+ /** @param {string} id */
425
+ #load(id) {
426
+ if (this.#loading.has(id)) return;
427
+ this.#loading.add(id);
428
+ (async () => {
429
+ try {
430
+ await this.#inflight.get(id)?.catch(() => {}); // bytes arriving with a paste: wait for them rather than report them missing
431
+ /** @type {Blob | null} */
432
+ let blob = null;
433
+ try { blob = await this.store.get(id); } catch (error) { this.#nabu.warn(`asset ${id}: the store failed: ${error}`); }
434
+ /** @type {string | null} */
435
+ let url = null;
436
+ if (blob) {
437
+ url = URL.createObjectURL(blob);
438
+ this.#warmFrom(id, blob).catch(() => {});
439
+ } else {
440
+ const hosted = /** @type {any} */ (this.index.get(id))?.url;
441
+ if (typeof hosted === 'string' && hosted) url = this.config.resolve ? this.config.resolve(hosted) : hosted;
442
+ }
443
+ this.#urls.set(id, url);
444
+ this.#scheduleSweep(id);
445
+ } finally {
446
+ this.#loading.delete(id);
447
+ }
448
+ })();
449
+ }
450
+
451
+ /**
452
+ * A block displaying `ref` is mounted: its objectURL stays alive until the returned function is called (the media
453
+ * components call this from an effect). An objectURL no mounted block uses any more is revoked after a short grace period.
454
+ * @param {string} ref @returns {() => void}
455
+ */
456
+ hold(ref) {
457
+ const raw = ref ? assetIdOf(ref) : null;
458
+ if (raw === null) return () => {};
459
+ const id = this.#canonical(raw);
460
+ this.#holds.set(id, (this.#holds.get(id) ?? 0) + 1);
461
+ let released = false;
462
+ return () => {
463
+ if (released) return;
464
+ released = true;
465
+ const left = (this.#holds.get(id) ?? 1) - 1;
466
+ if (left > 0) { this.#holds.set(id, left); return; }
467
+ this.#holds.delete(id);
468
+ this.#scheduleSweep(id);
469
+ };
470
+ }
471
+
472
+ /** @param {string} id */
473
+ #scheduleSweep(id) {
474
+ setTimeout(() => {
475
+ if (this.#holds.has(id)) return;
476
+ const url = this.#urls.get(id);
477
+ if (typeof url !== 'string') return;
478
+ if (url.startsWith('blob:')) URL.revokeObjectURL(url);
479
+ this.#urls.delete(id); // a later display loads it again
480
+ }, this.revokeGraceMs);
481
+ }
482
+
483
+ /** A beta asset still inside the document (migration pending): shown from its Loro bytes, like before. @param {string} ref @param {string} raw @returns {string} */
484
+ #legacyUrl(ref, raw) {
485
+ const cached = this.#legacyUrls.get(ref);
486
+ if (cached) return cached;
487
+ const sub = /** @type {any} */ (this.assets.get(raw));
488
+ const data = sub && typeof sub.get === 'function' ? sub.get('data') : null;
489
+ if (!data) return '';
490
+ const url = URL.createObjectURL(new Blob([data], { type: sub.get('type') || 'application/octet-stream' }));
491
+ this.#legacyUrls.set(ref, url);
492
+ return url;
493
+ }
494
+
495
+ /**
496
+ * Read the bytes of a stored file into the embed cache, so that a later copy / export (synchronous) can carry them.
497
+ * Cheap no-op for big files, which are never embedded.
498
+ * @param {string} ref
499
+ */
500
+ warm(ref) {
501
+ const raw = ref ? assetIdOf(ref) : null;
502
+ if (raw === null) return;
503
+ const id = this.#canonical(raw);
504
+ if (!isHashId(id) || this.#embed.has(id) || this.#warming.has(id)) return;
505
+ const size = /** @type {any} */ (this.index.get(id))?.size;
506
+ if (typeof size === 'number' && size > this.maxInlineSize) return;
507
+ this.#warming.add(id);
508
+ this.#track((async () => {
509
+ try {
510
+ await this.#inflight.get(id)?.catch(() => {});
511
+ const blob = await this.store.get(id);
512
+ if (blob) await this.#warmFrom(id, blob);
513
+ } catch { /* not embeddable: nothing to do */ } finally { this.#warming.delete(id); }
514
+ })());
515
+ }
516
+
517
+ /**
518
+ * P-65: at open, read the bytes of every file the document indexes (up to `maxInlineSize` each, and about the budget of the
519
+ * embed cache in total) so that a copy / `serialize('json')` made right after opening carries them. `whenIdle()` waits for it.
520
+ */
521
+ #preload() {
522
+ let planned = 0;
523
+ for (const [id, meta] of Object.entries(/** @type {Record<string, any>} */ (this.index.toJSON()))) {
524
+ if (!isHashId(id)) continue;
525
+ const size = typeof meta?.size === 'number' ? meta.size : 0;
526
+ if (size > this.maxInlineSize) continue;
527
+ planned += size;
528
+ if (planned > EMBED_CACHE_BUDGET) break;
529
+ this.warm(ASSET_PREFIX + id);
530
+ }
531
+ }
532
+
533
+ /** @param {string} id @param {Blob} blob */
534
+ async #warmFrom(id, blob) {
535
+ if (this.#embed.has(id) || blob.size > this.maxInlineSize) return;
536
+ const bytes = new Uint8Array(await blob.arrayBuffer());
537
+ const entry = /** @type {any} */ (this.index.get(id));
538
+ const stat = entry ? null : await this.store.stat?.(id);
539
+ this.#remember(id, bytes, { mime: entry?.mime ?? stat?.mime ?? (blob.type || 'application/octet-stream'), name: entry?.name ?? stat?.name ?? '', size: bytes.length });
540
+ }
541
+
542
+ // ── Clipboard (P-51): media travelling between documents ─────────────────────────────────
543
+
544
+ /**
545
+ * The bytes behind a `nabu-asset:` ref (or bare id), when they are at hand SYNCHRONOUSLY (a copy / export cannot wait):
546
+ * the files of at most `maxInlineSize` that were added or displayed in this session. `null` otherwise.
547
+ * @param {string} ref @returns {{ id: string, data: Uint8Array, type: string, name: string } | null}
548
+ */
549
+ getAsset(ref) {
550
+ const raw = assetIdOf(ref.startsWith(ASSET_PREFIX) ? ref : ASSET_PREFIX + ref);
551
+ if (raw === null) return null;
552
+ const id = this.#canonical(raw);
553
+ const hit = this.#embed.get(id);
554
+ if (hit) return { id, data: hit.data, type: hit.type, name: hit.name };
555
+ if (isHashId(id)) return null;
556
+ // a beta asset whose migration has not run yet
557
+ const sub = /** @type {any} */ (this.assets.get(raw));
558
+ if (!sub || typeof sub.get !== 'function') return null;
559
+ const data = sub.get('data');
560
+ if (!data || typeof data.length !== 'number') return null;
561
+ return { id: raw, data, type: sub.get('type') || 'application/octet-stream', name: sub.get('name') || '' };
562
+ }
563
+
564
+ /**
565
+ * COPY: the bytes of every `nabu-asset:` media of `blocks`, for the `assets` map of the fragment (keyed by hash id, ADR 014
566
+ * §3.8). A file whose bytes cannot go along (total over `maxInlineSize`, or not in the in-memory cache — evicted, or not
567
+ * read yet) is NOT silently dropped: it gets an entry `{ mime, name, size, omitted: true }` so the receiver shows the block
568
+ * as `missing` with the reason `not-embedded` (unless its own store has the file), and `nabu.warn` says so. The blocks keep
569
+ * their ref either way.
570
+ * @param {any[]} blocks PasteBlocks about to be copied
571
+ * @returns {Record<string, EmbeddedAsset> | undefined} `undefined` when there is nothing to carry
572
+ */
573
+ embedAssets(blocks) {
574
+ const ids = collectAssetIds(blocks);
575
+ /** @type {Array<{ key: string } & NonNullable<ReturnType<Files['getAsset']>>>} */
576
+ const found = [];
577
+ /** @type {string[]} */
578
+ const omitted = [];
579
+ for (const key of ids) {
580
+ const asset = this.getAsset(key);
581
+ if (asset) found.push({ key, ...asset });
582
+ else if (isHashId(key) && this.index.get(key)) omitted.push(key);
583
+ }
584
+ const total = found.reduce((n, a) => n + a.data.length, 0);
585
+ const tooBig = total > this.maxInlineSize;
586
+ if (tooBig) this.#nabu.warn(`copy: ${found.length} embedded file(s) total ${(total / 1048576).toFixed(1)}MB > maxInlineSize (${(this.maxInlineSize / 1048576).toFixed(1)}MB): the bytes are not put on the clipboard, pasting in another document will show them as missing`);
587
+ if (omitted.length) this.#nabu.warn(`copy: file(s) ${omitted.join(', ')} cannot be embedded (larger than maxInlineSize, or their bytes are not loaded yet): pasting in another document will show them as missing unless that document's store has them`);
588
+ if (!found.length && !omitted.length) return undefined;
589
+ /** @type {Record<string, EmbeddedAsset>} */
590
+ const assets = {};
591
+ for (const a of found) {
592
+ assets[a.key] = tooBig
593
+ ? { mime: a.type, name: a.name, size: a.data.length, omitted: true }
594
+ : { mime: a.type, name: a.name, size: a.data.length, data: bytesToBase64(a.data) };
595
+ }
596
+ for (const key of omitted) {
597
+ const meta = /** @type {any} */ (this.index.get(key));
598
+ assets[key] = { mime: meta?.mime ?? 'application/octet-stream', name: meta?.name ?? '', size: meta?.size ?? 0, omitted: true };
599
+ }
600
+ return assets;
601
+ }
602
+
603
+ /**
604
+ * COPY, `text/html` and `text/plain`: a copy of `blocks` where no `nabu-asset:` ref is left (it means nothing outside
605
+ * Nabu). With `inline` (HTML), a media of at most {@link HTML_INLINE_LIMIT} bytes whose type `sanitizeUrl(kind:'media')`
606
+ * accepts (image / video) becomes a `data:` URL; any other asset gets an empty ref, which the block serializers render
607
+ * as a label (alt / file name) rather than a broken `src`.
608
+ * @param {any[]} blocks @param {{ inline?: boolean }} [options]
609
+ * @returns {any[]}
610
+ */
611
+ externalize(blocks, { inline = false } = {}) {
612
+ return mapAssetBlocks(blocks, (_pb, id) => {
613
+ const asset = inline ? this.getAsset(id) : null;
614
+ if (asset && asset.data.length <= HTML_INLINE_LIMIT) {
615
+ const url = 'data:' + asset.type + ';base64,' + bytesToBase64(asset.data);
616
+ if (sanitizeUrl(url, { kind: 'media' }) !== null) return { ref: url };
617
+ }
618
+ return { ref: '' };
619
+ });
620
+ }
621
+
622
+ /**
623
+ * PASTE / import: make every `nabu-asset:` media of `blocks` valid in THIS document (ADR 014 §3.4, §3.8). Synchronous:
624
+ * the refs are content hashes, so a block keeps its ref and the storage happens in the background (see {@link Files#whenIdle}).
625
+ * - a hash ref whose bytes the fragment carries: they are verified (the hash must match, else the file is treated as
626
+ * missing — reason `corrupt` — and `nabu.warn` says so) and written to the store, unless it already has them; over
627
+ * `files.maxFileSize` the block becomes `rejected` (no ref, a readable reason) instead;
628
+ * - a hash ref the document already indexes: reused as is;
629
+ * - a hash ref with no bytes and no index entry: kept, then flagged `status: 'missing'` unless the local store has the file
630
+ * (reason `not-embedded` when the copy said it left the bytes out, else `unavailable`);
631
+ * - a beta `nabu-asset:<uuid>` ref (older exports / clipboards) with its bytes: re-created through {@link Files#ingest}
632
+ * and given its hash ref when done (the block is `pending` with a local preview meanwhile); without bytes: `missing`;
633
+ * - with a host hook, a file the host does not have yet makes the block `pending`: the upload starts in the background (the
634
+ * block keeps its hash ref; the host location lands in `assetIndex[hash].url`).
635
+ * No commit; the caller commits. Never throws.
636
+ * @param {any[]} blocks PasteBlocks (already sanitized)
637
+ * @param {Record<string, EmbeddedAsset> | null | undefined} embedded the `assets` map of the fragment
638
+ * @returns {any[]}
639
+ */
640
+ adoptAssets(blocks, embedded) {
641
+ /** @type {Map<string, EmbeddedBytes | null>} */
642
+ const decoded = new Map();
643
+ /** @param {string} id @returns {EmbeddedBytes | null} */
644
+ const embeddedOf = (id) => {
645
+ if (decoded.has(id)) return decoded.get(id) ?? null;
646
+ const e = embedded && typeof embedded === 'object' ? /** @type {any} */ (embedded)[id] : null;
647
+ const bytes = e && typeof e === 'object' && typeof e.data === 'string' ? base64ToBytes(e.data) : null;
648
+ const value = bytes ? {
649
+ bytes,
650
+ type: typeof e.mime === 'string' && e.mime ? e.mime : 'application/octet-stream',
651
+ name: typeof e.name === 'string' ? e.name : '',
652
+ } : null;
653
+ decoded.set(id, value);
654
+ return value;
655
+ };
656
+ /** @param {string} id @returns {boolean} the copy declared it left this file's bytes out */
657
+ const omittedOf = (id) => Boolean(embedded && typeof embedded === 'object' && /** @type {any} */ (embedded)[id]?.omitted === true);
658
+ return mapAssetBlocks(blocks, (_pb, id) => isHashId(id) ? this.#adoptHash(id, embeddedOf(id), omittedOf(id)) : this.#adoptLegacy(id, embeddedOf(id)));
659
+ }
660
+
661
+ /** @param {string} id @param {EmbeddedBytes | null} emb @param {boolean} omitted @returns {Record<string, any> | null} */
662
+ #adoptHash(id, emb, omitted) {
663
+ const known = Boolean(this.index.get(id));
664
+ const rejection = emb && !known ? this.checkSize(emb.bytes.length) : null;
665
+ if (rejection) {
666
+ this.#nabu.warn(`paste: file ${id} refused: ${rejection.message}`);
667
+ return { ref: '', status: 'rejected', reason: rejection };
668
+ }
669
+ if (emb || !known) this.#ensure(id, emb, omitted);
670
+ // With a host: a file it does not have yet is sent in the background; the block is pending until then.
671
+ if ((emb || known) && this.#uploads.needsUpload(id)) return { status: 'pending' };
672
+ return null;
673
+ }
674
+
675
+ /** @param {string} id @param {EmbeddedBytes | null} emb @returns {Record<string, any> | null} */
676
+ #adoptLegacy(id, emb) {
677
+ const migrated = this.#legacy.get(id);
678
+ if (migrated) return { ref: ASSET_PREFIX + migrated };
679
+ if (this.assets.get(id)) return null; // still inside this document: the migration will rewrite the refs
680
+ const memo = this.#adopted.get(id);
681
+ if (memo) return memo.startsWith(PENDING_PREFIX) ? { ref: memo, status: 'pending' } : { ref: memo, status: this.initialStatus(memo.slice(ASSET_PREFIX.length)) };
682
+ if (!emb) return { status: 'missing', reason: reasonOf('unavailable') };
683
+ return this.#adoptPending(id, emb);
684
+ }
685
+
686
+ /**
687
+ * The bytes are re-created in the background ({@link Files#ingest}: local store, index); the block shows a local preview as
688
+ * `pending` and gets its hash ref in a silent commit (still `pending` while a host has to get the file).
689
+ * @param {string} id @param {EmbeddedBytes} emb @returns {Record<string, any>}
690
+ */
691
+ #adoptPending(id, emb) {
692
+ const tempRef = PENDING_PREFIX + (globalThis.crypto?.randomUUID?.() ?? String(Date.now()) + Math.random().toString(36).slice(2));
693
+ this.#pendingUrls.set(tempRef, URL.createObjectURL(new Blob([/** @type {BlobPart} */ (emb.bytes)], { type: emb.type })));
694
+ this.#adopted.set(id, tempRef);
695
+ const stored = this.ingest(new File([/** @type {BlobPart} */ (emb.bytes)], emb.name, { type: emb.type })).then(
696
+ ({ ref }) => this.#settle(id, tempRef, ref),
697
+ (error) => {
698
+ if (error instanceof FileRejectedError) return this.#settle(id, tempRef, null, null, error.reason);
699
+ return this.#settle(id, tempRef, null);
700
+ },
701
+ );
702
+ this.#track(stored); // local storage only: quick, the import can wait for it (an upload to a host is not waited for)
703
+ return { ref: tempRef, status: 'pending' };
704
+ }
705
+
706
+ /**
707
+ * Make sure the store (and the index) has the file `id`, in the background. With bytes (from a paste / import) they
708
+ * are verified against the hash first. Without bytes and without any other source, the blocks showing it are flagged
709
+ * `missing`.
710
+ * @param {string} id @param {EmbeddedBytes | null} emb @param {boolean} [omitted] the copy declared it left the bytes out
711
+ */
712
+ #ensure(id, emb, omitted = false) {
713
+ if (this.#inflight.has(id)) return;
714
+ const job = this.#ensureStored(id, emb, omitted).catch((error) => { this.#nabu.warn(`asset ${id}: could not be stored: ${error}`); });
715
+ this.#inflight.set(id, job);
716
+ this.#track(job).finally(() => {
717
+ if (this.#inflight.get(id) === job) this.#inflight.delete(id);
718
+ this.#uploads.schedule(); // the bytes are there now: a pending block can be sent
719
+ });
720
+ }
721
+
722
+ /** @param {string} id @param {EmbeddedBytes | null} emb @param {boolean} omitted */
723
+ async #ensureStored(id, emb, omitted) {
724
+ if (await this.store.has(id).catch(() => false)) {
725
+ await this.#touch(id);
726
+ if (!this.index.get(id)) {
727
+ const stat = emb ? null : await this.store.stat?.(id);
728
+ const blob = emb || stat ? null : await this.store.get(id);
729
+ /** @type {AssetMeta} */
730
+ const meta = emb ? { mime: emb.type, name: emb.name, size: emb.bytes.length } : stat ?? { mime: blob?.type || 'application/octet-stream', name: '', size: blob?.size ?? 0 };
731
+ await this.#silent(() => this.#setIndex(id, meta));
732
+ }
733
+ return;
734
+ }
735
+ if (emb) {
736
+ const actual = await sha256Id(/** @type {BufferSource} */ (emb.bytes));
737
+ if (actual !== id) {
738
+ this.#nabu.warn(`asset ${id}: the embedded bytes hash to ${actual}: ignored, the file is treated as missing`);
739
+ await this.#markMissing(id, reasonOf('corrupt'));
740
+ return;
741
+ }
742
+ await this.#storeBytes(id, emb.bytes, { mime: emb.type, name: emb.name, size: emb.bytes.length });
743
+ return;
744
+ }
745
+ const hosted = /** @type {any} */ (this.index.get(id))?.url;
746
+ if (!hosted) await this.#markMissing(id, reasonOf(omitted ? 'not-embedded' : 'unavailable'));
747
+ }
748
+
749
+ /** Flag as `missing` every live block that shows file `id` (silent commit). @param {string} id @param {FileReason} reason */
750
+ async #markMissing(id, reason) {
751
+ const ref = ASSET_PREFIX + id;
752
+ /** @type {any[]} */
753
+ const targets = [];
754
+ for (const block of this.#nabu.blocks.values()) {
755
+ const node = /** @type {any} */ (block.node);
756
+ if (node.isDeleted?.() || node.data.get('ref') !== ref || node.data.get('status') === 'missing') continue;
757
+ targets.push(node);
758
+ }
759
+ if (!targets.length) return;
760
+ this.#urls.set(id, null);
761
+ await this.#silent(() => { for (const node of targets) { node.data.set('status', 'missing'); node.data.set('reason', reason); } });
762
+ }
763
+
764
+ // ── Beta documents (ADR 014 §3.7) ────────────────────────────────────────────────────────────
765
+
766
+ /**
767
+ * A document saved by the beta keeps the bytes of its files in the Loro `assets` map. Each entry is hashed and written to
768
+ * the store, `assetIndex` gets its metadata, the blocks that referenced `nabu-asset:<uuid>` get `nabu-asset:sha256-…`, and
769
+ * the legacy entries are removed — all in ONE silent commit (not an undo step). An entry that cannot be stored stays as it
770
+ * was. (The old bytes remain in the document's history: only an explicit compaction frees them.)
771
+ */
772
+ async #migrate() {
773
+ const legacy = /** @type {Record<string, any>} */ (this.assets.toJSON());
774
+ /** @type {Array<{ uuid: string, id: string, meta: AssetMeta }>} */
775
+ const done = [];
776
+ for (const [uuid, value] of Object.entries(legacy)) {
777
+ const data = value?.data;
778
+ if (!data || !ArrayBuffer.isView(data)) continue;
779
+ const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
780
+ /** @type {AssetMeta} */
781
+ const meta = { mime: typeof value.type === 'string' && value.type ? value.type : 'application/octet-stream', name: typeof value.name === 'string' ? value.name : '', size: bytes.length };
782
+ try {
783
+ const id = await sha256Id(/** @type {BufferSource} */ (bytes));
784
+ if (!(await this.store.has(id))) await this.store.put(id, new Blob([/** @type {BlobPart} */ (bytes)], { type: meta.mime }), meta);
785
+ else await this.#touch(id);
786
+ this.#remember(id, bytes, meta);
787
+ done.push({ uuid, id, meta });
788
+ } catch (error) {
789
+ this.#nabu.warn(`asset ${uuid}: migration to the store failed, kept in the document: ${error}`);
790
+ }
791
+ }
792
+ if (!done.length) return;
793
+ for (const d of done) this.#legacy.set(d.uuid, d.id);
794
+ await this.#silent(() => {
795
+ for (const d of done) { this.#setIndex(d.id, d.meta); this.assets.delete(d.uuid); }
796
+ for (const block of this.#nabu.blocks.values()) {
797
+ const node = /** @type {any} */ (block.node);
798
+ if (node.isDeleted?.()) continue;
799
+ const ref = node.data.get('ref');
800
+ const migrated = typeof ref === 'string' && ref.startsWith(ASSET_PREFIX) ? this.#legacy.get(ref.slice(ASSET_PREFIX.length)) : null;
801
+ if (migrated) node.data.set('ref', ASSET_PREFIX + migrated);
802
+ }
803
+ });
804
+ for (const url of this.#legacyUrls.values()) URL.revokeObjectURL(url);
805
+ this.#legacyUrls.clear();
806
+ }
807
+
808
+ // ── Clipboard: files pasted from outside ──────────────────────────────────────────────────
809
+
810
+ /**
811
+ * PASTE FILES: read a pasted File and prepare it for {@link Files#adoptAssets}. The file is hashed and written to the local
812
+ * store right here (no base64 round trip), whatever the mode: the fragment only carries its hash ref, as one undo step with
813
+ * the blocks. `props` is a patch for the block: `status: 'pending'` when a host still has to get the file (the upload starts
814
+ * once the block is in the document), or `status: 'rejected'` + `reason` (and an empty ref) when it is over `files.maxFileSize`.
815
+ * @param {File} file
816
+ * @returns {Promise<{ id: string, ref: string, asset: EmbeddedAsset | null, props?: Record<string, any> }>}
817
+ */
818
+ async stage(file) {
819
+ const rejection = this.checkSize(file.size);
820
+ if (rejection) return { id: '', ref: '', asset: null, props: { status: 'rejected', reason: rejection } };
821
+ const { id, ref } = await this.ingest(file);
822
+ return { id, ref, asset: null, ...(this.#uploads.needsUpload(id) ? { props: { status: 'pending' } } : {}) };
823
+ }
824
+
825
+ /**
826
+ * PASTE (HTML from outside): with `config.importRemote`, every block of `blocks` whose `ref` is a remote `http(s)` URL is
827
+ * fetched and stored in the local store ({@link Files#ingest}). The block shows the original URL at once, as `pending`, and gets its
828
+ * `nabu-asset:` ref in the background (a silent commit, not an undo step; still `pending` while a host uploads it); when the
829
+ * fetch or the storage fails (or the file is over `maxFileSize`) it keeps the original URL. Without the option, `blocks` come back untouched. No commit; never throws.
830
+ * @param {any[]} blocks PasteBlocks (already sanitized)
831
+ * @returns {any[]}
832
+ */
833
+ importRemote(blocks) {
834
+ if (!this.config.importRemote || typeof globalThis.fetch !== 'function') return blocks;
835
+ /** @type {Map<string, string>} */
836
+ const seen = new Map();
837
+ return mapRemoteBlocks(blocks, (_pb, url) => {
838
+ let tempRef = seen.get(url);
839
+ if (!tempRef) {
840
+ tempRef = PENDING_PREFIX + (globalThis.crypto?.randomUUID?.() ?? String(Date.now()) + Math.random().toString(36).slice(2));
841
+ this.#pendingUrls.set(tempRef, url); // shown from where it comes from while it is fetched and stored
842
+ seen.set(url, tempRef);
843
+ this.#fetchRemote(url, tempRef);
844
+ }
845
+ return { ref: tempRef, status: 'pending' };
846
+ });
847
+ }
848
+
849
+ /** @param {string} url @param {string} tempRef */
850
+ async #fetchRemote(url, tempRef) {
851
+ /** @type {string | null} */
852
+ let finalRef = null;
853
+ try {
854
+ const response = await fetch(url, { credentials: 'omit', referrerPolicy: 'no-referrer' });
855
+ if (!response.ok) throw new Error('HTTP ' + response.status);
856
+ const blob = await response.blob();
857
+ if (/^(text\/|application\/(xhtml|json))/i.test(blob.type)) throw new Error('not a media file: ' + blob.type);
858
+ finalRef = (await this.ingest(new File([blob], remoteFileName(url, blob.type), { type: blob.type }))).ref;
859
+ } catch (error) {
860
+ if (error instanceof FileRejectedError) this.#nabu.warn(`paste: ${url} not imported: ${error.reason.message} The original URL is kept.`);
861
+ finalRef = null; // kept as a link to the original
862
+ }
863
+ await this.#settle(null, tempRef, finalRef, url);
864
+ }
865
+
866
+ /**
867
+ * End of a background re-creation: every block still holding `tempRef` gets the final ref (or the `error` status
868
+ * when the storage failed). Committed with a silent origin: not an undo step of its own, the paste stays ONE step.
869
+ * With a host the block stays `pending` until the upload (started by the document watcher) ends.
870
+ * @param {string | null} id asset id of a media pasted from another document (`null`: a remote URL, see importRemote)
871
+ * @param {string} tempRef @param {string | null} finalRef
872
+ * @param {string | null} [fallbackRef] the ref to keep when there is no final one (the original URL of a remote media)
873
+ * @param {FileReason | null} [reason] why there is no final ref (a refused file)
874
+ */
875
+ async #settle(id, tempRef, finalRef, fallbackRef = null, reason = null) {
876
+ if (id !== null) { if (finalRef) this.#adopted.set(id, finalRef); else this.#adopted.delete(id); }
877
+ const nabu = this.#nabu;
878
+ let touched = false;
879
+ const status = finalRef ? this.initialStatus(finalRef.slice(ASSET_PREFIX.length)) : fallbackRef ? 'ready' : reason ? 'rejected' : 'error';
880
+ for (const block of nabu.blocks.values()) {
881
+ const node = /** @type {any} */ (block.node);
882
+ if (node.isDeleted?.() || node.data.get('ref') !== tempRef) continue;
883
+ node.data.set('ref', finalRef ?? fallbackRef ?? '');
884
+ node.data.set('status', status);
885
+ if (status === 'error') node.data.set('reason', reasonOf('upload-failed'));
886
+ else if (status === 'rejected' && reason) node.data.set('reason', reason);
887
+ touched = true;
888
+ }
889
+ try {
890
+ if (touched) await nabu.commit({ origin: SILENT_ORIGIN });
891
+ } finally {
892
+ const url = this.#pendingUrls.get(tempRef);
893
+ this.#pendingUrls.delete(tempRef);
894
+ if (url?.startsWith('blob:')) URL.revokeObjectURL(url);
895
+ }
896
+ }
93
897
  }