@conloca/content-api 0.1.15 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +164 -0
  10. package/dist/asset-operations.d.ts.map +1 -0
  11. package/dist/asset-operations.js +784 -0
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +72 -0
  14. package/dist/asset-types.d.ts.map +1 -0
  15. package/dist/asset-types.js +13 -0
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +63 -0
  22. package/dist/base-content-index.d.ts.map +1 -0
  23. package/dist/base-content-index.js +200 -0
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.d.ts +31 -0
  26. package/dist/cf-access.d.ts.map +1 -0
  27. package/dist/cf-access.js +67 -0
  28. package/dist/cf-access.js.map +1 -0
  29. package/dist/component-registry.d.ts +50 -0
  30. package/dist/component-registry.d.ts.map +1 -0
  31. package/dist/component-registry.js +121 -0
  32. package/dist/component-registry.js.map +1 -0
  33. package/dist/component-registry.types.d.ts +11 -0
  34. package/dist/component-registry.types.d.ts.map +1 -0
  35. package/dist/component-registry.types.js +2 -0
  36. package/dist/component-registry.types.js.map +1 -0
  37. package/dist/component-vocabulary.d.ts +33 -0
  38. package/dist/component-vocabulary.d.ts.map +1 -0
  39. package/dist/component-vocabulary.js +105 -0
  40. package/dist/component-vocabulary.js.map +1 -0
  41. package/dist/content-api.interface.d.ts +64 -0
  42. package/dist/content-api.interface.d.ts.map +1 -0
  43. package/dist/content-api.interface.js +2 -0
  44. package/dist/content-api.interface.js.map +1 -0
  45. package/dist/content-filters.d.ts +31 -0
  46. package/dist/content-filters.d.ts.map +1 -0
  47. package/dist/content-filters.js +247 -0
  48. package/dist/content-filters.js.map +1 -0
  49. package/dist/content-index.d.ts +184 -0
  50. package/dist/content-index.d.ts.map +1 -0
  51. package/dist/content-index.js +546 -0
  52. package/dist/content-index.js.map +1 -0
  53. package/dist/content-operations.d.ts +157 -0
  54. package/dist/content-operations.d.ts.map +1 -0
  55. package/dist/content-operations.js +359 -0
  56. package/dist/content-operations.js.map +1 -0
  57. package/dist/content-path.d.ts +59 -0
  58. package/dist/content-path.d.ts.map +1 -0
  59. package/dist/content-path.js +88 -0
  60. package/dist/content-path.js.map +1 -0
  61. package/dist/content-reader.d.ts +10 -0
  62. package/dist/content-reader.d.ts.map +1 -0
  63. package/dist/content-reader.js +14 -0
  64. package/dist/content-reader.js.map +1 -0
  65. package/dist/content-utils.d.ts +175 -0
  66. package/dist/content-utils.d.ts.map +1 -0
  67. package/dist/content-utils.js +421 -0
  68. package/dist/content-utils.js.map +1 -0
  69. package/dist/content-watcher.d.ts +43 -0
  70. package/dist/content-watcher.d.ts.map +1 -0
  71. package/dist/content-watcher.js +86 -0
  72. package/dist/content-watcher.js.map +1 -0
  73. package/dist/data-index.d.ts +8 -0
  74. package/dist/data-index.d.ts.map +1 -0
  75. package/dist/data-index.js +8 -0
  76. package/dist/data-index.js.map +1 -0
  77. package/dist/data.d.ts +35 -0
  78. package/dist/data.d.ts.map +1 -0
  79. package/dist/data.js +104 -0
  80. package/dist/data.js.map +1 -0
  81. package/dist/editor-data-bindings.d.ts +10 -0
  82. package/dist/editor-data-bindings.d.ts.map +1 -0
  83. package/dist/editor-data-bindings.js +67 -0
  84. package/dist/editor-data-bindings.js.map +1 -0
  85. package/dist/etag-utils.d.ts +77 -0
  86. package/dist/etag-utils.d.ts.map +1 -0
  87. package/dist/etag-utils.js +161 -0
  88. package/dist/etag-utils.js.map +1 -0
  89. package/dist/filesystem-content-api.d.ts +162 -0
  90. package/dist/filesystem-content-api.d.ts.map +1 -0
  91. package/dist/filesystem-content-api.js +2307 -0
  92. package/dist/filesystem-content-api.js.map +1 -0
  93. package/dist/filesystem-reader-backend.d.ts +46 -0
  94. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  95. package/dist/filesystem-reader-backend.js +119 -0
  96. package/dist/filesystem-reader-backend.js.map +1 -0
  97. package/dist/fragment-index.d.ts +8 -0
  98. package/dist/fragment-index.d.ts.map +1 -0
  99. package/dist/fragment-index.js +8 -0
  100. package/dist/fragment-index.js.map +1 -0
  101. package/dist/fragments.d.ts +16 -0
  102. package/dist/fragments.d.ts.map +1 -0
  103. package/dist/fragments.js +104 -0
  104. package/dist/fragments.js.map +1 -0
  105. package/dist/git-operations.d.ts +49 -0
  106. package/dist/git-operations.d.ts.map +1 -0
  107. package/dist/git-operations.js +256 -0
  108. package/dist/git-operations.js.map +1 -0
  109. package/dist/header-parser.d.ts +37 -0
  110. package/dist/header-parser.d.ts.map +1 -0
  111. package/dist/header-parser.js +233 -0
  112. package/dist/header-parser.js.map +1 -0
  113. package/dist/in-memory-content-api.d.ts +35 -0
  114. package/dist/in-memory-content-api.d.ts.map +1 -0
  115. package/dist/in-memory-content-api.js +609 -0
  116. package/dist/in-memory-content-api.js.map +1 -0
  117. package/dist/index.d.ts +26 -0
  118. package/dist/index.d.ts.map +1 -0
  119. package/dist/index.js +28 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/indexing.d.ts +5 -0
  122. package/dist/indexing.d.ts.map +1 -0
  123. package/dist/indexing.js +8 -0
  124. package/dist/indexing.js.map +1 -0
  125. package/dist/json-whitespace-view.d.ts +32 -0
  126. package/dist/json-whitespace-view.d.ts.map +1 -0
  127. package/dist/json-whitespace-view.js +153 -0
  128. package/dist/json-whitespace-view.js.map +1 -0
  129. package/dist/middleware.d.ts +20 -0
  130. package/dist/middleware.d.ts.map +1 -0
  131. package/dist/middleware.js +1082 -0
  132. package/dist/middleware.js.map +1 -0
  133. package/dist/node.d.ts +32 -0
  134. package/dist/node.d.ts.map +1 -0
  135. package/dist/node.js +27 -0
  136. package/dist/node.js.map +1 -0
  137. package/dist/page-references.d.ts +21 -0
  138. package/dist/page-references.d.ts.map +1 -0
  139. package/dist/page-references.js +50 -0
  140. package/dist/page-references.js.map +1 -0
  141. package/dist/read-date.d.ts +3 -0
  142. package/dist/read-date.d.ts.map +1 -0
  143. package/dist/read-date.js +9 -0
  144. package/dist/read-date.js.map +1 -0
  145. package/dist/reader-backend.d.ts +54 -0
  146. package/dist/reader-backend.d.ts.map +1 -0
  147. package/dist/reader-backend.js +2 -0
  148. package/dist/reader-backend.js.map +1 -0
  149. package/dist/reader.d.ts +15 -0
  150. package/dist/reader.d.ts.map +1 -0
  151. package/dist/reader.js +14 -0
  152. package/dist/reader.js.map +1 -0
  153. package/dist/schemas/index.d.ts +102 -0
  154. package/dist/schemas/index.d.ts.map +1 -0
  155. package/dist/schemas/index.js +88 -0
  156. package/dist/schemas/index.js.map +1 -0
  157. package/dist/site-index.d.ts +60 -0
  158. package/dist/site-index.d.ts.map +1 -0
  159. package/dist/site-index.js +291 -0
  160. package/dist/site-index.js.map +1 -0
  161. package/dist/site.d.ts +23 -0
  162. package/dist/site.d.ts.map +1 -0
  163. package/dist/site.js +180 -0
  164. package/dist/site.js.map +1 -0
  165. package/dist/types.d.ts +641 -0
  166. package/dist/types.d.ts.map +1 -0
  167. package/dist/types.js +45 -0
  168. package/dist/types.js.map +1 -0
  169. package/dist/url-safe-base64.d.ts +12 -0
  170. package/dist/url-safe-base64.d.ts.map +1 -0
  171. package/dist/url-safe-base64.js +41 -0
  172. package/dist/url-safe-base64.js.map +1 -0
  173. package/dist/url-validation.d.ts +28 -0
  174. package/dist/url-validation.d.ts.map +1 -0
  175. package/dist/url-validation.js +123 -0
  176. package/dist/url-validation.js.map +1 -0
  177. package/dist/utils/atomic-write.d.ts +6 -0
  178. package/dist/utils/atomic-write.d.ts.map +1 -0
  179. package/dist/utils/atomic-write.js +21 -0
  180. package/dist/utils/atomic-write.js.map +1 -0
  181. package/dist/utils.d.ts +46 -0
  182. package/dist/utils.d.ts.map +1 -0
  183. package/dist/utils.js +71 -0
  184. package/dist/utils.js.map +1 -0
  185. package/dist/vite-plugin.d.ts +12 -0
  186. package/dist/vite-plugin.d.ts.map +1 -0
  187. package/dist/vite-plugin.js +30 -0
  188. package/dist/vite-plugin.js.map +1 -0
  189. package/dist/vxjson-serialize.d.ts +13 -0
  190. package/dist/vxjson-serialize.d.ts.map +1 -0
  191. package/dist/vxjson-serialize.js +53 -0
  192. package/dist/vxjson-serialize.js.map +1 -0
  193. package/dist/vxjson.d.ts +113 -0
  194. package/dist/vxjson.d.ts.map +1 -0
  195. package/dist/vxjson.js +381 -0
  196. package/dist/vxjson.js.map +1 -0
  197. package/dist/xxhash.d.ts +10 -0
  198. package/dist/xxhash.d.ts.map +1 -0
  199. package/dist/xxhash.js +35 -0
  200. package/dist/xxhash.js.map +1 -0
  201. package/package.json +132 -34
  202. package/src/asset-constraints.ts +33 -0
  203. package/src/asset-metadata-store.ts +401 -0
  204. package/src/asset-operations.ts +914 -0
  205. package/src/asset-types.ts +74 -0
  206. package/src/asset-usage.ts +47 -0
  207. package/src/base-content-index.ts +227 -0
  208. package/src/cf-access.ts +85 -0
  209. package/src/component-registry.ts +145 -0
  210. package/src/component-registry.types.ts +12 -0
  211. package/src/component-vocabulary.ts +87 -0
  212. package/src/content-api.interface.ts +94 -0
  213. package/src/content-filters.ts +278 -0
  214. package/src/content-index.ts +642 -0
  215. package/src/content-operations.ts +497 -0
  216. package/src/content-path.ts +113 -0
  217. package/src/content-reader.ts +18 -0
  218. package/src/content-utils.ts +474 -0
  219. package/src/content-watcher.ts +122 -0
  220. package/src/data-index.ts +7 -0
  221. package/src/data.ts +134 -0
  222. package/src/editor-data-bindings.ts +66 -0
  223. package/src/etag-utils.ts +204 -0
  224. package/src/filesystem-content-api.ts +2685 -0
  225. package/src/filesystem-reader-backend.ts +135 -0
  226. package/src/fragment-index.ts +7 -0
  227. package/src/fragments.ts +113 -0
  228. package/src/git-operations.ts +340 -0
  229. package/src/header-parser.ts +272 -0
  230. package/src/in-memory-content-api.ts +760 -0
  231. package/src/index.ts +45 -0
  232. package/src/indexing.ts +8 -0
  233. package/src/json-whitespace-view.ts +155 -0
  234. package/src/middleware.ts +1341 -0
  235. package/src/node.ts +40 -0
  236. package/src/page-references.ts +76 -0
  237. package/src/read-date.ts +7 -0
  238. package/src/reader-backend.ts +54 -0
  239. package/src/reader.ts +15 -0
  240. package/src/schemas/index.ts +113 -0
  241. package/src/site-index.ts +330 -0
  242. package/src/site.ts +198 -0
  243. package/src/types.ts +759 -0
  244. package/src/url-safe-base64.ts +38 -0
  245. package/src/url-validation.ts +121 -0
  246. package/src/utils/atomic-write.ts +20 -0
  247. package/src/utils.ts +84 -0
  248. package/src/vite-plugin.ts +45 -0
  249. package/src/vxjson-serialize.ts +66 -0
  250. package/src/vxjson.ts +442 -0
  251. package/src/xxhash.ts +43 -0
  252. package/dist/component-registry.types-CBGONnYn.d.mts +0 -71
  253. package/dist/component-registry.types-CBGONnYn.d.mts.map +0 -1
  254. package/dist/content-operations-Dv67amz3.d.mts +0 -852
  255. package/dist/content-operations-Dv67amz3.d.mts.map +0 -1
  256. package/dist/data-Db1Iv9T0.mjs +0 -60
  257. package/dist/data-Db1Iv9T0.mjs.map +0 -1
  258. package/dist/filesystem-content-api-C1TM0GLo.d.mts +0 -119
  259. package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +0 -1
  260. package/dist/filesystem-content-api-kxKY5IUw.mjs +0 -2678
  261. package/dist/filesystem-content-api-kxKY5IUw.mjs.map +0 -1
  262. package/dist/index.d.mts +0 -79
  263. package/dist/index.d.mts.map +0 -1
  264. package/dist/index.mjs +0 -47
  265. package/dist/index.mjs.map +0 -1
  266. package/dist/node.d.mts +0 -378
  267. package/dist/node.d.mts.map +0 -1
  268. package/dist/node.mjs +0 -2618
  269. package/dist/node.mjs.map +0 -1
  270. package/dist/reader.d.mts +0 -18
  271. package/dist/reader.d.mts.map +0 -1
  272. package/dist/reader.mjs +0 -22
  273. package/dist/reader.mjs.map +0 -1
  274. package/dist/schemas/index.d.mts +0 -90
  275. package/dist/schemas/index.d.mts.map +0 -1
  276. package/dist/schemas/index.mjs +0 -70
  277. package/dist/schemas/index.mjs.map +0 -1
  278. package/dist/site-vNtJ5jCh.mjs +0 -538
  279. package/dist/site-vNtJ5jCh.mjs.map +0 -1
  280. package/dist/types-DWt912tu.mjs +0 -33
  281. package/dist/types-DWt912tu.mjs.map +0 -1
