@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
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * @typedef {Object} PasteBlock
7
7
  * @property {string} type
8
- * @property {'start' | 'end' | 'both' | false} partial
8
+ * @property {'start' | 'end' | 'both' | false} [partial] absent = false (a whole block)
9
9
  * @property {Record<string, any>} [props]
10
10
  * @property {import('loro-crdt').Delta<string>[]} [delta]
11
11
  * @property {PasteBlock[]} [children]
@@ -13,18 +13,115 @@
13
13
 
14
14
  /**
15
15
  * @typedef {Object} PasteFragment
16
+ * @property {boolean} [external] the content comes from outside the editor (the HTML of a web page, Docs…) rather than from
17
+ * Nabu itself: `files.importRemote` applies to its remote media URLs
16
18
  * @property {PasteBlock[]} blocks
19
+ * @property {Record<string, import('../files/files.svelte.js').EmbeddedAsset>} [assets] bytes (base64) of the
20
+ * `nabu-asset:` refs used by `blocks` (see docs/design/clipboard-format.md)
17
21
  */
18
22
 
19
23
  /**
20
24
  * @typedef {Object} PasteInterpreter
21
25
  * @property {string} format - MIME type géré ('application/x-nabu+json', 'text/html', 'text/plain')
22
26
  * @property {number} [priority] - Plus haut = appelé en premier (default: 0)
23
- * @property {(raw: string, nabu: Nabu) => PasteFragment | null} interpret
27
+ * @property {(raw: string, nabu: Nabu, options?: PasteInterpretOptions) => PasteFragment | null} interpret
28
+ * @property {(raw: string) => boolean} [outranksFiles] - Files on the clipboard normally win over the text payloads. Return
29
+ * true when THIS payload is worth more than the files that come with it (a spreadsheet range is put on the clipboard as
30
+ * a table AND as an image of it).
31
+ */
32
+
33
+ /**
34
+ * @typedef {Object} PasteFileHandler
35
+ * What an extension does with a FILE pasted from the clipboard (a screenshot, a file copied from the OS): it makes a block
36
+ * of it. The engine reads the bytes, stores them through `Files` (in the document, or sent to `files.onBeforePersist` with the
37
+ * optimistic `pending` block) and inserts the blocks at the caret, in the order of the files, as ONE undo step. The engine
38
+ * names no block type: whatever an extension accepts is its own business.
39
+ * @property {number} [priority] - Higher is asked first (default 0). The first handler that accepts a file takes it.
40
+ * @property {(file: File, nabu: Nabu) => boolean} accepts - Whether this handler takes `file` (by MIME type, name…)
41
+ * @property {(file: File, nabu: Nabu) => PasteBlock | null} block - The block the file becomes: `type` and the props other
42
+ * than `ref` (`name`, `alt`…), which the engine sets to the stored file. `null` declines the file.
43
+ */
44
+
45
+ /**
46
+ * A rule of a block class's `static htmlRules`: which HTML elements the block reads on paste. The rules of every registered
47
+ * block form one ruleset, tried by descending `priority` (default 0); the first whose `selector` (and `filter`) matches wins and
48
+ * its class's `static fromHTML(el, helpers, rule, siblings)` makes the block. Extra fields are the rule's own: the class reads them
49
+ * back from `rule`.
50
+ * @typedef {{
51
+ * selector: string,
52
+ * priority?: number,
53
+ * filter?: (el: Element) => boolean,
54
+ * embed?: boolean,
55
+ * props?: Record<string, any>,
56
+ * [field: string]: any,
57
+ * }} HtmlRule
58
+ * `selector` is a CSS selector tested with `el.matches()`. `priority`: higher is tried first (a specific block beats a generic
59
+ * fallback). `filter`: an extra test once the selector matches. `embed`: the element may sit inside the inline content of another
60
+ * block and is then lifted out as a block of its own. `props`: props the rule asks `fromHTML` to set.
61
+ */
62
+
63
+ /**
64
+ * What a block's `static fromHTML` receives to read an element.
65
+ * @typedef {Object} HtmlHelpers
66
+ * @property {(el: Element) => import('loro-crdt').Delta<string>[]} parseInline - The inline content of an element, as a Loro delta
67
+ * @property {(el: Element) => PasteBlock | null} parseBlock - The first block an element makes
68
+ * @property {(el: Element) => PasteBlock[]} parseBlocks - Every block an element makes
69
+ * @property {(el: Element) => PasteBlock[]} parseChildren - The blocks made by each child of an element
70
+ */
71
+
72
+ /**
73
+ * What a block's `static fromMarkdown` receives to read its lines (and what `markdownRules` callbacks receive).
74
+ * @typedef {Object} MarkdownHelpers
75
+ * @property {(text: string) => import('loro-crdt').Delta<string>[]} parseInline - Inline markdown to a Loro delta
76
+ * @property {(text: string) => any[]} parseInlineSegments - Inline markdown to segments (text, images...)
77
+ * @property {boolean} joinLines - CommonMark semantics: consecutive lines join into one paragraph (`importMarkdown`); false on paste
78
+ * @property {string} [softBreak] - What replaces a soft line break in a nested parse
79
+ * @property {(lines: string[], index: number) => boolean} interrupts - Whether the line at `index` starts a block that ends the paragraph above it
80
+ * @property {(lines: string[], overrides?: { joinLines?: boolean, softBreak?: string }) => PasteBlock[]} [parseBlocks] - Parse lines as a document of their own (the body of a quote...)
81
+ */
82
+
83
+ /**
84
+ * A rule of a block class's `static markdownRules`: how a block starts and how many lines it takes. The rules of every registered
85
+ * block form one ruleset, tried by descending `priority` (default 0) at each line; the first whose `detect` matches and whose class's
86
+ * `static fromMarkdown(lines, helpers, rule)` returns a block (or several) takes the lines `consume` counted. Extra fields are the
87
+ * rule's own.
88
+ * @typedef {{
89
+ * detect: RegExp | ((line: string, lines: string[], index: number, helpers: MarkdownHelpers) => boolean),
90
+ * consume: (lines: string[], index: number, helpers: MarkdownHelpers) => number,
91
+ * priority?: number,
92
+ * interruptsParagraph?: boolean | ((line: string, lines: string[], index: number, helpers: MarkdownHelpers) => boolean),
93
+ * [field: string]: any,
94
+ * }} MarkdownRule
95
+ * `detect`: does the block start at this line. `consume`: how many lines it takes from `index` (at least 1). `priority`: higher is
96
+ * tried first. `interruptsParagraph`: the block may start in the middle of a paragraph (a fence, a heading, a quote...); `true`
97
+ * means "whenever `detect` matches".
98
+ */
99
+
100
+ /**
101
+ * The second argument of a block's `static toMarkdown(pb, ctx)` / `static toHtml(pb, ctx)`: the clipboard and `serialize` call it
102
+ * once per block, with helpers to serialize children without knowing their type. Other fields are the caller's own (a list passes its `listType`, `index`...).
103
+ * @typedef {{
104
+ * recurse: (child: PasteBlock, ctx?: Record<string, any>) => string,
105
+ * recurseAll?: (children: PasteBlock[], ctx?: Record<string, any>) => string[],
106
+ * before?: PasteBlock[],
107
+ * after?: PasteBlock[],
108
+ * [field: string]: any,
109
+ * }} SerializeContext
110
+ * `recurse`: serialize one child block. `recurseAll` (markdown only): serialize siblings in order, telling each its neighbours.
111
+ * `before` / `after` (markdown only): the siblings around this block.
112
+ */
113
+
114
+ /**
115
+ * @typedef {Object} PasteInterpretOptions
116
+ * @property {boolean} [joinLines] - false/absent (paste): one non-blank line = one block.
117
+ * true (`importMarkdown`): CommonMark semantics, consecutive lines join into one paragraph.
118
+ * Forwarded to block markdown rules as `helpers.joinLines` (and 3rd arg of `consume`).
24
119
  */
