qarpeo 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/chunks/tools.mjs +993 -31
  2. package/dist/cli/index.mjs +1071 -31
  3. package/dist/fate/index.d.ts +9 -1
  4. package/dist/fate/index.mjs +20 -3
  5. package/dist/module.mjs +296 -750
  6. package/dist/runtime/browser.mjs +2 -2
  7. package/dist/runtime/comments-server.d.ts +3 -0
  8. package/dist/runtime/comments-server.mjs +2 -0
  9. package/dist/runtime/comments.d.ts +0 -2
  10. package/dist/runtime/comments.mjs +0 -2
  11. package/dist/runtime/db.d.ts +10 -9
  12. package/dist/runtime/db.mjs +79 -8
  13. package/dist/runtime/drizzle.mjs +21 -6
  14. package/dist/runtime/index.d.ts +4 -0
  15. package/dist/runtime/realtime-server.d.ts +4 -0
  16. package/dist/runtime/realtime-server.mjs +13 -0
  17. package/dist/runtime/realtime.d.ts +1 -4
  18. package/dist/runtime/realtime.mjs +0 -13
  19. package/dist/runtime/replica.d.ts +27 -0
  20. package/dist/runtime/replica.mjs +229 -0
  21. package/dist/runtime/server/durable-objects/agent.mjs +14 -2
  22. package/dist/runtime/server/durable-objects/room.d.ts +10 -0
  23. package/dist/runtime/server/durable-objects/room.mjs +119 -28
  24. package/dist/runtime/server/middleware/devtools.mjs +1 -1
  25. package/dist/runtime/server/middleware/tenancy.mjs +7 -4
  26. package/dist/runtime/server/plugins/store.mjs +1 -1
  27. package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
  28. package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
  29. package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
  30. package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
  31. package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
  32. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
  33. package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
  34. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
  35. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
  36. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
  37. package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
  38. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
  39. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
  40. package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
  41. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
  42. package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
  43. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
  44. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
  45. package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
  46. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
  47. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
  48. package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
  49. package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
  50. package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
  51. package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
  52. package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
  53. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
  54. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
  55. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
  56. package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
  57. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
  58. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
  59. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
  60. package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
  61. package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
  62. package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
  63. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
  64. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
  65. package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
  66. package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
  67. package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
  68. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
  69. package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
  70. package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
  71. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
  72. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
  73. package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
  74. package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
  75. package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
  76. package/dist/runtime/server/routes/fate.d.ts +6 -0
  77. package/dist/runtime/server/routes/fate.mjs +32 -3
  78. package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
  79. package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
  80. package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
  81. package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
  82. package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
  83. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
  84. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
  85. package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
  86. package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
  87. package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
  88. package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
  89. package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
  90. package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
  91. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  92. package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
  93. package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
  94. package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
  95. package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
  96. package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
  97. package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
  98. package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
  99. package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
  100. package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
  101. package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
  102. package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
  103. package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
  104. package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
  105. package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
  106. package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
  107. package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
  108. package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
  109. package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
  110. package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
  111. package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
  112. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
  113. package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
  114. package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
  115. package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
  116. package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
  117. package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
  118. package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
  119. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
  120. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
  121. package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
  122. package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
  123. package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
  124. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
  125. package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
  126. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
  127. package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
  128. package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
  129. package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
  130. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
  131. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
  132. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
  133. package/dist/runtime/server/utils/ai.d.ts +6 -0
  134. package/dist/runtime/server/utils/ai.mjs +12 -2
  135. package/dist/runtime/server/utils/analytics-query.mjs +8 -4
  136. package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
  137. package/dist/runtime/server/utils/browser-utils.mjs +135 -0
  138. package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
  139. package/dist/runtime/server/utils/cms/cache.mjs +95 -0
  140. package/dist/runtime/server/utils/cms/common.mjs +1 -1
  141. package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
  142. package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
  143. package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
  144. package/dist/runtime/server/utils/cms/path.d.ts +8 -0
  145. package/dist/runtime/server/utils/cms/path.mjs +23 -0
  146. package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
  147. package/dist/runtime/server/utils/cms/queries.mjs +366 -0
  148. package/dist/runtime/server/utils/cms/references.d.ts +48 -0
  149. package/dist/runtime/server/utils/cms/references.mjs +309 -0
  150. package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
  151. package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
  152. package/dist/runtime/server/utils/cms/sync.mjs +3 -3
  153. package/dist/runtime/server/utils/cms.d.ts +5 -82
  154. package/dist/runtime/server/utils/cms.mjs +28 -1367
  155. package/dist/runtime/server/utils/comments.d.ts +11 -0
  156. package/dist/runtime/server/utils/comments.mjs +65 -17
  157. package/dist/runtime/server/utils/crypto.mjs +1 -1
  158. package/dist/runtime/server/utils/domains.mjs +9 -0
  159. package/dist/runtime/server/utils/drizzle.d.ts +26 -1
  160. package/dist/runtime/server/utils/drizzle.mjs +78 -19
  161. package/dist/runtime/server/utils/email-inbound.mjs +9 -1
  162. package/dist/runtime/server/utils/impersonation.mjs +58 -1
  163. package/dist/runtime/server/utils/lock.d.ts +11 -0
  164. package/dist/runtime/server/utils/lock.mjs +4 -0
  165. package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
  166. package/dist/runtime/server/utils/mail.d.ts +2 -1
  167. package/dist/runtime/server/utils/mail.mjs +17 -11
  168. package/dist/runtime/server/utils/notifications.d.ts +13 -4
  169. package/dist/runtime/server/utils/notifications.mjs +20 -4
  170. package/dist/runtime/server/utils/organization.mjs +36 -1
  171. package/dist/runtime/server/utils/passwordless.mjs +8 -0
  172. package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
  173. package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
  174. package/dist/runtime/server/utils/payments/common.d.ts +45 -0
  175. package/dist/runtime/server/utils/payments/common.mjs +234 -0
  176. package/dist/runtime/server/utils/payments/index.d.ts +9 -0
  177. package/dist/runtime/server/utils/payments/index.mjs +21 -0
  178. package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
  179. package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
  180. package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
  181. package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
  182. package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
  183. package/dist/runtime/server/utils/payments/polar.mjs +66 -0
  184. package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
  185. package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
  186. package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
  187. package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
  188. package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
  189. package/dist/runtime/server/utils/payments/usage.mjs +143 -0
  190. package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
  191. package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
  192. package/dist/runtime/server/utils/payments.d.ts +1 -158
  193. package/dist/runtime/server/utils/payments.mjs +1 -1289
  194. package/dist/runtime/server/utils/queue.d.ts +2 -0
  195. package/dist/runtime/server/utils/queue.mjs +34 -21
  196. package/dist/runtime/server/utils/rag.mjs +30 -17
  197. package/dist/runtime/server/utils/realtime.d.ts +5 -1
  198. package/dist/runtime/server/utils/realtime.mjs +43 -7
  199. package/dist/runtime/server/utils/session.mjs +16 -3
  200. package/dist/runtime/server/utils/sso.d.ts +3 -0
  201. package/dist/runtime/server/utils/sso.mjs +43 -0
  202. package/dist/runtime/server/utils/storage.mjs +12 -1
  203. package/dist/runtime/server/utils/store/cart.d.ts +63 -0
  204. package/dist/runtime/server/utils/store/cart.mjs +542 -0
  205. package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
  206. package/dist/runtime/server/utils/store/checkout.mjs +118 -0
  207. package/dist/runtime/server/utils/store/common.d.ts +29 -0
  208. package/dist/runtime/server/utils/store/common.mjs +479 -0
  209. package/dist/runtime/server/utils/store/index.d.ts +7 -0
  210. package/dist/runtime/server/utils/store/index.mjs +30 -0
  211. package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
  212. package/dist/runtime/server/utils/store/inventory.mjs +190 -0
  213. package/dist/runtime/server/utils/store/orders.d.ts +60 -0
  214. package/dist/runtime/server/utils/store/orders.mjs +590 -0
  215. package/dist/runtime/server/utils/store/products.d.ts +35 -0
  216. package/dist/runtime/server/utils/store/products.mjs +461 -0
  217. package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
  218. package/dist/runtime/server/utils/store/vendor.mjs +68 -0
  219. package/dist/runtime/server/utils/store.d.ts +1 -207
  220. package/dist/runtime/server/utils/store.mjs +1 -2227
  221. package/dist/runtime/server/utils/string.d.ts +1 -1
  222. package/dist/runtime/server/utils/string.mjs +12 -4
  223. package/dist/runtime/server/utils/tenant.mjs +19 -5
  224. package/dist/runtime/server/utils/tracker.mjs +2 -0
  225. package/dist/runtime/server.d.ts +3 -3
  226. package/dist/runtime/server.mjs +4 -4
  227. package/dist/runtime/storage-server.d.ts +2 -0
  228. package/dist/runtime/storage-server.mjs +1 -0
  229. package/dist/runtime/storage.d.ts +1 -1
  230. package/dist/runtime/storage.mjs +0 -1
  231. package/dist/runtime/store.d.ts +0 -1
  232. package/dist/runtime/store.mjs +0 -1
  233. package/dist/runtime/test-utils.d.ts +4 -0
  234. package/dist/runtime/test-utils.mjs +54 -0
  235. package/dist/runtime/types/d1.d.ts +43 -0
  236. package/dist/runtime/types/drizzle.d.ts +6 -0
  237. package/dist/runtime/types/store.d.ts +1 -1
  238. package/dist/types/analytics.d.ts +80 -0
  239. package/dist/types/auth.d.ts +282 -0
  240. package/dist/types/cache.d.ts +55 -0
  241. package/dist/types/comments.d.ts +130 -0
  242. package/dist/types/db.d.ts +29 -0
  243. package/dist/types/email.d.ts +182 -0
  244. package/dist/types/index.d.ts +22 -0
  245. package/dist/types/jobs.d.ts +58 -0
  246. package/dist/types/notifications.d.ts +77 -0
  247. package/dist/types/options.d.ts +363 -0
  248. package/dist/types/payments.d.ts +145 -0
  249. package/dist/types/ratelimit.d.ts +71 -0
  250. package/dist/types/realtime.d.ts +136 -0
  251. package/dist/types/site.d.ts +121 -0
  252. package/dist/types/storage.d.ts +164 -0
  253. package/dist/types/store-options.d.ts +199 -0
  254. package/dist/types/tenant.d.ts +100 -0
  255. package/dist/types.d.ts +1 -2174
  256. package/dist/utils/migration-lock.d.ts +139 -0
  257. package/dist/utils/pkg.d.ts +14 -1
  258. package/dist/utils/schema-diff.d.ts +39 -0
  259. package/package.json +55 -17
  260. package/dist/chunks/auth-schema.mjs +0 -364
