@aphexcms/cms-core 9.9.0 → 10.0.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 (324) hide show
  1. package/dist/api/assets.d.ts +62 -7
  2. package/dist/api/assets.d.ts.map +1 -1
  3. package/dist/api/assets.js +116 -9
  4. package/dist/api/client.d.ts +1 -1
  5. package/dist/api/client.d.ts.map +1 -1
  6. package/dist/api/client.js +39 -9
  7. package/dist/api/limits.d.ts +55 -0
  8. package/dist/api/limits.d.ts.map +1 -0
  9. package/dist/api/limits.js +58 -0
  10. package/dist/api/schemas/assets.d.ts +94 -4
  11. package/dist/api/schemas/assets.d.ts.map +1 -1
  12. package/dist/api/schemas/assets.js +82 -5
  13. package/dist/api/schemas/documents.d.ts +1 -0
  14. package/dist/api/schemas/documents.d.ts.map +1 -1
  15. package/dist/api/schemas/documents.js +1 -0
  16. package/dist/api/types.d.ts +25 -0
  17. package/dist/api/types.d.ts.map +1 -1
  18. package/dist/api/upload-timeout.d.ts +17 -0
  19. package/dist/api/upload-timeout.d.ts.map +1 -0
  20. package/dist/api/upload-timeout.js +35 -0
  21. package/dist/api/upload.d.ts +42 -0
  22. package/dist/api/upload.d.ts.map +1 -0
  23. package/dist/api/upload.js +144 -0
  24. package/dist/components/AdminApp.svelte +213 -32
  25. package/dist/components/AdminApp.svelte.d.ts.map +1 -1
  26. package/dist/components/admin/AssetBrowserModal.svelte +4 -3
  27. package/dist/components/admin/AssetBrowserModal.svelte.d.ts +2 -1
  28. package/dist/components/admin/AssetBrowserModal.svelte.d.ts.map +1 -1
  29. package/dist/components/admin/MediaBrowser.svelte +1859 -281
  30. package/dist/components/admin/MediaBrowser.svelte.d.ts +21 -1
  31. package/dist/components/admin/MediaBrowser.svelte.d.ts.map +1 -1
  32. package/dist/components/admin/fields/ArrayField.svelte +21 -10
  33. package/dist/components/admin/fields/ArrayField.svelte.d.ts.map +1 -1
  34. package/dist/components/admin/fields/FileField.svelte +9 -2
  35. package/dist/components/admin/fields/FileField.svelte.d.ts.map +1 -1
  36. package/dist/components/admin/fields/ImageField.svelte +47 -12
  37. package/dist/components/admin/fields/ImageField.svelte.d.ts.map +1 -1
  38. package/dist/config.d.ts.map +1 -1
  39. package/dist/config.js +14 -0
  40. package/dist/db/interfaces/asset.d.ts +114 -5
  41. package/dist/db/interfaces/asset.d.ts.map +1 -1
  42. package/dist/db/interfaces/document.d.ts +107 -3
  43. package/dist/db/interfaces/document.d.ts.map +1 -1
  44. package/dist/hooks.d.ts.map +1 -1
  45. package/dist/hooks.js +2 -1
  46. package/dist/image/Image.svelte +72 -0
  47. package/dist/image/Image.svelte.d.ts +40 -0
  48. package/dist/image/Image.svelte.d.ts.map +1 -0
  49. package/dist/image/index.d.ts +3 -0
  50. package/dist/image/index.d.ts.map +1 -0
  51. package/dist/image/index.js +11 -0
  52. package/dist/image/types.d.ts +28 -0
  53. package/dist/image/types.d.ts.map +1 -0
  54. package/dist/image/types.js +1 -0
  55. package/dist/images/generate.d.ts +55 -0
  56. package/dist/images/generate.d.ts.map +1 -0
  57. package/dist/images/generate.js +243 -0
  58. package/dist/images/index.d.ts +2 -0
  59. package/dist/images/index.d.ts.map +1 -0
  60. package/dist/images/index.js +7 -0
  61. package/dist/images/variants.d.ts +82 -0
  62. package/dist/images/variants.d.ts.map +1 -0
  63. package/dist/images/variants.js +124 -0
  64. package/dist/jobs/asset-reference-jobs.d.ts +49 -0
  65. package/dist/jobs/asset-reference-jobs.d.ts.map +1 -0
  66. package/dist/jobs/asset-reference-jobs.js +74 -0
  67. package/dist/jobs/run-batch.d.ts.map +1 -1
  68. package/dist/jobs/run-batch.js +5 -0
  69. package/dist/lib/api/assets.d.ts +62 -7
  70. package/dist/lib/api/assets.d.ts.map +1 -1
  71. package/dist/lib/api/assets.js +116 -9
  72. package/dist/lib/api/assets.js.map +1 -1
  73. package/dist/lib/api/client.d.ts +1 -1
  74. package/dist/lib/api/client.d.ts.map +1 -1
  75. package/dist/lib/api/client.js +39 -9
  76. package/dist/lib/api/client.js.map +1 -1
  77. package/dist/lib/api/limits.d.ts +55 -0
  78. package/dist/lib/api/limits.d.ts.map +1 -0
  79. package/dist/lib/api/limits.js +59 -0
  80. package/dist/lib/api/limits.js.map +1 -0
  81. package/dist/lib/api/schemas/assets.d.ts +94 -4
  82. package/dist/lib/api/schemas/assets.d.ts.map +1 -1
  83. package/dist/lib/api/schemas/assets.js +82 -5
  84. package/dist/lib/api/schemas/assets.js.map +1 -1
  85. package/dist/lib/api/schemas/documents.d.ts +1 -0
  86. package/dist/lib/api/schemas/documents.d.ts.map +1 -1
  87. package/dist/lib/api/schemas/documents.js +1 -0
  88. package/dist/lib/api/schemas/documents.js.map +1 -1
  89. package/dist/lib/api/types.d.ts +25 -0
  90. package/dist/lib/api/types.d.ts.map +1 -1
  91. package/dist/lib/api/upload-timeout.d.ts +17 -0
  92. package/dist/lib/api/upload-timeout.d.ts.map +1 -0
  93. package/dist/lib/api/upload-timeout.js +36 -0
  94. package/dist/lib/api/upload-timeout.js.map +1 -0
  95. package/dist/lib/api/upload.d.ts +42 -0
  96. package/dist/lib/api/upload.d.ts.map +1 -0
  97. package/dist/lib/api/upload.js +145 -0
  98. package/dist/lib/api/upload.js.map +1 -0
  99. package/dist/lib/config.d.ts.map +1 -1
  100. package/dist/lib/config.js +14 -0
  101. package/dist/lib/config.js.map +1 -1
  102. package/dist/lib/db/interfaces/asset.d.ts +114 -5
  103. package/dist/lib/db/interfaces/asset.d.ts.map +1 -1
  104. package/dist/lib/db/interfaces/document.d.ts +107 -3
  105. package/dist/lib/db/interfaces/document.d.ts.map +1 -1
  106. package/dist/lib/hooks.d.ts.map +1 -1
  107. package/dist/lib/hooks.js +2 -1
  108. package/dist/lib/hooks.js.map +1 -1
  109. package/dist/lib/image/index.d.ts +3 -0
  110. package/dist/lib/image/index.d.ts.map +1 -0
  111. package/dist/lib/image/index.js +12 -0
  112. package/dist/lib/image/index.js.map +1 -0
  113. package/dist/lib/image/types.d.ts +28 -0
  114. package/dist/lib/image/types.d.ts.map +1 -0
  115. package/dist/lib/image/types.js +2 -0
  116. package/dist/lib/image/types.js.map +1 -0
  117. package/dist/lib/images/generate.d.ts +55 -0
  118. package/dist/lib/images/generate.d.ts.map +1 -0
  119. package/dist/lib/images/generate.js +244 -0
  120. package/dist/lib/images/generate.js.map +1 -0
  121. package/dist/lib/images/index.d.ts +2 -0
  122. package/dist/lib/images/index.d.ts.map +1 -0
  123. package/dist/lib/images/index.js +8 -0
  124. package/dist/lib/images/index.js.map +1 -0
  125. package/dist/lib/images/variants.d.ts +82 -0
  126. package/dist/lib/images/variants.d.ts.map +1 -0
  127. package/dist/lib/images/variants.js +125 -0
  128. package/dist/lib/images/variants.js.map +1 -0
  129. package/dist/lib/jobs/asset-reference-jobs.d.ts +49 -0
  130. package/dist/lib/jobs/asset-reference-jobs.d.ts.map +1 -0
  131. package/dist/lib/jobs/asset-reference-jobs.js +75 -0
  132. package/dist/lib/jobs/asset-reference-jobs.js.map +1 -0
  133. package/dist/lib/jobs/run-batch.d.ts.map +1 -1
  134. package/dist/lib/jobs/run-batch.js +5 -0
  135. package/dist/lib/jobs/run-batch.js.map +1 -1
  136. package/dist/lib/local-api/collection-api.d.ts +25 -2
  137. package/dist/lib/local-api/collection-api.d.ts.map +1 -1
  138. package/dist/lib/local-api/collection-api.js +107 -20
  139. package/dist/lib/local-api/collection-api.js.map +1 -1
  140. package/dist/lib/preview/assets.d.ts +19 -0
  141. package/dist/lib/preview/assets.d.ts.map +1 -1
  142. package/dist/lib/preview/assets.js +6 -0
  143. package/dist/lib/preview/assets.js.map +1 -1
  144. package/dist/lib/routes/assets-cdn.d.ts +19 -0
  145. package/dist/lib/routes/assets-cdn.d.ts.map +1 -1
  146. package/dist/lib/routes/assets-cdn.js +295 -17
  147. package/dist/lib/routes/assets-cdn.js.map +1 -1
  148. package/dist/lib/schema-utils/utils.d.ts +31 -1
  149. package/dist/lib/schema-utils/utils.d.ts.map +1 -1
  150. package/dist/lib/schema-utils/utils.js +68 -0
  151. package/dist/lib/schema-utils/utils.js.map +1 -1
  152. package/dist/lib/server/api/index.d.ts.map +1 -1
  153. package/dist/lib/server/api/index.js +87 -8
  154. package/dist/lib/server/api/index.js.map +1 -1
  155. package/dist/lib/server/api/routes/assets-bulk.d.ts.map +1 -1
  156. package/dist/lib/server/api/routes/assets-bulk.js +36 -7
  157. package/dist/lib/server/api/routes/assets-bulk.js.map +1 -1
  158. package/dist/lib/server/api/routes/assets-by-id.d.ts.map +1 -1
  159. package/dist/lib/server/api/routes/assets-by-id.js +32 -15
  160. package/dist/lib/server/api/routes/assets-by-id.js.map +1 -1
  161. package/dist/lib/server/api/routes/assets-direct-upload.d.ts +4 -0
  162. package/dist/lib/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  163. package/dist/lib/server/api/routes/assets-direct-upload.js +164 -0
  164. package/dist/lib/server/api/routes/assets-direct-upload.js.map +1 -0
  165. package/dist/lib/server/api/routes/assets-poster.d.ts +4 -0
  166. package/dist/lib/server/api/routes/assets-poster.d.ts.map +1 -0
  167. package/dist/lib/server/api/routes/assets-poster.js +120 -0
  168. package/dist/lib/server/api/routes/assets-poster.js.map +1 -0
  169. package/dist/lib/server/api/routes/assets-references.d.ts.map +1 -1
  170. package/dist/lib/server/api/routes/assets-references.js +64 -5
  171. package/dist/lib/server/api/routes/assets-references.js.map +1 -1
  172. package/dist/lib/server/api/routes/assets.d.ts.map +1 -1
  173. package/dist/lib/server/api/routes/assets.js +116 -12
  174. package/dist/lib/server/api/routes/assets.js.map +1 -1
  175. package/dist/lib/server/api/routes/clear-asset-references.d.ts +18 -0
  176. package/dist/lib/server/api/routes/clear-asset-references.d.ts.map +1 -0
  177. package/dist/lib/server/api/routes/clear-asset-references.js +32 -0
  178. package/dist/lib/server/api/routes/clear-asset-references.js.map +1 -0
  179. package/dist/lib/server/api/routes/documents.d.ts.map +1 -1
  180. package/dist/lib/server/api/routes/documents.js +28 -1
  181. package/dist/lib/server/api/routes/documents.js.map +1 -1
  182. package/dist/lib/server/index.d.ts +2 -0
  183. package/dist/lib/server/index.d.ts.map +1 -1
  184. package/dist/lib/server/index.js +4 -0
  185. package/dist/lib/server/index.js.map +1 -1
  186. package/dist/lib/services/asset-references-service.d.ts +93 -0
  187. package/dist/lib/services/asset-references-service.d.ts.map +1 -0
  188. package/dist/lib/services/asset-references-service.js +198 -0
  189. package/dist/lib/services/asset-references-service.js.map +1 -0
  190. package/dist/lib/services/asset-service.d.ts +115 -14
  191. package/dist/lib/services/asset-service.d.ts.map +1 -1
  192. package/dist/lib/services/asset-service.js +312 -31
  193. package/dist/lib/services/asset-service.js.map +1 -1
  194. package/dist/lib/services/references-service.d.ts +19 -15
  195. package/dist/lib/services/references-service.d.ts.map +1 -1
  196. package/dist/lib/services/references-service.js +59 -31
  197. package/dist/lib/services/references-service.js.map +1 -1
  198. package/dist/lib/services/version-service.d.ts +10 -1
  199. package/dist/lib/services/version-service.d.ts.map +1 -1
  200. package/dist/lib/services/version-service.js +26 -4
  201. package/dist/lib/services/version-service.js.map +1 -1
  202. package/dist/lib/storage/adapters/local-storage-adapter.d.ts +38 -0
  203. package/dist/lib/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  204. package/dist/lib/storage/adapters/local-storage-adapter.js +86 -19
  205. package/dist/lib/storage/adapters/local-storage-adapter.js.map +1 -1
  206. package/dist/lib/storage/index.d.ts +1 -0
  207. package/dist/lib/storage/index.d.ts.map +1 -1
  208. package/dist/lib/storage/index.js +2 -0
  209. package/dist/lib/storage/index.js.map +1 -1
  210. package/dist/lib/storage/interfaces/storage.d.ts +135 -5
  211. package/dist/lib/storage/interfaces/storage.d.ts.map +1 -1
  212. package/dist/lib/storage/keys.d.ts +96 -0
  213. package/dist/lib/storage/keys.d.ts.map +1 -0
  214. package/dist/lib/storage/keys.js +160 -0
  215. package/dist/lib/storage/keys.js.map +1 -0
  216. package/dist/lib/type-gen.d.ts.map +1 -1
  217. package/dist/lib/type-gen.js +11 -5
  218. package/dist/lib/type-gen.js.map +1 -1
  219. package/dist/lib/types/asset.d.ts +92 -12
  220. package/dist/lib/types/asset.d.ts.map +1 -1
  221. package/dist/lib/types/capabilities.d.ts +11 -0
  222. package/dist/lib/types/capabilities.d.ts.map +1 -1
  223. package/dist/lib/types/capabilities.js +20 -6
  224. package/dist/lib/types/capabilities.js.map +1 -1
  225. package/dist/lib/types/config.d.ts +127 -0
  226. package/dist/lib/types/config.d.ts.map +1 -1
  227. package/dist/lib/types/filters.d.ts +31 -0
  228. package/dist/lib/types/filters.d.ts.map +1 -1
  229. package/dist/lib/types/schemas.d.ts +14 -0
  230. package/dist/lib/types/schemas.d.ts.map +1 -1
  231. package/dist/lib/utils/asset-reference-walk.d.ts +44 -0
  232. package/dist/lib/utils/asset-reference-walk.d.ts.map +1 -0
  233. package/dist/lib/utils/asset-reference-walk.js +144 -0
  234. package/dist/lib/utils/asset-reference-walk.js.map +1 -0
  235. package/dist/lib/utils/image-url.d.ts +61 -26
  236. package/dist/lib/utils/image-url.d.ts.map +1 -1
  237. package/dist/lib/utils/image-url.js +143 -26
  238. package/dist/lib/utils/image-url.js.map +1 -1
  239. package/dist/lib/utils/video-metadata.d.ts +39 -0
  240. package/dist/lib/utils/video-metadata.d.ts.map +1 -0
  241. package/dist/lib/utils/video-metadata.js +161 -0
  242. package/dist/lib/utils/video-metadata.js.map +1 -0
  243. package/dist/local-api/collection-api.d.ts +25 -2
  244. package/dist/local-api/collection-api.d.ts.map +1 -1
  245. package/dist/local-api/collection-api.js +107 -20
  246. package/dist/preview/assets.d.ts +19 -0
  247. package/dist/preview/assets.d.ts.map +1 -1
  248. package/dist/preview/assets.js +6 -0
  249. package/dist/routes/assets-cdn.d.ts +19 -0
  250. package/dist/routes/assets-cdn.d.ts.map +1 -1
  251. package/dist/routes/assets-cdn.js +295 -17
  252. package/dist/schema-utils/utils.d.ts +31 -1
  253. package/dist/schema-utils/utils.d.ts.map +1 -1
  254. package/dist/schema-utils/utils.js +68 -0
  255. package/dist/server/api/index.d.ts.map +1 -1
  256. package/dist/server/api/index.js +87 -8
  257. package/dist/server/api/routes/assets-bulk.d.ts.map +1 -1
  258. package/dist/server/api/routes/assets-bulk.js +36 -7
  259. package/dist/server/api/routes/assets-by-id.d.ts.map +1 -1
  260. package/dist/server/api/routes/assets-by-id.js +32 -15
  261. package/dist/server/api/routes/assets-direct-upload.d.ts +4 -0
  262. package/dist/server/api/routes/assets-direct-upload.d.ts.map +1 -0
  263. package/dist/server/api/routes/assets-direct-upload.js +163 -0
  264. package/dist/server/api/routes/assets-poster.d.ts +4 -0
  265. package/dist/server/api/routes/assets-poster.d.ts.map +1 -0
  266. package/dist/server/api/routes/assets-poster.js +119 -0
  267. package/dist/server/api/routes/assets-references.d.ts.map +1 -1
  268. package/dist/server/api/routes/assets-references.js +64 -5
  269. package/dist/server/api/routes/assets.d.ts.map +1 -1
  270. package/dist/server/api/routes/assets.js +116 -12
  271. package/dist/server/api/routes/clear-asset-references.d.ts +18 -0
  272. package/dist/server/api/routes/clear-asset-references.d.ts.map +1 -0
  273. package/dist/server/api/routes/clear-asset-references.js +31 -0
  274. package/dist/server/api/routes/documents.d.ts.map +1 -1
  275. package/dist/server/api/routes/documents.js +28 -1
  276. package/dist/server/index.d.ts +2 -0
  277. package/dist/server/index.d.ts.map +1 -1
  278. package/dist/server/index.js +4 -0
  279. package/dist/services/asset-references-service.d.ts +93 -0
  280. package/dist/services/asset-references-service.d.ts.map +1 -0
  281. package/dist/services/asset-references-service.js +197 -0
  282. package/dist/services/asset-service.d.ts +115 -14
  283. package/dist/services/asset-service.d.ts.map +1 -1
  284. package/dist/services/asset-service.js +312 -31
  285. package/dist/services/references-service.d.ts +19 -15
  286. package/dist/services/references-service.d.ts.map +1 -1
  287. package/dist/services/references-service.js +59 -31
  288. package/dist/services/version-service.d.ts +10 -1
  289. package/dist/services/version-service.d.ts.map +1 -1
  290. package/dist/services/version-service.js +26 -4
  291. package/dist/storage/adapters/local-storage-adapter.d.ts +38 -0
  292. package/dist/storage/adapters/local-storage-adapter.d.ts.map +1 -1
  293. package/dist/storage/adapters/local-storage-adapter.js +86 -19
  294. package/dist/storage/index.d.ts +1 -0
  295. package/dist/storage/index.d.ts.map +1 -1
  296. package/dist/storage/index.js +2 -0
  297. package/dist/storage/interfaces/storage.d.ts +135 -5
  298. package/dist/storage/interfaces/storage.d.ts.map +1 -1
  299. package/dist/storage/keys.d.ts +96 -0
  300. package/dist/storage/keys.d.ts.map +1 -0
  301. package/dist/storage/keys.js +159 -0
  302. package/dist/type-gen.d.ts.map +1 -1
  303. package/dist/type-gen.js +11 -5
  304. package/dist/types/asset.d.ts +92 -12
  305. package/dist/types/asset.d.ts.map +1 -1
  306. package/dist/types/capabilities.d.ts +11 -0
  307. package/dist/types/capabilities.d.ts.map +1 -1
  308. package/dist/types/capabilities.js +20 -6
  309. package/dist/types/config.d.ts +127 -0
  310. package/dist/types/config.d.ts.map +1 -1
  311. package/dist/types/filters.d.ts +31 -0
  312. package/dist/types/filters.d.ts.map +1 -1
  313. package/dist/types/schemas.d.ts +14 -0
  314. package/dist/types/schemas.d.ts.map +1 -1
  315. package/dist/utils/asset-reference-walk.d.ts +44 -0
  316. package/dist/utils/asset-reference-walk.d.ts.map +1 -0
  317. package/dist/utils/asset-reference-walk.js +143 -0
  318. package/dist/utils/image-url.d.ts +61 -26
  319. package/dist/utils/image-url.d.ts.map +1 -1
  320. package/dist/utils/image-url.js +143 -26
  321. package/dist/utils/video-metadata.d.ts +39 -0
  322. package/dist/utils/video-metadata.d.ts.map +1 -0
  323. package/dist/utils/video-metadata.js +160 -0
  324. package/package.json +6 -1