25
120
 
26
121
  /**
27
122
  * @typedef {Object} InputRule
123
+ * A declarative text-replacement rule applied while typing: when the text before the caret matches `pattern`, `handler` runs
124
+ * (the markdown shortcuts and the typography substitutions are input rules).
28
125
  * @property {RegExp} pattern - Testé sur le texte AVANT le curseur (avec l'inputType "insertText")
29
126
  * @property {string} [inputType] - Défaut: "insertText"
30
127
  * @property {(nabu: Nabu, block: Block, match: RegExpMatchArray, sel: {from: number, to: number, isCollapsed: boolean, data: string}) => boolean | void} handler
@@ -32,84 +129,229 @@
32
129
  * - Retourne true pour BREAK. NE PAS appeler commit() dans le handler.
33
130
  */
34
131
 
132
+ /**
133
+ * @typedef {Object} SplitData
134
+ * What `onSplit` receives besides the block: where the text is cut, and the tail that moves to the new block.
135
+ * @property {number} offset caret offset in the block's text
136
+ * @property {import('loro-crdt').Delta<string>[]} delta the text from `offset` to the end, as a Loro delta
137
+ */
138
+
35
139
  /**
36
140
  * @typedef {{
37
- * onInit: function(Nabu): void,
38
- * onBlockCreate: function(Nabu, Block): void,
39
- * onBlockDelete: function(Nabu, Block): void,
40
- * onBlockUpdate: function(Nabu, Block): void,
41
- * onBeforeTransaction: function(Nabu, Array<{type: string, block: Block}>): void,
42
- * onAfterTransaction: function(Nabu, Array<{type: string, block: Block}>): void,
43
- * onSplit: function(Nabu, Block, Event, {offset: number, delta: import('loro-crdt').Delta<string>}): {block: Block},
44
- * onBeforeInput: function(Nabu, InputEvent, Block): void,
45
- * onInput: function(Nabu, InputEvent, Block): void,
46
- * } & Object<string, function>} ExtensionHooks
141
+ * onInit(nabu: Nabu): void,
142
+ * onBlockCreate(nabu: Nabu, block: Block): void,
143
+ * onBlockDelete(nabu: Nabu, block: Block): void,
144
+ * onBlockUpdate(nabu: Nabu, block: Block): void,
145
+ * onBeforeTransaction(nabu: Nabu, ...args: any[]): void,
146
+ * onAfterTransaction(nabu: Nabu, ...args: any[]): void,
147
+ * onSplit(nabu: Nabu, block: Block, event: Event | null, data: SplitData): { block: Block } | void,
148
+ * onBeforeInput(nabu: Nabu, event: InputEvent, block: Block): symbol | boolean | void,
149
+ * onKeyDown(nabu: Nabu, event: KeyboardEvent, block: Block): symbol | boolean | void,
150
+ * onBeforeMerge(nabu: Nabu, survivor: Block, victim: Block): symbol | void,
151
+ * onInput(nabu: Nabu, event: InputEvent, block: Block): void,
152
+ * [hook: string]: (nabu: Nabu, ...args: any[]) => any,
153
+ * }} ExtensionHooks
154
+ * The hooks an extension can register (`ExtensionInit.hooks`). A hook returns `nabu.BREAK` (or, for `onSplit`, an object)
155
+ * to stop the engine from going on; the others return nothing. Any other name is a custom hook, run with `nabu.trigger(name, ...args)`.
156
+ * Declared as methods, so a handler may narrow the block parameter (`(nabu, block: Paragraph) => ...`).
157
+ *
158
+ * `onBlockCreate`, `onBlockDelete`, `onBlockUpdate`, `onAfterTransaction` and `onInput` are declared for forward compatibility:
159
+ * the engine does not call them yet.
47
160
  */
