@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
@@ -4,6 +4,8 @@ import { cmsLogger } from '../../../utils/logger.js';
4
4
  import { validateFile } from '../../../utils/mime-detect.js';
5
5
  import { listAssetsQuery } from '../../../api/schemas/assets.js';
6
6
  import { hasCapability } from '../../../types/capabilities.js';
7
+ import { resolveMaxUploadBytes } from '../../../api/limits.js';
8
+ import { configHashFor, resolveImageConfig } from '../../../images.js';
7
9
  export const assetsRouter = new Hono()
8
10
  .get('/', zValidator('query', listAssetsQuery, (result, c) => {
9
11
  if (!result.success) {
@@ -20,25 +22,76 @@ export const assetsRouter = new Hono()
20
22
  if (!auth || auth.type === 'partial_session') {
21
23
  return c.json({ success: false, error: 'Unauthorized' }, 401);
22
24
  }
25
+ if (!hasCapability(auth, 'asset.read')) {
26
+ return c.json({ success: false, error: 'Forbidden: asset.read capability required' }, 403);
27
+ }
23
28
  const q = c.req.valid('query');
24
29
  const filters = {
25
30
  assetType: q.assetType,
26
31
  mimeType: q.mimeType,
32
+ category: q.category,
27
33
  search: q.search,
34
+ usage: q.usage,
28
35
  includeSystem: q.includeSystem ?? false,
36
+ sort: q.sort ?? 'newest',
29
37
  limit: q.limit ?? 20,
30
38
  offset: q.offset ?? 0
31
39
  };
32
40
  const { databaseAdapter } = c.var.aphexCMS;
41
+ // The usage filter reads the asset-reference index, which is now written
42
+ // inside each document's own write transaction. Content predating the
43
+ // index still has no rows, so a one-time bulk pass is needed — enqueued,
44
+ // never run here. That walk covers every document in the org, and doing
45
+ // it inline meant the first editor to open "Unused" wore the whole thing
46
+ // before their page rendered.
47
+ //
48
+ // Enqueued unconditionally, because the versioned idempotency key is the
49
+ // marker: `scheduleJob` returns the existing row rather than inserting a
50
+ // duplicate, so the first request creates the job and every later one is
51
+ // a single indexed lookup.
52
+ //
53
+ // This used to be gated on "does the index have any rows" instead. Saves
54
+ // create rows too, so one edit after release closed the gate for good and
55
+ // the rebuild never ran — leaving "Unused" listing assets that were in
56
+ // use. Asking a question whose answer another code path can set was the
57
+ // whole mistake; a completed job row means what it says.
58
+ let indexing = false;
59
+ if (filters.usage) {
60
+ try {
61
+ const { ASSET_REFERENCES_BACKFILL_JOB, assetReferencesBackfillKey } = await import('../../../jobs/asset-reference-jobs.js');
62
+ const job = await databaseAdapter.scheduleJob({
63
+ organizationId: auth.organizationId,
64
+ type: ASSET_REFERENCES_BACKFILL_JOB,
65
+ idempotencyKey: assetReferencesBackfillKey(auth.organizationId),
66
+ payload: {
67
+ documentTypes: (c.var.aphexCMS.config?.schemaTypes ?? [])
68
+ .filter((schema) => schema.type === 'document')
69
+ .map((schema) => schema.name)
70
+ }
71
+ });
72
+ // Only tell the editor their results are provisional while the pass
73
+ // is genuinely outstanding — otherwise the banner would be permanent.
74
+ indexing = job.status === 'pending' || job.status === 'leased';
75
+ }
76
+ catch (err) {
77
+ // Never fail a listing because indexing couldn't be scheduled.
78
+ cmsLogger.debug('[Assets]', 'Could not enqueue reference backfill:', err);
79
+ }
80
+ }
81
+ // The same filters go to both calls. `countAssets` used to receive a
82
+ // hand-copied subset, so every filter added after it was written was
83
+ // applied to the page but not to the total — the pager then read
84
+ // "1–20 of 300" above eleven rows. `limit`/`offset`/`sort` are ignored
85
+ // by the count, so passing the whole object is safe as well as correct.
33
86
  const [fetchedAssets, total] = await Promise.all([
34
87
  assetService.findAssets(auth.organizationId, filters),
35
- databaseAdapter.countAssets(auth.organizationId, {
36
- assetType: filters.assetType,
37
- mimeType: filters.mimeType,
38
- search: filters.search,
39
- includeSystem: filters.includeSystem
40
- })
88
+ databaseAdapter.countAssets(auth.organizationId, filters)
41
89
  ]);
90
+ // Resolved once and reported, so the browser can request a derivative
91
+ // for a thumbnail rather than the original. Grid views are where the
92
+ // original's size hurts most: thirty full-resolution images to draw
93
+ // thirty 200px tiles.
94
+ const imageConfig = resolveImageConfig(c.var.aphexCMS.config?.images);
42
95
  const pageSize = filters.limit || 20;
43
96
  const currentPage = Math.floor(filters.offset / pageSize) + 1;
44
97
  const totalPages = Math.ceil(total / pageSize);
@@ -52,7 +105,35 @@ export const assetsRouter = new Hono()
52
105
  totalPages,
53
106
  hasNextPage: currentPage < totalPages,
54
107
  hasPrevPage: currentPage > 1
55
- }
108
+ },
109
+ // Reported so the admin UI can refuse an oversized file before
110
+ // sending it, without hardcoding a number that drifts from the
111
+ // server's. The browser already calls this endpoint on mount, so
112
+ // it costs no extra request.
113
+ // True when a usage filter was requested before the index exists, so the
114
+ // UI can say "indexing" rather than present an empty or wholly-unused
115
+ // library as fact.
116
+ indexing,
117
+ limits: {
118
+ maxUploadBytes: resolveMaxUploadBytes(c.var.aphexCMS),
119
+ // Reported rather than assumed: the client can't know whether
120
+ // the adapter signs, a key is configured, or the operator
121
+ // opted in — and guessing wrong means every upload fails.
122
+ // Every hop optional-chained: this is a reporting field on a read
123
+ // endpoint, and listing assets must not fail because some part
124
+ // of the upload configuration is absent.
125
+ directUpload: Boolean(c.var.aphexCMS.config?.upload?.direct &&
126
+ c.var.aphexCMS.storageAdapter?.getSignedUploadUrl &&
127
+ c.var.aphexCMS.storageAdapter?.resolvePath &&
128
+ c.var.aphexCMS.config?.security?.secretEncryptionKey)
129
+ },
130
+ images: imageConfig
131
+ ? {
132
+ widths: imageConfig.widths,
133
+ quality: imageConfig.quality,
134
+ configHash: configHashFor(imageConfig)
135
+ }
136
+ : null
56
137
  });
