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