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,580 @@
1
+ import { createReadStream } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { dirname, extname, join, resolve, sep } from 'node:path'
4
+ import { Readable } from 'node:stream'
5
+ import { pipeline } from 'node:stream/promises'
6
+ import { DEFAULT_MEDIA_BASE, encodeStorageKey, isSafeStorageKey, resolveS3Delivery, storedMediaUrl, type S3Delivery } from '../../shared/storage-delivery'
7
+ import { byteRange, etagMatches, singleRange } from './cmsRange'
8
+
9
+ /** Result of persisting a blob. */
10
+ export interface StoredObject {
11
+ key: string
12
+ url: string
13
+ size: number
14
+ }
15
+
16
+ /**
17
+ * Pluggable blob storage. The DB only ever holds metadata (a `cms_media` row);
18
+ * the bytes live behind one of these drivers. This is the runtime-divergence seam:
19
+ * Node dev → LocalDriver; production → S3/R2 (same interface, swapped via config).
20
+ */
21
+ export interface StorageDriver {
22
+ /** Persist `body` under `key`. Returns the public URL + byte size. */
23
+ put(key: string, body: Buffer, contentType: string): Promise<StoredObject>
24
+ /**
25
+ * Persist the file at `path` (an upload received to disk, see cmsUpload) under `key`
26
+ * without reading it into memory: the local driver moves it, S3 streams it. The
27
+ * file is consumed on success; the caller removes it when this throws.
28
+ */
29
+ putFile(key: string, path: string, info: { size: number; sha256: string; contentType: string }): Promise<StoredObject>
30
+ /** Where uploads are received before they are stored: a folder on a disk, not in memory. */
31
+ readonly tempDir: string
32
+ /** Read the whole file into memory. For small files (picture sizes, a resize's source); serving uses `read`. */
33
+ get(key: string): Promise<{ body: Buffer; contentType: string } | null>
34
+ /**
35
+ * Read as a stream, optionally one byte range: what the serving route sends, so a
36
+ * video is never held in memory. `null` when the file does not exist.
37
+ */
38
+ read(key: string, opts?: StorageReadOptions): Promise<StorageRead | null>
39
+ /** Best-effort removal. */
40
+ delete(key: string): Promise<void>
41
+ /** The address stored in the database and handed to browsers. Never expires. */
42
+ url(key: string): string
43
+ /**
44
+ * A signed address that serves the file straight from the store for `seconds`
45
+ * (`delivery: 'redirect'`). Never stored anywhere. Absent for drivers without one.
46
+ */
47
+ presign?(key: string, seconds: number, contentDisposition?: string): Promise<string>
48
+ /** How browsers get the files (S3 only); the raw route redirects under `redirect`. */
49
+ readonly delivery?: S3Delivery
50
+ }
51
+
52
+ export interface StorageReadOptions {
53
+ /** The request's `Range` header (one range; anything else is ignored). */
54
+ range?: string
55
+ /** The request's `If-None-Match` header. */
56
+ ifNoneMatch?: string
57
+ }
58
+
59
+ /** A file being read: whole (200), one range (206), unchanged since the caller's copy (304) or a range outside the file (416). */
60
+ export interface StorageRead {
61
+ status: 200 | 206 | 304 | 416
62
+ contentType: string
63
+ /** Bytes in `body`, when the store says. */
64
+ contentLength?: number
65
+ /** The Content-Range header: the bytes sent and the file's size (206), or only the size (416). */
66
+ contentRange?: string
67
+ etag?: string
68
+ lastModified?: string
69
+ /** `null` for 304 and 416. */
70
+ body: ReadableStream<Uint8Array> | null
71
+ }
72
+
73
+ /**
74
+ * A file as a web stream that reads only as fast as it is consumed. `Readable.toWeb` alone
75
+ * counts its queue in *chunks* for a byte stream (its high-water mark of 64 KB then means 65 536
76
+ * chunks, 4 GB), so the whole file is read ahead into memory as fast as the disk can: a
77
+ * 100 MB upload to a bucket, or a video for a slow phone, took half its size in RAM. Here the
78
+ * queue is counted in bytes.
79
+ */
80
+ export function fileWebStream(path: string, range?: { start: number; end: number }): ReadableStream<Uint8Array> {
81
+ const HIGH_WATER_MARK = 256 * 1024
82
+ const node = createReadStream(path, { ...range, highWaterMark: HIGH_WATER_MARK })
83
+ return Readable.toWeb(node, { strategy: { highWaterMark: HIGH_WATER_MARK, size: (chunk: Uint8Array) => chunk.byteLength } }) as ReadableStream<Uint8Array>
84
+ }
85
+
86
+ /** PUT the file at `path` to `url` with these (signed) headers; resolves with the HTTP status. Streams from disk with backpressure. */
87
+ async function sendFile(url: string, headers: Record<string, string>, path: string): Promise<number> {
88
+ const { request } = url.startsWith('https:') ? await import('node:https') : await import('node:http')
89
+ return new Promise<number>((resolve, reject) => {
90
+ let status = 0
91
+ // A store that refuses (403, 5xx) may answer before the whole body is sent and close the
92
+ // connection: its answer is what counts, not the broken pipe after it.
93
+ const failed = (err: Error) => (status ? resolve(status) : reject(err))
94
+ const req = request(url, { method: 'PUT', headers }, (res) => {
95
+ status = res.statusCode ?? 0
96
+ res.resume() // the answer is only its status
97
+ res.on('end', () => resolve(status))
98
+ res.on('close', () => resolve(status))
99
+ res.on('error', failed)
100
+ })
101
+ req.setTimeout(60_000, () => req.destroy(new Error('timeout')))
102
+ req.on('error', failed)
103
+ pipeline(createReadStream(path), req).catch(failed)
104
+ })
105
+ }
106
+
107
+ const MIME_BY_EXT: Record<string, string> = {
108
+ '.png': 'image/png',
109
+ '.jpg': 'image/jpeg',
110
+ '.jpeg': 'image/jpeg',
111
+ '.gif': 'image/gif',
112
+ '.webp': 'image/webp',
113
+ '.avif': 'image/avif',
114
+ '.svg': 'image/svg+xml',
115
+ '.mp4': 'video/mp4',
116
+ '.webm': 'video/webm',
117
+ '.mov': 'video/quicktime',
118
+ '.mp3': 'audio/mpeg',
119
+ '.pdf': 'application/pdf',
120
+ '.txt': 'text/plain',
121
+ }
122
+
123
+ /** Best-effort content type from a key's extension (for the local serving route). */
124
+ export function mimeFromKey(key: string): string {
125
+ return MIME_BY_EXT[extname(key).toLowerCase()] || 'application/octet-stream'
126
+ }
127
+
128
+ /**
129
+ * Local filesystem driver. Stores under an absolute `dir` (outside the build
130
+ * output so uploads survive a redeploy) and serves bytes through a Nitro route
131
+ * at `publicBase`. Path-traversal is blocked in `pathFor`.
132
+ */
133
+ class LocalDriver implements StorageDriver {
134
+ constructor(private readonly dir: string, private readonly publicBase: string) {}
135
+
136
+ private pathFor(key: string): string {
137
+ const abs = resolve(this.dir, key)
138
+ if (abs !== this.dir && !abs.startsWith(this.dir + sep)) {
139
+ throw createError({ statusCode: 400, statusMessage: 'Invalid storage key' })
140
+ }
141
+ return abs
142
+ }
143
+
144
+ async put(key: string, body: Buffer): Promise<StoredObject> {
145
+ const { mkdir, writeFile } = await import('node:fs/promises')
146
+ const abs = this.pathFor(key)
147
+ await mkdir(dirname(abs), { recursive: true })
148
+ await writeFile(abs, body)
149
+ return { key, url: this.url(key), size: body.length }
150
+ }
151
+
152
+ /** On the storage disk itself, so moving a received upload in is a rename, never a copy. */
153
+ get tempDir(): string {
154
+ return join(this.dir, '.incoming')
155
+ }
156
+
157
+ async putFile(key: string, path: string, info: { size: number }): Promise<StoredObject> {
158
+ const { copyFile, mkdir, rename, unlink } = await import('node:fs/promises')
159
+ const abs = this.pathFor(key)
160
+ await mkdir(dirname(abs), { recursive: true })
161
+ try {
162
+ await rename(path, abs)
163
+ }
164
+ catch (err: any) {
165
+ if (err?.code !== 'EXDEV') throw err
166
+ await copyFile(path, abs)
167
+ await unlink(path).catch(() => {})
168
+ }
169
+ return { key, url: this.url(key), size: info.size }
170
+ }
171
+
172
+ async get(key: string): Promise<{ body: Buffer; contentType: string } | null> {
173
+ try {
174
+ const { readFile } = await import('node:fs/promises')
175
+ const body = await readFile(this.pathFor(key))
176
+ return { body, contentType: mimeFromKey(key) }
177
+ } catch {
178
+ return null
179
+ }
180
+ }
181
+
182
+ async read(key: string, opts: StorageReadOptions = {}): Promise<StorageRead | null> {
183
+ const { stat } = await import('node:fs/promises')
184
+ let abs: string
185
+ let info: Awaited<ReturnType<typeof stat>>
186
+ try {
187
+ abs = this.pathFor(key)
188
+ info = await stat(abs)
189
+ }
190
+ catch {
191
+ return null
192
+ }
193
+ if (!info.isFile()) return null
194
+ const size = info.size
195
+ const contentType = mimeFromKey(key)
196
+ const etag = '"' + size.toString(16) + '-' + Math.floor(info.mtimeMs).toString(16) + '"'
197
+ const lastModified = info.mtime.toUTCString()
198
+ if (etagMatches(opts.ifNoneMatch, etag)) return { status: 304, contentType, etag, lastModified, body: null }
199
+ const range = byteRange(opts.range, size)
200
+ if (range === 'unsatisfiable') return { status: 416, contentType, contentRange: 'bytes */' + size, body: null }
201
+ const [start, end] = range ? [range.start, range.end] : [0, size - 1]
202
+ // An empty file has no byte to start from: createReadStream would read it all, which is nothing.
203
+ const body = size === 0 ? new ReadableStream<Uint8Array>({ start: (c) => c.close() }) : fileWebStream(abs, { start, end })
204
+ return {
205
+ status: range ? 206 : 200,
206
+ contentType,
207
+ contentLength: size === 0 ? 0 : end - start + 1,
208
+ contentRange: range ? 'bytes ' + start + '-' + end + '/' + size : undefined,
209
+ etag,
210
+ lastModified,
211
+ body,
212
+ }
213
+ }
214
+
215
+ async delete(key: string): Promise<void> {
216
+ try {
217
+ const { unlink } = await import('node:fs/promises')
218
+ await unlink(this.pathFor(key))
219
+ } catch {
220
+ /* already gone — fine */
221
+ }
222
+ }
223
+
224
+ url(key: string): string {
225
+ return `${this.publicBase}/${key}`
226
+ }
227
+ }
228
+
229
+ /** The local-disk driver for a folder (`useCmsStorage` builds it from the runtime config; tests build it directly). */
230
+ export function createLocalDriver(dir: string, publicBase: string = DEFAULT_MEDIA_BASE): StorageDriver {
231
+ return new LocalDriver(resolve(dir), publicBase)
232
+ }
233
+
234
+ export interface S3Config {
235
+ /** Service endpoint. R2: https://<account>.r2.cloudflarestorage.com — MinIO: http://localhost:9000 */
236
+ endpoint: string
237
+ /** SigV4 region. R2 uses 'auto'; AWS uses e.g. 'us-east-1'. */
238
+ region: string
239
+ bucket: string
240
+ accessKeyId: string
241
+ secretAccessKey: string
242
+ /** Public URL prefix used to serve objects (CDN / r2.dev / custom domain). Defaults to `${endpoint}/${bucket}`. */
243
+ publicBaseUrl?: string
244
+ /**
245
+ * How browsers get the files: `public` (the stored address is the bucket's own),
246
+ * `proxy` (the app streams them) or `redirect` (the app sends a short-lived signed
247
+ * address). Default `public` when `publicBaseUrl` is set, otherwise `proxy`.
248
+ */
249
+ delivery?: S3Delivery
250
+ /** Where the app serves files from under `proxy` and `redirect` (the local driver's address). */
251
+ appBase?: string
252
+ }
253
+
254
+ /** How long a signed address of `redirect` delivery lives, and how long a browser may keep the redirect (less, so it never follows a dead one). */
255
+ export const PRESIGN_SECONDS = 300
256
+ export const REDIRECT_CACHE_SECONDS = 240
257
+
258
+ /** The store answered, but not with a file: the visitor gets 502; the log gets the status, never an address. */
259
+ function storageUnavailable(what: string): never {
260
+ throw createError({ statusCode: 502, statusMessage: 'Media storage is not available', cause: new Error(what) })
261
+ }
262
+
263
+ /**
264
+ * S3-compatible driver (AWS S3, Cloudflare R2, MinIO, Pushbase Storage). Requests are
265
+ * signed with SigV4 via `aws4fetch` (`fetch` + Web Crypto). Uses path-style addressing
266
+ * (`endpoint/bucket/key`), which R2, MinIO and Pushbase accept (and always does:
267
+ * a `FORCE_PATH_STYLE` setting from a hosting platform is ignored).
268
+ *
269
+ * `delivery` decides how browsers reach the files:
270
+ * - `public`: straight from the bucket's public URL or a CDN (`publicBaseUrl`); the raw
271
+ * route is not involved.
272
+ * - `proxy`: the bucket is private; the raw route streams each file from it.
273
+ * - `redirect`: the bucket is private; the raw route redirects to a signed address.
274
+ * Under `proxy` and `redirect` the stored address is the app path, which never expires.
275
+ */
276
+ class S3Driver implements StorageDriver {
277
+ private _client: any
278
+ private checkedPublic = false
279
+ readonly delivery: S3Delivery
280
+ constructor(private readonly cfg: S3Config) {
281
+ this.delivery = cfg.delivery ?? (cfg.publicBaseUrl ? 'public' : 'proxy')
282
+ }
283
+
284
+ private async client() {
285
+ return (this._client ??= await this.makeClient(2))
286
+ }
287
+
288
+ private async makeClient(retries: number) {
289
+ let AwsClient: any
290
+ try {
291
+ ;({ AwsClient } = await import('aws4fetch'))
292
+ } catch {
293
+ throw createError({
294
+ statusCode: 500,
295
+ statusMessage: "The 's3'/'r2' storage driver requires the 'aws4fetch' package (pnpm add aws4fetch).",
296
+ })
297
+ }
298
+ return new AwsClient({
299
+ accessKeyId: this.cfg.accessKeyId,
300
+ secretAccessKey: this.cfg.secretAccessKey,
301
+ region: this.cfg.region,
302
+ service: 's3',
303
+ // aws4fetch retries 5xx and network errors ten times with growing pauses (half a
304
+ // minute in all): far too long for a visitor waiting for a picture.
305
+ retries,
306
+ })
307
+ }
308
+
309
+ // Keys are RFC3986-safe by construction (date / uuid / ext), so per-segment
310
+ // encoding is a no-op here and aws4fetch will not double-encode them. If
311
+ // arbitrary keys are ever allowed, drop this and let aws4fetch own the encoding.
312
+ // A key with `..` would be resolved by the URL and reach another bucket: refused.
313
+ private objectUrl(key: string): string {
314
+ if (!isSafeStorageKey(key)) throw createError({ statusCode: 400, statusMessage: 'Invalid storage key' })
315
+ const endpoint = this.cfg.endpoint.replace(/\/$/, '')
316
+ return endpoint + '/' + this.cfg.bucket + '/' + encodeStorageKey(key)
317
+ }
318
+
319
+ async put(key: string, body: Buffer, contentType: string): Promise<StoredObject> {
320
+ const client = await this.client()
321
+ const res = await client.fetch(this.objectUrl(key), {
322
+ method: 'PUT',
323
+ body: new Uint8Array(body),
324
+ headers: { 'content-type': contentType },
325
+ })
326
+ if (!res.ok) {
327
+ throw createError({ statusCode: 502, statusMessage: `S3 upload failed (${res.status} ${res.statusText})` })
328
+ }
329
+ if (this.delivery === 'public') this.checkPublic(key)
330
+ return { key, url: this.url(key), size: body.length }
331
+ }
332
+
333
+ /**
334
+ * Once, after the first upload: under `public` delivery the file just stored must be
335
+ * readable without a signature. A 401/403 means the bucket is private and every
336
+ * picture on the site would fail — say so in the log, with the way out.
337
+ */
338
+ private checkPublic(key: string) {
339
+ if (this.checkedPublic) return
340
+ this.checkedPublic = true
341
+ fetch(this.url(key), { method: 'HEAD' }).then((res) => {
342
+ if (res.status === 401 || res.status === 403) {
343
+ console.warn(`[cms] storage delivery is 'public', but a file just uploaded answers ${res.status} to an anonymous request: the bucket is private. `
344
+ + "Set NUXT_CMS_STORAGE_S3_DELIVERY=proxy (or 'redirect'), see https://github.com/tinyzookeeper/tinyzoo/blob/main/docs/deploying.md#media")
345
+ }
346
+ }).catch(() => { /* the public address is not reachable from here (a CDN in front, a firewall): nothing to say */ })
347
+ }
348
+
349
+ get tempDir(): string {
350
+ return join(tmpdir(), 'tinyzoo-uploads')
351
+ }
352
+
353
+ /**
354
+ * Streams the received file to the bucket: one PUT whose body is read from the disk as it
355
+ * is sent (never in memory). The payload hash was taken while the file was received and
356
+ * goes in the signature, so the body needs no second pass. It is sent with `node:http(s)`
357
+ * and a plain pipe: `fetch` (undici) reads a stream body far ahead of the socket and held
358
+ * most of a 300 MB file in memory. A failed attempt starts over with a new stream.
359
+ */
360
+ async putFile(key: string, path: string, info: { size: number; sha256: string; contentType: string }): Promise<StoredObject> {
361
+ const client = await this.makeClient(0)
362
+ const address = this.objectUrl(key)
363
+ let status = 0
364
+ for (let attempt = 0; attempt < 3 && (status === 0 || status >= 500); attempt++) {
365
+ const signed = await client.sign(address, {
366
+ method: 'PUT',
367
+ headers: { 'content-type': info.contentType, 'content-length': String(info.size), 'x-amz-content-sha256': info.sha256 },
368
+ })
369
+ status = await sendFile(signed.url, Object.fromEntries(signed.headers.entries()), path).catch(() => 0)
370
+ }
371
+ if (!status) throw createError({ statusCode: 502, statusMessage: 'S3 upload failed (no answer)' })
372
+ if (status < 200 || status >= 300) {
373
+ throw createError({ statusCode: 502, statusMessage: `S3 upload failed (${status})` })
374
+ }
375
+ const { unlink } = await import('node:fs/promises')
376
+ await unlink(path).catch(() => {})
377
+ if (this.delivery === 'public') this.checkPublic(key)
378
+ return { key, url: this.url(key), size: info.size }
379
+ }
380
+
381
+ async get(key: string): Promise<{ body: Buffer; contentType: string } | null> {
382
+ const client = await this.client()
383
+ const res = await client.fetch(this.objectUrl(key))
384
+ if (!res.ok) return null
385
+ const body = Buffer.from(await res.arrayBuffer())
386
+ return { body, contentType: res.headers.get('content-type') || mimeFromKey(key) }
387
+ }
388
+
389
+ async read(key: string, opts: StorageReadOptions = {}): Promise<StorageRead | null> {
390
+ const client = await this.client()
391
+ const headers: Record<string, string> = {}
392
+ const range = singleRange(opts.range)
393
+ if (range) headers.range = range
394
+ if (opts.ifNoneMatch) headers['if-none-match'] = opts.ifNoneMatch
395
+ const address = this.objectUrl(key)
396
+ let res: Response
397
+ try {
398
+ res = await client.fetch(address, { headers })
399
+ }
400
+ catch (err: any) {
401
+ // Never the error's own text: the store's address is in some of them.
402
+ return storageUnavailable('S3 read failed: ' + (err?.cause?.code || err?.name || 'network error'))
403
+ }
404
+ const generic = /^(application|binary)\/octet-stream$/i
405
+ const type = res.headers.get('content-type')
406
+ const meta = {
407
+ contentType: type && !generic.test(type) ? type : mimeFromKey(key),
408
+ etag: res.headers.get('etag') ?? undefined,
409
+ lastModified: res.headers.get('last-modified') ?? undefined,
410
+ }
411
+ if (res.status === 404) {
412
+ await res.body?.cancel().catch(() => {})
413
+ return null
414
+ }
415
+ if (res.status === 304) {
416
+ await res.body?.cancel().catch(() => {})
417
+ return { status: 304, ...meta, body: null }
418
+ }
419
+ if (res.status === 416) {
420
+ await res.body?.cancel().catch(() => {})
421
+ // S3 itself leaves out the Content-Range of a 416: the size comes from a HEAD.
422
+ let contentRange = res.headers.get('content-range') ?? undefined
423
+ if (!contentRange) {
424
+ const head = await client.fetch(address, { method: 'HEAD' }).catch(() => null)
425
+ const size = head?.ok ? head.headers.get('content-length') : null
426
+ if (size !== null && size !== undefined) contentRange = 'bytes */' + size
427
+ }
428
+ return { status: 416, ...meta, contentRange, body: null }
429
+ }
430
+ if ((res.status !== 200 && res.status !== 206) || !res.body) {
431
+ await res.body?.cancel().catch(() => {})
432
+ return storageUnavailable('S3 read answered ' + res.status)
433
+ }
434
+ // A stored Content-Encoding would be undone by fetch and the length would no longer fit.
435
+ const length = Number(res.headers.get('content-length'))
436
+ return {
437
+ status: res.status,
438
+ ...meta,
439
+ contentLength: Number.isFinite(length) && length >= 0 && !res.headers.get('content-encoding') ? length : undefined,
440
+ contentRange: res.status === 206 ? res.headers.get('content-range') ?? undefined : undefined,
441
+ body: res.body as ReadableStream<Uint8Array>,
442
+ }
443
+ }
444
+
445
+ async presign(key: string, seconds: number, contentDisposition?: string): Promise<string> {
446
+ const client = await this.client()
447
+ const url = new URL(this.objectUrl(key))
448
+ url.searchParams.set('X-Amz-Expires', String(seconds))
449
+ // The store sends this as the file's Content-Disposition (a PDF's name).
450
+ if (contentDisposition && contentDisposition !== 'inline') url.searchParams.set('response-content-disposition', contentDisposition)
451
+ const signed = await client.sign(url.toString(), { method: 'GET', aws: { signQuery: true } })
452
+ return signed.url
453
+ }
454
+
455
+ async delete(key: string): Promise<void> {
456
+ const client = await this.client()
457
+ const res = await client.fetch(this.objectUrl(key), { method: 'DELETE' })
458
+ // S3/R2 return 204 on success; treat 404 as already-gone (idempotent).
459
+ if (!res.ok && res.status !== 404) {
460
+ throw createError({ statusCode: 502, statusMessage: `S3 delete failed (${res.status} ${res.statusText})` })
461
+ }
462
+ }
463
+
464
+ url(key: string): string {
465
+ return storedMediaUrl({ ...this.cfg, delivery: this.delivery }, key)
466
+ }
467
+ }
468
+
469
+ /** The S3 driver for a ready configuration (`useCmsStorage` builds it from the runtime config; tests build it directly). */
470
+ export function createS3Driver(cfg: S3Config): StorageDriver {
471
+ return new S3Driver(cfg)
472
+ }
473
+
474
+ /**
475
+ * Fallback for an unknown driver name. Fails loudly so a typo in
476
+ * `cms.storage.driver` never silently swallows uploads.
477
+ */
478
+ class UnconfiguredDriver implements StorageDriver {
479
+ constructor(private readonly name: string) {}
480
+ private fail(): never {
481
+ throw createError({
482
+ statusCode: 501,
483
+ statusMessage: `Storage driver '${this.name}' is not implemented yet. Set cms.storage.driver to 'local'.`,
484
+ })
485
+ }
486
+ readonly tempDir = join(tmpdir(), 'tinyzoo-uploads')
487
+ put(): Promise<StoredObject> {
488
+ return this.fail()
489
+ }
490
+ putFile(): Promise<StoredObject> {
491
+ return this.fail()
492
+ }
493
+ get(): Promise<{ body: Buffer; contentType: string } | null> {
494
+ return this.fail()
495
+ }
496
+ read(): Promise<StorageRead | null> {
497
+ return this.fail()
498
+ }
499
+ delete(): Promise<void> {
500
+ return this.fail()
501
+ }
502
+ url(): string {
503
+ return this.fail()
504
+ }
505
+ }
506
+
507
+ let _driver: StorageDriver | undefined
508
+
509
+ /**
510
+ * Resolve the configured storage driver (memoized).
511
+ * NB: NOT named `useStorage` — that's a built-in Nitro (unstorage) helper.
512
+ */
513
+ export function useCmsStorage(): StorageDriver {
514
+ if (_driver) return _driver
515
+ const cfg = ((useRuntimeConfig().cms as any)?.storage ?? {}) as {
516
+ driver?: string
517
+ local?: { dir?: string; publicBase?: string }
518
+ s3?: Partial<S3Config> & { delivery?: string }
519
+ }
520
+ const driver = cfg.driver || 'local'
521
+ if (driver === 'local') {
522
+ const dir = resolve(process.cwd(), cfg.local?.dir || '.cms-uploads')
523
+ const publicBase = cfg.local?.publicBase || DEFAULT_MEDIA_BASE
524
+ if (process.env.NODE_ENV === 'production') {
525
+ console.warn(`[cms] media are stored on this server's disk (${dir}). Containers lose it on every deploy — `
526
+ + 'use object storage in production (NUXT_CMS_STORAGE_DRIVER=s3, see https://github.com/tinyzookeeper/tinyzoo/blob/main/docs/deploying.md#media).')
527
+ }
528
+ _driver = new LocalDriver(dir, publicBase)
529
+ } else if (driver === 's3' || driver === 'r2') {
530
+ const s = cfg.s3 ?? {}
531
+ const missing = (['endpoint', 'bucket', 'accessKeyId', 'secretAccessKey'] as const).filter((k) => !s[k])
532
+ if (missing.length) {
533
+ throw createError({
534
+ statusCode: 500,
535
+ statusMessage: `Storage driver '${driver}' is missing config: ${missing.join(', ')} `
536
+ + `(set cms.storage.s3.* or NUXT_CMS_STORAGE_S3_* env vars).`,
537
+ })
538
+ }
539
+ let delivery: S3Delivery
540
+ try { delivery = resolveS3Delivery(s.delivery, s.publicBaseUrl) }
541
+ catch (err: any) { throw createError({ statusCode: 500, statusMessage: err.message }) }
542
+ // NB: do NOT memoize on the misconfigured path above — let it re-throw until fixed.
543
+ _driver = new S3Driver({
544
+ endpoint: s.endpoint!,
545
+ region: s.region || (driver === 'r2' ? 'auto' : 'us-east-1'),
546
+ bucket: s.bucket!,
547
+ accessKeyId: s.accessKeyId!,
548
+ secretAccessKey: s.secretAccessKey!,
549
+ publicBaseUrl: s.publicBaseUrl || undefined,
550
+ delivery,
551
+ appBase: cfg.local?.publicBase || DEFAULT_MEDIA_BASE,
552
+ })
553
+ } else {
554
+ _driver = new UnconfiguredDriver(driver)
555
+ }
556
+ return _driver
557
+ }
558
+
559
+ /** Configured per-file upload ceiling in bytes (default 10MB). */
560
+ export function maxUploadBytes(): number {
561
+ const mb = Number((useRuntimeConfig().cms as any)?.storage?.maxSizeMb) || 10
562
+ return mb * 1024 * 1024
563
+ }
564
+
565
+ /** Per-user total storage quota in bytes (0 = unlimited). */
566
+ export function maxBytesPerUser(): number {
567
+ return Number((useRuntimeConfig().cms as any)?.storage?.maxBytesPerUser) || 0
568
+ }
569
+
570
+ /** Max uploads per user per minute (0 = unlimited; default 60). */
571
+ export function uploadRatePerMin(): number {
572
+ return Number((useRuntimeConfig().cms as any)?.storage?.uploadRatePerMin ?? 60) || 0
573
+ }
574
+
575
+ /** A library folder name: one level, trimmed, bounded; empty = no folder. */
576
+ export function cleanFolder(value: unknown): string | null {
577
+ if (typeof value !== 'string') return null
578
+ const v = value.replace(/[\u0000-\u001f\u007f/\\]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 80)
579
+ return v || null
580
+ }
@@ -0,0 +1,109 @@
1
+ import { createRedisStore } from '../store/redis'
2
+
3
+ import type { SharedStore } from '../store/types'
4
+
5
+ /**
6
+ * State shared by every instance: Redis when `cms.redis.url` or REDIS_URL is set
7
+ * (Pushbase injects REDIS_URL for a linked Redis service); otherwise this process's
8
+ * memory — correct for one instance only.
9
+ */
10
+ export type { SharedStore } from '../store/types'
11
+
12
+ function memoryStore(): SharedStore {
13
+ const handlers = new Map<string, Set<(message: string) => void>>()
14
+ return {
15
+ kind: 'memory',
16
+ async hit(key, windowMs) {
17
+ // Sliding window in this process (see cmsRateLimit).
18
+ return rateLimitCount(key, windowMs)
19
+ },
20
+ async unhit(key, windowMs) {
21
+ rateLimitRefundMemory(key, windowMs)
22
+ },
23
+ async publish(channel, message) {
24
+ for (const h of handlers.get(channel) ?? []) h(message)
25
+ },
26
+ async subscribe(channel, handler) {
27
+ if (!handlers.has(channel)) handlers.set(channel, new Set())
28
+ handlers.get(channel)!.add(handler)
29
+ return async () => { handlers.get(channel)?.delete(handler) }
30
+ },
31
+ }
32
+ }
33
+
34
+ let store: Promise<SharedStore> | undefined
35
+
36
+ export function useCmsStore(): Promise<SharedStore> {
37
+ store ??= (async () => {
38
+ const cfg = (useRuntimeConfig().cms as any)?.redis ?? {}
39
+ const env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {}
40
+ const redisUrl = String(cfg.url || env.REDIS_URL || '')
41
+ try {
42
+ const redis = await createRedisStore({ redisUrl, prefix: cmsStorePrefix(cfg.prefix) })
43
+ if (redis) {
44
+ console.info('[cms] shared store: redis')
45
+ return redis
46
+ }
47
+ }
48
+ catch (err) {
49
+ console.error('[cms] redis unavailable, falling back to memory', err)
50
+ }
51
+ return memoryStore()
52
+ })()
53
+ return store
54
+ }
55
+
56
+ /**
57
+ * Keys and channels are namespaced so that environments sharing one Redis (staging
58
+ * and production, two client sites) never share counters or messages:
59
+ * `cms.redis.prefix` / NUXT_CMS_REDIS_PREFIX, else `cms:<database name>`.
60
+ */
61
+ export function cmsStorePrefix(configured: string = (useRuntimeConfig().cms as any)?.redis?.prefix): string {
62
+ if (configured) return String(configured)
63
+ try {
64
+ const env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {}
65
+ const url = env.NUXT_CMS_DATABASE_URL || env.DATABASE_URL || (useRuntimeConfig().cms as any)?.databaseUrl
66
+ const name = url ? decodeURIComponent(new URL(url).pathname.slice(1)) : ''
67
+ return name ? `cms:${name}` : 'cms'
68
+ }
69
+ catch {
70
+ return 'cms'
71
+ }
72
+ }
73
+
74
+ /** Close the store's connections (server shutdown). */
75
+ export async function closeCmsStore(): Promise<void> {
76
+ if (!store) return
77
+ const s = await store.catch(() => null)
78
+ store = undefined
79
+ await s?.close?.()
80
+ }
81
+
82
+ /**
83
+ * Rate limit: true if this action is allowed (and counts it). Shared across instances
84
+ * when Redis is configured. `max <= 0` means unlimited. When Redis cannot answer, this
85
+ * instance counts on its own instead — an outage must neither lock everyone out nor
86
+ * switch brute-force protection off.
87
+ */
88
+ export async function rateLimit(key: string, max: number, windowMs: number): Promise<boolean> {
89
+ if (max <= 0) return true
90
+ try {
91
+ const s = await useCmsStore()
92
+ if (s.kind === 'memory') return rateLimitOk(key, max, windowMs)
93
+ return (await s.hit(key.slice(0, 200), windowMs)) <= max
94
+ }
95
+ catch (err) {
96
+ console.error('[cms] rate limit store error, counting locally:', (err as Error)?.message ?? err)
97
+ return rateLimitOk(key, max, windowMs)
98
+ }
99
+ }
100
+
101
+ /** Take back the hit `rateLimit` just counted for `key` (a sign-in that worked is not an attempt to guess). */
102
+ export async function rateLimitRefund(key: string, windowMs: number): Promise<void> {
103
+ try {
104
+ await (await useCmsStore()).unhit(key.slice(0, 200), windowMs)
105
+ }
106
+ catch {
107
+ // The count only stays one higher for the rest of the window.
108
+ }
109
+ }