57
138
  }
58
139
  catch (error) {
@@ -81,14 +162,21 @@ export const assetsRouter = new Hono()
81
162
  }
82
163
  const arrayBuffer = await file.arrayBuffer();
83
164
  const buffer = Buffer.from(arrayBuffer);
84
- const SERVER_MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB hard limit
165
+ // The server's ceiling is the configured body limit, not a constant of
166
+ // its own. This used to be a hardcoded 50MB that could never be
167
+ // reached: the `bodyLimit` middleware rejects at 10MB by default, so
168
+ // nothing between 10MB and 50MB ever arrived here to be checked.
169
+ //
170
+ // A client may ask for something *smaller* (a schema field capping its
171
+ // own uploads); it may not ask for something larger.
172
+ const serverMaxSize = resolveMaxUploadBytes(c.var.aphexCMS);
85
173
  const allowedMimeTypesRaw = formData.get('allowedMimeTypes');
86
174
  const maxSizeRaw = formData.get('maxSize');
87
175
  const allowedMimeTypes = allowedMimeTypesRaw ? JSON.parse(allowedMimeTypesRaw) : undefined;
88
176
  const clientMaxSize = maxSizeRaw ? parseInt(maxSizeRaw, 10) : undefined;
89
- const maxSize = clientMaxSize
90
- ? Math.min(clientMaxSize, SERVER_MAX_FILE_SIZE)
91
- : SERVER_MAX_FILE_SIZE;
177
+ const maxSize = clientMaxSize && Number.isFinite(clientMaxSize) && clientMaxSize > 0
178
+ ? Math.min(clientMaxSize, serverMaxSize)
179
+ : serverMaxSize;
92
180
  const validation = validateFile(buffer, file.name, file.type, {
93
181
  allowedMimeTypes,
94
182
  maxSize
@@ -101,6 +189,17 @@ export const assetsRouter = new Hono()
101
189
  const description = formData.get('description') || undefined;
102
190
  const alt = formData.get('alt') || undefined;
103
191
  const creditLine = formData.get('creditLine') || undefined;
192
+ // Video facts the browser read off the file. Bounded rather than trusted:
193
+ // they arrive from a client and land in columns other code reasons about.
194
+ // A negative or absurd value is dropped, not clamped to a wrong number.
195
+ const boundedNumber = (raw, max) => {
196
+ const value = raw == null ? NaN : Number(raw);
197
+ return Number.isFinite(value) && value > 0 && value <= max ? value : undefined;
198
+ };
199
+ // 24h, and 16K — past either, something is wrong with the claim.
200
+ const videoDuration = boundedNumber(formData.get('videoDuration'), 86_400);
201
+ const videoWidth = boundedNumber(formData.get('videoWidth'), 16_384);
202
+ const videoHeight = boundedNumber(formData.get('videoHeight'), 16_384);
104
203
  const schemaType = formData.get('schemaType') || undefined;
105
204
  const fieldPath = formData.get('fieldPath') || undefined;
106
205
  const system = formData.get('system') === 'true' || undefined;
@@ -117,11 +216,16 @@ export const assetsRouter = new Hono()
117
216
  alt,
118
217
  creditLine,
119
218
  createdBy: auth.type === 'session' ? auth.user.id : undefined,
219
+ // Dimensions are columns the image pipeline fills; for video they sit
220
+ // null, so the browser's reading is the only source there is.
221
+ width: videoWidth,
222
+ height: videoHeight,
120
223
  metadata: {
121
224
  schemaType,
122
225
  fieldPath,
123
226
  system,
124
- usage
227
+ usage,
228
+ duration: videoDuration
125
229
  }
126
230
  };
127
231
  const asset = await assetService.uploadAsset(targetOrganizationId, uploadData);
@@ -0,0 +1,18 @@
1
+ import type { DatabaseAdapter } from '../../../db/index.js';
2
+ /**
3
+ * Strip a deleted asset's references out of document data.
4
+ *
5
+ * Shared by the single and bulk delete routes so they can't drift: bulk delete
6
+ * previously skipped this entirely, so a batch delete left every reference
7
+ * behind while an identical single delete cleaned up.
8
+ *
9
+ * The adapter method is optional, so a third-party adapter that doesn't
10
+ * implement it degrades to "references stay behind" rather than failing the
11
+ * delete. That is survivable because asset resolution is null-safe — an
12
+ * unresolved `_ref` renders as nothing rather than throwing.
13
+ *
14
+ * Never throws: the asset is already gone by the time this runs, so a cleanup
15
+ * failure must not turn a successful delete into a 500.
16
+ */
17
+ export declare function clearAssetReferences(databaseAdapter: DatabaseAdapter, organizationId: string, assetId: string): Promise<void>;
18
+ //# sourceMappingURL=clear-asset-references.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clear-asset-references.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/clear-asset-references.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAGzD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,oBAAoB,CACzC,eAAe,EAAE,eAAe,EAChC,cAAc,EAAE,MAAM,EACtB,OAAO,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,CAcf"}
@@ -0,0 +1,31 @@
1
+ import { cmsLogger } from '../../../utils/logger.js';
2
+ /**
3
+ * Strip a deleted asset's references out of document data.
4
+ *
5
+ * Shared by the single and bulk delete routes so they can't drift: bulk delete
6
+ * previously skipped this entirely, so a batch delete left every reference
7
+ * behind while an identical single delete cleaned up.
8
+ *
9
+ * The adapter method is optional, so a third-party adapter that doesn't
10
+ * implement it degrades to "references stay behind" rather than failing the
11
+ * delete. That is survivable because asset resolution is null-safe — an
12
+ * unresolved `_ref` renders as nothing rather than throwing.
13
+ *
14
+ * Never throws: the asset is already gone by the time this runs, so a cleanup
15
+ * failure must not turn a successful delete into a 500.
16
+ */
17
+ export async function clearAssetReferences(databaseAdapter, organizationId, assetId) {
18
+ if (!databaseAdapter.clearAssetReferences) {
19
+ cmsLogger.debug('[Asset Delete] clearAssetReferences not available on adapter');
20
+ return;
21
+ }
22
+ try {
23
+ const cleared = await databaseAdapter.clearAssetReferences(organizationId, assetId);
24
+ if (cleared > 0) {
25
+ cmsLogger.debug(`[Asset Delete] Cleared asset ${assetId} from ${cleared} document(s)`);
26
+ }
27
+ }
28
+ catch (error) {
29
+ cmsLogger.error(`[Asset Delete] Failed clearing references for asset ${assetId}:`, error);
30
+ }
31
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAW5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,QAAQ,CAyNzC,CAAC"}
1
+ {"version":3,"file":"documents.d.ts","sourceRoot":"","sources":["../../../../src/lib/server/api/routes/documents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAW5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,QAAQ,CAqPzC,CAAC"}
@@ -18,9 +18,35 @@ export const documentsRouter = new Hono()
18
18
  }
19
19
  }), async (c) => {
20
20
  try {
21
- const { localAPI } = c.var.aphexCMS;
21
+ const { localAPI, databaseAdapter } = c.var.aphexCMS;
22
22
  const context = authToContext(c.var.auth);
23
23
  const q = c.req.valid('query');
24
+ // Build the back-reference index once for content that predates it.
25
+ //
26
+ // Enqueued from a read because there is no better trigger: the index is
27
+ // consumed by the publish/unpublish guards, and those run in the write
28
+ // path where a bulk walk cannot go. Listing documents is the earliest
29
+ // point at which we know an org is in use and can afford to notice.
30
+ //
31
+ // A fixed idempotency key collapses every list request onto one job,
32
+ // and the handler short-circuits once rows exist, so this settles to a
33
+ // no-op almost immediately.
34
+ if (context.organizationId && databaseAdapter.hasAnyReferences) {
35
+ try {
36
+ if (!(await databaseAdapter.hasAnyReferences(context.organizationId))) {
37
+ const { DOCUMENT_REFERENCES_BACKFILL_JOB } = await import('../../../jobs/asset-reference-jobs.js');
38
+ await databaseAdapter.scheduleJob({
39
+ organizationId: context.organizationId,
40
+ type: DOCUMENT_REFERENCES_BACKFILL_JOB,
41
+ idempotencyKey: `references:backfill:${context.organizationId}`
42
+ });
43
+ }
44
+ }
45
+ catch (err) {
46
+ // Never fail a listing because indexing couldn't be scheduled.
47
+ cmsLogger.debug('[Documents]', 'Could not enqueue reference backfill:', err);
48
+ }
49
+ }
24
50
  const docType = q.type ?? q.docType;
25
51
  const status = q.status;
26
52
  const sortParam = Array.isArray(q.sort) ? q.sort.join(',') : q.sort;
@@ -55,6 +81,7 @@ export const documentsRouter = new Hono()
55
81
  offset,
56
82
  depth,
57
83
  sort: sortParam || undefined,
84
+ search: q.search,
58
85
  perspective,
59
86
  includeChildOrganizations
60
87
  });