@@ -1,29 +1,3 @@
1
- import { createError, getCookie } from "nuxt/server";
2
- import { getKVBinding } from "../../kv.mjs";
3
- import { fireCMSWebhooks, fireCMSDeployTrigger } from "./cms-events.mjs";
4
- import {
5
- getCMSDb,
6
- nanoid,
7
- getCMSConfig,
8
- resolveCollectionApproval,
9
- getCMSTenantId,
10
- getCMSTenantPrefix,
11
- cmsCollectionTbl,
12
- cmsEntryTbl,
13
- cmsRevisionTbl,
14
- cmsCategoryTbl
15
- } from "./cms/common.mjs";
16
- import { resolveTableName } from "./table-names.mjs";
17
- const userTbl = (e) => resolveTableName("user", e);
18
- import { syncEntryToGit, registerEntryFormatter } from "./cms/git.mjs";
19
- import {
20
- parseMarkdownAST,
21
- processMarkdown,
22
- formatFrontmatter
23
- } from "./cms/markdown.mjs";
24
- import { verifyPreviewToken } from "./cms/preview.mjs";
25
- import { syncCMSEntryTags } from "./cms/taxonomy.mjs";
26
- import { getAuthContext } from "./context.mjs";
27
1
  export * from "./cms/common.mjs";
28
2
  export * from "./cms/path.mjs";
29
3
  export * from "./cms/markdown.mjs";
@@ -34,1344 +8,31 @@ export * from "./cms/taxonomy.mjs";
34
8
  export * from "./cms/navigation.mjs";
35
9
  export * from "./cms/sync.mjs";
36
10
  export * from "./cms/collections.mjs";