@@ -0,0 +1,1082 @@
1
+ import { Hono } from 'hono';
2
+ import { AssetOperations } from './asset-operations.js';
3
+ import { findAssetUsage } from './asset-usage.js';
4
+ import { localesOf, normalizeAndValidatePathname } from './content-utils.js';
5
+ import { createGitOperations } from './git-operations.js';
6
+ import { ErrorCodes } from './types.js';
7
+ /**
8
+ * Helper to create standardized error responses
9
+ */
10
+ function errorResponse(code, message, details) {
11
+ return {
12
+ error: {
13
+ code,
14
+ message,
15
+ ...(details && { details }),
16
+ },
17
+ };
18
+ }
19
+ /**
20
+ * Helper to log and create error responses for unexpected errors
21
+ */
22
+ function logAndCreateErrorResponse(error, code, message, details) {
23
+ console.error(`[Content API] ${message}:`, error);
24
+ return errorResponse(code, message, details);
25
+ }
26
+ function errorMessage(error, fallback) {
27
+ return error instanceof Error ? error.message : fallback;
28
+ }
29
+ /**
30
+ * How a refused create or update answers, by reason: the error code, the HTTP status and the
31
+ * message when the backend gave none. 409 when another entry has the path or name, or a page
32
+ * redirects from the path; 400 when the caller can fix the input. A caller that can fix it by
33
+ * changing one field is told which one (`details.field`), so none of these falls through to a 500
34
+ * whose only clue is a raw error string.
35
+ */
36
+ const refusals = {
37
+ already_exists: { code: ErrorCodes.ALREADY_EXISTS, status: 409, message: 'Content already exists' },
38
+ name_taken: { code: ErrorCodes.NAME_TAKEN, status: 409, message: 'A fragment with that name already exists' },
39
+ pathname_taken: { code: ErrorCodes.PATHNAME_TAKEN, status: 409, message: 'Pathname already taken' },
40
+ pathname_in_redirects: {
41
+ code: ErrorCodes.PATHNAME_TAKEN,
42
+ status: 409,
43
+ message: 'Pathname is already in use as a redirect',
44
+ },
45
+ invalid_name: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Invalid name' },
46
+ invalid_collection: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Invalid collection' },
47
+ invalid_locale: { code: ErrorCodes.INVALID_LOCALE, status: 400, message: 'Invalid locale' },
48
+ invalid_pathname: { code: ErrorCodes.INVALID_PATHNAME, status: 400, message: 'Invalid pathname' },
49
+ metadata_too_large: { code: ErrorCodes.METADATA_TOO_LARGE, status: 400, message: 'Metadata too large' },
50
+ missing_field: { code: ErrorCodes.MISSING_REQUIRED_FIELD, status: 400, message: 'Missing required field' },
51
+ // Site resolution failing, not a bad field: with no sites configured at all, no value the caller
52
+ // could send would satisfy it.
53
+ no_sites_configured: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Site not found' },
54
+ unknown_site: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Site not found' },
55
+ };
56
+ function refusalOf(reason) {
57
+ return reason !== undefined && Object.hasOwn(refusals, reason) ? refusals[reason] : undefined;
58
+ }
59
+ /**
60
+ * Whether a request is a write another website made the browser send. The routes write into the
61
+ * project, and any page open in the browser can make it send a form post without asking the
62
+ * server first. The browser says where a request comes from: `Sec-Fetch-Site`, or in older
63
+ * browsers the `Origin` of the page, which for the editor is the address it sent the request to
64
+ * (the `Host`). A request with neither did not come from a web page.
65
+ */
66
+ function isCrossSiteWrite(c) {
67
+ if (c.req.method === 'GET' || c.req.method === 'HEAD' || c.req.method === 'OPTIONS')
68
+ return false;
69
+ const fetchSite = c.req.header('Sec-Fetch-Site');
70
+ if (fetchSite !== undefined)
71
+ return fetchSite !== 'same-origin';
72
+ const origin = c.req.header('Origin');
73
+ if (origin === undefined)
74
+ return false;
75
+ return !URL.canParse(origin) || new URL(origin).host !== c.req.header('Host');
76
+ }
77
+ export function createContentAPIRouter(api, options) {
78
+ const app = new Hono();
79
+ // The editor calls these routes from the page they are served with, so no other origin is
80
+ // granted access (no CORS headers), and a write another website sends is refused.
81
+ app.use('/*', async (c, next) => {
82
+ if (!isCrossSiteWrite(c))
83
+ return next();
84
+ return c.json(errorResponse(ErrorCodes.FORBIDDEN, 'Refused a write another website sent through the browser'), 403);
85
+ });
86
+ // GET /auth/user - Get current authenticated user
87
+ app.get('/auth/user', async (c) => {
88
+ const email = c.req.header('X-CF-User-Email');
89
+ const sub = c.req.header('X-CF-User-Sub');
90
+ if (!email) {
91
+ return c.json({ authenticated: false });
92
+ }
93
+ return c.json({
94
+ authenticated: true,
95
+ user: { email, sub },
96
+ });
97
+ });
98
+ // GET /content/collections - List all collections across all sites
99
+ app.get('/content/collections', async (c) => {
100
+ try {
101
+ const allCollections = new Set();
102
+ // Get collections from fragments
103
+ const fragmentCollections = api.fragments.collections;
104
+ for (const collection of fragmentCollections) {
105
+ allCollections.add(collection);
106
+ }
107
+ // Get collections from all sites
108
+ for (const siteName of Object.keys(api.sitesConfig.sites)) {
109
+ const site = api.getSite(siteName);
110
+ if (site) {
111
+ const siteCollections = site.collections;
112
+ for (const collection of siteCollections) {
113
+ allCollections.add(collection);
114
+ }
115
+ }
116
+ }
117
+ return c.json({
118
+ collections: Array.from(allCollections).sort(),
119
+ });
120
+ }
121
+ catch (error) {
122
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list collections'), 500);
123
+ }
124
+ });
125
+ // GET /content - List all content with optional filters
126
+ app.get('/content', async (c) => {
127
+ const kind = c.req.query('kind'); // 'fragment' or 'page'
128
+ const site = c.req.query('site');
129
+ const collection = c.req.query('collection');
130
+ const locales = c.req.query('locales'); // comma-separated
131
+ const type = c.req.query('type'); // 'puck' or 'mdx'
132
+ const published = c.req.query('published');
133
+ const localization = c.req.query('localization'); // 'complete', 'partial', 'one'
134
+ const missingLocales = c.req.query('missingLocales'); // comma-separated
135
+ try {
136
+ const filters = {};
137
+ // Pass all filters to the API - let it handle the logic
138
+ if (kind)
139
+ filters.kind = kind;
140
+ if (site)
141
+ filters.site = site;
142
+ if (collection)
143
+ filters.collection = collection;
144
+ if (locales)
145
+ filters.locales = locales.split(',').map((l) => l.trim());
146
+ if (type)
147
+ filters.type = type;
148
+ if (published !== undefined)
149
+ filters.published = published === 'true';
150
+ if (localization)
151
+ filters.localization = localization;
152
+ if (missingLocales)
153
+ filters.missingLocales = missingLocales.split(',').map((l) => l.trim());
154
+ const items = Array.from(api.listAllContent(filters));
155
+ return c.json({ items, total: items.length });
156
+ }
157
+ catch (error) {
158
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list content'), 500);
159
+ }
160
+ });
161
+ // GET /content/:id - Get all locales for content ID
162
+ app.get('/content/:id', async (c) => {
163
+ const id = c.req.param('id');
164
+ try {
165
+ const content = await api.getContent(id);
166
+ if (!content) {
167
+ return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
168
+ }
169
+ return c.json(content);
170
+ }
171
+ catch (error) {
172
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch content'), 500);
173
+ }
174
+ });
175
+ // GET /content/:id/:locale - Get specific locale only
176
+ app.get('/content/:id/:locale', async (c) => {
177
+ const id = c.req.param('id');
178
+ const locale = c.req.param('locale');
179
+ try {
180
+ const content = await api.getLocalized(id, locale);
181
+ if (!content) {
182
+ return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
183
+ }
184
+ // Set ETag header
185
+ c.header('ETag', content.localized.etag);
186
+ return c.json(content);
187
+ }
188
+ catch (error) {
189
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch localized content'), 500);
190
+ }
191
+ });
192
+ // POST /content - Create new content
193
+ app.post('/content', async (c) => {
194
+ try {
195
+ const data = await c.req.json();
196
+ const result = await api.createContent(data);
197
+ if (!result.success) {
198
+ // Map structured CreateResult failures onto the standard error
199
+ // envelope so the client can decode `error.code` / `error.message`
200
+ // and surface them in the UI. Without the envelope the client falls
201
+ // back to a generic "API error: 500" string and inline error copy
202
+ // like "already exists" never reaches the user.
203
+ const errMessage = (result.error instanceof Error ? result.error.message : undefined) ?? '';
204
+ const fieldDetails = result.field ? { field: result.field } : undefined;
205
+ const refusal = refusalOf(result.reason);
206
+ if (refusal) {
207
+ return c.json({ ...result, ...errorResponse(refusal.code, errMessage || refusal.message, fieldDetails) }, refusal.status);
208
+ }
209
+ return c.json({ ...result, ...errorResponse(ErrorCodes.WRITE_ERROR, errMessage || 'Failed to create content') }, 500);
210
+ }
211
+ return c.json(result, 201);
212
+ }
213
+ catch (error) {
214
+ console.error('[Content API] Failed to create content:', error);
215
+ return c.json({
216
+ success: false,
217
+ reason: 'write_error',
218
+ ...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, 'Failed to create content')),
219
+ }, 500);
220
+ }
221
+ });
222
+ // PUT /content/:id - Update content (full update); PATCH /content/:id - Partial update
223
+ const updateContent = async (c) => {
224
+ const id = c.req.param('id') ?? '';
225
+ const locale = c.req.query('locale');
226
+ const etag = c.req.query('etag') || '';
227
+ if (!locale) {
228
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }), 400);
229
+ }
230
+ try {
231
+ const data = await c.req.json();
232
+ const result = await api.updateLocalized({ id, locale, data, etag });
233
+ if (!result.success) {
234
+ if (result.reason === 'stale_write') {
235
+ return c.json(errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
236
+ currentEtag: result.currentEtag,
237
+ }), 412);
238
+ }
239
+ if (result.reason === 'not_found') {
240
+ return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
241
+ }
242
+ const refusal = refusalOf(result.reason);
243
+ if (refusal) {
244
+ return c.json({ ...result, ...errorResponse(refusal.code, errorMessage(result.error, refusal.message)) }, refusal.status);
245
+ }
246
+ // The backend's own refusals, such as an emptied title or metadata over 4 KB, carry their
247
+ // message in an Error, which serializes to `{}`: send it as a refused create does.
248
+ return c.json({
249
+ ...result,
250
+ ...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(result.error, 'Failed to update content')),
251
+ }, 500);
252
+ }
253
+ // Set ETag header
254
+ c.header('ETag', result.etag);
255
+ return c.json(result);
256
+ }
257
+ catch (error) {
258
+ console.error('[Content API] Failed to update content:', error);
259
+ return c.json({
260
+ success: false,
261
+ reason: 'write_error',
262
+ ...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, 'Failed to update content')),
263
+ }, 500);
264
+ }
265
+ };
266
+ app.put('/content/:id', updateContent);
267
+ app.patch('/content/:id', updateContent);
268
+ // DELETE /content/:id - Delete content (entire entry or specific locale)
269
+ app.delete('/content/:id', async (c) => {
270
+ const id = c.req.param('id');
271
+ const locale = c.req.query('locale');
272
+ const ifMatch = c.req.header('If-Match') || '';
273
+ try {
274
+ let result;
275
+ if (locale) {
276
+ // Delete specific locale
277
+ result = await api.deleteLocalized({ id, locale, etag: ifMatch });
278
+ }
279
+ else {
280
+ // Delete entire content entry
281
+ result = await api.deleteContent(id, ifMatch);
282
+ }
283
+ if (!result.success) {
284
+ if (result.reason === 'not_found') {
285
+ return c.json({
286
+ success: false,
287
+ error: 'Content not found',
288
+ }, 404);
289
+ }
290
+ if (result.reason === 'stale_write') {
291
+ return c.json({
292
+ success: false,
293
+ reason: result.reason,
294
+ currentEtag: result.currentEtag,
295
+ message: 'Content has been modified',
296
+ }, 412);
297
+ }
298
+ return c.json(result, 500);
299
+ }
300
+ return c.json({ success: true });
301
+ }
302
+ catch (error) {
303
+ console.error('[Content API] Failed to delete content:', error);
304
+ return c.json({
305
+ success: false,
306
+ error: error instanceof Error ? error.message : 'Unknown error',
307
+ }, 500);
308
+ }
309
+ });
310
+ // ===== Data Routes =====
311
+ // NOTE: These routes MUST come before /:site/* routes to avoid being captured by them
312
+ // GET /data/collections - List all data collections (must be before /data/:name)
313
+ app.get('/data/collections', async (c) => {
314
+ try {
315
+ const collections = api.data.collections;
316
+ return c.json({
317
+ collections: Array.from(collections).sort(),
318
+ });
319
+ }
320
+ catch (error) {
321
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data collections'), 500);
322
+ }
323
+ });
324
+ // GET /data/name-available - Check if data name is available
325
+ app.get('/data/name-available', async (c) => {
326
+ const name = c.req.query('name');
327
+ const collection = c.req.query('collection');
328
+ const excludeId = c.req.query('excludeId');
329
+ if (!name) {
330
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }), 400);
331
+ }
332
+ if (!collection) {
333
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {
334
+ field: 'collection',
335
+ }), 400);
336
+ }
337
+ try {
338
+ const available = api.data.isNameAvailable(collection, name, excludeId);
339
+ if (available) {
340
+ return c.json({ available: true });
341
+ }
342
+ return c.json({
343
+ available: false,
344
+ existingId: api.data.getNameConflict(collection, name, excludeId),
345
+ });
346
+ }
347
+ catch (error) {
348
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check data name availability'), 500);
349
+ }
350
+ });
351
+ // GET /data - List data entries
352
+ app.get('/data', async (c) => {
353
+ const collection = c.req.query('collection');
354
+ const locale = c.req.query('locale');
355
+ try {
356
+ const filters = { kind: 'data' };
357
+ if (collection)
358
+ filters.collection = collection;
359
+ if (locale)
360
+ filters.locales = [locale];
361
+ const items = Array.from(api.listAllContent(filters));
362
+ return c.json({ items, total: items.length });
363
+ }
364
+ catch (error) {
365
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data entries'), 500);
366
+ }
367
+ });
368
+ // GET /data/:name - Get data entry by name
369
+ app.get('/data/:name', async (c) => {
370
+ const name = c.req.param('name');
371
+ const collection = c.req.query('collection');
372
+ const locale = c.req.query('locale');
373
+ if (!collection) {
374
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {
375
+ field: 'collection',
376
+ }), 400);
377
+ }
378
+ try {
379
+ const dataEntry = api.data.getByName(collection, name, locale);
380
+ if (!dataEntry) {
381
+ return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Data entry not found', { name, collection }), 404);
382
+ }
383
+ // If locale specified and provided, filter the response
384
+ if (locale && dataEntry.locales[locale]) {
385
+ return c.json({
386
+ ...dataEntry,
387
+ locales: { [locale]: dataEntry.locales[locale] },
388
+ });
389
+ }
390
+ return c.json(dataEntry);
391
+ }
392
+ catch (error) {
393
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch data entry'), 500);
394
+ }
395
+ });
396
+ // ===== Asset Routes =====
397
+ // Must be registered BEFORE /:site routes to avoid route conflicts (/:site would match "assets")
398
+ if (options?.assetsPath) {
399
+ // Asset metadata records live under the content root. There is no falling
400
+ // back to the media folder: a site serves it, so a record there is published.
401
+ if (!options.contentRoot) {
402
+ throw new Error('The assetsPath option needs contentRoot as well: asset metadata is kept under the content root');
403
+ }
404
+ const assetOps = new AssetOperations({
405
+ assetsPath: options.assetsPath,
406
+ contentRoot: options.contentRoot,
407
+ ...options.assetConfig,
408
+ });
409
+ // Split a relative asset path into folder and filename
410
+ // e.g. 'uploads/photo.png' → { folder: '/uploads', filename: 'photo.png' }
411
+ // e.g. 'photo.png' → { folder: '/', filename: 'photo.png' }
412
+ function splitAssetPath(relativePath) {
413
+ const lastSlash = relativePath.lastIndexOf('/');
414
+ if (lastSlash > 0) {
415
+ return { folder: `/${relativePath.slice(0, lastSlash)}`, filename: relativePath.slice(lastSlash + 1) };
416
+ }
417
+ return { folder: '/', filename: relativePath };
418
+ }
419
+ // The router decodes `%2F`, so a path in the address can climb out of the assets folder. The
420
+ // containment check refuses it, and that is the caller's mistake, not a server fault.
421
+ function isPathTraversal(error) {
422
+ return error instanceof Error && error.message === 'Path traversal detected';
423
+ }
424
+ // POST /assets/move — move assets between folders
425
+ app.post('/assets/move', async (c) => {
426
+ try {
427
+ const { filenames, sourceFolder, targetFolder } = await c.req.json();
428
+ if (!Array.isArray(filenames)) {
429
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'filenames must be an array'), 400);
430
+ }
431
+ if (typeof sourceFolder !== 'string') {
432
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'sourceFolder is required'), 400);
433
+ }
434
+ if (typeof targetFolder !== 'string') {
435
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'targetFolder is required'), 400);
436
+ }
437
+ const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
438
+ if (!result.success) {
439
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
440
+ }
441
+ return c.json(result);
442
+ }
443
+ catch (error) {
444
+ if (isPathTraversal(error)) {
445
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);
446
+ }
447
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move assets'), 500);
448
+ }
449
+ });
450
+ // POST /assets/upload — multipart form data upload
451
+ app.post('/assets/upload', async (c) => {
452
+ try {
453
+ const body = await c.req.parseBody();
454
+ const file = body.file;
455
+ if (!(file instanceof File)) {
456
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'No file provided in "file" field'), 400);
457
+ }
458
+ const alt = typeof body.alt === 'string' ? body.alt : undefined;
459
+ const folder = typeof body.folder === 'string' ? body.folder : undefined;
460
+ // The uploader is deliberately not read from the request: anyone who can
461
+ // reach this route could otherwise put any name on any picture, and an
462
+ // audit trail that anyone can write is worse than no audit trail.
463
+ const result = await assetOps.upload(file, { alt, folder });
464
+ if (!result.success) {
465
+ return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
466
+ }
467
+ return c.json(result.asset, 201);
468
+ }
469
+ catch (error) {
470
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'Upload failed'), 500);
471
+ }
472
+ });
473
+ // POST /assets/import-url — import image from URL
474
+ app.post('/assets/import-url', async (c) => {
475
+ try {
476
+ const { url, alt, folder } = await c.req.json();
477
+ if (!url) {
478
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'url is required'), 400);
479
+ }
480
+ // As with /assets/upload: the uploader never comes off the wire
481
+ const result = await assetOps.importFromUrl(url, { alt, folder });
482
+ if (!result.success) {
483
+ return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
484
+ }
485
+ return c.json(result.asset, 201);
486
+ }
487
+ catch (error) {
488
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'URL import failed'), 500);
489
+ }
490
+ });
491
+ // GET /assets — list all assets
492
+ app.get('/assets', async (c) => {
493
+ try {
494
+ const assets = await assetOps.list();
495
+ return c.json({ assets });
496
+ }
497
+ catch (error) {
498
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list assets'), 500);
499
+ }
500
+ });
501
+ // GET /assets/folders — list assets and subfolders within a folder
502
+ app.get('/assets/folders', async (c) => {
503
+ try {
504
+ const path = c.req.query('path') || '/';
505
+ const result = await assetOps.listFolder(path);
506
+ return c.json(result);
507
+ }
508
+ catch (error) {
509
+ if (isPathTraversal(error)) {
510
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);
511
+ }
512
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list folder'), 500);
513
+ }
514
+ });
515
+ // POST /assets/folders — create a folder
516
+ app.post('/assets/folders', async (c) => {
517
+ try {
518
+ const { path } = await c.req.json();
519
+ if (!path) {
520
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'path is required'), 400);
521
+ }
522
+ const result = await assetOps.createFolder(path);
523
+ if (!result.success) {
524
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
525
+ }
526
+ return c.json({ success: true }, 201);
527
+ }
528
+ catch (error) {
529
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to create folder'), 500);
530
+ }
531
+ });
532
+ // GET /assets/folder-tree — get complete folder hierarchy with asset counts
533
+ app.get('/assets/folder-tree', async (c) => {
534
+ try {
535
+ const tree = await assetOps.getFolderTree();
536
+ return c.json({ tree });
537
+ }
538
+ catch (error) {
539
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get folder tree'), 500);
540
+ }
541
+ });
542
+ // GET /assets/usage/:path{.+} — content that links to the asset at this path from the assets root
543
+ app.get('/assets/usage/:path{.+}', async (c) => {
544
+ try {
545
+ const usage = await findAssetUsage(api, c.req.param('path'));
546
+ return c.json({ usage });
547
+ }
548
+ catch (error) {
549
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);
550
+ }
551
+ });
552
+ // GET /assets/serve/:path{.+} — serve actual asset file (supports subfolders)
553
+ app.get('/assets/serve/:path{.+}', async (c) => {
554
+ try {
555
+ const { folder, filename } = splitAssetPath(c.req.param('path'));
556
+ assetOps.getAssetPath(filename, folder);
557
+ const result = await assetOps.readAssetFile(filename, folder);
558
+ if (!result.success) {
559
+ return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
560
+ }
561
+ return new Response(new Uint8Array(result.buffer), {
562
+ headers: {
563
+ 'Content-Type': result.mimeType,
564
+ 'Cache-Control': 'public, max-age=31536000, immutable',
565
+ },
566
+ });
567
+ }
568
+ catch (error) {
569
+ if (isPathTraversal(error)) {
570
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
571
+ }
572
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to serve asset'), 500);
573
+ }
574
+ });
575
+ // GET /assets/meta/:path{.+} — get single asset metadata (supports subfolders)
576
+ app.get('/assets/meta/:path{.+}', async (c) => {
577
+ try {
578
+ const { folder, filename } = splitAssetPath(c.req.param('path'));
579
+ assetOps.getAssetPath(filename, folder);
580
+ const asset = await assetOps.getAsset(filename, folder);
581
+ if (!asset) {
582
+ return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, 'Asset not found'), 404);
583
+ }
584
+ return c.json(asset);
585
+ }
586
+ catch (error) {
587
+ if (isPathTraversal(error)) {
588
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
589
+ }
590
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset'), 500);
591
+ }
592
+ });
593
+ // PATCH /assets/meta/:path{.+} — update asset metadata (supports subfolders)
594
+ app.patch('/assets/meta/:path{.+}', async (c) => {
595
+ try {
596
+ const { folder, filename } = splitAssetPath(c.req.param('path'));
597
+ assetOps.getAssetPath(filename, folder);
598
+ const { alt, tags } = await c.req.json();
599
+ const result = await assetOps.updateMetadata(filename, { alt, tags }, folder);
600
+ if (!result.success) {
601
+ // A disk problem is not a missing picture: saying 404 sent the editor
602
+ // back to refetch a value it had just failed to store.
603
+ return result.reason === 'not-found'
604
+ ? c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404)
605
+ : c.json(errorResponse(ErrorCodes.INTERNAL_ERROR, result.error), 500);
606
+ }
607
+ return c.json(result.asset);
608
+ }
609
+ catch (error) {
610
+ if (isPathTraversal(error)) {
611
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
612
+ }
613
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to update asset'), 500);
614
+ }
615
+ });
616
+ // DELETE /assets/meta/:path{.+} — delete asset (supports subfolders)
617
+ app.delete('/assets/meta/:path{.+}', async (c) => {
618
+ try {
619
+ const { folder, filename } = splitAssetPath(c.req.param('path'));
620
+ assetOps.getAssetPath(filename, folder);
621
+ const result = await assetOps.delete(filename, folder);
622
+ if (!result.success) {
623
+ return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
624
+ }
625
+ return c.json({ success: true });
626
+ }
627
+ catch (error) {
628
+ if (isPathTraversal(error)) {
629
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
630
+ }
631
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to delete asset'), 500);
632
+ }
633
+ });
634
+ }
635
+ // ===== Site Routes =====
636
+ // These use /:site parameter which matches any path segment
637
+ // GET /:site/collections - Get collections for a site
638
+ app.get('/:site/collections', async (c) => {
639
+ const site = c.req.param('site');
640
+ try {
641
+ if (site === 'fragments') {
642
+ // Use the efficient collections getter for fragments
643
+ const collections = Array.from(api.fragments.collections).sort();
644
+ return c.json({ collections });
645
+ }
646
+ // Use the efficient collections getter for sites
647
+ const siteObj = api.getSite(site);
648
+ if (!siteObj) {
649
+ return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
650
+ }
651
+ const collections = Array.from(siteObj.collections).sort();
652
+ return c.json({ collections });
653
+ }
654
+ catch {
655
+ return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
656
+ }
657
+ });
658
+ // GET /:site/pages - Get pages for a site (not valid for fragments)
659
+ app.get('/:site/pages', async (c) => {
660
+ const site = c.req.param('site');
661
+ const locale = c.req.query('locale');
662
+ try {
663
+ if (site === 'fragments') {
664
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Fragments do not have pages. Use /content?kind=fragment to list fragments.'), 400);
665
+ }
666
+ const siteObj = api.getSite(site);
667
+ if (!siteObj) {
668
+ return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
669
+ }
670
+ // Use listContent with locales filter
671
+ const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));
672
+ const result = { items, total: items.length };
673
+ return c.json(result);
674
+ }
675
+ catch (error) {
676
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, {
677
+ site,
678
+ }), 500);
679
+ }
680
+ });
681
+ // GET /:site/pathname-available - Check if pathname is available
682
+ app.get('/:site/pathname-available', async (c) => {
683
+ const site = c.req.param('site');
684
+ const pathname = c.req.query('pathname');
685
+ const locale = c.req.query('locale') || 'en';
686
+ const excludeId = c.req.query('excludeId');
687
+ if (!pathname) {
688
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'pathname query parameter is required', { field: 'pathname' }), 400);
689
+ }
690
+ try {
691
+ if (site === 'fragments') {
692
+ return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Fragments do not have pathnames. This endpoint is only for page content.'), 400);
693
+ }
694
+ // Defensive: if the pathname shape is malformed, short-circuit with
695
+ // a structured reason instead of a meaningless index lookup. The
696
+ // dialog short-circuits client-side already, so this guards direct
697
+ // API callers (and future clients) from getting a misleading
698
+ // `{ available: true }` for an invalid path.
699
+ const validation = normalizeAndValidatePathname(pathname);
700
+ if (!validation.valid) {
701
+ return c.json({
702
+ available: false,
703
+ reason: 'invalid_pathname',
704
+ message: validation.message,
705
+ });
706
+ }
707
+ const normalized = validation.value;
708
+ // Use the optimized pathname index via site.isPathnameAvailable
709
+ const siteObj = api.getSite(site);
710
+ if (!siteObj) {
711
+ return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
712
+ }
713
+ const available = siteObj.isPathnameAvailable(normalized, locale, excludeId);
714
+ if (available) {
715
+ return c.json({ available: true });
716
+ }
717
+ // Get the conflicting content ID if pathname is taken
718
+ const existingId = siteObj.getPathnameConflict(normalized, locale, excludeId);
719
+ return c.json({
720
+ available: false,
721
+ existingId,
722
+ });
723
+ }
724
+ catch (error) {
725
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check pathname availability'), 500);
726
+ }
727
+ });
728
+ // GET /fragments - Shorthand for all fragments
729
+ app.get('/fragments', async (c) => {
730
+ const collection = c.req.query('collection');
731
+ const locale = c.req.query('locale');
732
+ try {
733
+ const filters = { kind: 'fragment' };
734
+ if (collection)
735
+ filters.collection = collection;
736
+ if (locale)
737
+ filters.locales = [locale];
738
+ const items = Array.from(api.listAllContent(filters));
739
+ return c.json({ items, total: items.length });
740
+ }
741
+ catch (error) {
742
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list fragments'), 500);
743
+ }
744
+ });
745
+ // GET /fragments/name-available - Check if fragment name is available
746
+ app.get('/fragments/name-available', async (c) => {
747
+ const name = c.req.query('name');
748
+ const collection = c.req.query('collection') || 'components';
749
+ const locale = c.req.query('locale') || 'en';
750
+ const excludeId = c.req.query('excludeId');
751
+ if (!name) {
752
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }), 400);
753
+ }
754
+ try {
755
+ // Check fragment name availability through listing
756
+ const existing = Array.from(api.listAllContent({
757
+ kind: 'fragment',
758
+ collection: collection,
759
+ locales: [locale],
760
+ }));
761
+ let taken;
762
+ for (const item of existing) {
763
+ for (const localeVersion of localesOf(item)) {
764
+ if (localeVersion.name === name) {
765
+ taken = item;
766
+ break;
767
+ }
768
+ }
769
+ }
770
+ // If no existing fragment, name is available
771
+ if (!taken) {
772
+ return c.json({ available: true });
773
+ }
774
+ // If existing fragment has same ID as excludeId, name is available
775
+ // (useful when editing existing fragment)
776
+ if (excludeId && taken.id === excludeId) {
777
+ return c.json({ available: true });
778
+ }
779
+ // Otherwise, name is taken
780
+ return c.json({
781
+ available: false,
782
+ existingId: taken.id,
783
+ });
784
+ }
785
+ catch (error) {
786
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check fragment name availability'), 500);
787
+ }
788
+ });
789
+ // GET /fragments/:name - Get fragment by name
790
+ app.get('/fragments/:name', async (c) => {
791
+ const name = c.req.param('name');
792
+ const collection = c.req.query('collection') || 'components';
793
+ const locale = c.req.query('locale');
794
+ try {
795
+ const fragment = api.fragments.getByName(collection, name, locale);
796
+ if (!fragment) {
797
+ return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Fragment not found', { name, collection }), 404);
798
+ }
799
+ // If locale specified and provided, filter the response
800
+ if (locale && fragment.locales[locale]) {
801
+ return c.json({
802
+ ...fragment,
803
+ locales: { [locale]: fragment.locales[locale] },
804
+ });
805
+ }
806
+ return c.json(fragment);
807
+ }
808
+ catch (error) {
809
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch fragment'), 500);
810
+ }
811
+ });
812
+ // POST /:site/move - Move page to new pathname
813
+ app.post('/:site/move', async (c) => {
814
+ const site = c.req.param('site');
815
+ try {
816
+ const { id, pathname, locale, etag } = await c.req.json();
817
+ if (!id || !pathname || !locale || !etag) {
818
+ return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'id, pathname, locale, and etag are required'), 400);
819
+ }
820
+ const siteObj = api.getSite(site);
821
+ if (!siteObj) {
822
+ return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
823
+ }
824
+ // First check if the pathname is available
825
+ const existing = siteObj.getByPathname(pathname, locale);
826
+ if (existing && existing.id !== id) {
827
+ return c.json({
828
+ moved: false,
829
+ reason: 'already_exists',
830
+ ...errorResponse(ErrorCodes.PATHNAME_TAKEN, 'Pathname already taken', { existingId: existing.id }),
831
+ }, 409);
832
+ }
833
+ // Get current content to track previous pathname
834
+ const current = await api.getLocalized(id, locale);
835
+ if (!current) {
836
+ return c.json({ moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) }, 404);
837
+ }
838
+ const previousPathname = current.localized.pathname;
839
+ // Update with new pathname using updateLocalized for etag validation
840
+ const updateResult = await api.updateLocalized({
841
+ id,
842
+ locale,
843
+ data: {
844
+ pathname: pathname,
845
+ meta: current.localized.meta,
846
+ },
847
+ etag: etag,
848
+ });
849
+ if (!updateResult.success) {
850
+ if (updateResult.reason === 'stale_write') {
851
+ return c.json({
852
+ moved: false,
853
+ reason: 'stale_write',
854
+ currentEtag: updateResult.currentEtag,
855
+ message: 'Content has been modified',
856
+ }, 412);
857
+ }
858
+ if (updateResult.reason === 'not_found') {
859
+ return c.json({ moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) }, 404);
860
+ }
861
+ // The update checks the new path as a create does: a malformed one is invalid_pathname, and
862
+ // another page's path written loosely ('/team/') passes the check above but not the update.
863
+ // A move calls a taken path already_exists, as the check above does.
864
+ const refusal = refusalOf(updateResult.reason);
865
+ if (refusal) {
866
+ const reason = updateResult.reason === 'invalid_pathname' ? 'invalid_pathname' : 'already_exists';
867
+ return c.json({ moved: false, reason, ...errorResponse(refusal.code, errorMessage(updateResult.error, 'Move refused')) }, refusal.status);
868
+ }
869
+ return c.json({ moved: false, ...errorResponse(ErrorCodes.WRITE_ERROR, 'Update failed') }, 500);
870
+ }
871
+ return c.json({
872
+ moved: true,
873
+ previousPathname: previousPathname,
874
+ etag: updateResult.etag,
875
+ });
876
+ }
877
+ catch (error) {
878
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move page'), 500);
879
+ }
880
+ });
881
+ // GET /untranslated/:locale - Find untranslated content
882
+ app.get('/untranslated/:targetLocale', async (c) => {
883
+ const targetLocale = c.req.param('targetLocale');
884
+ const excludeSites = c.req
885
+ .query('excludeSites')
886
+ ?.split(',')
887
+ .map((s) => s.trim())
888
+ .filter((s) => s);
889
+ const includeUnpublished = c.req.query('includeUnpublished') === 'true';
890
+ try {
891
+ const options = {
892
+ ...(excludeSites?.length && { excludeSites }),
893
+ ...(includeUnpublished && { includeUnpublished }),
894
+ };
895
+ const items = Array.from(api.findUntranslatedContent(targetLocale, options));
896
+ return c.json({ items, total: items.length });
897
+ }
898
+ catch (error) {
899
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to find untranslated content'), 500);
900
+ }
901
+ });
902
+ // GET /sites - Get sites configuration
903
+ app.get('/sites', async (c) => {
904
+ try {
905
+ const config = api.sitesConfig;
906
+ return c.json(config);
907
+ }
908
+ catch (error) {
909
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch sites configuration'), 500);
910
+ }
911
+ });
912
+ // POST /content/batch - Batch update operations
913
+ app.post('/content/batch', async (c) => {
914
+ try {
915
+ const { operations } = await c.req.json();
916
+ const result = await api.batchUpdate(operations);
917
+ if (!result.success) {
918
+ return c.json(result, 207); // Multi-status
919
+ }
920
+ return c.json(result);
921
+ }
922
+ catch (error) {
923
+ console.error('[Content API] Failed to batch update:', error);
924
+ return c.json({
925
+ success: false,
926
+ error: error instanceof Error ? error.message : 'Unknown error',
927
+ }, 500);
928
+ }
929
+ });
930
+ // ===== Git Routes =====
931
+ /**
932
+ * Get git config from router options or environment variables.
933
+ * contentRoot from router options takes priority over CONTENT_PATH env var.
934
+ * Optional: GIT_BRANCH (defaults to current checked-out branch)
935
+ */
936
+ function getGitConfig() {
937
+ const contentPath = options?.contentRoot || process.env.CONTENT_PATH;
938
+ if (!contentPath) {
939
+ throw new Error('contentRoot option or CONTENT_PATH environment variable is required for git operations');
940
+ }
941
+ return {
942
+ contentPath,
943
+ branch: process.env.GIT_BRANCH,
944
+ };
945
+ }
946
+ // GET /git/status - Get git repository status
947
+ app.get('/git/status', async (c) => {
948
+ try {
949
+ const config = getGitConfig();
950
+ const gitOps = createGitOperations(config);
951
+ const status = await gitOps.getStatus();
952
+ if (!status.isRepo) {
953
+ return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, 'Repository not accessible'), 400);
954
+ }
955
+ return c.json(status);
956
+ }
957
+ catch (error) {
958
+ if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
959
+ return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
960
+ }
961
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, 'Failed to get git status'), 500);
962
+ }
963
+ });
964
+ // POST /git/commit - Commit all changes
965
+ app.post('/git/commit', async (c) => {
966
+ try {
967
+ const body = await c.req.json().catch(() => undefined);
968
+ // Auto-generate message if not provided
969
+ const date = new Date();
970
+ const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
971
+ const defaultMessage = `CMS changes - ${monthNames[date.getMonth()]} ${date.getDate()}`;
972
+ const message = body?.message || defaultMessage;
973
+ // Extract user email from CF Access header for commit attribution
974
+ const userEmail = c.req.header('X-CF-User-Email');
975
+ const author = userEmail ? { name: userEmail.split('@')[0], email: userEmail } : undefined;
976
+ const config = getGitConfig();
977
+ const gitOps = createGitOperations(config);
978
+ const result = await gitOps.commitAll(message, author);
979
+ if (!result.success) {
980
+ return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || 'Commit failed'), 500);
981
+ }
982
+ return c.json(result);
983
+ }
984
+ catch (error) {
985
+ if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
986
+ return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
987
+ }
988
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, 'Failed to commit changes'), 500);
989
+ }
990
+ });
991
+ // POST /git/push - Push to origin
992
+ app.post('/git/push', async (c) => {
993
+ try {
994
+ const config = getGitConfig();
995
+ const gitOps = createGitOperations(config);
996
+ const result = await gitOps.pushOrigin();
997
+ if (!result.success) {
998
+ return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || 'Push failed'), 500);
999
+ }
1000
+ return c.json(result);
1001
+ }
1002
+ catch (error) {
1003
+ if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
1004
+ return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
1005
+ }
1006
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, 'Failed to push to origin'), 500);
1007
+ }
1008
+ });
1009
+ // POST /git/pull - Pull from origin with autostash + rebase
1010
+ app.post('/git/pull', async (c) => {
1011
+ try {
1012
+ const config = getGitConfig();
1013
+ const gitOps = createGitOperations(config);
1014
+ const result = await gitOps.pull();
1015
+ if (!result.success) {
1016
+ return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || 'Pull failed'), 500);
1017
+ }
1018
+ return c.json(result);
1019
+ }
1020
+ catch (error) {
1021
+ if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
1022
+ return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
1023
+ }
1024
+ return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, 'Failed to pull from origin'), 500);
1025
+ }
1026
+ });
1027
+ return app;
1028
+ }
1029
+ /**
1030
+ * Create middleware for backwards compatibility with existing code
1031
+ * This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse
1032
+ */
1033
+ export function createContentMiddleware(contentApi, options) {
1034
+ const app = createContentAPIRouter(contentApi, options);
1035
+ // Convert Hono app to Node.js middleware
1036
+ return async (req, res, next) => {
1037
+ const url = new URL(req.url, `http://${req.headers.host}`);
1038
+ // Only handle API routes (base path depends on context)
1039
+ const basePath = url.pathname.startsWith('/__cms/api') ? '/__cms/api' : '/__conloca/api';
1040
+ if (!url.pathname.startsWith(basePath)) {
1041
+ return next();
1042
+ }
1043
+ // Strip the base path to match Hono routes
1044
+ const path = url.pathname.replace(basePath, '');
1045
+ // Create a Request object for Hono
1046
+ const request = new Request(`http://localhost${path}${url.search}`, {
1047
+ method: req.method,
1048
+ headers: req.headers,
1049
+ body: ['GET', 'HEAD'].includes(req.method) ? undefined : await readBody(req),
1050
+ });
1051
+ // Handle with Hono
1052
+ const response = await app.fetch(request);
1053
+ // Copy response headers
1054
+ response.headers.forEach((value, key) => {
1055
+ res.setHeader(key, value);
1056
+ });
1057
+ // Set status code
1058
+ res.statusCode = response.status;
1059
+ // Send response body
1060
+ const body = await response.text();
1061
+ res.end(body);
1062
+ };
1063
+ }
1064
+ // Helper to read request body
1065
+ function readBody(req) {
1066
+ return new Promise((resolve, reject) => {
1067
+ const chunks = [];
1068
+ req.on('data', (chunk) => chunks.push(new Uint8Array(chunk)));
1069
+ req.on('end', () => {
1070
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1071
+ const combined = new Uint8Array(totalLength);
1072
+ let offset = 0;
1073
+ for (const chunk of chunks) {
1074
+ combined.set(chunk, offset);
1075
+ offset += chunk.length;
1076
+ }
1077
+ resolve(Buffer.from(combined).toString());
1078
+ });
1079
+ req.on('error', reject);
1080
+ });
1081
+ }
1082
+ //# sourceMappingURL=middleware.js.map