48
161
 
49
162
  /**
50
163
  * @typedef {Object} ExtensionInit
164
+ * What an extension is made of: a block class and its component, hooks, serializers, actions, commands, paste interpreters and
165
+ * file handlers, input rules, slash menu entries and Loro text styles. Every field is optional; pass it to `extension(name, init)`.
51
166
  * @property {string} [name]
52
167
  * @property {import('svelte').Component} [component]
53
168
  * @property {typeof Block} [block]
169
+ * @property {boolean} [defaultBlock]
170
+ * Marks `block` as the editor's DEFAULT text block (the one created when the engine needs an
171
+ * empty text block of its own: a caret below a trailing void block, …). Last one wins.
54
172
  * @property {Partial<ExtensionHooks>} [hooks]
55
173
  * @property {Record<string, (nabu: Nabu) => any>} [serializers]
56
174
  * @property {Record<string, (nabu: Nabu, data: any, topic: string) => any>} [actions]
175
+ * Handlers of the action bus, by topic (`nabu.exec(topic, data)`). COLLISION RULE: several extensions may declare the same topic and
176
+ * ALL their handlers run (that is how an extension observes another one's topic), so give a topic of your own a distinctive name
177
+ * (`namespace:verb`): two extensions that each mean something different by `code` would both fire. Built-in topics: `mark:*`, `block:*`, `list:*`...
178
+ * @property {Record<string, import('./commands.js').CommandDef>} [commands]
179
+ * Commands (ADR 017): `{ [id]: { label, keys?, when?, scope?, run(nabu, ctx, data?), confirm? } }`. Each one is also an action of the
180
+ * bus (`nabu.exec(id, data)`); the engine resolves their `keys` at keydown, before the legacy `onKeyDown` hooks.
181
+ * @property {(nabu: Nabu, ctx: import('./commands.js').CommandContext) => Record<string, any> | void} [commandContext]
182
+ * Contributes FACTS to the context given to the `when` / `run` / `label` of commands (e.g. `{ atStartOfRegion: true }`).
183
+ * Called once per candidate key press; keep it cheap. It cannot replace the engine's own fields.
57
184
  * @property {PasteInterpreter[]} [pasteInterpreters]
185
+ * @property {PasteFileHandler[]} [pasteFileHandlers]
186
+ * Make a block of a file pasted from the clipboard (see {@link PasteFileHandler}).
58
187
  * @property {InputRule[]} [inputRules]
59
188
  * Declarative text-replacement rules applied while typing (e.g. markdown
60
189
  * shortcuts, smart typography). Tested against the text before the cursor.
190
+ * @property {import('../ui/slash-menu.svelte.js').SlashCommand[]} [slashCommands]
191
+ * Entries this extension adds to the slash menu (collected in `nabu.slashCommands`; the menu has no entry of its own, so a
192
+ * block type absent from the editor is never offered). The menu sorts them by `group`, `order`, then declaration order,
193
+ * whatever the load order of the extensions. A `when(engine, block)` limits an entry to the places where it applies (the
194
+ * block holding the caret); without it the entry is always offered.
61
195
  * @property {Record<string, { expand: 'after' | 'before' | 'both' | 'none' }>} [loroTextStyles]
62
196
  * Loro text style configuration required by this extension.
63
197
  * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
64
198
  * `applyDelta` with these attributes works correctly.
65
199
  */
