tinyzoo 0.0.0-stage → 0.2.0

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 (391) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +99 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +392 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTooMany.ts +9 -0
  312. package/server/utils/cmsTranslationWrite.ts +186 -0
  313. package/server/utils/cmsTree.ts +251 -0
  314. package/server/utils/cmsTreeAddress.ts +65 -0
  315. package/server/utils/cmsUpload.ts +197 -0
  316. package/server/utils/cmsWebhooks.ts +101 -0
  317. package/shared/json.ts +11 -0
  318. package/shared/richtext-editor.ts +56 -0
  319. package/shared/richtext-normalize.ts +33 -0
  320. package/shared/richtext-paste.ts +151 -0
  321. package/shared/storage-delivery.ts +53 -0
  322. package/src/blocks.ts +624 -0
  323. package/src/changes.ts +54 -0
  324. package/src/content-shape.ts +340 -0
  325. package/src/deprecate.ts +64 -0
  326. package/src/descriptor.ts +149 -0
  327. package/src/docs.ts +27 -0
  328. package/src/emitter.ts +94 -0
  329. package/src/entity.ts +624 -0
  330. package/src/errorReport.ts +41 -0
  331. package/src/fields.ts +465 -0
  332. package/src/i18n.ts +26 -0
  333. package/src/index.ts +54 -0
  334. package/src/linkref.ts +31 -0
  335. package/src/links.ts +179 -0
  336. package/src/locales.ts +39 -0
  337. package/src/media.ts +48 -0
  338. package/src/migrate.ts +236 -0
  339. package/src/openapi.ts +377 -0
  340. package/src/paths.ts +88 -0
  341. package/src/plugin.ts +505 -0
  342. package/src/presets.ts +230 -0
  343. package/src/richtext.ts +88 -0
  344. package/src/sdk.ts +181 -0
  345. package/src/search.ts +312 -0
  346. package/src/seed.ts +225 -0
  347. package/src/setupCode.ts +30 -0
  348. package/src/system.ts +219 -0
  349. package/src/tree.ts +421 -0
  350. package/src/upgrades.ts +137 -0
  351. package/starter/.env.example +10 -0
  352. package/starter/README.md +65 -0
  353. package/starter/app/app.config.ts +10 -0
  354. package/starter/app/app.vue +12 -0
  355. package/starter/app/assets/css/main.css +15 -0
  356. package/starter/app/components/global/BlockContact.vue +15 -0
  357. package/starter/app/components/global/BlockCta.vue +15 -0
  358. package/starter/app/components/global/BlockHero.vue +23 -0
  359. package/starter/app/components/global/BlockImage.vue +13 -0
  360. package/starter/app/components/global/BlockText.vue +12 -0
  361. package/starter/app/composables/useSite.ts +77 -0
  362. package/starter/app/error.vue +28 -0
  363. package/starter/app/layouts/default.vue +106 -0
  364. package/starter/app/lib/cms-content.ts +152 -0
  365. package/starter/app/pages/[...slug].vue +66 -0
  366. package/starter/app/pages/hledat.vue +59 -0
  367. package/starter/app/pages/index.vue +20 -0
  368. package/starter/cms.config.ts +137 -0
  369. package/starter/compose.yaml +15 -0
  370. package/starter/drizzle.config.ts +8 -0
  371. package/starter/gitignore.txt +8 -0
  372. package/starter/nuxt.config.ts +13 -0
  373. package/starter/package.json +38 -0
  374. package/starter/scripts/typecheck.mjs +38 -0
  375. package/starter/seed/index.ts +297 -0
  376. package/starter/seed/media/about.jpg +0 -0
  377. package/starter/seed/media/hero.jpg +0 -0
  378. package/starter/seed/media/logo.png +0 -0
  379. package/starter/seed/media/news-bread.jpg +0 -0
  380. package/starter/seed/media/news-morning.jpg +0 -0
  381. package/starter/server/db/migrations/0000_init.sql +269 -0
  382. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  383. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  384. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  385. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  386. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  387. package/starter/server/db/migrations/meta/_journal.json +27 -0
  388. package/starter/server/db/schema.ts +253 -0
  389. package/starter/server/plugins/sitemap.ts +11 -0
  390. package/starter/server/routes/robots.txt.get.ts +12 -0
  391. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,197 @@