37
- export function formatEntryAsMarkdown(entry) {
38
- const e = entry;
39
- let metadata = {};
40
- try {
41
- if (e.metadata && typeof e.metadata === "object") {
42
- metadata = e.metadata;
43
- } else if (e.metadataJson || e.metadata_json) {
44
- metadata = JSON.parse(e.metadataJson || e.metadata_json);
45
- }
46
- } catch {
47
- }
48
- const cleanMetadata = {};
49
- for (const [k, v] of Object.entries(metadata)) {
50
- if (!k.startsWith("_")) {
51
- cleanMetadata[k] = v;
52
- }
53
- }
54
- const serializedMetadata = serializeReferencesForFrontmatter(cleanMetadata);
55
- const rawTags = e.tags;
56
- const tags = Array.isArray(rawTags) ? rawTags : typeof rawTags === "string" && rawTags.length > 0 ? rawTags.split(",").map((t) => t.trim()) : void 0;
57
- const fmData = {
58
- title: e.title,
59
- slug: e.slug,
60
- ...e.description ? { description: e.description } : {},
61
- ...e.coverImage || e.cover_image ? { coverImage: e.coverImage || e.cover_image } : {},
62
- ...tags && tags.length > 0 ? { tags } : {},
63
- ...typeof e.order === "number" && e.order !== 0 ? { order: e.order } : {},
64
- ...e.status && e.status !== "published" ? { status: e.status } : {},
65
- ...serializedMetadata
66
- };
67
- const body = e.contentMd ?? e.content_md ?? "";
68
- return formatFrontmatter(fmData, body);
69
- }
70
- registerEntryFormatter(formatEntryAsMarkdown);
71
- export function projectCMSEntry(entry, fields) {
72
- if (!entry) return null;
73
- if (!fields) return entry;
74
- const fieldList = Array.isArray(fields) ? fields.flatMap((f) => typeof f === "string" ? f.split(",") : []).map((s) => s.trim()).filter(Boolean) : String(fields).split(",").map((s) => s.trim()).filter(Boolean);
75
- if (!fieldList.length) return entry;
76
- const projected = {};
77
- for (const field of fieldList) {
78
- if (field in entry) {
79
- projected[field] = entry[field];
80
- }
81
- }
82
- return projected;
83
- }
84
- export function rowToEntry(row) {
85
- let metadata;
86
- try {
87
- metadata = JSON.parse(row.metadata_json || "{}");
88
- } catch {
89
- metadata = {};
90
- }
91
- const toc = metadata?._toc || void 0;
92
- const nav = metadata?._nav || void 0;
93
- const tocObj = toc || { links: [] };
94
- const ast = metadata?._ast || void 0;
95
- if (metadata) {
96
- delete metadata._ast;
97
- delete metadata._toc;
98
- delete metadata._nav;
99
- }
100
- const body = ast && Array.isArray(ast.nodes) ? {
101
- ...ast,
102
- toc: tocObj
103
- } : {
104
- value: row.content_md || "",
105
- content: row.content_md || "",
106
- toc: tocObj
107
- };
108
- const rawText = row.content_md || "";
109
- const words = rawText.trim() ? rawText.trim().split(/\s+/).length : 0;
110
- const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
111
- const readingTime = row.reading_time || metadata?.readingTime || metadata?.reading_time || calculatedReadingTime;
112
- return {
113
- ...metadata,
114
- id: row.id,
115
- collectionId: row.collection_id,
116
- slug: row.slug,
117
- path: row.path || void 0,
118
- title: row.title,
119
- description: row.description,
120
- coverImage: row.cover_image,
121
- tags: row.tags,
122
- order: row.order,
123
- contentMd: row.content_md,
124
- contentHtml: row.content_html,
125
- body,
126
- toc: toc || { links: [] },
127
- navigation: nav,
128
- readingTime,
129
- categoryId: row.category_id || void 0,
130
- subCategoryId: row.sub_category_id || void 0,
131
- featured: Boolean(row.featured),
132
- viewCount: row.view_count || 0,
133
- metadataJson: row.metadata_json,
134
- metadata: { ...metadata, readingTime },
135
- status: row.status,
136
- source: row.source,
137
- filePath: row.file_path,
138
- contentHash: row.content_hash,
139
- authorId: row.author_id,
140
- publishedAt: row.published_at,
141
- tenantId: row.tenant_id || void 0,
142
- locale: row.locale || "en",
143
- version: row.version || "latest",
144
- createdAt: row.created_at,
145
- updatedAt: row.updated_at
146
- };
147
- }
148
- function isReferenceValue(v) {
149
- return !!v && typeof v === "object" && !Array.isArray(v) && typeof v.collectionId === "string" && typeof v.slug === "string";
150
- }
151
- export async function getCollectionFields(event, collectionId) {
152
- const config = getCMSConfig(event);
153
- const configFields = config.collections?.[collectionId]?.fields;
154
- let dbFields;
155
- try {
156
- const db = getCMSDb(event);
157
- const row = await db.prepare(`SELECT schema_json FROM ${cmsCollectionTbl(event)} WHERE id = ?`).bind(collectionId).first();
158
- if (row?.schema_json) {
159
- dbFields = JSON.parse(row.schema_json);
160
- }
161
- } catch {
162
- }
163
- return { ...configFields, ...dbFields };
164
- }
165
- async function fetchEntryRef(event, collectionId, slugOrId) {
166
- const db = getCMSDb(event);
167
- const tenantId = getCMSTenantId(event);
168
- const row = await db.prepare(
169
- `SELECT id, collection_id, slug, title FROM ${cmsEntryTbl(event)}
170
- WHERE collection_id = ? AND (slug = ? OR id = ?)
171
- ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""}
172
- LIMIT 1`
173
- ).bind(
174
- ...tenantId ? [collectionId, slugOrId, slugOrId, tenantId] : [collectionId, slugOrId, slugOrId]
175
- ).first();
176
- if (!row) return null;
177
- return {
178
- id: row.id,
179
- collectionId: row.collection_id,
180
- slug: row.slug,
181
- title: row.title
182
- };
183
- }
184
- async function resolveReferenceInput(event, input, defaultTargetCollectionId, filter, fieldName) {
185
- if (input == null || input === "") {
186
- throw createError({ statusCode: 400, message: "Reference value is required" });
187
- }
188
- let collectionId;
189
- let slugOrId;
190
- if (typeof input === "string") {
191
- const trimmed = input.trim();
192
- if (!trimmed) {
193
- throw createError({ statusCode: 400, message: "Reference value is required" });
194
- }
195
- const slashIdx = trimmed.indexOf("/");
196
- if (slashIdx > 0) {
197
- collectionId = trimmed.slice(0, slashIdx);
198
- slugOrId = trimmed.slice(slashIdx + 1);
199
- } else {
200
- collectionId = defaultTargetCollectionId;
201
- slugOrId = trimmed;
202
- }
203
- } else if (isReferenceValue(input)) {
204
- collectionId = input.collectionId;
205
- slugOrId = input.id || input.slug;
206
- } else {
207
- throw createError({
208
- statusCode: 400,
209
- message: 'Invalid reference value: expected an id, "collection/slug", or a reference object'
210
- });
211
- }
212
- if (!collectionId || !slugOrId) {
213
- throw createError({
214
- statusCode: 400,
215
- message: "Reference value is missing collection or slug/id"
216
- });
217
- }
218
- const resolved = await fetchEntryRef(event, collectionId, slugOrId);
219
- if (!resolved) {
220
- throw createError({
221
- statusCode: 400,
222
- message: `Referenced entry "${slugOrId}" not found in collection "${collectionId}"`
223
- });
224
- }
225
- if (filter && Object.keys(filter).length > 0) {
226
- const fullEntry = await getCMSEntry(event, collectionId, resolved.id, { preview: true });
227
- if (fullEntry) {
228
- for (const [key, expected] of Object.entries(filter)) {
229
- const actual = fullEntry.metadata?.[key];
230
- if (actual !== expected) {
231
- const label = fieldName ? `reference field "${fieldName}"` : "reference";
232
- throw createError({
233
- statusCode: 400,
234
- message: `The ${label} target "${resolved.slug}" does not match the required filter (${key} must be ${String(expected)})`
235
- });
236
- }
237
- }
238
- }
239
- }
240
- return resolved;
241
- }
242
- async function validateAndNormalizeReferenceFields(event, collectionId, metadata) {
243
- const fields = await getCollectionFields(event, collectionId);
244
- for (const [fieldName, fieldDef] of Object.entries(fields)) {
245
- if (fieldDef.type !== "reference" || !fieldDef.reference) continue;
246
- const refOpts = fieldDef.reference;
247
- const multiple = refOpts.multiple === true;
248
- const value = metadata[fieldName];
249
- if (value == null || value === "") {
250
- if (fieldDef.required) {
251
- throw createError({
252
- statusCode: 400,
253
- message: `Reference field "${fieldName}" is required`
254
- });
255
- }
256
- if (multiple) metadata[fieldName] = [];
257
- continue;
258
- }
259
- if (multiple) {
260
- const items = Array.isArray(value) ? value : [value];
261
- const resolved = [];
262
- for (const item of items) {
263
- if (item == null || item === "") continue;
264
- resolved.push(
265
- await resolveReferenceInput(event, item, refOpts.to, refOpts.filter, fieldName)
266
- );
267
- }
268
- metadata[fieldName] = resolved;
269
- } else {
270
- metadata[fieldName] = await resolveReferenceInput(
271
- event,
272
- value,
273
- refOpts.to,
274
- refOpts.filter,
275
- fieldName
276
- );
277
- }
278
- }
279
- return metadata;
280
- }
281
- function resolveComponentDefinition(fieldDef, config) {
282
- if (fieldDef.type !== "component") return null;
283
- const compOpts = fieldDef.component;
284
- if (!compOpts) return null;
285
- if (typeof compOpts === "string") {
286
- return config.components?.[compOpts] ?? null;
287
- }
288
- if (compOpts.name) {
289
- return config.components?.[compOpts.name] ?? null;
290
- }
291
- if (compOpts.fields) {
292
- return { fields: compOpts.fields };
293
- }
294
- return null;
295
- }
296
- async function validateAndNormalizeComponentFields(event, collectionId, metadata) {
297
- const config = getCMSConfig(event);
298
- const fields = await getCollectionFields(event, collectionId);
299
- for (const [fieldName, fieldDef] of Object.entries(fields)) {
300
- if (fieldDef.type !== "component") continue;
301
- const compDef = resolveComponentDefinition(fieldDef, config);
302
- if (!compDef) continue;
303
- const compOpts = typeof fieldDef.component === "object" ? fieldDef.component : null;
304
- const isRepeatable = fieldDef.repeatable || (compOpts?.repeatable ?? false);
305
- const value = metadata[fieldName];
306
- if (value == null || value === "") {
307
- if (fieldDef.required) {
308
- throw createError({
309
- statusCode: 400,
310
- message: `Component field "${fieldName}" is required`
311
- });
312
- }
313
- if (isRepeatable) metadata[fieldName] = [];
314
- continue;
315
- }
316
- if (isRepeatable && !Array.isArray(value)) {
317
- metadata[fieldName] = [value];
318
- }
319
- if (isRepeatable && compOpts?.max != null && Array.isArray(metadata[fieldName])) {
320
- const arr = metadata[fieldName];
321
- if (arr.length > compOpts.max) {
322
- throw createError({
323
- statusCode: 400,
324
- message: `Component field "${fieldName}" exceeds maximum of ${compOpts.max} items`
325
- });
326
- }
327
- }
328
- if (isRepeatable && compOpts?.min != null && Array.isArray(metadata[fieldName])) {
329
- const arr = metadata[fieldName];
330
- if (arr.length < compOpts.min) {
331
- throw createError({
332
- statusCode: 400,
333
- message: `Component field "${fieldName}" requires at least ${compOpts.min} items`
334
- });
335
- }
336
- }
337
- }
338
- return metadata;
339
- }
340
- export function defineCMSComponent(def) {
341
- return def;
342
- }
343
- export async function resolveReference(event, ref) {
344
- if (!ref || !ref.id && !ref.slug) return null;
345
- const collectionId = ref.collectionId;
346
- if (!collectionId) return null;
347
- const slugOrId = ref.id || ref.slug;
348
- if (!slugOrId) return null;
349
- return getCMSEntry(event, collectionId, slugOrId);
350
- }
351
- async function populateReferenceFields(event, entry, populate) {
352
- const resEntry = { ...entry };
353
- if (resEntry.authorId && (populate === true || Array.isArray(populate) && (populate.includes("author") || populate.includes("authorId")))) {
354
- try {
355
- const db = getCMSDb(event);
356
- if (db) {
357
- const userRow = await db.prepare(
358
- `SELECT id, name, email, image, username, avatar, role, bio FROM ${userTbl(event)} WHERE id = ? LIMIT 1`
359
- ).bind(resEntry.authorId).first();
360
- if (userRow) {
361
- resEntry.author = {
362
- id: userRow.id,
363
- name: userRow.name || userRow.username || (userRow.email ? userRow.email.split("@")[0] : "User"),
364
- username: userRow.username || null,
365
- email: userRow.email || null,
366
- avatar: userRow.avatar || userRow.image || null,
367
- role: userRow.role || null,
368
- bio: userRow.bio || null
369
- };
370
- }
371
- }
372
- } catch {
373
- }
374
- }
375
- if (!resEntry.metadata || Object.keys(resEntry.metadata).length === 0) return resEntry;
376
- const fields = await getCollectionFields(event, resEntry.collectionId);
377
- const populatedMeta = { ...resEntry.metadata };
378
- for (const [fieldName, fieldDef] of Object.entries(fields)) {
379
- if (fieldDef.type !== "reference") continue;
380
- if (Array.isArray(populate) && !populate.includes(fieldName)) continue;
381
- const value = populatedMeta[fieldName];
382
- if (value == null) continue;
383
- if (Array.isArray(value)) {
384
- populatedMeta[fieldName] = await Promise.all(
385
- value.filter(isReferenceValue).map(async (r) => ({
386
- ...r,
387
- entry: await resolveReference(event, r)
388
- }))
389
- );
390
- } else if (isReferenceValue(value)) {
391
- populatedMeta[fieldName] = { ...value, entry: await resolveReference(event, value) };
392
- }
393
- }
394
- return { ...resEntry, metadata: populatedMeta };
395
- }
396
- const REFERENCE_PATH_RE = /^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/;
397
- function serializeReferencesForFrontmatter(metadata) {
398
- const out = {};
399
- for (const [k, v] of Object.entries(metadata)) {
400
- if (isReferenceValue(v)) {
401
- out[k] = `${v.collectionId}/${v.slug}`;
402
- } else if (Array.isArray(v) && v.length > 0 && v.every((item) => isReferenceValue(item))) {
403
- out[k] = v.map(
404
- (item) => `${item.collectionId}/${item.slug}`
405
- );
406
- } else {
407
- out[k] = v;
408
- }
409
- }
410
- return out;
411
- }
412
- export async function resolveReferenceFieldsFromFrontmatter(event, collectionId, fm) {
413
- const fields = await getCollectionFields(event, collectionId);
414
- for (const [fieldName, fieldDef] of Object.entries(fields)) {
415
- if (fieldDef.type !== "reference" || !fieldDef.reference) continue;
416
- const refOpts = fieldDef.reference;
417
- const multiple = refOpts.multiple === true;
418
- const value = fm[fieldName];
419
- if (value == null) continue;
420
- const resolveString = async (str) => {
421
- if (!REFERENCE_PATH_RE.test(str)) return null;
422
- const slashIdx = str.indexOf("/");
423
- const refCollectionId = str.slice(0, slashIdx);
424
- const refSlug = str.slice(slashIdx + 1);
425
- return fetchEntryRef(event, refCollectionId, refSlug);
426
- };
427
- if (multiple) {
428
- const items = Array.isArray(value) ? value : [value];
429
- const resolved = [];
430
- for (const item of items) {
431
- if (typeof item === "string") {
432
- const r = await resolveString(item);
433
- if (r) resolved.push(r);
434
- } else if (isReferenceValue(item)) {
435
- resolved.push(item);
436
- }
437
- }
438
- if (resolved.length > 0) fm[fieldName] = resolved;
439
- } else if (typeof value === "string" && REFERENCE_PATH_RE.test(value)) {
440
- const r = await resolveString(value);
441
- if (r) fm[fieldName] = r;
442
- }
443
- }
444
- }
445
- function runCMSBackgroundTask(event, task) {
446
- const ev = event;
447
- const ctx = ev?.context?.cloudflare?.context || ev?.node?.req?.context?.cloudflare?.context || ev?.context?.waitUntil;
448
- if (ctx && typeof ctx.waitUntil === "function") {
449
- ctx.waitUntil(
450
- task.catch((err) => console.warn("[qarpeo:cms:cache] Background task error:", err))
451
- );
452
- } else if (typeof ctx === "function") {
453
- ctx(task.catch((err) => console.warn("[qarpeo:cms:cache] Background task error:", err)));
454
- } else {
455
- task.catch(() => {
456
- });
457
- }
458
- }
459
- async function getCachedEntry(event, collectionId, slugOrId) {
460
- const config = getCMSConfig(event);
461
- if (!config.cache) return null;
462
- try {
463
- const kv = getKVBinding("KV", event);
464
- const tenantPrefix = getCMSTenantPrefix(event);
465
- const cached = await kv.get(`${tenantPrefix}cms:entry:${collectionId}:${slugOrId}`, {
466
- type: "json"
467
- });
468
- return cached;
469
- } catch {
470
- return null;
471
- }
472
- }
473
- async function setCachedEntry(event, collectionId, slugOrId, entry) {
474
- const config = getCMSConfig(event);
475
- if (!config.cache) return;
476
- const tenantPrefix = getCMSTenantPrefix(event);
477
- const task = (async () => {
478
- try {
479
- const kv = getKVBinding("KV", event);
480
- await kv.put(`${tenantPrefix}cms:entry:${collectionId}:${slugOrId}`, JSON.stringify(entry), {
481
- expirationTtl: 60
482
- });
483
- } catch {
484
- }
485
- })();
486
- runCMSBackgroundTask(event, task);
487
- return task;
488
- }
489
- async function getCachedList(event, key) {
490
- const config = getCMSConfig(event);
491
- if (!config.cache) return null;
492
- try {
493
- const kv = getKVBinding("KV", event);
494
- const tenantPrefix = getCMSTenantPrefix(event);
495
- const cached = await kv.get(`${tenantPrefix}${key}`, { type: "json" });
496
- return cached;
497
- } catch {
498
- return null;
499
- }
500
- }
501
- async function setCachedList(event, key, data) {
502
- const config = getCMSConfig(event);
503
- if (!config.cache) return;
504
- const tenantPrefix = getCMSTenantPrefix(event);
505
- const task = (async () => {
506
- try {
507
- const kv = getKVBinding("KV", event);
508
- await kv.put(`${tenantPrefix}${key}`, JSON.stringify(data), { expirationTtl: 30 });
509
- } catch {
510
- }
511
- })();
512
- runCMSBackgroundTask(event, task);
513
- return task;
514
- }
515
- export async function invalidateCMSEntryCache(event, collectionId, slug) {
516
- const config = getCMSConfig(event);
517
- if (!config.cache) return;
518
- const tenantPrefix = getCMSTenantPrefix(event);
519
- const task = (async () => {
520
- try {
521
- const kv = getKVBinding("KV", event);
522
- const slugs = Array.isArray(slug) ? slug : slug ? [slug] : [];
523
- for (const s of slugs) {
524
- if (s) {
525
- await kv.delete(`${tenantPrefix}cms:entry:${collectionId}:${s}`);
526
- }
527
- }
528
- const listRes = await kv.list({ prefix: `${tenantPrefix}cms:list:${collectionId}:` });
529
- if (listRes?.keys?.length) {
530
- await Promise.all(listRes.keys.map((k) => kv.delete(k.name)));
531
- }
532
- } catch {
533
- }
534
- })();
535
- runCMSBackgroundTask(event, task);
536
- return task;
537
- }
538
- export async function queryCMSEntries(event, collectionId, opts = {}) {
539
- const status = opts.status || "published";
540
- const isCacheable = status === "published";
541
- const fieldsKey = opts.fields ? Array.isArray(opts.fields) ? opts.fields.join(",") : String(opts.fields) : "";
542
- const listCacheKey = isCacheable && !opts.populate ? `cms:list:${collectionId}:${opts.page || 1}:${opts.limit || 10}:${opts.sort || ""}:${opts.tag || ""}:${opts.category || ""}:${opts.categoryId || ""}:${opts.authorId || ""}:${opts.locale || ""}:${opts.version || ""}:${opts.search || ""}:${fieldsKey}:${opts.where ? JSON.stringify(opts.where) : ""}` : null;
543
- if (listCacheKey) {
544
- const cached = await getCachedList(event, listCacheKey);
545
- if (cached) return cached;
546
- }
547
- const db = getCMSDb(event);
548
- const page = Math.max(1, opts.page || 1);
549
- const limit = Math.min(100, opts.limit || 10);
550
- const offset = (page - 1) * limit;
551
- const conditions = ["collection_id = ?"];
552
- const binds = [collectionId];
553
- const tenantId = getCMSTenantId(event);
554
- if (tenantId) {
555
- conditions.push("(tenant_id = ? OR tenant_id IS NULL)");
556
- binds.push(tenantId);
557
- }
558
- if (status !== "all") {
559
- conditions.push("status = ?");
560
- binds.push(status);
561
- }
562
- if (opts.categoryId) {
563
- conditions.push("category_id = ?");
564
- binds.push(opts.categoryId);
565
- }
566
- if (opts.category) {
567
- conditions.push(
568
- `(category_id IN (SELECT id FROM ${cmsCategoryTbl(event)} WHERE slug = ?) OR category_id = ?)`
569
- );
570
- binds.push(opts.category, opts.category);
571
- }
572
- if (opts.authorId) {
573
- conditions.push("author_id = ?");
574
- binds.push(opts.authorId);
575
- }
576
- if (opts.locale) {
577
- conditions.push("locale = ?");
578
- binds.push(opts.locale);
579
- }
580
- if (opts.version) {
581
- conditions.push("version = ?");
582
- binds.push(opts.version);
583
- }
584
- if (opts.search) {
585
- conditions.push("(title LIKE ? OR description LIKE ?)");
586
- const term = `%${opts.search}%`;
587
- binds.push(term, term);
588
- }
589
- if (opts.tag) {
590
- conditions.push("(tags LIKE ? OR tags LIKE ? OR tags LIKE ? OR tags = ?)");
591
- binds.push(`${opts.tag},%`, `%,${opts.tag},%`, `%,${opts.tag}`, opts.tag);
592
- }
593
- if (opts.where && typeof opts.where === "object") {
594
- for (const [key, value] of Object.entries(opts.where)) {
595
- if (value === void 0 || !/^[a-zA-Z0-9_]+$/.test(key)) continue;
596
- const jsonPath = `$.${key}`;
597
- if (value === null) {
598
- conditions.push("json_extract(metadata_json, ?) IS NULL");
599
- binds.push(jsonPath);
600
- } else if (typeof value === "boolean") {
601
- conditions.push("json_extract(metadata_json, ?) = ?");
602
- binds.push(jsonPath, value ? 1 : 0);
603
- } else {
604
- conditions.push("json_extract(metadata_json, ?) = ?");
605
- binds.push(jsonPath, value);
606
- }
607
- }
608
- }
609
- const where = `WHERE ${conditions.join(" AND ")}`;
610
- const [sortField, sortDir] = (opts.sort || "published_at:desc").split(":");
611
- const safeSortField = [
612
- "published_at",
613
- "created_at",
614
- "updated_at",
615
- "title",
616
- "order",
617
- "view_count",
618
- "reading_time",
619
- "featured"
620
- ].includes(sortField) ? sortField : "published_at";
621
- const safeDir = sortDir === "asc" ? "ASC" : "DESC";
622
- let countResult = null;
623
- let dataResult = null;
624
- if (db) {
625
- try {
626
- ;
627
- [countResult, dataResult] = await Promise.all([
628
- db.prepare(`SELECT COUNT(*) as total FROM ${cmsEntryTbl(event)} ${where}`).bind(...binds).first(),
629
- db.prepare(
630
- `SELECT * FROM ${cmsEntryTbl(event)} ${where} ORDER BY ${safeSortField} ${safeDir} LIMIT ? OFFSET ?`
631
- ).bind(...binds, limit, offset).all()
632
- ]);
633
- } catch {
634
- }
635
- }
636
- let total = countResult?.total ?? 0;
637
- let rawRows = dataResult?.results || [];
638
- if (!rawRows.length) {
639
- try {
640
- const { manifestEntries } = await import("#qarpeo/cms/manifest");
641
- let matching = (manifestEntries || []).filter(
642
- (e) => e.collection_id === collectionId || collectionId === "content"
643
- );
644
- if (status !== "all") {
645
- matching = matching.filter((e) => e.status === status);
646
- }
647
- total = matching.length;
648
- rawRows = matching.slice(offset, offset + limit).map((e) => ({
649
- id: e.slug || e.id,
650
- collection_id: e.collection_id,
651
- slug: e.slug,
652
- title: e.title,
653
- description: e.description,
654
- cover_image: e.cover_image,
655
- tags: e.tags,
656
- order: e.order ?? 0,
657
- content_md: e.content_md || "",
658
- content_html: e.content_html || "",
659
- metadata_json: typeof e.metadata_json === "string" ? e.metadata_json : JSON.stringify(e.metadata || {}),
660
- status: e.status || "published",
661
- source: "file",
662
- path: e.path,
663
- file_path: e.file_path,
664
- content_hash: e.content_hash,
665
- published_at: e.published_at || Date.now(),
666
- created_at: e.created_at || Date.now(),
667
- updated_at: e.updated_at || Date.now()
668
- }));
669
- } catch {
670
- }
671
- }
672
- const entries = rawRows.map(rowToEntry);
673
- const populatedEntries = opts.populate ? await Promise.all(entries.map((e) => populateReferenceFields(event, e, opts.populate))) : entries;
674
- const projectedEntries = opts.fields ? populatedEntries.map((e) => projectCMSEntry(e, opts.fields)) : populatedEntries;
675
- const result = { entries: projectedEntries, total, page, limit };
676
- if (listCacheKey) {
677
- await setCachedList(event, listCacheKey, result);
678
- }
679
- return result;
680
- }
681
- export async function getCMSEntry(event, collectionId, slugOrId, opts = {}) {
682
- const db = getCMSDb(event);
683
- let allowDraft = false;
684
- const previewCookie = event ? getCookie(event, "qarpeo_preview") : null;
685
- let cookieObj = null;
686
- if (previewCookie) {
687
- try {
688
- cookieObj = typeof previewCookie === "string" ? JSON.parse(previewCookie) : previewCookie;
689
- } catch {
690
- }
691
- }
692
- const isMatchingCookie = Boolean(
693
- cookieObj && (!cookieObj.collection || cookieObj.collection === collectionId) && (!cookieObj.slug || cookieObj.slug === slugOrId)
694
- );
695
- const isPreviewRequested = opts.preview || isMatchingCookie;
696
- if (isPreviewRequested) {
697
- const auth = await getAuthContext(event).catch(() => null);
698
- const config = getCMSConfig(event);
699
- if (auth?.user && config.roles.some((r) => r === auth.role || auth.isAdmin)) {
700
- allowDraft = true;
701
- }
702
- if (!allowDraft) {
703
- const token = opts.previewToken || (isMatchingCookie ? cookieObj?.token : void 0);
704
- const expires = opts.previewExpires || (isMatchingCookie ? cookieObj?.expires : void 0);
705
- if (token && expires) {
706
- allowDraft = await verifyPreviewToken(event, collectionId, slugOrId, token, expires);
707
- }
708
- }
709
- }
710
- if (!allowDraft) {
711
- const cached = await getCachedEntry(event, collectionId, slugOrId);
712
- if (cached) return cached;
713
- }
714
- const statusClause = allowDraft ? "AND status IN ('draft', 'published', 'scheduled')" : "AND status = 'published'";
715
- const statusOrder = allowDraft ? "ORDER BY CASE WHEN status = 'draft' THEN 1 WHEN status = 'scheduled' THEN 2 ELSE 3 END" : "";
716
- const tenantId = getCMSTenantId(event);
717
- const tenantClause = tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : "";
718
- const binds = tenantId ? [collectionId, slugOrId, slugOrId, tenantId] : [collectionId, slugOrId, slugOrId];
719
- let row = null;
720
- if (db) {
721
- try {
722
- row = await db.prepare(
723
- `SELECT * FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND (slug = ? OR id = ?) ${statusClause} ${tenantClause} ${statusOrder} LIMIT 1`
724
- ).bind(...binds).first();
725
- } catch {
726
- }
727
- }
728
- if (!row) {
729
- try {
730
- const { manifestEntries } = await import("#qarpeo/cms/manifest");
731
- const candidate = (manifestEntries || []).find(
732
- (e) => (e.collection_id === collectionId || collectionId === "content") && (e.slug === slugOrId || e.id === slugOrId)
733
- );
734
- if (candidate) {
735
- row = {
736
- id: candidate.slug || candidate.id,
737
- collection_id: candidate.collection_id,
738
- slug: candidate.slug,
739
- title: candidate.title,
740
- description: candidate.description,
741
- cover_image: candidate.cover_image,
742
- tags: candidate.tags,
743
- order: candidate.order ?? 0,
744
- content_md: candidate.content_md || "",
745
- content_html: candidate.content_html || "",
746
- metadata_json: typeof candidate.metadata_json === "string" ? candidate.metadata_json : JSON.stringify(candidate.metadata || {}),
747
- status: candidate.status || "published",
748
- source: "file",
749
- path: candidate.path,
750
- file_path: candidate.file_path,
751
- content_hash: candidate.content_hash,
752
- published_at: candidate.published_at || Date.now(),
753
- created_at: candidate.created_at || Date.now(),
754
- updated_at: candidate.updated_at || Date.now()
755
- };
756
- }
757
- } catch {
758
- }
759
- }
760
- const entry = row ? rowToEntry(row) : null;
761
- if (entry && (!entry.body || !Array.isArray(entry.body.nodes)) && entry.contentMd) {
762
- const ast = await parseMarkdownAST(entry.contentMd, event);
763
- entry.body = {
764
- ...ast,
765
- value: entry.contentMd,
766
- content: entry.contentMd,
767
- toc: entry.toc || { links: [] }
768
- };
769
- }
770
- if (entry && !allowDraft) {
771
- await setCachedEntry(event, collectionId, slugOrId, entry);
772
- if (entry.slug && entry.slug !== slugOrId) {
773
- await setCachedEntry(event, collectionId, entry.slug, entry);
774
- }
775
- }
776
- let finalEntry = entry;
777
- if (entry && opts.populate) {
778
- finalEntry = await populateReferenceFields(event, entry, opts.populate);
779
- }
780
- if (finalEntry && opts.fields) {
781
- return projectCMSEntry(finalEntry, opts.fields);
782
- }
783
- return finalEntry;
784
- }
785
- export async function createCMSEntry(event, collectionId, data) {
786
- const db = getCMSDb(event);
787
- const cmsConfig = getCMSConfig(event);
788
- const isSingleton = cmsConfig.collections?.[collectionId]?.singleton;
789
- if (isSingleton) {
790
- const existing = await db.prepare(`SELECT COUNT(*) as total FROM ${cmsEntryTbl(event)} WHERE collection_id = ?`).bind(collectionId).first();
791
- if (existing && existing.total > 0) {
792
- throw createError({
793
- statusCode: 409,
794
- message: `Collection '${collectionId}' is a singleton and already has an entry.`
795
- });
796
- }
797
- }
798
- const id = data.id || nanoid();
799
- const now = Date.now();
800
- const rawContent = data.contentMd ?? data.content ?? "";
801
- const { ast, html: contentHtml } = await processMarkdown(rawContent);
802
- const metadata = data.metadata || {};
803
- await validateAndNormalizeReferenceFields(event, collectionId, metadata);
804
- await validateAndNormalizeComponentFields(event, collectionId, metadata);
805
- const metadataJson = JSON.stringify(metadata);
806
- const publishedAt = data.status === "published" ? data.publishedAt ?? now : data.status === "scheduled" && data.publishedAt ? data.publishedAt : data.publishedAt ?? null;
807
- const tenantId = getCMSTenantId(event);
808
- const existingSlug = await db.prepare(
809
- `SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
810
- ).bind(...tenantId ? [collectionId, data.slug, tenantId] : [collectionId, data.slug]).first();
811
- if (existingSlug?.id) {
812
- throw createError({
813
- statusCode: 409,
814
- message: `An entry with slug '${data.slug}' already exists in collection '${collectionId}'.`
815
- });
816
- }
817
- const words = rawContent.trim() ? rawContent.trim().split(/\s+/).length : 0;
818
- const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
819
- const readingTime = data.readingTime ?? metadata.readingTime ?? calculatedReadingTime;
820
- try {
821
- await db.prepare(
822
- `INSERT INTO ${cmsEntryTbl(event)}
823
- (id, collection_id, slug, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, author_id, category_id, sub_category_id, featured, view_count, reading_time, published_at, created_at, updated_at, tenant_id)
824
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
825
- ).bind(
826
- id,
827
- collectionId,
828
- data.slug,
829
- data.title,
830
- data.description ?? null,
831
- data.coverImage ?? null,
832
- data.tags ?? null,
833
- data.order ?? 0,
834
- rawContent,
835
- contentHtml,
836
- metadataJson,
837
- data.status || "draft",
838
- data.source || "db",
839
- data.authorId ?? null,
840
- data.categoryId ?? null,
841
- data.subCategoryId ?? null,
842
- data.featured ? 1 : 0,
843
- data.viewCount ?? 0,
844
- readingTime,
845
- publishedAt,
846
- now,
847
- now,
848
- tenantId
849
- ).run();
850
- } catch (err) {
851
- if (err?.message?.includes("UNIQUE constraint failed")) {
852
- throw createError({
853
- statusCode: 409,
854
- message: `An entry with slug "${data.slug}" already exists in collection "${collectionId}".`
855
- });
856
- }
857
- throw err;
858
- }
859
- const entry = {
860
- id,
861
- collectionId,
862
- slug: data.slug,
863
- title: data.title,
864
- description: data.description ?? null,
865
- coverImage: data.coverImage ?? null,
866
- tags: data.tags ?? null,
867
- order: data.order ?? 0,
868
- contentMd: rawContent,
869
- contentHtml,
870
- metadataJson,
871
- metadata,
872
- body: ast ? { ...ast, value: rawContent, content: rawContent } : void 0,
873
- status: data.status || "draft",
874
- source: "db",
875
- filePath: null,
876
- contentHash: null,
877
- authorId: data.authorId ?? null,
878
- categoryId: data.categoryId ?? void 0,
879
- subCategoryId: data.subCategoryId ?? void 0,
880
- featured: Boolean(data.featured),
881
- viewCount: data.viewCount ?? 0,
882
- readingTime,
883
- publishedAt,
884
- tenantId: tenantId ?? null,
885
- createdAt: now,
886
- updatedAt: now
887
- };
888
- const gitResult = await syncEntryToGit(event, collectionId, entry, "create");
889
- if (gitResult?.filePath) {
890
- entry.filePath = gitResult.filePath;
891
- entry.contentHash = gitResult.contentHash || null;
892
- entry.source = "file";
893
- }
894
- await invalidateCMSEntryCache(
895
- event,
896
- collectionId,
897
- [data.slug, entry.id].filter(Boolean)
898
- );
899
- await syncCMSEntryTags(event, null, data.tags ?? null).catch(() => {
900
- });
901
- fireCMSWebhooks(getCMSConfig(event), collectionId, "create", entry).catch(console.warn);
902
- return entry;
903
- }
904
- export async function updateCMSEntry(event, entryId, data) {
905
- const db = getCMSDb(event);
906
- const now = Date.now();
907
- const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
908
- if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
909
- const tenantId = getCMSTenantId(event);
910
- if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
911
- throw createError({
912
- statusCode: 403,
913
- message: "Forbidden: Cannot modify an entry belonging to another tenant"
914
- });
915
- }
916
- if (data.slug && data.slug !== existing.slug) {
917
- const slugCollision = await db.prepare(
918
- `SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? AND id != ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
919
- ).bind(
920
- ...tenantId ? [existing.collection_id, data.slug, entryId, tenantId] : [existing.collection_id, data.slug, entryId]
921
- ).first();
922
- if (slugCollision?.id) {
923
- throw createError({
924
- statusCode: 409,
925
- message: `An entry with slug '${data.slug}' already exists in collection '${existing.collection_id}'.`
926
- });
927
- }
928
- }
929
- const contentMd = data.contentMd ?? data.content ?? existing.content_md;
930
- let contentHtml = existing.content_html;
931
- if (data.contentMd !== void 0 || data.content !== void 0) {
932
- const res = await processMarkdown(contentMd);
933
- contentHtml = res.html;
934
- }
935
- let metadataObj = data.metadata;
936
- if (!metadataObj && existing.metadata_json) {
937
- try {
938
- metadataObj = JSON.parse(existing.metadata_json);
939
- } catch {
940
- }
941
- }
942
- if (metadataObj && (data.metadata || data.status === "published")) {
943
- await validateAndNormalizeReferenceFields(event, existing.collection_id, metadataObj);
944
- await validateAndNormalizeComponentFields(event, existing.collection_id, metadataObj);
945
- }
946
- const metadataJson = metadataObj ? JSON.stringify(metadataObj) : existing.metadata_json;
947
- const status = data.status ?? existing.status;
948
- let publishedAt;
949
- if (data.publishedAt !== void 0) {
950
- publishedAt = data.publishedAt;
951
- } else if (status === "published") {
952
- publishedAt = existing.published_at ?? now;
953
- } else if (status === "scheduled") {
954
- publishedAt = existing.published_at ?? now;
955
- } else {
956
- publishedAt = existing.published_at;
957
- }
958
- const words = contentMd.trim() ? contentMd.trim().split(/\s+/).length : 0;
959
- const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
960
- const readingTime = data.readingTime !== void 0 ? data.readingTime : data.contentMd !== void 0 || data.content !== void 0 ? calculatedReadingTime : existing.reading_time || calculatedReadingTime;
961
- await db.prepare(
962
- `INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
963
- ).bind(
964
- nanoid(),
965
- entryId,
966
- existing.title,
967
- existing.content_md,
968
- existing.metadata_json,
969
- existing.author_id,
970
- now
971
- ).run();
972
- await db.prepare(
973
- `UPDATE ${cmsEntryTbl(event)} SET
974
- slug = COALESCE(?, slug), title = COALESCE(?, title),
975
- description = COALESCE(?, description), cover_image = COALESCE(?, cover_image),
976
- tags = COALESCE(?, tags), "order" = COALESCE(?, "order"),
977
- content_md = ?, content_html = ?, metadata_json = ?,
978
- status = ?, source = COALESCE(?, source),
979
- category_id = COALESCE(?, category_id),
980
- sub_category_id = COALESCE(?, sub_category_id),
981
- featured = COALESCE(?, featured),
982
- view_count = COALESCE(?, view_count),
983
- reading_time = COALESCE(?, reading_time),
984
- published_at = ?, updated_at = ?
985
- WHERE id = ?`
986
- ).bind(
987
- data.slug ?? null,
988
- data.title ?? null,
989
- data.description ?? null,
990
- data.coverImage ?? null,
991
- data.tags ?? null,
992
- data.order ?? null,
993
- contentMd,
994
- contentHtml,
995
- metadataJson,
996
- status,
997
- data.source ?? null,
998
- data.categoryId !== void 0 ? data.categoryId : null,
999
- data.subCategoryId !== void 0 ? data.subCategoryId : null,
1000
- data.featured !== void 0 ? data.featured ? 1 : 0 : null,
1001
- data.viewCount !== void 0 ? data.viewCount : null,
1002
- readingTime ?? null,
1003
- publishedAt,
1004
- now,
1005
- entryId
1006
- ).run();
1007
- const config = getCMSConfig(event);
1008
- const maxRevisions = typeof config.revisions === "object" ? config.revisions.max ?? 10 : 10;
1009
- await pruneRevisions(event, entryId, maxRevisions);
1010
- const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1011
- const updatedEntry = rowToEntry(updated);
1012
- const gitResult = await syncEntryToGit(event, updatedEntry.collectionId, updatedEntry, "update");
1013
- if (gitResult?.filePath) {
1014
- updatedEntry.filePath = gitResult.filePath;
1015
- updatedEntry.contentHash = gitResult.contentHash || null;
1016
- updatedEntry.source = "file";
1017
- }
1018
- await invalidateCMSEntryCache(
1019
- event,
1020
- updatedEntry.collectionId,
1021
- [
1022
- updatedEntry.slug,
1023
- updatedEntry.id,
1024
- existing.slug,
1025
- existing.id
1026
- ].filter(Boolean)
1027
- );
1028
- await syncCMSEntryTags(
1029
- event,
1030
- existing.tags,
1031
- data.tags !== void 0 ? data.tags : existing.tags
1032
- ).catch(() => {
1033
- });
1034
- fireCMSWebhooks(getCMSConfig(event), updatedEntry.collectionId, "update", updatedEntry).catch(
1035
- console.warn
1036
- );
1037
- return updatedEntry;
1038
- }
1039
- async function nullifyOrphanedReferences(event, deletedEntryId) {
1040
- const db = getCMSDb(event);
1041
- try {
1042
- const tenantId = getCMSTenantId(event);
1043
- const tenantClause = tenantId ? " AND (tenant_id = ? OR tenant_id IS NULL)" : "";
1044
- const searchPattern = `%"${deletedEntryId}"%`;
1045
- const binds = tenantId ? [searchPattern, tenantId] : [searchPattern];
1046
- const rows = (await db.prepare(
1047
- `SELECT id, collection_id, slug, metadata_json FROM ${cmsEntryTbl(event)}
1048
- WHERE json_extract(metadata_json, '$') IS NOT NULL
1049
- AND metadata_json LIKE ?${tenantClause}`
1050
- ).bind(...binds).all()).results;
1051
- for (const row of rows) {
1052
- let meta;
1053
- try {
1054
- meta = JSON.parse(row.metadata_json);
1055
- } catch {
1056
- continue;
1057
- }
1058
- let changed = false;
1059
- for (const [key, value] of Object.entries(meta)) {
1060
- if (isReferenceValue(value) && value.id === deletedEntryId) {
1061
- meta[key] = null;
1062
- changed = true;
1063
- } else if (Array.isArray(value)) {
1064
- const filtered = value.filter(
1065
- (item) => !(isReferenceValue(item) && item.id === deletedEntryId)
1066
- );
1067
- if (filtered.length !== value.length) {
1068
- meta[key] = filtered;
1069
- changed = true;
1070
- }
1071
- }
1072
- }
1073
- if (changed) {
1074
- await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET metadata_json = ? WHERE id = ?`).bind(JSON.stringify(meta), row.id).run();
1075
- await invalidateCMSEntryCache(event, row.collection_id, row.slug);
1076
- }
1077
- }
1078
- } catch (err) {
1079
- console.warn("[qarpeo:cms] nullifyOrphanedReferences failed:", err);
1080
- }
1081
- }
1082
- export async function deleteCMSEntry(event, entryId) {
1083
- const db = getCMSDb(event);
1084
- const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1085
- if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1086
- const tenantId = getCMSTenantId(event);
1087
- if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
1088
- throw createError({
1089
- statusCode: 403,
1090
- message: "Forbidden: Cannot delete an entry belonging to another tenant"
1091
- });
1092
- }
1093
- await db.batch([
1094
- db.prepare(`DELETE FROM ${cmsRevisionTbl(event)} WHERE entry_id = ?`).bind(entryId),
1095
- db.prepare(`DELETE FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId)
1096
- ]);
1097
- if (existing) {
1098
- await nullifyOrphanedReferences(event, entryId);
1099
- await syncCMSEntryTags(event, existing.tags, null).catch(() => {
1100
- });
1101
- await invalidateCMSEntryCache(
1102
- event,
1103
- existing.collection_id,
1104
- [existing.slug, existing.id].filter(Boolean)
1105
- );
1106
- await syncEntryToGit(
1107
- event,
1108
- existing.collection_id,
1109
- rowToEntry(existing),
1110
- "delete"
1111
- ).catch((err) => console.warn("[qarpeo:cms] Git sync on delete failed:", err));
1112
- fireCMSWebhooks(
1113
- getCMSConfig(event),
1114
- existing.collection_id,
1115
- "delete",
1116
- rowToEntry(existing)
1117
- ).catch(console.warn);
1118
- }
1119
- }
1120
- export async function publishCMSEntry(event, entryId, targetStatus, targetPublishedAt) {
1121
- const db = getCMSDb(event);
1122
- const now = Date.now();
1123
- const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1124
- if (!existing) {
1125
- throw createError({ statusCode: 404, message: "Entry not found" });
1126
- }
1127
- const tenantId = getCMSTenantId(event);
1128
- if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
1129
- throw createError({
1130
- statusCode: 403,
1131
- message: "Forbidden: Cannot publish an entry belonging to another tenant"
1132
- });
1133
- }
1134
- const publishedAt = targetStatus === "published" ? targetPublishedAt ?? existing.published_at ?? now : targetStatus === "scheduled" ? targetPublishedAt ?? existing.published_at ?? now : null;
1135
- const collectionId = existing.collection_id;
1136
- const config = getCMSConfig(event);
1137
- const colConfig = config.collections[collectionId] || {};
1138
- const approval = resolveCollectionApproval(colConfig, config.approval);
1139
- let metadataJson = existing.metadata_json || "{}";
1140
- if ((targetStatus === "published" || targetStatus === "scheduled") && approval) {
1141
- const auth = await getAuthContext(event);
1142
- const userRole = auth?.role || "user";
1143
- const isAuthorized = auth?.isAdmin || approval.roles?.includes(userRole);
1144
- if (!isAuthorized) {
1145
- throw createError({
1146
- statusCode: 403,
1147
- message: `${targetStatus === "scheduled" ? "Scheduling" : "Publishing"} in "${collectionId}" requires one of the following approver roles: ${approval.roles?.join(", ")}.`
1148
- });
1149
- }
1150
- if (!approval.allowSelfApproval && existing.author_id && auth?.user?.id === existing.author_id) {
1151
- throw createError({
1152
- statusCode: 403,
1153
- message: `Self-approval is disabled for "${collectionId}". Another team member must approve this entry.`
1154
- });
1155
- }
1156
- let metaObj = {};
1157
- try {
1158
- metaObj = JSON.parse(metadataJson);
1159
- } catch {
1160
- }
1161
- metaObj._approval = {
1162
- ...metaObj._approval,
1163
- approvedBy: auth?.user?.id || null,
1164
- approvedByName: auth?.user?.name || auth?.user?.email || "Admin",
1165
- approvedAt: now
1166
- };
1167
- metadataJson = JSON.stringify(metaObj);
1168
- }
1169
- await db.prepare(
1170
- `UPDATE ${cmsEntryTbl(event)} SET status = ?, published_at = ?, metadata_json = ?, updated_at = ? WHERE id = ?`
1171
- ).bind(targetStatus, publishedAt, metadataJson, now, entryId).run();
1172
- const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1173
- if (updatedRow) {
1174
- const updated = rowToEntry(updatedRow);
1175
- await invalidateCMSEntryCache(
1176
- event,
1177
- collectionId,
1178
- [
1179
- updated.slug,
1180
- updated.id,
1181
- existing.slug,
1182
- existing.id
1183
- ].filter(Boolean)
1184
- );
1185
- await syncEntryToGit(
1186
- event,
1187
- updated.collectionId,
1188
- updated,
1189
- targetStatus === "published" ? "publish" : "update"
1190
- );
1191
- const webhookEvent = targetStatus === "published" ? "publish" : targetStatus === "scheduled" ? "update" : "unpublish";
1192
- fireCMSWebhooks(config, updated.collectionId, webhookEvent, updated).catch(console.warn);
1193
- if (targetStatus === "published" || targetStatus === "draft") {
1194
- fireCMSDeployTrigger(
1195
- config,
1196
- updated.collectionId,
1197
- targetStatus === "published" ? "publish" : "unpublish"
1198
- ).catch(console.warn);
1199
- }
1200
- }
1201
- }
1202
- export async function publishDueScheduledEntries(event) {
1203
- const db = getCMSDb(event);
1204
- if (!db) {
1205
- return [];
1206
- }
1207
- const now = Date.now();
1208
- const config = getCMSConfig(event);
1209
- const rows = await db.prepare(
1210
- `SELECT * FROM ${cmsEntryTbl(event)} WHERE status = 'scheduled' AND published_at IS NOT NULL AND published_at <= ?`
1211
- ).bind(now).all();
1212
- const entriesToPublish = rows.results || [];
1213
- const publishedEntries = [];
1214
- for (const row of entriesToPublish) {
1215
- const entryId = row.id;
1216
- const collectionId = row.collection_id;
1217
- await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET status = 'published', updated_at = ? WHERE id = ?`).bind(now, entryId).run();
1218
- const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1219
- if (updatedRow) {
1220
- const entry = rowToEntry(updatedRow);
1221
- publishedEntries.push(entry);
1222
- await invalidateCMSEntryCache(
1223
- event,
1224
- collectionId,
1225
- [
1226
- entry.slug,
1227
- entry.id,
1228
- row.slug,
1229
- row.id
1230
- ].filter(Boolean)
1231
- );
1232
- await syncEntryToGit(event, collectionId, entry, "publish").catch(console.warn);
1233
- fireCMSWebhooks(config, collectionId, "publish", entry).catch(console.warn);
1234
- fireCMSDeployTrigger(config, collectionId, "publish").catch(console.warn);
1235
- }
1236
- }
1237
- return publishedEntries;
1238
- }
1239
- export async function submitCMSEntryForReview(event, entryId, note) {
1240
- const db = getCMSDb(event);
1241
- const now = Date.now();
1242
- const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1243
- if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1244
- const tenantId = getCMSTenantId(event);
1245
- if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
1246
- throw createError({
1247
- statusCode: 403,
1248
- message: "Forbidden: Cannot modify an entry belonging to another tenant"
1249
- });
1250
- }
1251
- const auth = await getAuthContext(event);
1252
- let metaObj = {};
1253
- try {
1254
- metaObj = JSON.parse(existing.metadata_json || "{}");
1255
- } catch {
1256
- }
1257
- metaObj._approval = {
1258
- ...metaObj._approval,
1259
- submittedBy: auth?.user?.id || null,
1260
- submittedByName: auth?.user?.name || auth?.user?.email || "Editor",
1261
- submittedAt: now,
1262
- submissionNote: note || null
1263
- };
1264
- const metadataJson = JSON.stringify(metaObj);
1265
- await db.prepare(
1266
- `INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
1267
- ).bind(
1268
- nanoid(),
1269
- entryId,
1270
- existing.title,
1271
- existing.content_md,
1272
- metadataJson,
1273
- auth?.user?.id || existing.author_id,
1274
- now
1275
- ).run();
1276
- await db.prepare(
1277
- `UPDATE ${cmsEntryTbl(event)} SET status = 'pending_review', metadata_json = ?, updated_at = ? WHERE id = ?`
1278
- ).bind(metadataJson, now, entryId).run();
1279
- const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1280
- return rowToEntry(updated);
1281
- }
1282
- export async function rejectCMSEntryReview(event, entryId, reason) {
1283
- const db = getCMSDb(event);
1284
- const now = Date.now();
1285
- const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1286
- if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1287
- const tenantId = getCMSTenantId(event);
1288
- if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
1289
- throw createError({
1290
- statusCode: 403,
1291
- message: "Forbidden: Cannot modify an entry belonging to another tenant"
1292
- });
1293
- }
1294
- const collectionId = existing.collection_id;
1295
- const config = getCMSConfig(event);
1296
- const colConfig = config.collections[collectionId] || {};
1297
- const approval = resolveCollectionApproval(colConfig, config.approval);
1298
- const auth = await getAuthContext(event);
1299
- if (approval) {
1300
- const userRole = auth?.role || "user";
1301
- const isAuthorized = auth?.isAdmin || approval.roles?.includes(userRole);
1302
- if (!isAuthorized) {
1303
- throw createError({
1304
- statusCode: 403,
1305
- message: `Only reviewers with roles [${approval.roles?.join(", ")}] can request changes on entries in "${collectionId}".`
1306
- });
1307
- }
1308
- }
1309
- let metaObj = {};
1310
- try {
1311
- metaObj = JSON.parse(existing.metadata_json || "{}");
1312
- } catch {
1313
- }
1314
- metaObj._approval = {
1315
- ...metaObj._approval,
1316
- rejectedBy: auth?.user?.id || null,
1317
- rejectedByName: auth?.user?.name || auth?.user?.email || "Reviewer",
1318
- rejectedAt: now,
1319
- rejectionReason: reason || null
1320
- };
1321
- const metadataJson = JSON.stringify(metaObj);
1322
- await db.prepare(
1323
- `UPDATE ${cmsEntryTbl(event)} SET status = 'draft', metadata_json = ?, updated_at = ? WHERE id = ?`
1324
- ).bind(metadataJson, now, entryId).run();
1325
- const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1326
- return rowToEntry(updated);
1327
- }
1328
- export async function pruneRevisions(event, entryId, max) {
1329
- const db = getCMSDb(event);
1330
- await db.prepare(
1331
- `DELETE FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? AND id NOT IN (
1332
- SELECT id FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? ORDER BY created_at DESC LIMIT ?
1333
- )`
1334
- ).bind(entryId, entryId, max).run();
1335
- }
1336
- export async function listCMSRevisions(event, entryId) {
1337
- const db = getCMSDb(event);
1338
- if (!db) return [];
1339
- const res = await db.prepare(
1340
- `SELECT id, entry_id as entryId, title, content_md as contentMd, metadata_json as metadataJson, author_id as authorId, created_at as createdAt FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? ORDER BY created_at DESC`
1341
- ).bind(entryId).all().catch(() => ({ results: [] }));
1342
- return res?.results || [];
1343
- }
1344
- export async function restoreCMSRevision(event, entryId, revisionId) {
1345
- const db = getCMSDb(event);
1346
- if (!db) throw createError({ statusCode: 500, message: "Database not available" });
1347
- const tenantId = getCMSTenantId(event);
1348
- const entryCheck = await db.prepare(
1349
- `SELECT id FROM ${cmsEntryTbl(event)} WHERE id = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
1350
- ).bind(...tenantId ? [entryId, tenantId] : [entryId]).first();
1351
- if (!entryCheck?.id) {
1352
- throw createError({
1353
- statusCode: 404,
1354
- message: `Entry '${entryId}' not found`
1355
- });
1356
- }
1357
- const rev = await db.prepare(`SELECT * FROM ${cmsRevisionTbl(event)} WHERE id = ? AND entry_id = ?`).bind(revisionId, entryId).first();
1358
- if (!rev) {
1359
- throw createError({
1360
- statusCode: 404,
1361
- message: `Revision '${revisionId}' not found for entry '${entryId}'`
1362
- });
1363
- }
1364
- let meta = {};
1365
- try {
1366
- meta = JSON.parse(rev.metadata_json || "{}");
1367
- } catch {
1368
- }
1369
- delete meta._ast;
1370
- delete meta._toc;
1371
- delete meta._nav;
1372
- return await updateCMSEntry(event, entryId, {
1373
- title: rev.title,
1374
- contentMd: rev.content_md,
1375
- metadata: meta
1376
- });
1377
- }
11
+ export {
12
+ formatEntryAsMarkdown,
13
+ projectCMSEntry,
14
+ rowToEntry,
15
+ queryCMSEntries,
16
+ getCMSEntry
17
+ } from "./cms/queries.mjs";
18
+ export {
19
+ getCollectionFields,
20
+ defineCMSComponent,
21
+ resolveReference,
22
+ resolveReferenceFieldsFromFrontmatter
23
+ } from "./cms/references.mjs";
24
+ export { invalidateCMSEntryCache } from "./cms/cache.mjs";
25
+ export {
26
+ createCMSEntry,
27
+ updateCMSEntry,
28
+ deleteCMSEntry,
29
+ publishCMSEntry,
30
+ publishDueScheduledEntries,
31
+ submitCMSEntryForReview,
32
+ rejectCMSEntryReview
33
+ } from "./cms/mutations.mjs";
34
+ export {
35
+ pruneRevisions,
36
+ listCMSRevisions,
37
+ restoreCMSRevision
38
+ } from "./cms/revisions.mjs";