66
200
 
201
+ /**
202
+ * A named bundle of editor behaviour (see {@link ExtensionInit}); the built-in blocks and behaviours are extensions. Build one with
203
+ * `extension(name, init)` and pass it to `createEditor({ extensions })`.
204
+ */
67
205
  export class Extension {
68
206
  /** @param {string} name @param {ExtensionInit} init */
69
207
  constructor(name, init = {}) {
208
+ /** The extension's name (unique in an editor). */
70
209
  this.name = name;
210
+ /** The Svelte component that renders the extension's block. */
71
211
  this.component = init.component;
212
+ /** The block class this extension registers. */
72
213
  this.block = init.block;
73
- /** @type {Partial<ExtensionHooks>} */
214
+ /** Whether `block` is the editor's default text block. */
215
+ this.defaultBlock = !!init.defaultBlock;
216
+ /**
217
+ * The hooks of the extension, by name (see {@link ExtensionHooks}).
218
+ * @type {Partial<ExtensionHooks>}
219
+ */
74
220
  this.hooks = init.hooks || {};
75
- /** @type {Record<string, (nabu: Nabu) => any>} */
221
+ /**
222
+ * Serializers by format name, run by `nabu.serialize(format)`.
223
+ * @type {Record<string, (nabu: Nabu) => any>}
224
+ */
76
225
  this.serializers = init.serializers || {};
77
- /** @type {Record<string, (nabu: Nabu, data: any, topic: string) => any>} */
226
+ /**
227
+ * Handlers of the action bus by topic (`nabu.exec(topic, data)`); several extensions may declare the same topic and all run.
228
+ * @type {Record<string, (nabu: Nabu, data: any, topic: string) => any>}
229
+ */
78
230
  this.actions = init.actions || {};
79
- /** @type {PasteInterpreter[]} */
231
+ /**
232
+ * The commands this extension declares, by id (see {@link CommandDef}).
233
+ * @type {Record<string, import('./commands.js').CommandDef>}
234
+ */
235
+ this.commands = init.commands || {};
236
+ /**
237
+ * Contributes facts to the context given to command `when` / `run` functions.
238
+ * @type {ExtensionInit['commandContext']}
239
+ */
240
+ this.commandContext = init.commandContext;
241
+ /**
242
+ * Interpreters of clipboard formats (see {@link PasteInterpreter}).
243
+ * @type {PasteInterpreter[]}
244
+ */
80
245
  this.pasteInterpreters = init.pasteInterpreters || [];
81
- /** @type {InputRule[]} */
246
+ /**
247
+ * Handlers that make a block of a pasted file (see {@link PasteFileHandler}).
248
+ * @type {PasteFileHandler[]}
249
+ */
250
+ this.pasteFileHandlers = init.pasteFileHandlers || [];
251
+ /**
252
+ * Text-replacement rules applied while typing (see {@link InputRule}).
253
+ * @type {InputRule[]}
254
+ */
82
255
  this.inputRules = init.inputRules || [];
83
- /** @type {Record<string, { expand: 'after' | 'before' | 'both' | 'none' }>} */
256
+ /**
257
+ * Entries this extension adds to the slash menu.
258
+ * @type {import('../ui/slash-menu.svelte.js').SlashCommand[]}
259
+ */
260
+ this.slashCommands = init.slashCommands || [];
261
+ /**
262
+ * Loro text style configuration this extension needs for its marks.
263
+ * @type {Record<string, { expand: 'after' | 'before' | 'both' | 'none' }>}
264
+ */
84
265
  this.loroTextStyles = init.loroTextStyles || {};
85
266
  }
86
267
  }