1
+ import busboy from 'busboy'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { createWriteStream } from 'node:fs'
4
+ import { mkdir, readdir, stat, unlink } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { Transform } from 'node:stream'
7
+ import { pipeline } from 'node:stream/promises'
8
+
9
+ // Receiving an upload without holding it in memory.
10
+ //
11
+ // The multipart body is parsed as it arrives and the file part goes straight to a temp
12
+ // file on disk (while its SHA-256 and first bytes are taken on the way). From there the
13
+ // storage driver moves or streams it on, so a 100 MB video costs the process a few
14
+ // buffers, not a few hundred megabytes — the pods have 256 MiB.
15
+ //
16
+ // The size cap counts the bytes that really arrive, not the Content-Length header: a
17
+ // chunked body has none, and a client may lie. The moment the cap is crossed the
18
+ // upload is refused with 413 and nothing more is read into the process.
19
+
20
+ /** What the sniffers look at: the first bytes of the file (a JPEG's size can sit after a large EXIF block). */
21
+ export const UPLOAD_HEAD_BYTES = 512 * 1024
22
+ /** Multipart framing (boundaries, part headers, the small fields) on top of the file's own bytes. */
23
+ const FRAMING_BYTES = 1024 * 1024
24
+
25
+ export interface ReceivedFile {
26
+ /** The name the browser sent (display only: never used as a path). */
27
+ filename: string
28
+ /** The type the browser sent, lower case. */
29
+ type: string
30
+ /** Where the bytes are, in the storage driver's temp folder. The caller moves or removes it. */
31
+ path: string
32
+ size: number
33
+ sha256: string
34
+ /** The first bytes (up to UPLOAD_HEAD_BYTES). */
35
+ head: Buffer
36
+ }
37
+
38
+ export interface ReceivedUpload {
39
+ file: ReceivedFile | null
40
+ /** Text fields (folder, library), each short. */
41
+ fields: Record<string, string>
42
+ }
43
+
44
+ const tooLarge = (maxBytes: number) => createError({
45
+ statusCode: 413,
46
+ statusMessage: 'File too large (max ' + Math.round(maxBytes / 1024 / 1024) + 'MB)',
47
+ data: { code: 'file_too_large', maxMb: Math.round(maxBytes / 1024 / 1024) },
48
+ })
49
+
50
+ let swept = false
51
+ /** Leftovers of uploads a crashed process never finished (once per process; an hour old at least). */
52
+ function sweepOldTemp(dir: string) {
53
+ if (swept) return
54
+ swept = true
55
+ readdir(dir).then((names) => Promise.all(names.filter((n) => n.endsWith('.part')).map(async (n) => {
56
+ const file = join(dir, n)
57
+ const info = await stat(file).catch(() => null)
58
+ if (info && Date.now() - info.mtimeMs > 60 * 60 * 1000) await unlink(file).catch(() => {})
59
+ }))).catch(() => {})
60
+ }
61
+
62
+ /**
63
+ * Read the multipart upload of `event`: the first part named `file` with a filename is
64
+ * written to `tempDir`, the small text fields are returned. Throws 413 when more than
65
+ * `maxBytes` of file (or, with the framing, more than `maxBytes` + 1 MB of body) arrive,
66
+ * 400 for a body that is not multipart. Removes its temp file on every failure.
67
+ */
68
+ export async function receiveUpload(event: any, opts: { maxBytes: number; tempDir: string }): Promise<ReceivedUpload> {
69
+ const req = event.node.req
70
+ const { maxBytes, tempDir } = opts
71
+ await mkdir(tempDir, { recursive: true })
72
+ sweepOldTemp(tempDir)
73
+
74
+ let parser: busboy.Busboy
75
+ try {
76
+ parser = busboy({
77
+ headers: req.headers,
78
+ defParamCharset: 'utf8',
79
+ // One file, a handful of short fields; a byte over the cap shows as the file's 'limit'.
80
+ limits: { files: 1, fields: 12, fieldSize: 4096, parts: 16, fileSize: maxBytes + 1 },
81
+ })
82
+ }
83
+ catch {
84
+ throw createError({ statusCode: 400, statusMessage: 'No file uploaded (expected multipart field "file")' })
85
+ }
86
+
87
+ return new Promise<ReceivedUpload>((resolve, reject) => {
88
+ const fields: Record<string, string> = {}
89
+ let received: ReceivedFile | null = null
90
+ let tempPath = ''
91
+ let writing: Promise<void> | null = null
92
+ let finished = false
93
+ let total = 0
94
+
95
+ const stop = (err: unknown) => {
96
+ if (finished) return
97
+ finished = true
98
+ req.removeListener('data', count)
99
+ req.unpipe(parser)
100
+ // Answer now; the rest of the body is read and thrown away by Node (or the socket
101
+ // is closed after the answer), never kept: see the Connection header below.
102
+ if (!event.node.res.headersSent) event.node.res.setHeader('Connection', 'close')
103
+ const cleanup = writing ? writing.catch(() => {}) : Promise.resolve()
104
+ cleanup.then(() => (tempPath ? unlink(tempPath).catch(() => {}) : undefined)).finally(() => reject(err))
105
+ // The temp file may still be open: end its stream first (the pipeline ends with the error below).
106
+ parser.destroy()
107
+ }
108
+
109
+ // Counts what arrives on the socket, whatever the framing.
110
+ const cap = maxBytes + FRAMING_BYTES
111
+ const count = (chunk: Buffer) => {
112
+ total += chunk.length
113
+ if (total > cap) stop(tooLarge(maxBytes))
114
+ }
115
+
116
+ parser.on('field', (name, value, info) => {
117
+ if (info.valueTruncated || info.nameTruncated) return stop(createError({ statusCode: 400, statusMessage: 'A form field is too long' }))
118
+ fields[name] = value
119
+ })
120
+
121
+ parser.on('file', (name, stream, info) => {
122
+ if (name !== 'file' || !info.filename || received || writing) {
123
+ stream.resume() // a second or unexpected file: read past it
124
+ return
125
+ }
126
+ tempPath = join(tempDir, randomUUID() + '.part')
127
+ const hash = createHash('sha256')
128
+ const head: Buffer[] = []
129
+ let headBytes = 0
130
+ let size = 0
131
+ const meter = new Transform({
132
+ transform(chunk: Buffer, _enc, cb) {
133
+ size += chunk.length
134
+ hash.update(chunk)
135
+ if (headBytes < UPLOAD_HEAD_BYTES) {
136
+ const part = chunk.subarray(0, UPLOAD_HEAD_BYTES - headBytes)
137
+ head.push(part)
138
+ headBytes += part.length
139
+ }
140
+ cb(null, chunk)
141
+ },
142
+ })
143
+ stream.on('limit', () => stop(tooLarge(maxBytes)))
144
+ writing = pipeline(stream, meter, createWriteStream(tempPath)).then(() => {
145
+ received = { filename: info.filename ?? '', type: String(info.mimeType || '').toLowerCase(), path: tempPath, size, sha256: hash.digest('hex'), head: Buffer.concat(head) }
146
+ })
147
+ writing.catch((err) => stop(err))
148
+ })
149
+
150
+ parser.on('error', () => stop(createError({ statusCode: 400, statusMessage: 'The upload could not be read' })))
151
+ parser.on('partsLimit', () => stop(createError({ statusCode: 400, statusMessage: 'Too many parts in the upload' })))
152
+ parser.on('fieldsLimit', () => stop(createError({ statusCode: 400, statusMessage: 'Too many fields in the upload' })))
153
+
154
+ parser.on('close', async () => {
155
+ if (finished) return
156
+ try { await writing } catch { return } // stop() has already answered
157
+ if (finished) return
158
+ finished = true
159
+ req.removeListener('data', count)
160
+ resolve({ file: received, fields })
161
+ })
162
+
163
+ // The visitor went away mid-upload: nobody to answer; drop the half file.
164
+ req.once('close', () => { if (!req.complete) stop(createError({ statusCode: 499, statusMessage: 'Upload cancelled' })) })
165
+ req.on('data', count)
166
+ req.pipe(parser)
167
+ })
168
+ }
169
+
170
+ /** Remove a received file that was not stored (refused, or the store failed). */
171
+ export async function discardReceived(file: ReceivedFile | null | undefined): Promise<void> {
172
+ if (file) await unlink(file.path).catch(() => {})
173
+ }
174
+
175
+ const startsWith = (head: Buffer, bytes: number[], at = 0) => bytes.every((b, i) => head[at + i] === b)
176
+
177
+ /**
178
+ * Does the content look like what its type says? The pictures are checked by the size
179
+ * reader; for the rest the first bytes must carry the format's signature — a renamed
180
+ * text file or a download cut off before its header is not a PDF or a video.
181
+ */
182
+ export function looksLike(mime: string, head: Buffer): boolean {
183
+ switch (mime) {
184
+ case 'application/pdf':
185
+ // The header may follow a little junk, but within the first KB.
186
+ return head.subarray(0, 1024).includes('%PDF-')
187
+ case 'video/mp4':
188
+ return head.length >= 12 && head.subarray(4, 8).toString('latin1') === 'ftyp'
189
+ case 'video/webm':
190
+ return startsWith(head, [0x1a, 0x45, 0xdf, 0xa3]) // EBML
191
+ case 'audio/mpeg':
192
+ // An ID3 tag, or an MPEG audio frame (11 bits of sync).
193
+ return head.subarray(0, 3).toString('latin1') === 'ID3' || (head[0] === 0xff && ((head[1] ?? 0) & 0xe0) === 0xe0)
194
+ default:
195
+ return true
196
+ }
197
+ }
@@ -0,0 +1,101 @@
1
+ import type { CmsChange } from 'tinyzoo'
2
+
3
+ /**
4
+ * Publish webhooks: POST each public content change to the configured URLs so the
5
+ * website can purge its cache (`cms.webhooks.urls`, env NUXT_CMS_WEBHOOKS_URLS — comma
6
+ * separated; `cms.webhooks.secret` / NUXT_CMS_WEBHOOKS_SECRET signs them).
7
+ *
8
+ * Body: { delivery, type, entity, id, locale, public, paths, moved?, version, at } as JSON.
9
+ * `paths` are the website addresses to purge (old and new); in a page tree `moved` lists
10
+ * each address that changed with the write, `[{ id, locale, from, to }]`, the page's subpages included.
11
+ * `delivery` is unique per change and the same on every retry: deduplicate on it
12
+ * (it is inside the signed body, so a replay cannot pass as a new delivery).
13
+ * Headers:
14
+ * X-CMS-Event the change type, e.g. entry.published
15
+ * X-CMS-Delivery the delivery id again, for logs
16
+ * X-CMS-Signature t=<unix seconds>,v1=<hex HMAC-SHA256 of `${t}.${body}` with the secret>
17
+ *
18
+ * Verify by recomputing the HMAC over the raw body and rejecting a `t` older than a
19
+ * few minutes. Up to 3 attempts (the 2nd 1 s after the 1st fails, the 3rd 5 s after
20
+ * the 2nd); a 4xx answer other than 408/429 is final. Runs after the response and
21
+ * only ever logs failures. In production nothing is sent without a secret.
22
+ */
23
+ const RETRY_DELAYS_MS = [1_000, 5_000]
24
+ const TIMEOUT_MS = 5_000
25
+
26
+ export function webhookConfig(): { urls: string[]; secret: string } {
27
+ const cfg = (useRuntimeConfig().cms as any)?.webhooks ?? {}
28
+ const raw: string = Array.isArray(cfg.urls) ? cfg.urls.join(',') : String(cfg.urls || '')
29
+ const urls = raw.split(/[\s,]+/).map((u) => u.trim()).filter((u) => {
30
+ try {
31
+ const url = new URL(u)
32
+ return url.protocol === 'http:' || url.protocol === 'https:'
33
+ }
34
+ catch {
35
+ return false
36
+ }
37
+ })
38
+ return { urls, secret: String(cfg.secret || '') }
39
+ }
40
+
41
+ const toHex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
42
+
43
+ export async function signWebhook(secret: string, timestamp: number, body: string): Promise<string> {
44
+ const enc = new TextEncoder()
45
+ const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
46
+ return toHex(await crypto.subtle.sign('HMAC', key, enc.encode(`${timestamp}.${body}`)))
47
+ }
48
+
49
+ let warnedUnsigned = false
50
+
51
+ /** Send a change to every webhook URL. Never rejects. */
52
+ export async function sendWebhooks(change: CmsChange): Promise<void> {
53
+ const { urls, secret } = webhookConfig()
54
+ if (!urls.length) return
55
+ if (!secret) {
56
+ const production = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'
57
+ if (!warnedUnsigned) {
58
+ warnedUnsigned = true
59
+ console.warn(production
60
+ ? '[cms] webhooks are not sent: set NUXT_CMS_WEBHOOKS_SECRET'
61
+ : '[cms] webhooks are sent unsigned (development) — set NUXT_CMS_WEBHOOKS_SECRET')
62
+ }
63
+ if (production) return
64
+ }
65
+ const delivery = crypto.randomUUID()
66
+ // Who made the change stays inside the admin.
67
+ const { by: _by, ...rest } = change
68
+ const body = JSON.stringify({ delivery, ...rest })
69
+ await Promise.all(urls.map((url) => deliver(url, secret, change.type, delivery, body).catch(() => {})))
70
+ }
71
+
72
+ async function deliver(url: string, secret: string, type: string, delivery: string, body: string): Promise<void> {
73
+ let lastError = ''
74
+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
75
+ if (attempt) await new Promise((r) => setTimeout(r, RETRY_DELAYS_MS[attempt - 1]))
76
+ try {
77
+ const t = Math.floor(Date.now() / 1000)
78
+ const headers: Record<string, string> = {
79
+ 'content-type': 'application/json',
80
+ 'user-agent': 'cms-webhooks/1',
81
+ 'x-cms-event': type,
82
+ 'x-cms-delivery': delivery,
83
+ }
84
+ if (secret) headers['x-cms-signature'] = `t=${t},v1=${await signWebhook(secret, t, body)}`
85
+ const res = await fetch(url, { method: 'POST', headers, body, redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT_MS) })
86
+ // Drain the body so the connection can be reused.
87
+ await res.arrayBuffer().catch(() => {})
88
+ if (res.ok) return
89
+ lastError = `HTTP ${res.status}`
90
+ if (res.status >= 300 && res.status < 500 && res.status !== 408 && res.status !== 429) break
91
+ }
92
+ catch (err) {
93
+ lastError = (err as Error)?.message || String(err)
94
+ }
95
+ }
96
+ console.error(JSON.stringify({ level: 'error', msg: 'cms webhook delivery failed', url: safeUrl(url), type, delivery, error: lastError }))
97
+ reportCmsError({
98
+ source: 'webhook', error: new Error(`Webhook delivery failed: ${lastError}`), status: null, requestId: null, method: null, path: null, userId: null,
99
+ webhook: { url: safeUrl(url), type, delivery },
100
+ })
101
+ }
package/shared/json.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * JSON for comparing values: object keys sorted, so the same value compares equal
3
+ * however it was built — Postgres stores jsonb with its keys reordered, and the
4
+ * editor builds them in its own order. Shared by the admin and the server.
5
+ */
6
+ export function stableJson(value: unknown): string {
7
+ return JSON.stringify(value ?? null, (_key, v) =>
8
+ v && typeof v === 'object' && !Array.isArray(v)
9
+ ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]]))
10
+ : v)
11
+ }
@@ -0,0 +1,56 @@
1
+ import { getSchema, type AnyExtension } from '@tiptap/core'
2
+ import StarterKit from '@tiptap/starter-kit'
3
+ import Link from '@tiptap/extension-link'
4
+ import Image from '@tiptap/extension-image'
5
+
6
+ /**
7
+ * The rich-text editor's extensions, shared by the browser (the editor) and the
8
+ * server (shared editing builds documents with exactly the same schema).
9
+ */
10
+
11
+ // Image node that also records the cms_media id (as data-media-id) so the media GC
12
+ // can see images embedded in body text and never orphans them.
13
+ export const MediaImage = Image.extend({
14
+ addAttributes() {
15
+ return {
16
+ ...this.parent?.(),
17
+ mediaId: {
18
+ default: null,
19
+ parseHTML: (el: { getAttribute: (name: string) => string | null }) => el.getAttribute('data-media-id'),
20
+ renderHTML: (attrs: Record<string, any>) => (attrs.mediaId ? { 'data-media-id': attrs.mediaId } : {}),
21
+ },
22
+ }
23
+ },
24
+ })
25
+
26
+ // Links render with fixed target/rel and never with a class: shared text arrives from
27
+ // other people's browsers, and a crafted class (e.g. a full-screen overlay) or target
28
+ // must not reach the page. Same attributes, so stored JSON keeps its shape.
29
+ export const SafeLink = Link.extend({
30
+ addAttributes() {
31
+ const parent = this.parent?.() ?? {}
32
+ return {
33
+ ...parent,
34
+ target: { default: '_blank', parseHTML: () => '_blank', renderHTML: () => ({ target: '_blank' }) },
35
+ rel: { default: 'noopener noreferrer', parseHTML: () => 'noopener noreferrer', renderHTML: () => ({ rel: 'noopener noreferrer' }) },
36
+ class: { default: null, parseHTML: () => null, renderHTML: () => ({}) },
37
+ }
38
+ },
39
+ })
40
+
41
+ export function richTextExtensions(opts: { collaborative?: boolean } = {}): AnyExtension[] {
42
+ return [
43
+ // StarterKit v3 bundles Link (configured below) and an undo history, which shared
44
+ // editing replaces with its own (per person, not per document).
45
+ StarterKit.configure({ link: false, ...(opts.collaborative ? { undoRedo: false } : {}) }),
46
+ // `cms:<entity>/<id>` is a link to one of the site's pages (see src/links.ts): an allowed scheme here.
47
+ SafeLink.configure({ openOnClick: false, autolink: true, protocols: [{ scheme: 'cms', optionalSlashes: true }] }),
48
+ MediaImage.configure({ HTMLAttributes: { class: 'cms-embed-img' } }),
49
+ ]
50
+ }
51
+
52
+ let schema: ReturnType<typeof getSchema> | undefined
53
+ /** The ProseMirror schema of stored rich text. */
54
+ export function editorSchema() {
55
+ return (schema ??= getSchema(richTextExtensions()))
56
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Comparing rich text the way a person reads it: the editor adds an empty paragraph
3
+ * after a last heading, list or quote, and empty text is the same as no text. Shared
4
+ * by the admin (is the form unsaved?) and the server (is the shared document ahead of
5
+ * the saved entry?).
6
+ */
7
+ import { stableJson } from './json'
8
+
9
+ const emptyParagraph = (n: any) => n?.type === 'paragraph' && !(n.content?.length)
10
+
11
+ /** The document without empty paragraphs at its end (the same document when there are none). */
12
+ export function withoutTrailingEmpty<T>(doc: T): T {
13
+ const d = doc as any
14
+ if (!d || d.type !== 'doc' || !Array.isArray(d.content)) return doc
15
+ let end = d.content.length
16
+ while (end > 0 && emptyParagraph(d.content[end - 1])) end--
17
+ return end === d.content.length ? doc : ({ ...d, content: d.content.slice(0, end) } as T)
18
+ }
19
+
20
+ /** A value with every rich-text document inside it (also within blocks and groups) trimmed that way. */
21
+ export function withoutTrailingEmptyDeep(value: any): any {
22
+ if (Array.isArray(value)) return value.map(withoutTrailingEmptyDeep)
23
+ if (value && typeof value === 'object') {
24
+ if (value.type === 'doc' && Array.isArray(value.content)) return withoutTrailingEmpty(value)
25
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, withoutTrailingEmptyDeep(v)]))
26
+ }
27
+ return value
28
+ }
29
+
30
+ /** Stable JSON of a form value, rich text compared without its trailing empty paragraphs. */
31
+ export function formJson(value: unknown): string {
32
+ return stableJson(withoutTrailingEmptyDeep(value))
33
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Tidying HTML pasted into the rich-text editor, before the editor reads it.
3
+ *
4
+ * Word (and Outlook) put lists in as plain paragraphs marked with `mso-list`, with the
5
+ * bullet or number as text inside a hidden span, and tables as `<table>`. The editor
6
+ * has real lists and no table, and silently turns those paragraphs into text starting
7
+ * with a Symbol bullet. This turns them into what a person meant:
8
+ *
9
+ * - runs of list paragraphs become `<ul>` / `<ol>` with nested levels;
10
+ * - a table becomes one paragraph per row, its cells separated by " · " (the text is
11
+ * kept, nothing runs together);
12
+ * - an image that cannot be kept (a `file://` path on the other person's computer, a
13
+ * `data:` blob, no source) is dropped and counted, so the editor can say so instead
14
+ * of leaving an empty image.
15
+ *
16
+ * Works on the HTML text (no DOM), so it runs the same in a test. Only structure is
17
+ * rebuilt; the editor's own schema still decides what is kept, so scripts, styles and
18
+ * event handlers never get through (they are not in the schema), and text is copied
19
+ * through as it was, never rewritten into markup.
20
+ */
21
+
22
+ export interface PastedHtml {
23
+ html: string
24
+ /** Images left out (not a web address the page could show). */
25
+ droppedImages: number
26
+ }
27
+
28
+ const NAMED: Record<string, string> = {
29
+ nbsp: ' ', middot: '·', bull: '•', ndash: '–', mdash: '—', hellip: '…', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”',
30
+ bdquo: '„', sbquo: '‚', laquo: '«', raquo: '»', copy: '©', reg: '®', trade: '™', euro: '€', deg: '°', times: '×',
31
+ }
32
+ const decode = (s: string) => s
33
+ .replace(/&#160;|&#xa0;/gi, ' ')
34
+ .replace(/&([a-z]+);/gi, (m, name: string) => NAMED[name.toLowerCase()] ?? m)
35
+ .replace(/&#(\d+);/g, (_m, n) => String.fromCodePoint(Number(n)))
36
+ .replace(/&#x([0-9a-f]+);/gi, (_m, n) => String.fromCodePoint(parseInt(n, 16)))
37
+ .replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&quot;/gi, '"').replace(/&amp;/gi, '&')
38
+ // An entity the editor can read stays one (an unknown "&foo;" is not doubled into "&amp;foo;").
39
+ const escapeText = (s: string) => s.replace(/&(?!(?:#\d+|#x[0-9a-f]+|[a-z]+);)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
40
+ const textOf = (html: string) => decode(html.replace(/<(?:br|\/p|\/div|\/li|\/h[1-6])\b[^>]*>/gi, ' ').replace(/<[^>]*>/g, '')).replace(/\s+/g, ' ').trim()
41
+
42
+ /** Marker text that numbers an item ("1.", "a)", "iv.") rather than bullets it ("·", "o", "§"). */
43
+ const isNumbering = (marker: string) => /^\(?(?:\d{1,3}|[a-zA-Z]|[ivxlcdmIVXLCDM]{1,6})[.)]$/.test(marker) || /^\d{1,3}$/.test(marker)
44
+
45
+ /** Remove the first `<span … mso-list:Ignore>…</span>` (with whatever it nests) and return its text. */
46
+ function takeMarker(html: string): { marker: string; rest: string } {
47
+ const open = /<span\b[^>]*mso-list:\s*Ignore[^>]*>/i.exec(html)
48
+ if (!open) return { marker: '', rest: html }
49
+ const tags = /<\/?span\b[^>]*>/gi
50
+ tags.lastIndex = open.index + open[0].length
51
+ let depth = 1
52
+ let end = html.length
53
+ for (let m = tags.exec(html); m; m = tags.exec(html)) {
54
+ depth += m[0].startsWith('</') ? -1 : 1
55
+ if (depth === 0) {
56
+ end = m.index + m[0].length
57
+ break
58
+ }
59
+ }
60
+ const inner = html.slice(open.index + open[0].length, end)
61
+ const marker = textOf(inner.replace(/<span\b[\s\S]*$/i, '')).replace(/\s+/g, '')
62
+ return { marker, rest: html.slice(0, open.index) + html.slice(end) }
63
+ }
64
+
65
+ interface Item { level: number; ordered: boolean; html: string }
66
+
67
+ function listHtml(items: Item[]): string {
68
+ let out = ''
69
+ const stack: { tag: 'ul' | 'ol'; open: boolean }[] = []
70
+ const close = () => {
71
+ const top = stack.pop()!
72
+ out += `${top.open ? '</li>' : ''}</${top.tag}>`
73
+ }
74
+ for (const it of items) {
75
+ const level = Math.max(1, Math.min(8, it.level))
76
+ while (stack.length > level) close()
77
+ if (stack.length === level) {
78
+ const top = stack[stack.length - 1]!
79
+ if (top.open) out += '</li>'
80
+ top.open = false
81
+ }
82
+ while (stack.length < level) {
83
+ const tag = stack.length === level - 1 && it.ordered ? 'ol' : 'ul'
84
+ out += `<${tag}>`
85
+ stack.push({ tag, open: false })
86
+ }
87
+ out += `<li>${it.html}`
88
+ stack[stack.length - 1]!.open = true
89
+ }
90
+ while (stack.length) close()
91
+ return out
92
+ }
93
+
94
+ const LIST_PARAGRAPH = /<p\b[^>]*mso-list:\s*l\d+\s+level\d+[^>]*>[\s\S]*?<\/p>/gi
95
+
96
+ function convertLists(html: string): string {
97
+ const run = new RegExp(`(?:${LIST_PARAGRAPH.source}\\s*)+`, 'gi')
98
+ return html.replace(run, (chunk) => {
99
+ const items: Item[] = []
100
+ for (const p of chunk.match(new RegExp(LIST_PARAGRAPH.source, 'gi')) ?? []) {
101
+ const level = Number(/mso-list:\s*l\d+\s+level(\d+)/i.exec(p)?.[1] ?? 1)
102
+ const inner = p.replace(/^<p\b[^>]*>/i, '').replace(/<\/p>$/i, '')
103
+ const { marker, rest } = takeMarker(inner)
104
+ // Without Word's marker (and the empty wrapper it leaves) and its blank space.
105
+ const body = rest.replace(/<\/?o:p\b[^>]*>/gi, '').replace(/<span\b[^>]*>\s*<\/span>/gi, '').replace(/^(?:\s|&nbsp;|&#160;)+/i, '')
106
+ // Nothing but the marker (an empty item): not worth a bullet.
107
+ if (!textOf(body)) continue
108
+ items.push({ level, ordered: isNumbering(marker), html: body })
109
+ }
110
+ return items.length ? listHtml(items) : ''
111
+ })
112
+ }
113
+
114
+ function convertTables(html: string): string {
115
+ let out = html
116
+ // Innermost first, so a table inside a cell is flattened before its cell is read.
117
+ for (let guard = 0; guard < 20 && /<table\b/i.test(out); guard++) {
118
+ out = out.replace(/<table\b(?:(?!<table\b)[\s\S])*?<\/table>/gi, (table) => {
119
+ const rows = table.match(/<tr\b[\s\S]*?<\/tr>/gi) ?? []
120
+ return rows.map((tr) => {
121
+ const cells = (tr.match(/<t[dh]\b[\s\S]*?<\/t[dh]>/gi) ?? []).map(textOf).filter(Boolean)
122
+ return cells.length ? `<p>${escapeText(cells.join(' · '))}</p>` : ''
123
+ }).join('')
124
+ })
125
+ }
126
+ return out
127
+ }
128
+
129
+ function dropUnusableImages(html: string): { html: string; dropped: number } {
130
+ let dropped = 0
131
+ const out = html.replace(/<img\b[^>]*>/gi, (tag) => {
132
+ const src = /\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(tag)
133
+ const value = decode((src?.[1] ?? src?.[2] ?? src?.[3] ?? '').trim())
134
+ // Only a web address can be shown on the page; a path on the sender's computer, an embedded blob or nothing cannot.
135
+ if (/^https?:\/\//i.test(value) || value.startsWith('/')) return tag
136
+ dropped++
137
+ return ''
138
+ })
139
+ return { html: out, dropped }
140
+ }
141
+
142
+ /** Make pasted HTML (Word and the like) say what its author meant. See the top of this file. */
143
+ export function cleanPastedHtml(html: string): PastedHtml {
144
+ let out = String(html ?? '')
145
+ // Word's conditional comments: the hidden kind goes with its content, the "revealed" kind only its markers.
146
+ out = out.replace(/<!--\[if[\s\S]*?<!\[endif\]-->/gi, '').replace(/<!\[(?:if [^\]]*|endif)\]>/gi, '')
147
+ if (/mso-list:/i.test(out)) out = convertLists(out)
148
+ if (/<table\b/i.test(out)) out = convertTables(out)
149
+ const { html: withoutImages, dropped } = dropUnusableImages(out)
150
+ return { html: withoutImages, droppedImages: dropped }
151
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * How files in an S3-compatible bucket reach browsers (`cms.storage.s3.delivery`), and the
3
+ * address a stored file gets for it. Shared by the server's storage driver and the
4
+ * command line (`tinyzoo import` writes the same addresses), so the two cannot drift.
5
+ * No Nitro globals: the unit tests load it.
6
+ */
7
+
8
+ /**
9
+ * - `public`: the bucket (or a CDN in front of it) is readable by anyone; the stored address
10
+ * is the bucket's own (`publicBaseUrl`, or `<endpoint>/<bucket>/<key>`).
11
+ * - `proxy`: the bucket is private; the app streams each file (`/api/cms/_media/raw/<key>`).
12
+ * - `redirect`: the bucket is private; the app answers with a short-lived signed address.
13
+ * The stored address of `proxy` and `redirect` is the same app path, so it never expires.
14
+ */
15
+ export type S3Delivery = 'public' | 'proxy' | 'redirect'
16
+ export const S3_DELIVERIES: readonly S3Delivery[] = ['public', 'proxy', 'redirect']
17
+
18
+ /** The app path files are served from when the bucket is not (the one the local driver uses). */
19
+ export const DEFAULT_MEDIA_BASE = '/api/cms/_media/raw'
20
+
21
+ /** What was asked for, or the default: `public` when a public address is given, `proxy` otherwise. Throws for a name that is none of the three. */
22
+ export function resolveS3Delivery(value: unknown, publicBaseUrl?: string | null): S3Delivery {
23
+ const asked = String(value ?? '').trim().toLowerCase()
24
+ if (!asked) return publicBaseUrl ? 'public' : 'proxy'
25
+ if ((S3_DELIVERIES as readonly string[]).includes(asked)) return asked as S3Delivery
26
+ throw new Error(`Unknown storage delivery '${asked}' (NUXT_CMS_STORAGE_S3_DELIVERY is 'public', 'proxy' or 'redirect').`)
27
+ }
28
+
29
+ /** A key as the path of an address, one segment at a time. */
30
+ export function encodeStorageKey(key: string): string {
31
+ return key.split('/').map(encodeURIComponent).join('/')
32
+ }
33
+
34
+ /** A key that stays inside the bucket: no empty, `.` or `..` segments (a URL would resolve them), no backslash or control characters. */
35
+ export function isSafeStorageKey(key: string): boolean {
36
+ if (!key || key.length > 1024) return false
37
+ if (/[\\\u0000-\u001f\u007f]/.test(key)) return false
38
+ return key.split('/').every((part) => part !== '' && part !== '.' && part !== '..')
39
+ }
40
+
41
+ /** The address a file is stored under in the database, and handed to browsers. */
42
+ export function storedMediaUrl(
43
+ cfg: { delivery: S3Delivery; endpoint: string; bucket: string; publicBaseUrl?: string | null; appBase?: string | null },
44
+ key: string,
45
+ ): string {
46
+ if (cfg.delivery !== 'public') {
47
+ const base = (cfg.appBase || DEFAULT_MEDIA_BASE).replace(/\/+$/, '')
48
+ return base + '/' + key
49
+ }
50
+ const endpoint = cfg.endpoint.replace(/\/+$/, '')
51
+ const base = cfg.publicBaseUrl?.replace(/\/+$/, '') || endpoint + '/' + cfg.bucket
52
+ return base + '/' + encodeStorageKey(key)
53
+ }