@@ -1,4 +1,77 @@
1
1
  import { cmsLogger } from '../utils/logger.js';
2
+ import { parseVariantFilename, VARIANT_FORMAT, POSTER_FILENAME, buildPosterKey } from '../storage/keys.js';
3
+ import { configHashFor, pickVariant, resolveImageConfig } from '../images/variants.js';
4
+ import { generateVariant } from '../images/generate.js';
5
+ /**
6
+ * HTTP headers are ByteString-restricted, so a raw non-ASCII character in a
7
+ * filename throws when the Response is constructed. Callers pair this with a
8
+ * `filename*=UTF-8''` parameter for clients that understand it.
9
+ */
10
+ function asciiFilename(name) {
11
+ return name.replace(/[^\x20-\x7E]/g, '_').replace(/["\\]/g, '');
12
+ }
13
+ function stripExtension(name) {
14
+ const lastDot = name.lastIndexOf('.');
15
+ return lastDot > 0 ? name.slice(0, lastDot) : name;
16
+ }
17
+ /**
18
+ * Parse a single byte range against a known object size.
19
+ *
20
+ * Returns `null` when there is nothing to honour — no header, a form we don't
21
+ * serve, or an unknown size — in which case the caller answers `200` with the
22
+ * whole body. That is a legal response to any `Range` request, which is what
23
+ * makes ignoring multipart ranges (`bytes=0-99,200-299`) acceptable: they are
24
+ * fiddly to emit, essentially nothing sends them, and a full body is correct.
25
+ *
26
+ * `'unsatisfiable'` is different from `null`: the range is well-formed but lies
27
+ * outside the object, which must be answered `416`, not `200`. A client that
28
+ * seeks past the end otherwise receives a full file it did not ask for.
29
+ *
30
+ * Both bounds in the result are **inclusive**, as in the header itself.
31
+ */
32
+ export function parseByteRange(header, size) {
33
+ if (!header || size == null || size <= 0)
34
+ return null;
35
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
36
+ if (!match)
37
+ return null;
38
+ const [, rawStart, rawEnd] = match;
39
+ if (rawStart === '' && rawEnd === '')
40
+ return null;
41
+ // `bytes=-500` is a *suffix* range: the last 500 bytes, not "from 500 on".
42
+ // Reading it as a start offset is the classic way to serve the wrong half of
43
+ // a file to a player seeking near the end.
44
+ if (rawStart === '') {
45
+ const suffixLength = Number(rawEnd);
46
+ if (!Number.isFinite(suffixLength) || suffixLength <= 0)
47
+ return 'unsatisfiable';
48
+ return { start: Math.max(0, size - suffixLength), end: size - 1 };
49
+ }
50
+ const start = Number(rawStart);
51
+ if (!Number.isFinite(start) || start >= size)
52
+ return 'unsatisfiable';
53
+ // An open-ended `bytes=500-` runs to the last byte, and an end past the object
54
+ // is clamped rather than rejected — RFC 9110 treats an over-long end as the
55
+ // whole remainder, and players routinely ask for more than exists.
56
+ const requestedEnd = rawEnd === '' ? size - 1 : Number(rawEnd);
57
+ if (!Number.isFinite(requestedEnd))
58
+ return 'unsatisfiable';
59
+ const end = Math.min(requestedEnd, size - 1);
60
+ if (end < start)
61
+ return 'unsatisfiable';
62
+ return { start, end };
63
+ }
64
+ function toArrayBuffer(buffer) {
65
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
66
+ }
67
+ /**
68
+ * Lifetime of a signed URL when `signedDownloads.expiresIn` isn't set.
69
+ *
70
+ * Long enough to start and finish a large download, short enough that a leaked
71
+ * URL stops working quickly — the redirect is the one path where the file is
72
+ * reachable without passing back through this route's access checks.
73
+ */
74
+ const DEFAULT_SIGNED_URL_TTL_SECONDS = 900;
2
75
  export const GET = async ({ params, locals, setHeaders, request }) => {
3
76
  try {
4
77
  const { assetService, databaseAdapter, storageAdapter, cmsEngine, config } = locals.aphexCMS;
@@ -90,19 +163,217 @@ export const GET = async ({ params, locals, setHeaders, request }) => {
90
163
  return new Response('Forbidden', { status: 403 });
91
164
  }
92
165
  }
93
- // If asset has a direct URL (S3/R2), redirect to it
94
- if (asset.url && asset.url.startsWith('http')) {
166
+ // --- Serving ---------------------------------------------------------
167
+ //
168
+ // Everything above decided whether this caller may read the file. Only
169
+ // now do we fetch it, and by default we fetch it *through* the app rather
170
+ // than redirecting to the bucket.
171
+ //
172
+ // This route used to 302 straight to `asset.url` whenever it looked like
173
+ // an absolute URL — which meant the privacy checks above decided nothing
174
+ // for S3/R2-backed assets (anyone with the id got the public URL) and
175
+ // broke outright against a private bucket, where the redirect target
176
+ // isn't readable. Proxying is what makes those checks real.
177
+ if (!storageAdapter) {
178
+ cmsLogger.error('[Asset CDN]', 'No storage adapter configured');
179
+ return new Response('No storage adapter configured', { status: 500 });
180
+ }
181
+ // Opt out per-file: large downloads shouldn't tie up a server process, so
182
+ // they can be handed to the bucket as a short-lived signed URL. The
183
+ // access checks have already passed, so this only ever signs a request
184
+ // that was allowed. Falls through to the proxy when the adapter can't
185
+ // sign, since serving the file beats refusing to.
186
+ const signedDownloads = config.signedDownloads;
187
+ if (signedDownloads && storageAdapter.getSignedUrl) {
188
+ let useSigned = false;
189
+ try {
190
+ useSigned = await signedDownloads.shouldUseSignedURL(asset);
191
+ }
192
+ catch (err) {
193
+ cmsLogger.warn('[Asset CDN]', 'shouldUseSignedURL threw; proxying instead:', err);
194
+ }
195
+ if (useSigned) {
196
+ const signedUrl = await storageAdapter.getSignedUrl(asset.path, signedDownloads.expiresIn ?? DEFAULT_SIGNED_URL_TTL_SECONDS);
197
+ return new Response(null, {
198
+ status: 302,
199
+ headers: {
200
+ Location: signedUrl,
201
+ // The URL expires, so it must never be cached by a shared proxy.
202
+ 'Cache-Control': 'private, no-store'
203
+ }
204
+ });
205
+ }
206
+ }
207
+ // Stream when the adapter can, buffer when it can't.
208
+ //
209
+ // Not just an optimisation: a serverless host caps the *response body* it
210
+ // will return (Vercel Functions: 4.5 MB, then a 413), and a streamed
211
+ // response is exempt. Buffering an ordinary 5 MB photo there is a hard
212
+ // failure, not a slow request — so the streaming path is the correct one
213
+ // wherever it's available, and buffering is the fallback.
214
+ // --- Variants --------------------------------------------------------
215
+ //
216
+ // Reached only after every check above has passed, which is the entire
217
+ // reason derivatives live on this route instead of their own. A separate
218
+ // image endpoint would have to repeat the privacy and organization logic,
219
+ // and if it ever drifted the result would be a public derivative of a
220
+ // private original, cached at the edge under a guessable key.
221
+ // A video's poster frame. Served from this route, behind the same checks,
222
+ // for the reason stated above: a private video must not have a public
223
+ // thumbnail sitting at a guessable URL.
224
+ if (filename === POSTER_FILENAME) {
225
+ try {
226
+ const poster = await storageAdapter.getObject(buildPosterKey(asset.id));
227
+ setHeaders({
228
+ 'Content-Type': 'image/webp',
229
+ 'Content-Length': String(poster.length),
230
+ 'Cache-Control': isPrivate ? 'private, no-store' : 'public, max-age=31536000, immutable',
231
+ 'X-Content-Type-Options': 'nosniff'
232
+ });
233
+ return new Response(toArrayBuffer(poster));
234
+ }
235
+ catch {
236
+ // No poster (an API upload, or a codec the browser couldn't decode).
237
+ // 404 rather than falling through to the video: a <img> asking for a
238
+ // poster must not receive 30MB of MP4.
239
+ return new Response('No poster for this asset', { status: 404 });
240
+ }
241
+ }
242
+ const variantRequest = filename ? parseVariantFilename(filename) : null;
243
+ const imageConfig = resolveImageConfig(config.images);
244
+ if (variantRequest && imageConfig && asset.assetType === 'image') {
245
+ const configHash = configHashFor(imageConfig);
246
+ // A width outside the ladder, or a request under a superseded config,
247
+ // falls through and serves the original. The ladder being a closed set
248
+ // is what stops arbitrary dimensions turning into unbounded CPU and
249
+ // storage, so an unknown width must never trigger generation.
250
+ const servable = variantRequest.configHash === configHash &&
251
+ imageConfig.widths.includes(variantRequest.width);
252
+ if (servable) {
253
+ const existing = pickVariant(asset, variantRequest.width, configHash);
254
+ // A saved copy should get a readable name, not `w800-a1b2c3.webp`.
255
+ // The variant's *URL* keeps the generated name — it has to, since
256
+ // that's what makes it addressable and immutable — but what the
257
+ // browser writes to disk is this route's business.
258
+ const downloadName = `${stripExtension(asset.originalFilename || asset.filename)}.${VARIANT_FORMAT}`;
259
+ setHeaders({
260
+ 'Content-Type': `image/${VARIANT_FORMAT}`,
261
+ // Every variant URL embeds the config hash, so a change of ladder
262
+ // or quality produces a different URL rather than new bytes at the
263
+ // same one. That is what makes a year-long immutable cache safe.
264
+ 'Cache-Control': isPrivate ? 'private, no-store' : 'public, max-age=31536000, immutable',
265
+ 'Content-Disposition': `inline; filename="${asciiFilename(downloadName)}"; filename*=UTF-8''${encodeURIComponent(downloadName)}`,
266
+ 'X-Content-Type-Options': 'nosniff'
267
+ });
268
+ if (existing) {
269
+ try {
270
+ const buffer = await storageAdapter.getObject(existing.path);
271
+ return new Response(toArrayBuffer(buffer), {
272
+ headers: { 'Content-Length': String(buffer.length) }
273
+ });
274
+ }
275
+ catch (err) {
276
+ // Recorded but unreadable — the object was pruned, or the
277
+ // record outlived it. Fall through and regenerate rather
278
+ // than 404 on something we promised exists.
279
+ cmsLogger.warn('[Asset CDN]', 'Recorded variant unreadable; regenerating:', err);
280
+ }
281
+ }
282
+ try {
283
+ const { buffer } = await generateVariant({
284
+ asset,
285
+ width: variantRequest.width,
286
+ config: imageConfig,
287
+ configHash,
288
+ storage: storageAdapter,
289
+ database: databaseAdapter
290
+ });
291
+ return new Response(toArrayBuffer(buffer), {
292
+ headers: { 'Content-Length': String(buffer.length) }
293
+ });
294
+ }
295
+ catch (err) {
296
+ // A derivative that can't be produced must not break the page.
297
+ // Serving the original is heavier but correct, and the next
298
+ // request retries — which is the whole retry story for
299
+ // generate-on-miss.
300
+ cmsLogger.warn('[Asset CDN]', 'Variant generation failed; serving original:', err);
301
+ }
302
+ }
303
+ }
304
+ //
305
+ // The body and its length are resolved together because they're only
306
+ // knowable together: a stream doesn't carry a length, so it has to borrow
307
+ // the row's `size`, while a buffer knows its own and shouldn't trust the
308
+ // row. Omit the header rather than guess when neither is available — a
309
+ // wrong Content-Length truncates the response or hangs the client, both
310
+ // worse than sending none.
311
+ let body;
312
+ let contentLength;
313
+ // Byte ranges, which is what makes media usable. Without them a browser can
314
+ // only reach the middle of a recording by transferring everything before
315
+ // it, so seeking a large video costs a full download and the egress to
316
+ // match. Small files hide this — a few MB over localhost feels instant —
317
+ // which is why it reads as "fine in dev, expensive in production".
318
+ //
319
+ // The total has to be the object's real size, since it goes out in
320
+ // `Content-Range` and a client trusts it. `asset.size` is the row's claim
321
+ // and can be stale, so ask storage when it can tell us.
322
+ let totalSize = asset.size ?? null;
323
+ if (storageAdapter.getObjectMetadata) {
324
+ try {
325
+ const metadata = await storageAdapter.getObjectMetadata(asset.path);
326
+ if (typeof metadata?.size === 'number')
327
+ totalSize = metadata.size;
328
+ }
329
+ catch (err) {
330
+ // Reporting-only: a metadata failure must not fail the download.
331
+ cmsLogger.debug('[Asset CDN]', 'Could not read object metadata for range:', err);
332
+ }
333
+ }
334
+ const range = parseByteRange(request.headers.get('range'), totalSize);
335
+ if (range === 'unsatisfiable') {
336
+ // 416 must carry the true size so the client can correct itself.
95
337
  return new Response(null, {
96
- status: 302,
97
- headers: { Location: asset.url }
338
+ status: 416,
339
+ headers: {
340
+ 'Content-Range': `bytes */${totalSize}`,
341
+ 'Accept-Ranges': 'bytes'
342
+ }
98
343
  });
99
344
  }
100
- // Otherwise, serve from local storage
101
- if (!storageAdapter?.getObject) {
102
- cmsLogger.error('[Asset CDN]', 'Storage adapter does not support getObject');
103
- return new Response('Storage adapter does not support file serving', { status: 500 });
345
+ if (range) {
346
+ const rangeLength = range.end - range.start + 1;
347
+ if (storageAdapter.getObjectRange) {
348
+ body = await storageAdapter.getObjectRange(asset.path, range.start, range.end);
349
+ }
350
+ else {
351
+ // Correct, but reads the whole object to return part of it. Adapters
352
+ // should implement getObjectRange; both first-party ones do.
353
+ const fileBuffer = await storageAdapter.getObject(asset.path);
354
+ body = toArrayBuffer(fileBuffer.subarray(range.start, range.end + 1));
355
+ }
356
+ setHeaders({
357
+ 'Content-Type': asset.mimeType || 'application/octet-stream',
358
+ // The *range* length, never the file's. A Content-Length that
359
+ // disagrees with the body truncates the response or hangs the client.
360
+ 'Content-Length': String(rangeLength),
361
+ 'Content-Range': `bytes ${range.start}-${range.end}/${totalSize}`,
362
+ 'Accept-Ranges': 'bytes',
363
+ 'Cache-Control': isPrivate ? 'private, no-store' : 'public, max-age=31536000, immutable',
364
+ 'X-Content-Type-Options': 'nosniff'
365
+ });
366
+ return new Response(body, { status: 206 });
367
+ }
368
+ if (storageAdapter.getStream) {
369
+ body = await storageAdapter.getStream(asset.path);
370
+ contentLength = asset.size ?? null;
371
+ }
372
+ else {
373
+ const fileBuffer = await storageAdapter.getObject(asset.path);
374
+ body = toArrayBuffer(fileBuffer);
375
+ contentLength = fileBuffer.length;
104
376
  }
105
- const fileBuffer = await storageAdapter.getObject(asset.path);
106
377
  // RFC 6266 Content-Disposition: dual-encode the filename so it survives
107
378
  // non-ASCII characters in HTTP headers. HTTP headers are ByteString-
108
379
  // restricted (codepoints 0–255), so a raw character like U+202F NARROW
@@ -123,17 +394,24 @@ export const GET = async ({ params, locals, setHeaders, request }) => {
123
394
  const disposition = canInline ? 'inline' : 'attachment';
124
395
  setHeaders({
125
396
  'Content-Type': asset.mimeType || 'application/octet-stream',
126
- 'Content-Length': fileBuffer.length.toString(),
127
- 'Cache-Control': 'public, max-age=31536000, immutable',
397
+ ...(contentLength != null && { 'Content-Length': contentLength.toString() }),
398
+ // A private asset must never land in a shared cache. Now that these
399
+ // bytes flow through the app instead of coming from the bucket, an
400
+ // unconditional `public, immutable` would let any CDN or proxy in front
401
+ // of the app hand the file to the next caller without the checks above
402
+ // ever running again.
403
+ 'Cache-Control': isPrivate ? 'private, no-store' : 'public, max-age=31536000, immutable',
128
404
  'Content-Disposition': `${disposition}; filename="${asciiFallback}"; filename*=UTF-8''${utf8Encoded}`,
129
405
  'X-Content-Type-Options': 'nosniff',
130
- ...(asset.mimeType?.startsWith('image/') && {
131
- 'Accept-Ranges': 'bytes'
132
- })
406
+ // Advertised for every type, not just images. It used to be image-only
407
+ // while the route ignored `Range` entirely — so it was both a promise
408
+ // nothing kept and a promise withheld from video, the one type that
409
+ // actually needs it. Ranges are served above for anything whose size we
410
+ // know, falling back to a buffered slice when the adapter has no ranged
411
+ // read, so this is now true wherever it is sent.
412
+ ...(totalSize != null && { 'Accept-Ranges': 'bytes' })
133
413
  });
134
- // Convert Buffer to ArrayBuffer for Response
135
- const arrayBuffer = fileBuffer.buffer.slice(fileBuffer.byteOffset, fileBuffer.byteOffset + fileBuffer.byteLength);
136
- return new Response(arrayBuffer);
414
+ return new Response(body);
137
415
  }
138
416
  catch (error) {
139
417
  cmsLogger.error('[Asset CDN]', 'Error serving asset:', error);
@@ -1,4 +1,4 @@
1
- import type { SchemaType } from '../types/schemas.js';
1
+ import type { SchemaType, SearchFieldConfig } from '../types/schemas.js';
2
2
  /**
3
3
  * Schema utility functions that work with a schema registry
4
4
  * These functions accept schemas as parameters to avoid package-level dependencies
@@ -19,6 +19,36 @@ export declare function getDocumentTypes(schemas: SchemaType[]): SchemaType[];
19
19
  * Check if a schema type exists
20
20
  */
21
21
  export declare function schemaExists(schemas: SchemaType[], name: string): boolean;
22
+ /**
23
+ * Build a `search` config from every top-level string-ish field on a schema
24
+ * (`string`, `text`, `slug`, `url`) — the fields worth full-text matching.
25
+ * Doesn't recurse into `object`/`array` fields.
26
+ *
27
+ * Use this to opt a document type into field-wide search instead of hand-listing
28
+ * paths:
29
+ * ```ts
30
+ * const fields = [ ...define fields here... ];
31
+ * export default defineType({
32
+ * name: 'post',
33
+ * fields,
34
+ * search: searchableFields({ fields })
35
+ * })
36
+ * ```
37
+ */
38
+ export declare function searchableFields(schema: Pick<SchemaType, 'fields'>): SearchFieldConfig[];
39
+ /**
40
+ * Resolve which dot-paths a document's search index is built from: the
41
+ * schema's explicit `search` config if set, else the conventional title-ish
42
+ * fields (`title`/`heading`/`name`/`label`/`slug`) plus whatever
43
+ * `preview.select.title` points to — the same fields `resolvePreviewTitle`
44
+ * already uses to pick a display title.
45
+ */
46
+ export declare function resolveSearchPaths(schema: Pick<SchemaType, 'search' | 'preview'>): string[];
47
+ /**
48
+ * Flatten the given dot-paths off a document's data into a single normalized
49
+ * string — the value stored in `search_text` and indexed for full-text search.
50
+ */
51
+ export declare function buildSearchText(paths: string[], data: Record<string, unknown> | null | undefined): string;
22
52
  /**
23
53
  * Get the available types for an array field
24
54
  * Supports both schema references and inline object definitions
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/lib/schema-utils/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;GAGG;AAEH;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAEtF;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,CAElE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,CAEpE;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAEzE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,OAAO,EAAE,UAAU,EAAE,EACrB,UAAU,EAAE;IAAE,EAAE,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAA;KAAE,CAAC,CAAA;CAAE,GACzF,UAAU,EAAE,CA0Bd"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/lib/schema-utils/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAatE;;;GAGG;AAEH;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAEtF;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,CAElE;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,UAAU,EAAE,CAEpE;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAEzE;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,GAAG,iBAAiB,EAAE,CAIxF;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,QAAQ,GAAG,SAAS,CAAC,GAAG,MAAM,EAAE,CAQ3F;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC9B,KAAK,EAAE,MAAM,EAAE,EACf,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,GAC9C,MAAM,CAaR;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAC5B,OAAO,EAAE,UAAU,EAAE,EACrB,UAAU,EAAE;IAAE,EAAE,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAA;KAAE,CAAC,CAAA;CAAE,GACzF,UAAU,EAAE,CA0Bd"}
@@ -1,3 +1,12 @@
1
+ import { readPath } from '../utils/preview.js';
2
+ /** Field types treated as free text for the purposes of `searchableFields`. */
3
+ const SEARCHABLE_FIELD_TYPES = new Set(['string', 'text', 'slug', 'url']);
4
+ /**
5
+ * Conventional fallback field names for search when a schema doesn't declare
6
+ * an explicit `search` config. Mirrors the title-resolution fallback in
7
+ * `resolvePreviewTitle` (`title`/`heading`/`name`/`label`), plus `slug`.
8
+ */
9
+ const DEFAULT_SEARCH_FIELDS = ['title', 'heading', 'name', 'label', 'slug'];
1
10
  /**
2
11
  * Schema utility functions that work with a schema registry
3
12
  * These functions accept schemas as parameters to avoid package-level dependencies
@@ -26,6 +35,65 @@ export function getDocumentTypes(schemas) {
26
35
  export function schemaExists(schemas, name) {
27
36
  return schemas.some((schema) => schema.name === name);
28
37
  }
38
+ /**
39
+ * Build a `search` config from every top-level string-ish field on a schema
40
+ * (`string`, `text`, `slug`, `url`) — the fields worth full-text matching.
41
+ * Doesn't recurse into `object`/`array` fields.
42
+ *
43
+ * Use this to opt a document type into field-wide search instead of hand-listing
44
+ * paths:
45
+ * ```ts
46
+ * const fields = [ ...define fields here... ];
47
+ * export default defineType({
48
+ * name: 'post',
49
+ * fields,
50
+ * search: searchableFields({ fields })
51
+ * })
52
+ * ```
53
+ */
54
+ export function searchableFields(schema) {
55
+ return schema.fields
56
+ .filter((field) => SEARCHABLE_FIELD_TYPES.has(field.type))
57
+ .map((field) => ({ path: field.name }));
58
+ }
59
+ /**
60
+ * Resolve which dot-paths a document's search index is built from: the
61
+ * schema's explicit `search` config if set, else the conventional title-ish
62
+ * fields (`title`/`heading`/`name`/`label`/`slug`) plus whatever
63
+ * `preview.select.title` points to — the same fields `resolvePreviewTitle`
64
+ * already uses to pick a display title.
65
+ */
66
+ export function resolveSearchPaths(schema) {
67
+ if (schema.search?.length) {
68
+ return schema.search.map((field) => field.path);
69
+ }
70
+ const fallback = new Set(DEFAULT_SEARCH_FIELDS);
71
+ const titlePath = schema.preview?.select?.title;
72
+ if (titlePath)
73
+ fallback.add(titlePath);
74
+ return Array.from(fallback);
75
+ }
76
+ /**
77
+ * Flatten the given dot-paths off a document's data into a single normalized
78
+ * string — the value stored in `search_text` and indexed for full-text search.
79
+ */
80
+ export function buildSearchText(paths, data) {
81
+ if (!data)
82
+ return '';
83
+ const parts = [];
84
+ for (const path of paths) {
85
+ const value = readPath(data, path);
86
+ if (typeof value === 'string') {
87
+ const trimmed = value.trim();
88
+ if (trimmed)
89
+ parts.push(trimmed);
90
+ }
91
+ else if (typeof value === 'number' || typeof value === 'boolean') {
92
+ parts.push(String(value));
93
+ }
94
+ }
95
+ return parts.join(' ').replace(/\s+/g, ' ').trim();
96
+ }
29
97
  /**
30
98
  * Get the available types for an array field
31
99
  * Supports both schema references and inline object definitions
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/server/api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAyB7C;;;;;;;;;;GAUG;AACH,MAAM,MAAM,QAAQ,GAAG;IACtB,SAAS,EAAE;QACV,QAAQ,EAAE,YAAY,CAAC;QACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;KAClB,CAAC;IACF,QAAQ,EAAE;QACT,QAAQ,EAAE,YAAY,CAAC;QACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;KAClB,CAAC;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,cAAc,kGAqB7B;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,QAqErD;AAED,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;AAE1D;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,IACtE,GAAG,OAAO,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,uBAejD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/server/api/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AA6B7C;;;;;;;;;;GAUG;AACH,MAAM,MAAM,QAAQ,GAAG;IACtB,SAAS,EAAE;QACV,QAAQ,EAAE,YAAY,CAAC;QACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;KAClB,CAAC;IACF,QAAQ,EAAE;QACT,QAAQ,EAAE,YAAY,CAAC;QACvB,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC;KAClB,CAAC;CACF,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,cAAc,kGAqC7B;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,QAmGrD;AAED,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;AA0C1D;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,QAAQ,IACtE,GAAG,OAAO,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,uBAejD"}
@@ -1,5 +1,6 @@
1
1
  import { Hono } from 'hono';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
+ import { formatMegabytes, resolveMaxUploadBytes } from '../../api/limits.js';
3
4
  import { schemasRouter } from './routes/schemas.js';
4
5
  import { documentsRouter } from './routes/documents.js';
5
6
  import { documentsByIdRouter } from './routes/documents-by-id.js';
@@ -9,6 +10,8 @@ import { documentVersionsRouter } from './routes/document-versions.js';
9
10
  import { assetsRouter } from './routes/assets.js';
10
11
  import { assetsByIdRouter } from './routes/assets-by-id.js';
11
12
  import { assetsBulkRouter } from './routes/assets-bulk.js';
13
+ import { assetsDirectUploadRouter } from './routes/assets-direct-upload.js';
14
+ import { assetsPosterRouter } from './routes/assets-poster.js';
12
15
  import { assetsReferencesRouter } from './routes/assets-references.js';
13
16
  import { organizationsRouter } from './routes/organizations.js';
14
17
  import { organizationsByIdRouter } from './routes/organizations-by-id.js';
@@ -34,10 +37,25 @@ import { agentChangeSetsRouter } from './routes/agent-change-sets.js';
34
37
  export function createAphexApi() {
35
38
  const app = new Hono().basePath('/api');
36
39
  // Reject oversized request bodies before they're fully buffered.
37
- app.use('*', bodyLimit({
38
- maxSize: 10 * 1024 * 1024, // 10MB for JSON endpoints
39
- onError: (c) => c.json({ success: false, error: 'Request body too large (max 10MB)' }, 413)
40
- }));
40
+ //
41
+ // This applies to uploads as much as to JSON, and it is the *first* ceiling a
42
+ // large upload meets — lower than the 50MB the assets route checks against,
43
+ // which is why that check never fires. The admin UI pre-checks file sizes
44
+ // against the same constant so an oversized file is refused before it's sent.
45
+ // Read per-request rather than closing over a value at construction time:
46
+ // `createAphexApi()` runs once at module scope, before any config exists, but
47
+ // `c.env.aphexCMS` is supplied on every `app.fetch(req, env)` call. Building
48
+ // the middleware per request is negligible next to handling the body.
49
+ app.use('*', async (c, next) => {
50
+ const maxSize = resolveMaxUploadBytes(c.env?.aphexCMS);
51
+ return bodyLimit({
52
+ maxSize,
53
+ onError: (ctx) => ctx.json({
54
+ success: false,
55
+ error: `Request body too large (max ${formatMegabytes(maxSize)})`
56
+ }, 413)
57
+ })(c, next);
58
+ });
41
59
  // Bridge: lift values passed via app.fetch(req, env) onto c.var so
42
60
  // handlers can read c.var.aphexCMS / c.var.auth directly.
43
61
  app.use('*', async (c, next) => {
@@ -70,7 +88,11 @@ export function mountAphexBuiltins(app) {
70
88
  // Assets — same precedence rule: specific paths before parametric.
71
89
  // `/assets/bulk` and `/assets/references/counts` must register before
72
90
  // `/assets/:id` or Hono will capture them as `:id = "bulk"` etc.
91
+ // Before assets-by-id: Hono matches in registration order, and `/:id` would
92
+ // otherwise claim `/upload-url` and `/confirm`.
93
+ app.route('/assets', assetsDirectUploadRouter);
73
94
  app.route('/assets', assetsBulkRouter);
95
+ app.route('/assets', assetsPosterRouter);
74
96
  app.route('/assets', assetsReferencesRouter);
75
97
  app.route('/assets', assetsByIdRouter);
76
98
  app.route('/assets', assetsRouter);
@@ -103,18 +125,75 @@ export function mountAphexBuiltins(app) {
103
125
  // POST /api/agent/change-sets/:id/undo
104
126
  app.route('/agent', agentChangeSetsRouter);
105
127
  // Health check — unauthenticated, used by load balancers and uptime monitors.
128
+ //
129
+ // The database decides the status code: without it nothing can be served, so
130
+ // a failure is a genuine 503 and the node should leave rotation. Storage is
131
+ // reported but never fails the check — when object storage is down the site
132
+ // still renders, only uploads and media break, and 503-ing would pull healthy
133
+ // nodes out of the load balancer over a dependency they don't need to answer
134
+ // a page request. That case surfaces as `status: 'degraded'` with HTTP 200,
135
+ // which an uptime monitor can alert on without a proxy treating it as death.
136
+ //
137
+ // Storage is probed only when `config.storageHealthCheck` is enabled, since
138
+ // the probe bills against metered object storage on an unauthenticated route.
106
139
  app.get('/aphex-health', async (c) => {
107
140
  try {
108
- const { databaseAdapter } = c.var.aphexCMS;
109
- const dbHealthy = await databaseAdapter.isHealthy();
110
- const status = dbHealthy ? 'healthy' : 'degraded';
111
- return c.json({ status, database: dbHealthy }, dbHealthy ? 200 : 503);
141
+ const { databaseAdapter, storageAdapter, config } = c.var.aphexCMS;
142
+ const probeStorage = config?.storageHealthCheck === true;
143
+ const [dbHealthy, storageHealthy] = await Promise.all([
144
+ databaseAdapter.isHealthy(),
145
+ probeStorage ? checkStorageHealth(storageAdapter) : Promise.resolve(null)
146
+ ]);
147
+ const status = dbHealthy ? (storageHealthy === false ? 'degraded' : 'healthy') : 'degraded';
148
+ return c.json({
149
+ status,
150
+ database: dbHealthy,
151
+ // Omitted rather than reported false when not probed, so a monitor
152
+ // can't mistake "not checked" for "storage is down".
153
+ ...(probeStorage ? { storage: storageHealthy } : {})
154
+ }, dbHealthy ? 200 : 503);
112
155
  }
113
156
  catch {
114
157
  return c.json({ status: 'unhealthy', database: false }, 503);
115
158
  }
116
159
  });
117
160
  }
161
+ /**
162
+ * How long a storage health result is reused before the adapter is probed again.
163
+ */
164
+ const STORAGE_HEALTH_TTL_MS = 30_000;
165
+ let storageHealthCache = null;
166
+ /**
167
+ * Probe storage health, at most once per {@link STORAGE_HEALTH_TTL_MS}.
168
+ *
169
+ * The cache is the point, not an optimization. `/aphex-health` is
170
+ * unauthenticated by design, and a remote storage adapter answers `isHealthy()`
171
+ * with a real network round-trip to the bucket — on S3/R2 a billable one. Probing
172
+ * per request would let anyone turn an uptime endpoint into someone else's
173
+ * storage bill, and would put load on the bucket proportional to how aggressively
174
+ * the site is scraped. Thirty seconds is far below any useful alerting interval
175
+ * while collapsing a flood of requests into one probe.
176
+ *
177
+ * A throwing adapter reads as unhealthy rather than propagating: storage must not
178
+ * be able to turn a 200 into a 503 (see the route comment).
179
+ */
180
+ async function checkStorageHealth(storageAdapter) {
181
+ if (!storageAdapter)
182
+ return false;
183
+ const now = Date.now();
184
+ if (storageHealthCache && now - storageHealthCache.checkedAt < STORAGE_HEALTH_TTL_MS) {
185
+ return storageHealthCache.healthy;
186
+ }
187
+ let healthy;
188
+ try {
189
+ healthy = await storageAdapter.isHealthy();
190
+ }
191
+ catch {
192
+ healthy = false;
193
+ }
194
+ storageHealthCache = { healthy, checkedAt: now };
195
+ return healthy;
196
+ }
118
197
  /**
119
198
  * Adapter: wrap a SvelteKit-style `RequestHandler` so it can be mounted
120
199
  * onto a Hono router.
@@ -1 +1 @@
1
- {"version":3,"file":"assets-bulk.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-bulk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAyE3C,CAAC"}
1
+ {"version":3,"file":"assets-bulk.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/assets-bulk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAM5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEzC,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,QAAQ,CAsG3C,CAAC"}