@@ -12,6 +12,8 @@ export { createCMSConfig } from '../config.js';
12
12
  export { cmsLogger, setLogger, type Logger } from '../utils/logger.js';
13
13
  export { CMSEngine } from '../engine.js';
14
14
  export { createCMSHook, __notifyAphexConfigChanged, type CMSInstances } from '../hooks.js';
15
+ export * from '../api/limits.js';
16
+ export * from '../images/index.js';
15
17
  export * from '../db/interfaces/index.js';
16
18
  export * from '../storage/index.js';
17
19
  export * from '../storage/interfaces/index.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/server/index.ts"],"names":[],"mappings":"AAIA,cAAc,gBAAgB,CAAC;AAE/B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,gBAAgB,CAAC;AAE/B,cAAc,gBAAgB,CAAC;AAE/B,cAAc,aAAa,CAAC;AAG5B,OAAO,EAAE,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACxF,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AAGzC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAG5C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGpE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAE,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAGxF,cAAc,wBAAwB,CAAC;AAGvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,8BAA8B,CAAC;AAG7C,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAKzD,OAAO,EAAE,GAAG,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAI5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK/F,OAAO,EACN,WAAW,EACX,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,MAAM,kBAAkB,CAAC;AAG1B,cAAc,eAAe,CAAC;AAG9B,cAAc,uBAAuB,CAAC;AAGtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAGhE,OAAO,EAAE,qBAAqB,EAAE,KAAK,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAGxF,OAAO,EACN,oBAAoB,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACN,QAAQ,EACR,cAAc,EACd,WAAW,EACX,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,aAAa,EACb,WAAW,EACX,aAAa,EACb,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EACN,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/server/index.ts"],"names":[],"mappings":"AAIA,cAAc,gBAAgB,CAAC;AAE/B,cAAc,kBAAkB,CAAC;AAEjC,cAAc,gBAAgB,CAAC;AAE/B,cAAc,gBAAgB,CAAC;AAE/B,cAAc,aAAa,CAAC;AAG5B,OAAO,EAAE,SAAS,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACxF,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,0BAA0B,CAAC;AAGzC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAG5C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAGpE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGtC,OAAO,EAAE,aAAa,EAAE,0BAA0B,EAAE,KAAK,YAAY,EAAE,MAAM,UAAU,CAAC;AAKxF,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAEhC,cAAc,wBAAwB,CAAC;AAGvC,cAAc,kBAAkB,CAAC;AACjC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,8BAA8B,CAAC;AAG7C,cAAc,mBAAmB,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAKzD,OAAO,EAAE,GAAG,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAI5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAK/F,OAAO,EACN,WAAW,EACX,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,MAAM,kBAAkB,CAAC;AAG1B,cAAc,eAAe,CAAC;AAG9B,cAAc,uBAAuB,CAAC;AAGtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAGhE,OAAO,EAAE,qBAAqB,EAAE,KAAK,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAGxF,OAAO,EACN,oBAAoB,EACpB,KAAK,aAAa,EAClB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EACN,QAAQ,EACR,cAAc,EACd,WAAW,EACX,aAAa,EACb,uBAAuB,EACvB,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,aAAa,EACb,WAAW,EACX,aAAa,EACb,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,MAAM,oBAAoB,CAAC;AAI5B,OAAO,EACN,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,MAAM,cAAc,CAAC"}