87
268
 
88
269
 
89
- /** @param {string} name @param {ExtensionInit} init */
270
+ /**
271
+ * Create an extension: the unit that bundles a block type, its component, hooks, commands, actions, paste handlers and slash entries.
272
+ * Shorthand for `new Extension(name, init)`.
273
+ * @param {string} name @param {ExtensionInit} init
274
+ */
90
275
  export const extension = (name, init) => new Extension(name, init);
91
276
 
277
+ /**
278
+ * Current version of the `application/x-nabu+json` clipboard format (see docs/design/clipboard-format.md).
279
+ * Written on copy as `version`; the Nabu paste interpreter accepts it (and fragments without a version).
280
+ */
281
+ export const CLIPBOARD_FORMAT_VERSION = 1;
282
+
283
+ /**
284
+ * Degrades the blocks whose type is NOT registered in the receiving editor (a fragment copied from a richer
285
+ * editor, an old document, a third-party extension that is not loaded): nothing is dropped.
286
+ * - the block becomes a block of `fallbackType` (the editor's default text block) with its text (`delta`) and
287
+ * `partial` kept; its props are dropped (they belong to the unknown type);
288
+ * - its children are kept as normal blocks RIGHT AFTER it, at the same level (an unknown container has no
289
+ * body to hold them), recursively degraded;
290
+ * - the children of a known block are degraded in place.
291
+ * Pure: returns new objects, never mutates the input; the engine names no block type (`isKnown` and
292
+ * `fallbackType` come from the registry / `defaultBlockType`).
293
+ * @param {PasteBlock[]} blocks
294
+ * @param {(type: string) => boolean} isKnown
295
+ * @param {string | null | undefined} fallbackType the default text block type; falsy = nothing to degrade to
296
+ * @returns {PasteBlock[]}
297
+ */
298
+ export function degradeUnknownBlocks(blocks, isKnown, fallbackType) {
299
+ if (!Array.isArray(blocks) || !fallbackType) return blocks;
300
+ /** @param {PasteBlock[]} list @returns {PasteBlock[]} */
301
+ const walk = (list) => list.flatMap((pb) => {
302
+ if (!pb || typeof pb !== 'object') return [pb];
303
+ const kids = Array.isArray(pb.children) && pb.children.length ? walk(pb.children) : null;
304
+ if (isKnown(pb.type)) {
305
+ const { children: _drop, ...rest } = pb;
306
+ return [kids ? { ...rest, children: kids } : rest];
307
+ }
308
+ const { children: _c, props: _p, ...rest } = pb;
309
+ /** @type {PasteBlock} */
310
+ const own = { ...rest, type: fallbackType, delta: Array.isArray(pb.delta) ? pb.delta : [], partial: kids ? (pb.partial === 'start' || pb.partial === 'both' ? 'start' : false) : (pb.partial ?? false) };
311
+ return kids ? [own, ...kids] : [own];
312
+ });
313
+ return walk(blocks);
314
+ }
315
+
316
+ /** Version written by `serialize('json')` (document export). `importJSON` reads this one (a missing version is read as it). */
317
+ export const JSON_FORMAT_VERSION = '1';
318
+
319
+ /**
320
+ * Whether `importJSON` can read a document export of this `version` (see {@link JSON_FORMAT_VERSION}). A missing version is
321
+ * read as the current one; the number `1` and the string `'1'` are the same version.
322
+ * @param {unknown} version
323
+ * @returns {boolean}
324
+ */
325
+ export function isSupportedJsonVersion(version) {
326
+ return version === undefined || version === null || String(version) === JSON_FORMAT_VERSION;
327
+ }
328
+
92
329
  /**
93
330
  * Convert a `serialize('json')` document export back into PasteBlocks.
94
- * The json format stores text as Slate-like runs (`{text, ...marks}`);
95
- * PasteBlocks store Loro deltas (`{insert, attributes}`).
96
- * @param {Array<{type: string, props?: Record<string, any>, content?: Array<{text: string, [mark: string]: any}>, children?: any[]}>} blocks
331
+ * The json format stores text as Slate-like runs (`{text, ...marks}`) or, for a code block, as a plain string;
332
+ * PasteBlocks store Loro deltas (`{insert, attributes}`). Top-level keys other than `id` / `type` / `props` / `content` /
333
+ * `children` are read as props (the `checked` of a to-do item in the first exports sat next to `type`).
334
+ * @param {Array<{type: string, props?: Record<string, any>, content?: Array<{text: string, [mark: string]: any}> | string, children?: any[], [key: string]: any}>} blocks
97
335
  * @returns {PasteBlock[]}
98
336
  */