@@ -21,6 +21,10 @@ export { CMSEngine } from '../engine.js';
21
21
  // Hooks integration (SvelteKit server hooks)
22
22
  export { createCMSHook, __notifyAphexConfigChanged } from '../hooks.js';
23
23
  // Database interfaces (no longer export registry or adapters - use adapter packages)
24
+ // Plain constants and pure helpers — no imports of their own, so this adds
25
+ // nothing to any chunk that already touches this barrel.
26
+ export * from '../api/limits.js';
27
+ export * from '../images/index.js';
24
28
  export * from '../db/interfaces/index.js';
25
29
  // Storage adapters and interfaces
26
30
  export * from '../storage/index.js';
@@ -0,0 +1,93 @@
1
+ import type { DatabaseAdapter } from '../db/interfaces/index.js';
2
+ /**
3
+ * Maintains the asset-reference index — which documents use which assets.
4
+ *
5
+ * The sibling of {@link ReferencesService}, which does the same for
6
+ * document-to-document references, and deliberately the same shape: the
7
+ * collection API calls in after a save, the walk is replayed, and the rows for
8
+ * that document are replaced atomically.
9
+ *
10
+ * It exists because "where is this asset used?" was answered by
11
+ * `WHERE published_data::text LIKE '%<assetId>%'` — a full scan casting every
12
+ * document's JSON to text, which no index can serve. Tolerable for one asset,
13
+ * impossible as a filter: "show me unused assets" became assets × documents.
14
+ *
15
+ * **Written inside the document's own write transaction, and failures throw.**
16
+ *
17
+ * This was best-effort post-commit at first, on the reasoning that a stale index
18
+ * costs a wrong badge while the delete guard — which reads the documents
19
+ * themselves — keeps the destructive path safe. The guard part held. The rest
20
+ * did not: the "Unused" filter *is* the index, so a missed row doesn't produce a
21
+ * cosmetic blemish, it invites an editor to delete an asset that is in use. The
22
+ * only thing standing behind them at that point is the guard, and a feature
23
+ * whose correctness depends on a later safety net catching it is not correct.
24
+ *
25
+ * So the index is now maintained the way `appendEvent` maintains the outbox: in
26
+ * the same transaction as the change that caused it, such that a document cannot
27
+ * be saved without its references being recorded. The cost is real and worth
28
+ * naming — a bug in the walk now fails the editor's save rather than being
29
+ * swallowed — which is why {@link collectAssetReferences} is pure, separately
30
+ * tested, and skips malformed references instead of throwing.
31
+ *
32
+ * The delete guard still reads documents rather than this index. Defence in
33
+ * depth is cheap here, and it is what caught the drift this design replaced.
34
+ */
35
+ export declare class AssetReferencesService {
36
+ private databaseAdapter;
37
+ constructor(databaseAdapter: DatabaseAdapter);
38
+ /**
39
+ * Sync the asset-reference rows for a single document. Idempotent — safe to
40
+ * call repeatedly with the same data.
41
+ *
42
+ * Takes the adapter to write through rather than using the injected one, so
43
+ * the caller can hand it a `withTransaction` handle and have the rows commit
44
+ * or roll back with the document. Passing the root adapter is still valid —
45
+ * that's what the backfill does, where there is no document write to join.
46
+ *
47
+ * Draft and published data are walked separately and recorded under their own
48
+ * `plane`, because they answer different questions: an asset used only by an
49
+ * abandoned draft is a different risk from one on a live page.
50
+ */
51
+ syncAssetReferencesFor(db: DatabaseAdapter, organizationId: string, documentId: string, documentType: string, draftData: unknown, publishedData: unknown): Promise<void>;
52
+ /**
53
+ * Compare what the walker found against every asset ref reachable in the data,
54
+ * and report the difference. Returns how many were missed.
55
+ *
56
+ * This is the detector the first four index bugs did without. The walker is a
57
+ * structural allowlist, so it finds references in the shapes it models; the
58
+ * delete guard is a substring scan, so it finds them in shapes nobody
59
+ * anticipated. Every gap between the two has surfaced the same way — an asset
60
+ * reads as unused, an editor selects it, and the delete refuses — which is a
61
+ * terrible way to learn about it, weeks after the shape was introduced.
62
+ *
63
+ * Running it here costs one extra in-memory pass per document during a rebuild
64
+ * that already walks everything, and never touches the request path. It only
65
+ * logs: a gap means the *index* is incomplete, which is exactly what the
66
+ * rebuild cannot fix on its own — the walker has to learn the shape first.
67
+ */
68
+ private reportWalkerGaps;
69
+ /**
70
+ * One-time rebuild for content that predates the index.
71
+ *
72
+ * **Unconditional.** This used to be `backfillIfEmpty`, gated on "does the org
73
+ * have any rows" — which the *incremental* path also creates. So a single
74
+ * document save after the index shipped set that flag forever, the rebuild
75
+ * never ran, and every un-resaved document stayed invisible to the index. The
76
+ * "Unused" filter then listed assets that were plainly in use. Three separate
77
+ * gates were keyed on the same wrong question; this one is now keyed on
78
+ * nothing, and *whether* to run is the caller's business.
79
+ *
80
+ * The caller's marker is the job's versioned idempotency key
81
+ * ({@link ASSET_REFERENCES_BACKFILL_JOB_KEY}): a completed job row is the
82
+ * record that this org has been rebuilt, and bumping the version is how a
83
+ * change in indexing semantics forces exactly one more pass. That is a real
84
+ * marker for a one-time migration, rather than a heuristic that a row's
85
+ * existence can forge.
86
+ *
87
+ * Per-document failures are logged and skipped rather than abandoning the run:
88
+ * this is a repair pass, and one unparseable document should not deny the
89
+ * index to the rest of the org. The job's own retry handles a broader failure.
90
+ */
91
+ backfill(organizationId: string, documentTypes: string[]): Promise<void>;
92
+ }
93
+ //# sourceMappingURL=asset-references-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"asset-references-service.d.ts","sourceRoot":"","sources":["../../src/lib/services/asset-references-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAI9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,sBAAsB;IACtB,OAAO,CAAC,eAAe;gBAAf,eAAe,EAAE,eAAe;IAEpD;;;;;;;;;;;;OAYG;IACG,sBAAsB,CAC3B,EAAE,EAAE,eAAe,EACnB,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,OAAO,EAClB,aAAa,EAAE,OAAO,GACpB,OAAO,CAAC,IAAI,CAAC;IAShB;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,gBAAgB;IAyBxB;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,QAAQ,CAAC,cAAc,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA8F9E"}
@@ -0,0 +1,197 @@
1
+ import { collectAssetReferences, collectAssetIdsUnstructured } from '../utils/asset-reference-walk.js';
2
+ import { cmsLogger } from '../utils/logger.js';
3
+ /**
4
+ * Maintains the asset-reference index — which documents use which assets.
5
+ *
6
+ * The sibling of {@link ReferencesService}, which does the same for
7
+ * document-to-document references, and deliberately the same shape: the
8
+ * collection API calls in after a save, the walk is replayed, and the rows for
9
+ * that document are replaced atomically.
10
+ *
11
+ * It exists because "where is this asset used?" was answered by
12
+ * `WHERE published_data::text LIKE '%<assetId>%'` — a full scan casting every
13
+ * document's JSON to text, which no index can serve. Tolerable for one asset,
14
+ * impossible as a filter: "show me unused assets" became assets × documents.
15
+ *
16
+ * **Written inside the document's own write transaction, and failures throw.**
17
+ *
18
+ * This was best-effort post-commit at first, on the reasoning that a stale index
19
+ * costs a wrong badge while the delete guard — which reads the documents
20
+ * themselves — keeps the destructive path safe. The guard part held. The rest
21
+ * did not: the "Unused" filter *is* the index, so a missed row doesn't produce a
22
+ * cosmetic blemish, it invites an editor to delete an asset that is in use. The
23
+ * only thing standing behind them at that point is the guard, and a feature
24
+ * whose correctness depends on a later safety net catching it is not correct.
25
+ *
26
+ * So the index is now maintained the way `appendEvent` maintains the outbox: in
27
+ * the same transaction as the change that caused it, such that a document cannot
28
+ * be saved without its references being recorded. The cost is real and worth
29
+ * naming — a bug in the walk now fails the editor's save rather than being
30
+ * swallowed — which is why {@link collectAssetReferences} is pure, separately
31
+ * tested, and skips malformed references instead of throwing.
32
+ *
33
+ * The delete guard still reads documents rather than this index. Defence in
34
+ * depth is cheap here, and it is what caught the drift this design replaced.
35
+ */
36
+ export class AssetReferencesService {
37
+ databaseAdapter;
38
+ constructor(databaseAdapter) {
39
+ this.databaseAdapter = databaseAdapter;
40
+ }
41
+ /**
42
+ * Sync the asset-reference rows for a single document. Idempotent — safe to
43
+ * call repeatedly with the same data.
44
+ *
45
+ * Takes the adapter to write through rather than using the injected one, so
46
+ * the caller can hand it a `withTransaction` handle and have the rows commit
47
+ * or roll back with the document. Passing the root adapter is still valid —
48
+ * that's what the backfill does, where there is no document write to join.
49
+ *
50
+ * Draft and published data are walked separately and recorded under their own
51
+ * `plane`, because they answer different questions: an asset used only by an
52
+ * abandoned draft is a different risk from one on a live page.
53
+ */
54
+ async syncAssetReferencesFor(db, organizationId, documentId, documentType, draftData, publishedData) {
55
+ if (!db.replaceAssetReferences)
56
+ return;
57
+ const rows = [
58
+ ...collectAssetReferences(draftData).map((r) => ({ ...r, plane: 'draft' })),
59
+ ...collectAssetReferences(publishedData).map((r) => ({ ...r, plane: 'published' }))
60
+ ];
61
+ await db.replaceAssetReferences(organizationId, documentId, documentType, rows);
62
+ }
63
+ /**
64
+ * Compare what the walker found against every asset ref reachable in the data,
65
+ * and report the difference. Returns how many were missed.
66
+ *
67
+ * This is the detector the first four index bugs did without. The walker is a
68
+ * structural allowlist, so it finds references in the shapes it models; the
69
+ * delete guard is a substring scan, so it finds them in shapes nobody
70
+ * anticipated. Every gap between the two has surfaced the same way — an asset
71
+ * reads as unused, an editor selects it, and the delete refuses — which is a
72
+ * terrible way to learn about it, weeks after the shape was introduced.
73
+ *
74
+ * Running it here costs one extra in-memory pass per document during a rebuild
75
+ * that already walks everything, and never touches the request path. It only
76
+ * logs: a gap means the *index* is incomplete, which is exactly what the
77
+ * rebuild cannot fix on its own — the walker has to learn the shape first.
78
+ */
79
+ reportWalkerGaps(documentId, documentType, draftData, publishedData) {
80
+ let missed = 0;
81
+ for (const [plane, data] of [
82
+ ['draft', draftData],
83
+ ['published', publishedData]
84
+ ]) {
85
+ const indexed = new Set(collectAssetReferences(data).map((r) => r.assetId));
86
+ const reachable = collectAssetIdsUnstructured(data);
87
+ const gaps = [...reachable].filter((id) => !indexed.has(id));
88
+ if (gaps.length === 0)
89
+ continue;
90
+ missed += gaps.length;
91
+ cmsLogger.warn('[AssetReferences]', `Walker missed ${gaps.length} reference(s) in ${documentType} ${documentId} (${plane}): ${gaps.join(', ')}`);
92
+ }
93
+ return missed;
94
+ }
95
+ /**
96
+ * One-time rebuild for content that predates the index.
97
+ *
98
+ * **Unconditional.** This used to be `backfillIfEmpty`, gated on "does the org
99
+ * have any rows" — which the *incremental* path also creates. So a single
100
+ * document save after the index shipped set that flag forever, the rebuild
101
+ * never ran, and every un-resaved document stayed invisible to the index. The
102
+ * "Unused" filter then listed assets that were plainly in use. Three separate
103
+ * gates were keyed on the same wrong question; this one is now keyed on
104
+ * nothing, and *whether* to run is the caller's business.
105
+ *
106
+ * The caller's marker is the job's versioned idempotency key
107
+ * ({@link ASSET_REFERENCES_BACKFILL_JOB_KEY}): a completed job row is the
108
+ * record that this org has been rebuilt, and bumping the version is how a
109
+ * change in indexing semantics forces exactly one more pass. That is a real
110
+ * marker for a one-time migration, rather than a heuristic that a row's
111
+ * existence can forge.
112
+ *
113
+ * Per-document failures are logged and skipped rather than abandoning the run:
114
+ * this is a repair pass, and one unparseable document should not deny the
115
+ * index to the rest of the org. The job's own retry handles a broader failure.
116
+ */
117
+ async backfill(organizationId, documentTypes) {
118
+ if (!this.databaseAdapter.replaceAssetReferences)
119
+ return;
120
+ try {
121
+ // Every type actually present, not just the registered ones.
122
+ //
123
+ // Removing a schema type doesn't remove its documents, and those
124
+ // documents keep referencing whatever assets they always did. The delete
125
+ // guard reads documents unfiltered, so an index built from the schema
126
+ // registry disagrees with it on precisely those assets: "Unused" offers
127
+ // them for deletion and the delete then refuses, with the blocking
128
+ // document nowhere to be found in the admin.
129
+ //
130
+ // Walking them is possible here only because `collectAssetReferences`
131
+ // reads raw JSON and needs no schema. The document-to-document index
132
+ // can't do this — its walker is schema-aware — which is why
133
+ // `ReferencesService.backfill` still takes registered schemas.
134
+ const types = this.databaseAdapter.listStoredDocumentTypes
135
+ ? [
136
+ ...new Set([
137
+ ...documentTypes,
138
+ ...(await this.databaseAdapter.listStoredDocumentTypes(organizationId))
139
+ ])
140
+ ]
141
+ : documentTypes;
142
+ cmsLogger.info('[AssetReferences]', `Rebuilding asset-reference index for org ${organizationId} over ${types.length} type(s)`);
143
+ let indexed = 0;
144
+ let missed = 0;
145
+ for (const type of types) {
146
+ // Paged rather than loaded whole: this runs over an entire content set,
147
+ // and the point of the index is to stop asset questions costing one.
148
+ const PAGE = 100;
149
+ for (let offset = 0;; offset += PAGE) {
150
+ const page = await this.databaseAdapter.findManyDocAdvanced(organizationId, type, {
151
+ limit: PAGE,
152
+ offset
153
+ });
154
+ const docs = page?.docs ?? [];
155
+ if (docs.length === 0)
156
+ break;
157
+ for (const doc of docs) {
158
+ try {
159
+ await this.syncAssetReferencesFor(this.databaseAdapter, organizationId, doc.id, type, doc.draftData, doc.publishedData);
160
+ indexed++;
161
+ missed += this.reportWalkerGaps(doc.id, type, doc.draftData, doc.publishedData);
162
+ }
163
+ catch (err) {
164
+ cmsLogger.error('[AssetReferences]', 'Skipping document', doc.id, err);
165
+ }
166
+ }
167
+ if (docs.length < PAGE)
168
+ break;
169
+ }
170
+ }
171
+ if (missed > 0) {
172
+ cmsLogger.warn('[AssetReferences]', `${missed} reference(s) were reachable in the data but not recognised by the walker. ` +
173
+ `Assets referenced only that way will show as unused and then refuse to delete. ` +
174
+ `Add the shape to collectAssetReferences and bump REFERENCE_BACKFILL_VERSION.`);
175
+ }
176
+ cmsLogger.info('[AssetReferences]', `Backfill complete — ${indexed} document(s)`);
177
+ }
178
+ catch (err) {
179
+ // Rethrow. This used to be swallowed, back when the rebuild ran at boot
180
+ // and taking the app down over it would have been worse.
181
+ //
182
+ // As a queued job that is exactly backwards. Swallowing means a failure
183
+ // halfway through — a dropped connection at document 400 of 900 — returns
184
+ // normally, the worker marks the job **completed**, and the versioned
185
+ // idempotency key is spent. The index stays permanently half-built and
186
+ // nothing will ever re-run it: a failure that presents as success, which
187
+ // is the same trap `backfillIfEmpty` set and the hardest kind to notice.
188
+ //
189
+ // Throwing hands it to the queue, which is what the queue is for — retry
190
+ // with backoff, then dead-letter. Individual documents are still caught
191
+ // above, so one unparseable document doesn't abandon the run; this is
192
+ // only for failures that are actually systemic.
193
+ cmsLogger.error('[AssetReferences]', 'Backfill failed — will retry', err);
194
+ throw err;
195
+ }
196
+ }
197
+ }