99
337
  export function jsonToPasteBlocks(blocks) {
100
- return (blocks || []).map(b => {
338
+ return (Array.isArray(blocks) ? blocks : []).filter(b => b && typeof b === 'object' && typeof b.type === 'string').map(b => {
339
+ const { id: _id, type, props, content, children, ...extra } = b;
101
340
  /** @type {PasteBlock} */
102
- const pb = { type: b.type, partial: false };
103
- if (b.props) pb.props = b.props;
104
- if (Array.isArray(b.content)) {
105
- pb.delta = b.content.map(run => {
341
+ const pb = { type, partial: false };
342
+ const merged = { ...extra, ...(props && typeof props === 'object' ? props : {}) };
343
+ if (Object.keys(merged).length) pb.props = merged;
344
+ if (typeof content === 'string') {
345
+ if (content) pb.delta = [{ insert: content }];
346
+ } else if (Array.isArray(content)) {
347
+ pb.delta = content.filter(run => run && typeof run.text === 'string').map(run => {
106
348
  const { text, ...marks } = run;
107
349
  return Object.keys(marks).length
108
350
  ? { insert: text, attributes: marks }
109
351
  : { insert: text };
110
352
  });
111
353
  }
112
- if (Array.isArray(b.children)) pb.children = jsonToPasteBlocks(b.children);
354
+ if (Array.isArray(children)) pb.children = jsonToPasteBlocks(children);
113
355
  return pb;
114
356
  });
115
- }
357
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Escape text for use as HTML text content OR inside a quoted attribute value (& < > " ').
3
+ * @param {unknown} text
4
+ * @returns {string}
5
+ */
6
+ export function escapeHtml(text: unknown): string;
7
+ /**
8
+ * Escape a value for a quoted HTML attribute. Same table as {@link escapeHtml}; kept as a distinct name so the
9
+ * call sites say what they mean.
10
+ * @param {unknown} value
11
+ * @returns {string}
12
+ */
13
+ export function escapeAttr(value: unknown): string;
14
+ /**
15
+ * Return `url` when it is safe to put in an `href` / `src`, otherwise `null`.
16
+ *
17
+ * - `kind: 'link'` (default): http, https, mailto, tel, relative URLs, `#fragment`.
18
+ * - `kind: 'media'`: http, https, relative, `blob:`, `data:image/*`, `data:video/*`, and Nabu's internal
19
+ * `nabu-asset:` scheme (see Files).
20
+ *
21
+ * Everything else (`javascript:`, `vbscript:`, `data:text/html`, `file:`…) is refused, including obfuscated forms:
22
+ * surrounding / embedded whitespace and control characters (`java\nscript:`), mixed case, and HTML-entity-encoded
23
+ * schemes (`&#106;avascript:`). The URL is returned UNCHANGED (callers still have to escape it for the attribute).
24
+ *
25
+ * @param {unknown} url
26
+ * @param {{ kind?: 'link' | 'media' }} [options]
27
+ * @returns {string | null}
28
+ */
29
+ export function sanitizeUrl(url: unknown, { kind }?: {
30
+ kind?: "link" | "media";
31
+ }): string | null;
32
+ /**
33
+ * Sanitize the link / media URLs of PasteBlocks (the fragment format shared by paste, import and the clipboard):
34
+ * an unsafe `link` mark is dropped from the delta (the text stays), an unsafe `ref` / `src` / `href` / `url`
35
+ * prop is emptied. Returns NEW objects where something changed; never mutates the input.
36
+ * @template {{ delta?: any[], props?: Record<string, any>, children?: any[] }} B
37
+ * @param {B[]} blocks
38
+ * @returns {B[]}
39
+ */
40
+ export function sanitizePasteBlocks<B extends {
41
+ delta?: any[];
42
+ props?: Record<string, any>;
43
+ children?: any[];
44
+ }>(blocks: B[]): B[];
@@ -0,0 +1,183 @@
1
+ /**
2
+ * HTML / URL safety helpers — the ONE place that decides what may be written into markup or an `href` / `src`.
3
+ *
4
+ * Used by every HTML serializer (clipboard `text/html`, export), by the link / media rendering, and by the
5
+ * paste / import pipelines (defense in depth: the model, the render and the output are each guarded).
6
+ */
7
+
8
+ const HTML_ESCAPES = /** @type {Record<string, string>} */ ({
9
+ '&': '&amp;',
10
+ '<': '&lt;',
11
+ '>': '&gt;',
12
+ '"': '&quot;',
13
+ "'": '&#39;',
14
+ });
15
+
16
+ /**
17
+ * Escape text for use as HTML text content OR inside a quoted attribute value (& < > " ').
18
+ * @param {unknown} text
19
+ * @returns {string}
20
+ */
21
+ export function escapeHtml(text) {
22
+ return String(text ?? '').replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
23
+ }
24
+
25
+ /**
26
+ * Escape a value for a quoted HTML attribute. Same table as {@link escapeHtml}; kept as a distinct name so the
27
+ * call sites say what they mean.
28
+ * @param {unknown} value
29
+ * @returns {string}
30
+ */
31
+ export function escapeAttr(value) {
32
+ return escapeHtml(value);
33
+ }
34
+
35
+ /** Schemes allowed in a LINK (`<a href>`). Relative URLs and `#fragment` are always allowed. */
36
+ const LINK_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
37
+ /** Schemes allowed for MEDIA (`src` of img / video, `href` of a file chip). `data:` is handled separately. */
38
+ const MEDIA_SCHEMES = new Set(['http', 'https', 'blob', 'nabu-asset']);
39
+ /** `data:` URLs accepted for media only: images and videos, never HTML / script / text. */
40
+ const DATA_MEDIA = /^data:(?:image|video)\/[a-z0-9][a-z0-9.+-]*[;,]/i;
41
+
42
+ /** @type {Record<string, string>} */
43
+ const NAMED_ENTITIES = {
44
+ colon: ':', tab: '\t', newline: '\n', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", sol: '/', lpar: '(', rpar: ')',
45
+ };
46
+
47
+ /**
48
+ * Decode the HTML character references that could hide a URL scheme (`&#106;avascript:`, `&colon;`, `&Tab;`…).
49
+ * Decodes repeatedly (double-encoding) a bounded number of times.
50
+ * @param {string} s
51
+ * @returns {string}
52
+ */
53
+ function decodeEntities(s) {
54
+ let prev;
55
+ let out = s;
56
+ for (let i = 0; i < 4; i++) {
57
+ prev = out;
58
+ out = out.replace(/&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|([a-zA-Z]{2,8}));?/g, (m, dec, hex, name) => {
59
+ if (dec !== undefined || hex !== undefined) {
60
+ const cp = dec !== undefined ? parseInt(dec, 10) : parseInt(hex, 16);
61
+ try { return String.fromCodePoint(cp); } catch { return ''; }
62
+ }
63
+ const named = NAMED_ENTITIES[name.toLowerCase()];
64
+ return named !== undefined ? named : m;
65
+ });
66
+ if (out === prev) break;
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * Strip what a browser URL parser ignores or tolerates inside / around a scheme: ASCII control chars, whitespace
73
+ * (including unicode spaces, zero-width characters and BOM).
74
+ * @param {string} s
75
+ * @returns {string}
76
+ */
77
+ function stripInvisible(s) {
78
+ return s.replace(/[\u0000-\u0020\u007f-\u00a0\u00ad\u1680\u180e\u2000-\u200f\u2028-\u202f\u205f-\u2064\u3000\ufeff]/g, '');
79
+ }
80
+
81
+ /**
82
+ * Scheme of a (cleaned) URL, lower-cased, or `null` when it is relative / a fragment.
83
+ * @param {string} cleaned
84
+ * @returns {string | null}
85
+ */
86
+ function schemeOf(cleaned) {
87
+ const m = /^([a-z][a-z0-9+.-]*):/i.exec(cleaned);
88
+ return m ? m[1].toLowerCase() : null;
89
+ }
90
+
91
+ /**
92
+ * @param {string} cleaned whitespace/control-stripped URL
93
+ * @param {'link' | 'media'} kind
94
+ * @returns {boolean}
95
+ */
96
+ function isAllowed(cleaned, kind) {
97
+ const scheme = schemeOf(cleaned);
98
+ if (scheme === null) return true; // relative URL, `/path`, `?q`, `#frag`, `//host`
99
+ if (kind === 'media') return MEDIA_SCHEMES.has(scheme) || (scheme === 'data' && DATA_MEDIA.test(cleaned));
100
+ return LINK_SCHEMES.has(scheme);
101
+ }
102
+
103
+ /**
104
+ * Return `url` when it is safe to put in an `href` / `src`, otherwise `null`.
105
+ *
106
+ * - `kind: 'link'` (default): http, https, mailto, tel, relative URLs, `#fragment`.
107
+ * - `kind: 'media'`: http, https, relative, `blob:`, `data:image/*`, `data:video/*`, and Nabu's internal
108
+ * `nabu-asset:` scheme (see Files).
109
+ *
110
+ * Everything else (`javascript:`, `vbscript:`, `data:text/html`, `file:`…) is refused, including obfuscated forms:
111
+ * surrounding / embedded whitespace and control characters (`java\nscript:`), mixed case, and HTML-entity-encoded
112
+ * schemes (`&#106;avascript:`). The URL is returned UNCHANGED (callers still have to escape it for the attribute).
113
+ *
114
+ * @param {unknown} url
115
+ * @param {{ kind?: 'link' | 'media' }} [options]
116
+ * @returns {string | null}
117
+ */
118
+ export function sanitizeUrl(url, { kind = 'link' } = {}) {
119
+ if (typeof url !== 'string') return null;
120
+ const raw = url;
121
+ const cleaned = stripInvisible(raw);
122
+ if (!cleaned) return null;
123
+ // Both the literal form and its entity-decoded form must pass (the decoded one is what a browser would act
124
+ // on if this string ever went through an HTML parser).
125
+ if (!isAllowed(cleaned, kind)) return null;
126
+ if (cleaned.includes('&')) {
127
+ const decoded = stripInvisible(decodeEntities(raw));
128
+ if (!decoded || !isAllowed(decoded, kind)) return null;
129
+ }
130
+ // A backslash or percent-encoded scheme separator before the first `/` is not a scheme for browsers, but
131
+ // `%6Aavascript:` must not be mistaken for relative either: decode %XX once for the scheme check.
132
+ if (cleaned.includes('%')) {
133
+ let pct = cleaned;
134
+ try { pct = stripInvisible(decodeURIComponent(cleaned)); } catch { /* malformed escape: keep literal */ }
135
+ if (!isAllowed(pct, kind)) return null;
136
+ }
137
+ return raw;
138
+ }
139
+
140
+ /**
141
+ * Sanitize the link / media URLs of PasteBlocks (the fragment format shared by paste, import and the clipboard):
142
+ * an unsafe `link` mark is dropped from the delta (the text stays), an unsafe `ref` / `src` / `href` / `url`
143
+ * prop is emptied. Returns NEW objects where something changed; never mutates the input.
144
+ * @template {{ delta?: any[], props?: Record<string, any>, children?: any[] }} B
145
+ * @param {B[]} blocks
146
+ * @returns {B[]}
147
+ */
148
+ export function sanitizePasteBlocks(blocks) {
149
+ if (!Array.isArray(blocks)) return blocks;
150
+ return blocks.map((pb) => {
151
+ if (!pb || typeof pb !== 'object') return pb;
152
+ let out = pb;
153
+ if (Array.isArray(pb.delta)) {
154
+ let changed = false;
155
+ const delta = pb.delta.map((op) => {
156
+ const link = op?.attributes?.link;
157
+ if (link === undefined || link === null || link === false) return op;
158
+ if (typeof link === 'string' && sanitizeUrl(link, { kind: 'link' }) !== null) return op;
159
+ changed = true;
160
+ const { link: _drop, ...attributes } = op.attributes;
161
+ return Object.keys(attributes).length ? { ...op, attributes } : { insert: op.insert };
162
+ });
163
+ if (changed) out = { ...out, delta };
164
+ }
165
+ if (pb.props && typeof pb.props === 'object') {
166
+ let props = null;
167
+ for (const key of ['ref', 'src', 'href', 'url']) {
168
+ const v = pb.props[key];
169
+ const kind = key === 'ref' || key === 'src' ? 'media' : 'link';
170
+ if (typeof v === 'string' && v && sanitizeUrl(v, { kind }) === null) {
171
+ props ??= { ...pb.props };
172
+ props[key] = '';
173
+ }
174
+ }
175
+ if (props) out = { ...out, props };
176
+ }
177
+ if (Array.isArray(pb.children) && pb.children.length) {
178
+ const children = sanitizePasteBlocks(pb.children);
179
+ if (children.some((c, i) => c !== pb.children?.[i])) out = { ...out, children };
180
+ }
181
+ return out;
182
+ });
183
+ }
@@ -1,3 +1,6 @@
1
1
  export * from "./extensions.js";
2
2
  export * from "./selection.svelte.js";
3
3
  export * from "./placeholders.js";
4
+ export * from "./html.js";
5
+ export * from "./keys.js";
6
+ export * from "./commands.js";
@@ -1,3 +1,6 @@
1
1
  export * from "./extensions.js";
2
2
  export * from "./selection.svelte.js";
3
3
  export * from "./placeholders.js";
4
+ export * from "./html.js";
5
+ export * from "./keys.js";
6
+ export * from "./commands.js";