@conloca/content-api 0.1.16 → 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 (299) 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 +18 -13
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +302 -254
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  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 +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +59 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +88 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +407 -281
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +6 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +170 -119
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +914 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +47 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +113 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2685 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1341 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -0,0 +1,2685 @@
1
+ import { access, mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import sortKeys from 'sort-keys';
5
+ import type { ContentAPI } from './content-api.interface.js';
6
+ import { filterContentWithIndexes } from './content-filters.js';
7
+ import { ContentIndex, duplicateIdMessage, type IndexProblem, unknownSiteMessage } from './content-index.js';
8
+ import {
9
+ analyzeUpdateScope,
10
+ buildLocaleVersion,
11
+ buildPathnameHistory,
12
+ checkEntryName,
13
+ checkMdxPagesPathname,
14
+ checkPagePathname,
15
+ generateContentId,
16
+ isContentPublished,
17
+ type PathnameRefusal,
18
+ shouldUpdateModifiedTimestamp,
19
+ UPDATE_SCOPE,
20
+ updatePublishDates,
21
+ validateAndPrepareMetadata,
22
+ validateCreateContent,
23
+ } from './content-operations.js';
24
+ import { type ContentPathLayout, parseContentPathLayout, parseLocaleFilename } from './content-path.js';
25
+ import {
26
+ applyMetaPatch,
27
+ localesOf,
28
+ mapSiteNames,
29
+ resolvePublishDate,
30
+ serializeMdxWithFrontmatter,
31
+ } from './content-utils.js';
32
+ import { Data } from './data.js';
33
+ import { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils.js';
34
+ import { Fragments } from './fragments.js';
35
+ import { Site } from './site.js';
36
+ import type {
37
+ BatchOperationResult,
38
+ BatchResult,
39
+ ContentAPIOptions,
40
+ ContentData,
41
+ ContentEntry,
42
+ ContentIdentity,
43
+ ContentManifest,
44
+ ContentMeta,
45
+ ContentProp,
46
+ ContentType,
47
+ CreateContentInput,
48
+ CreateResult,
49
+ DeleteLocaleInput,
50
+ DeleteResult,
51
+ FindOptions,
52
+ GlobalFilters,
53
+ LocaleFileData,
54
+ LocalePathData,
55
+ LocaleVersion,
56
+ LocalizedEntry,
57
+ LocalizedManifest,
58
+ SitesConfig,
59
+ UpdateLocaleInput,
60
+ UpdateResult,
61
+ VXJSONFile,
62
+ } from './types.js';
63
+ import { atomicWriteFile } from './utils/atomic-write.js';
64
+ import { xxh64 } from './xxhash.js';
65
+
66
+ interface ReindexResult {
67
+ filesProcessed: number;
68
+ filesSkipped: number;
69
+ filesDeleted?: number;
70
+ errors?: number;
71
+ // Return manifests of updated locales (without content)
72
+ updated: LocalizedManifest[];
73
+ deleted?: Array<{ id: string; locale: string; kind: 'page' | 'fragment' | 'data' }>;
74
+ }
75
+
76
+ import { VXJSON } from './vxjson.js';
77
+
78
+ // Helper to ensure we have an Error object
79
+ function ensureError(error: unknown): Error {
80
+ if (error instanceof Error) {
81
+ return error;
82
+ }
83
+ return new Error(String(error));
84
+ }
85
+
86
+ // Reusable TextDecoder instance - safe to reuse as it's stateless
87
+ const textDecoder = new TextDecoder();
88
+
89
+ async function readFilePrefix(filePath: string, buffer: Uint8Array): Promise<number> {
90
+ const handle = await open(filePath, 'r');
91
+ try {
92
+ return (await handle.read(buffer, 0, buffer.byteLength, 0)).bytesRead;
93
+ } finally {
94
+ await handle.close();
95
+ }
96
+ }
97
+
98
+ // Parse 4KB MDX content - extracts frontmatter from buffer
99
+ function parse4KBMDX(
100
+ buffer: Uint8Array,
101
+ bytesRead: number,
102
+ ): {
103
+ id?: string;
104
+ created?: string;
105
+ modified?: string;
106
+ publishAt?: string;
107
+ unpublishAt?: string;
108
+ meta: ContentMeta;
109
+ contentStartPos?: number; // Position where content starts (after second ---)
110
+ } {
111
+ // Only convert to string what we need
112
+ const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));
113
+ // Empty options opt out of gray-matter's module-level memo cache — a plain
114
+ // object keyed by the raw input, so inputs naming an Object.prototype member
115
+ // ('valueOf', 'toString', …) return the inherited member instead of a parse.
116
+ // Same at every matter() call below.
117
+ const { data: frontmatter } = matter(partialContent, {});
118
+
119
+ // Find where content starts (after second ---)
120
+ const delimiter = new TextEncoder().encode('---');
121
+ let delimiterCount = 0;
122
+ let contentStartPos = -1;
123
+
124
+ for (let i = 0; i <= bytesRead - delimiter.length; i++) {
125
+ let match = true;
126
+ for (let j = 0; j < delimiter.length; j++) {
127
+ if (buffer[i + j] !== delimiter[j]) {
128
+ match = false;
129
+ break;
130
+ }
131
+ }
132
+ if (match) {
133
+ delimiterCount++;
134
+ if (delimiterCount === 2) {
135
+ // Skip past --- and newline
136
+ contentStartPos = i + delimiter.length;
137
+ while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {
138
+ contentStartPos++;
139
+ }
140
+ break;
141
+ }
142
+ }
143
+ }
144
+
145
+ // Extract special fields and treat the rest as metadata
146
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
147
+
148
+ return {
149
+ id,
150
+ created,
151
+ modified,
152
+ publishAt,
153
+ unpublishAt,
154
+ meta: metaFields as ContentMeta, // All other fields are metadata
155
+ contentStartPos,
156
+ };
157
+ }
158
+
159
+ /**
160
+ * FileSystem-based Content API Implementation
161
+ *
162
+ * Stores content as files on disk in a git-friendly format:
163
+ * - Pages: /{site}/pages/{filename}.{locale}.vxjson
164
+ * - Fragments: /fragments/{collection}/{filename}.{locale}.{mdx|vxjson}
165
+ *
166
+ * ## Indexing
167
+ *
168
+ * Content is indexed at startup for performance. The index is cached per
169
+ * content root path and cleared when the process restarts.
170
+ *
171
+ * ## Read-Repair
172
+ *
173
+ * Since files can be modified externally (git, editors), this implementation:
174
+ *
175
+ * 1. Repairs invalid VXJSON files (ensures "content" field is last)
176
+ * 2. Adds missing required fields (id, created, modified)
177
+ * 3. Handles files added after initial indexing
178
+ * 4. Updates the index when files are repaired or discovered
179
+ *
180
+ * ## Performance
181
+ *
182
+ * - Initial indexing reads only first 4KB of each file
183
+ * - Full content is loaded on demand
184
+ * - ETags are calculated using streaming for efficiency
185
+ */
186
+ /**
187
+ * Read and validate `<contentRoot>/sites.json`. Returns a safe default
188
+ * (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
189
+ * has invalid structure, with a warning logged in each case.
190
+ *
191
+ * Exported standalone so the Astro integration (and any other tooling
192
+ * that needs to inspect per-site config at startup time) can read the
193
+ * config without spinning up a full content-api instance.
194
+ */
195
+ export async function readSitesConfig(contentRoot: string): Promise<SitesConfig> {
196
+ const absoluteContentRoot = resolve(contentRoot);
197
+ const sitesPath = join(absoluteContentRoot, 'sites.json');
198
+ let content: string;
199
+ try {
200
+ content = await readFile(sitesPath, 'utf-8');
201
+ } catch {
202
+ // A genuinely absent sites.json is a normal starting state.
203
+ console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
204
+ return { sites: {}, globalLocales: ['en'] };
205
+ }
206
+
207
+ // Tolerating a malformed sites.json is deliberate ("Handle invalid sites.json gracefully"). What
208
+ // was not deliberate is the diagnosis: this used to share the catch above
209
+ // and report the file as MISSING, naming a path where it plainly sits,
210
+ // while every page silently dropped out of every site. Say what is
211
+ // actually wrong; the tolerance itself is unchanged.
212
+ let parsed: SitesConfig;
213
+ try {
214
+ parsed = JSON.parse(content);
215
+ } catch (error) {
216
+ console.warn(
217
+ `Warning: sites.json at ${sitesPath} is not valid JSON (${messageOf(error)}). ` +
218
+ 'Using empty configuration — every site will be empty until this is fixed.',
219
+ );
220
+ return { sites: {}, globalLocales: ['en'] };
221
+ }
222
+ // Validate the structure. `null` is valid JSON, so `parsed` itself needs
223
+ // the null check before anything reads a property off it.
224
+ if (!parsed?.sites || typeof parsed.sites !== 'object') {
225
+ console.warn(
226
+ `Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`,
227
+ );
228
+ return { sites: {}, globalLocales: ['en'] };
229
+ }
230
+ if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
231
+ console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
232
+ return {
233
+ sites: parsed.sites,
234
+ globalLocales: ['en'],
235
+ };
236
+ }
237
+ return parsed;
238
+ }
239
+
240
+ export type { IndexProblem } from './content-index.js';
241
+
242
+ function messageOf(error: unknown): string {
243
+ return error instanceof Error ? error.message : String(error);
244
+ }
245
+
246
+ export class FileSystemContentAPI implements ContentAPI {
247
+ private contentRoot: string;
248
+ private absoluteContentRoot: string;
249
+ private contentIndex: ContentIndex;
250
+ readonly sitesConfig: SitesConfig;
251
+ readonly fragments: Fragments;
252
+ readonly data: Data;
253
+ private readonly sites: Record<string, Site>;
254
+
255
+ // mdx-page support: optional second filesystem root for kind:'page'+type:'mdx'.
256
+ // Canonical source is the resolved site's `mdxPages` in sites.json; the
257
+ // ContentAPIOptions.mdxPagesRoot option exists as a test/programmatic
258
+ // override. See ContentAPIOptions.mdxPagesRoot for the design rationale.
259
+ private absoluteMdxPagesRoot?: string;
260
+ private mdxPagesDefaultLocale = 'en';
261
+ private mdxPagesSite = 'default';
262
+ private mdxPagesCollection = 'pages';
263
+
264
+ // Resolved locale list used to decide whether a path segment that
265
+ // looks locale-shaped (e.g. `de`, `en-US`) is actually a configured
266
+ // locale. Source-of-truth resolution (option > sites.json) happens in
267
+ // the constructor; parsers read this set directly.
268
+ private readonly availableLocales: ReadonlySet<string>;
269
+
270
+ // Getter for testing purposes
271
+ get normalizedContentRoot(): string {
272
+ return this.contentRoot;
273
+ }
274
+
275
+ private constructor(
276
+ contentRoot: string,
277
+ sitesConfig: SitesConfig,
278
+ contentIndex: ContentIndex,
279
+ mdxPagesOptions?: {
280
+ root?: string;
281
+ defaultLocale?: string;
282
+ site?: string;
283
+ },
284
+ localeOptions?: {
285
+ availableLocales?: string[];
286
+ defaultLocale?: string;
287
+ },
288
+ ) {
289
+ // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is
290
+ if (contentRoot.startsWith('./')) {
291
+ this.contentRoot = contentRoot.slice(2);
292
+ } else if (contentRoot.startsWith('/')) {
293
+ // Absolute path, keep as-is
294
+ this.contentRoot = contentRoot;
295
+ } else {
296
+ // Already normalized relative path
297
+ this.contentRoot = contentRoot;
298
+ }
299
+
300
+ // Store absolute path for file operations
301
+ this.absoluteContentRoot = resolve(this.contentRoot);
302
+
303
+ this.sitesConfig = sitesConfig;
304
+ this.contentIndex = contentIndex;
305
+
306
+ // Resolve which site owns mdx-type pages. Resolution order:
307
+ // 1. Explicit `mdxPagesOptions.site` (test / programmatic override)
308
+ // 2. First site in sites.json that declares an `mdxPages` path
309
+ // 3. First configured site (any)
310
+ // 4. Literal 'default'
311
+ const siteNames = Object.keys(sitesConfig.sites);
312
+ const firstSiteName = siteNames[0];
313
+ const firstSiteWithMdxPages = siteNames.find((name) => sitesConfig.sites[name]?.mdxPages);
314
+ this.mdxPagesSite = mdxPagesOptions?.site ?? firstSiteWithMdxPages ?? firstSiteName ?? 'default';
315
+
316
+ // Resolve the mdx-pages path. Option wins over sites.json so tests and
317
+ // programmatic callers can supply a path without writing a sites.json
318
+ // file. When neither is set, .mdx files fall back to living alongside
319
+ // Puck pages under `{contentRoot}/{site}/pages/`.
320
+ const sitesJsonMdxPages = sitesConfig.sites[this.mdxPagesSite]?.mdxPages;
321
+ const resolvedMdxPages = mdxPagesOptions?.root ?? sitesJsonMdxPages;
322
+ if (resolvedMdxPages) {
323
+ const normalizedMdxPages = resolvedMdxPages.startsWith('./') ? resolvedMdxPages.slice(2) : resolvedMdxPages;
324
+ this.absoluteMdxPagesRoot = resolve(normalizedMdxPages);
325
+ }
326
+ // Default locale: top-level option > mdxPages option > resolved-site's
327
+ // defaultLocale > first global locale > 'en'. The top-level option wins
328
+ // because it represents an explicit framework-level declaration (e.g.
329
+ // forwarded from Astro's i18n block via localesFromAstroI18n).
330
+ const siteConfig = sitesConfig.sites[this.mdxPagesSite];
331
+ this.mdxPagesDefaultLocale =
332
+ localeOptions?.defaultLocale ??
333
+ mdxPagesOptions?.defaultLocale ??
334
+ siteConfig?.defaultLocale ??
335
+ sitesConfig.globalLocales[0] ??
336
+ 'en';
337
+
338
+ // Resolve the available-locales set. The top-level option is
339
+ // authoritative when present; otherwise we merge sites.json's global
340
+ // locales with the resolved-site's per-site locales. The default
341
+ // locale is always added so getFilePath round-trips work.
342
+ const merged = new Set<string>();
343
+ if (localeOptions?.availableLocales && localeOptions.availableLocales.length > 0) {
344
+ for (const loc of localeOptions.availableLocales) merged.add(loc);
345
+ } else {
346
+ for (const loc of sitesConfig.globalLocales) merged.add(loc);
347
+ if (siteConfig?.locales) {
348
+ for (const loc of siteConfig.locales) merged.add(loc);
349
+ }
350
+ }
351
+ merged.add(this.mdxPagesDefaultLocale);
352
+ this.availableLocales = merged;
353
+
354
+ // Initialize fragments
355
+ this.fragments = new Fragments(this, this.contentIndex.getFragmentIndex());
356
+
357
+ // Initialize data
358
+ this.data = new Data(this, this.contentIndex.getDataIndex());
359
+
360
+ // Initialize all sites
361
+ this.sites = mapSiteNames(sitesConfig, (siteName) => {
362
+ const siteIndex = this.contentIndex.getSiteIndex(siteName);
363
+ if (!siteIndex) {
364
+ throw new Error(`Site index not found for ${siteName}`);
365
+ }
366
+ return new Site(siteName, this, siteIndex);
367
+ });
368
+ }
369
+
370
+ static async create(options: ContentAPIOptions): Promise<FileSystemContentAPI> {
371
+ // Keep contentRoot as provided (will be normalized in constructor)
372
+ const contentRoot = options.contentRoot;
373
+
374
+ // Load sites config (canonical home for per-site fields including mdxPages).
375
+ let sitesConfig = await readSitesConfig(contentRoot);
376
+
377
+ // Apply the top-level locales option as the authoritative source.
378
+ // We expand sitesConfig so that the FragmentIndex (which keys on
379
+ // globalLocales) and the resolved SiteIndex (which keys on the
380
+ // site's locales array) both have slots for every option-declared
381
+ // locale. Without this, the parser would correctly identify a file's
382
+ // locale but `addContent` would crash on a missing index bucket.
383
+ // We preserve the resolved site's existing `mdxPages` and `domains`
384
+ // through the rewrite so the locale-override doesn't clobber the
385
+ // per-site content config.
386
+ if (options.availableLocales && options.availableLocales.length > 0) {
387
+ const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
388
+ const optionSite = options.mdxPagesSite ?? Object.keys(sitesConfig.sites)[0] ?? 'default';
389
+ const existingSite = sitesConfig.sites[optionSite];
390
+ sitesConfig = {
391
+ sites: {
392
+ ...sitesConfig.sites,
393
+ [optionSite]: {
394
+ locales: options.availableLocales,
395
+ defaultLocale: optionDefaultLocale,
396
+ ...(existingSite?.domains && { domains: existingSite.domains }),
397
+ ...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),
398
+ },
399
+ },
400
+ globalLocales: Array.from(new Set([...sitesConfig.globalLocales, ...options.availableLocales])),
401
+ };
402
+ }
403
+
404
+ // Get cached content index or create new one
405
+ // Use the normalized contentRoot for cache key
406
+ const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;
407
+ const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
408
+
409
+ // Create instance (not cached)
410
+ const api = new FileSystemContentAPI(
411
+ contentRoot,
412
+ sitesConfig,
413
+ contentIndex,
414
+ {
415
+ root: options.mdxPagesRoot,
416
+ defaultLocale: options.mdxPagesDefaultLocale,
417
+ site: options.mdxPagesSite,
418
+ },
419
+ {
420
+ availableLocales: options.availableLocales,
421
+ defaultLocale: options.defaultLocale,
422
+ },
423
+ );
424
+
425
+ // Index all content files (only if index is empty).
426
+ //
427
+ // FileSystemContentAPI continues to hydrate via parseFileHeaderWithRepair
428
+ // (legacy path), which performs read-repair side effects on disk (renaming
429
+ // missing-locale files, rewriting non-canonical VXJSON, adding missing
430
+ // id/created/modified). ContentIndex.indexAll(backend) is the newer,
431
+ // backend-agnostic hydration path for content that is not on disk;
432
+ // FileSystemContentAPI's behavior must stay identical, so this call site
433
+ // keeps the legacy path until the repair side effects move behind a backend.
434
+ if (contentIndex.entryCount === 0) {
435
+ await api.indexAllContent();
436
+ }
437
+
438
+ return api;
439
+ }
440
+
441
+ /**
442
+ * Hydrate the content index for this FileSystemContentAPI by scanning the
443
+ * content root and running parseFileHeaderWithRepair on each file. This is
444
+ * the legacy hydration path that preserves the filesystem read-repair
445
+ * behavior (file renames, canonical-form rewrites, id/timestamp backfill).
446
+ *
447
+ * ContentIndex.indexAll(backend) is the backend-agnostic replacement for
448
+ * content that is not on disk; this private method exists so FileSystemContentAPI
449
+ * can keep its repair-on-read side effects until they are lifted onto a
450
+ * dedicated FileSystemReaderBackend field.
451
+ */
452
+ private async indexAllContent(): Promise<void> {
453
+ // Also drops the previous problems: they describe an index that no longer exists.
454
+ this.contentIndex.clear();
455
+
456
+ const files = await this.scanContentFiles();
457
+ const OPTIMAL_BATCH_SIZE = 1000;
458
+ console.debug(`Indexing ${files.length} content files...`);
459
+
460
+ // Which file claimed each id+locale — same guard ContentIndex.indexAll
461
+ // carries. Without it a duplicated file merges into the first one's
462
+ // locale slot and a page silently stops existing, and this legacy path
463
+ // is the one every local dev server and Astro build hydrates through.
464
+ const claimedBy = new Map<string, string>();
465
+
466
+ // Reuse a small pool of 4KB buffers across the batch; matches the
467
+ // existing reindex() loop. parseFileHeaderWithRepair owns the buffer
468
+ // contract (reads up to 4096 bytes from offset 0).
469
+ const buffers = Array.from({ length: Math.min(files.length, 100) }, () => new Uint8Array(4096));
470
+
471
+ for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
472
+ const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
473
+ await Promise.all(
474
+ batch.map(async (filePath, batchIndex) => {
475
+ const buffer = buffers[(i + batchIndex) % buffers.length];
476
+ try {
477
+ const result = await this.parseFileHeaderWithRepair(filePath, buffer);
478
+ if (result) {
479
+ // Same reason as the shared indexAll loop: a page under a site
480
+ // sites.json does not declare would be filed nowhere and
481
+ // silently vanish from every lookup and build.
482
+ if (
483
+ result.manifest.kind === 'page' &&
484
+ result.manifest.site &&
485
+ !this.contentIndex.hasSite(result.manifest.site)
486
+ ) {
487
+ this.recordIndexProblem(filePath, 'unknown-site', unknownSiteMessage(result.manifest.site));
488
+ return;
489
+ }
490
+ const claim = `${result.manifest.id}::${result.localeVersion.locale}`;
491
+ const claimant = claimedBy.get(claim);
492
+ if (claimant !== undefined && claimant !== filePath) {
493
+ this.recordIndexProblem(
494
+ filePath,
495
+ 'duplicate-id',
496
+ duplicateIdMessage(result.manifest.id, result.localeVersion.locale, claimant),
497
+ );
498
+ return;
499
+ }
500
+ claimedBy.set(claim, filePath);
501
+ this.contentIndex.addContent(result.manifest, result.localeVersion, result.content);
502
+ }
503
+ } catch (error) {
504
+ console.error(`Failed to index ${filePath}: ${messageOf(error)}`);
505
+ this.recordIndexProblem(filePath, 'index-error', messageOf(error));
506
+ }
507
+ }),
508
+ );
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Record a file the indexer could not read. Signature matches the `onError`
514
+ * callback of ContentIndex.indexAll so it can be handed over unchanged when
515
+ * this class migrates off the legacy repair-on-read hydration path. The
516
+ * problems live on the index itself, not on this instance: the index is
517
+ * cached per content root, and a later instance over the same root reuses it
518
+ * without re-indexing, so instance-local problems would vanish.
519
+ */
520
+ private recordIndexProblem(path: string, reason: string, message: string): void {
521
+ this.contentIndex.recordProblem(path, reason, message);
522
+ }
523
+
524
+ /**
525
+ * Files the indexer could not read. They are absent from listAllContent(),
526
+ * so any caller that treats that list as complete — `conloca doctor`, most
527
+ * of all — must consult this to avoid reporting success over broken content.
528
+ */
529
+ getIndexProblems(): readonly IndexProblem[] {
530
+ return this.contentIndex.getProblems();
531
+ }
532
+
533
+ /**
534
+ * Clear all caches - useful for testing
535
+ */
536
+ static clearCaches(): void {
537
+ ContentIndex.clearCache();
538
+ // TODO: CanvasIndex.clearCache() when implemented
539
+ }
540
+
541
+ private async parseFileHeaderWithRepair(
542
+ originalFilePath: string,
543
+ buffer: Uint8Array,
544
+ ): Promise<{
545
+ manifest: ContentManifest;
546
+ locale: string;
547
+ localeVersion: LocaleVersion;
548
+ bytesRead: number;
549
+ content?: ContentData;
550
+ } | null> {
551
+ let bytesRead = 0;
552
+ let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed
553
+
554
+ try {
555
+ bytesRead = await readFilePrefix(filePath, buffer);
556
+ } catch (error) {
557
+ console.error(`Error reading ${filePath}:`, error);
558
+ throw error;
559
+ }
560
+
561
+ try {
562
+ // Now parse the buffer content
563
+
564
+ // Parse file to extract metadata
565
+ let relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
566
+ let parts = relativePath.split('/');
567
+
568
+ // Determine site/collection structure
569
+ let site: string | undefined;
570
+ let collection: string;
571
+ let locale = 'en';
572
+ let name: string | undefined;
573
+ let pathname: string | undefined;
574
+ // Type for parsed metadata from files
575
+ interface ParsedMetadata {
576
+ id?: string;
577
+ created?: string;
578
+ modified?: string;
579
+ publishAt?: string;
580
+ unpublishAt?: string;
581
+ pathname?: string;
582
+ name?: string;
583
+ previousPathnames?: Record<string, string>;
584
+ meta?: ContentMeta;
585
+ type?: 'puck' | 'mdx' | 'json';
586
+ contentStartPos?: number;
587
+ data?: Record<string, unknown>; // For data collection entries
588
+ }
589
+ let parsedData: ParsedMetadata = {};
590
+ let kind: 'fragment' | 'page' | 'data';
591
+
592
+ // Files under the optional mdxPagesRoot are kind:'page' + type:'mdx',
593
+ // independent of the directory tree rooted at absoluteContentRoot. The
594
+ // leading prefix is stripped here; locale lives as a directory segment
595
+ // ({locale}/{slug}.mdx for non-default locales, {slug}.mdx at the root
596
+ // for the default locale).
597
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(`${this.absoluteMdxPagesRoot}/`)) {
598
+ kind = 'page';
599
+ site = this.mdxPagesSite;
600
+ collection = this.mdxPagesCollection;
601
+ const mdxRelativePath = filePath.replace(`${this.absoluteMdxPagesRoot}/`, '');
602
+ const mdxParts = mdxRelativePath.split('/');
603
+ const mdxFilename = mdxParts[mdxParts.length - 1];
604
+
605
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
606
+ if (!noLocaleMatch) return null;
607
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
608
+
609
+ // A leading folder counts as a locale only when it's a configured
610
+ // locale. A two-letter folder like `qa/` or `id/` is therefore
611
+ // left in the slug, not silently classified as a language.
612
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
613
+ locale = mdxParts[0];
614
+ const slugParts = mdxParts.slice(1);
615
+ pathname =
616
+ slugParts[slugParts.length - 1] === 'index'
617
+ ? `/${slugParts.slice(0, -1).join('/')}`
618
+ : `/${slugParts.join('/')}`;
619
+ } else {
620
+ locale = this.mdxPagesDefaultLocale;
621
+ pathname =
622
+ mdxParts[mdxParts.length - 1] === 'index'
623
+ ? `/${mdxParts.slice(0, -1).join('/')}`
624
+ : `/${mdxParts.join('/')}`;
625
+ }
626
+
627
+ parsedData = parse4KBMDX(buffer, bytesRead);
628
+ } else if (parts[0] === 'fragments') {
629
+ kind = 'fragment';
630
+
631
+ // Check if fragment is directly in fragments/ directory (no collection subdirectory)
632
+ if (parts.length === 2) {
633
+ // Keep the direct layout unless the repair move succeeds.
634
+ collection = '';
635
+ const filename = parts[1];
636
+
637
+ // Create the general directory if it doesn't exist
638
+ const generalDir = join(this.absoluteContentRoot, 'fragments', 'general');
639
+ try {
640
+ await mkdir(generalDir, { recursive: true });
641
+ } catch {
642
+ // Directory might already exist, that's fine
643
+ }
644
+
645
+ // Move the file to the general collection
646
+ const newFilePath = join(generalDir, filename);
647
+
648
+ try {
649
+ // Check if target file already exists
650
+ try {
651
+ await access(newFilePath);
652
+ console.warn(`Cannot move ${filename} to fragments/general/: target file already exists`);
653
+ } catch {
654
+ // Target doesn't exist, safe to move
655
+ await rename(filePath, newFilePath);
656
+ console.log(`Repaired: Moved ${filename} to fragments/general/ collection`);
657
+
658
+ // The file now uses the repaired collection layout.
659
+ collection = 'general';
660
+ filePath = newFilePath;
661
+
662
+ // Update relativePath and parts for the new file path
663
+ relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
664
+ parts = relativePath.split('/');
665
+
666
+ bytesRead = await readFilePrefix(filePath, buffer);
667
+ }
668
+ } catch (moveError) {
669
+ console.error(`Failed to move ${filename} to general collection:`, moveError);
670
+ // Continue processing with original file
671
+ bytesRead = await readFilePrefix(filePath, buffer);
672
+ }
673
+ } else {
674
+ // Fragment is in a collection subdirectory
675
+ collection = parts[1];
676
+ }
677
+
678
+ const filename = parts[parts.length - 1];
679
+ // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en
680
+ // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json.
681
+ // The locale grammar is the shared one (content-path.ts): a suffix that is not
682
+ // a locale ('hero.v2.mdx') takes the rename repair below instead of being
683
+ // indexed under a made-up locale.
684
+ const localeSuffix = parseLocaleFilename(filename);
685
+ const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
686
+
687
+ if (localeSuffix && localeSuffix.extension !== 'json') {
688
+ name = localeSuffix.base;
689
+ locale = localeSuffix.locale;
690
+ } else if (matchWithoutLocale) {
691
+ name = matchWithoutLocale[1];
692
+ // Use default locale from sites config instead of hardcoded 'en'
693
+ locale = this.contentIndex.getDefaultLocale('');
694
+
695
+ console.log(`Found file without locale suffix: ${filename}`);
696
+ // Rename file to include locale suffix
697
+ const extension = matchWithoutLocale[2];
698
+ const newFilename = `${name}.${locale}.${extension}`;
699
+ const newFilePath = join(dirname(filePath), newFilename);
700
+ console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
701
+
702
+ // Check if target file already exists
703
+ try {
704
+ await access(newFilePath);
705
+
706
+ // Target file exists, skip renaming to avoid conflict
707
+ console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
708
+ } catch {
709
+ // Target file doesn't exist, safe to rename
710
+ console.log(`Target file doesn't exist, proceeding with rename`);
711
+ try {
712
+ await rename(filePath, newFilePath);
713
+ console.log(`Successfully renamed ${filename} to ${newFilename}`);
714
+
715
+ // Update filePath to the new path for further processing
716
+ filePath = newFilePath;
717
+
718
+ // Update relativePath and parts for the new file path
719
+ relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
720
+ parts = relativePath.split('/');
721
+
722
+ bytesRead = await readFilePrefix(filePath, buffer);
723
+ } catch (renameError) {
724
+ console.error(`Failed to rename ${filename}:`, renameError);
725
+ // Continue processing with original file
726
+ bytesRead = await readFilePrefix(filePath, buffer);
727
+ }
728
+ }
729
+ }
730
+
731
+ // Parse content based on file type
732
+ if (filePath.endsWith('.mdx')) {
733
+ parsedData = parse4KBMDX(buffer, bytesRead);
734
+ } else {
735
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
736
+ }
737
+ } else if (parts[0] === 'data') {
738
+ // Data collection entry: data/{collection}/{name}.{locale}.json
739
+ kind = 'data';
740
+ collection = parts[1];
741
+
742
+ const filename = parts[parts.length - 1];
743
+ // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en.
744
+ // The locale grammar is the shared one (content-path.ts).
745
+ const localeSuffix = parseLocaleFilename(filename);
746
+ if (localeSuffix?.extension === 'json') {
747
+ name = localeSuffix.base;
748
+ locale = localeSuffix.locale;
749
+ }
750
+
751
+ // Parse JSON to get ID, metadata, and data
752
+ const content = textDecoder.decode(buffer.subarray(0, bytesRead));
753
+ try {
754
+ const jsonData = JSON.parse(content);
755
+ parsedData = {
756
+ id: jsonData.id,
757
+ type: 'json',
758
+ created: jsonData.created,
759
+ modified: jsonData.modified,
760
+ publishAt: jsonData.publishAt,
761
+ unpublishAt: jsonData.unpublishAt,
762
+ meta: jsonData.meta || { title: name || 'Untitled' },
763
+ data: jsonData.data,
764
+ name,
765
+ };
766
+ } catch (error) {
767
+ console.error(`Failed to parse JSON data file ${filePath}: ${messageOf(error)}`);
768
+ this.recordIndexProblem(filePath, 'malformed-json', messageOf(error));
769
+ return null;
770
+ }
771
+ } else {
772
+ kind = 'page';
773
+ site = parts[0];
774
+ collection = parts[1];
775
+
776
+ // Build pathname from file path. Accepts both .vxjson (Puck pages) and
777
+ // .mdx (mdx-type pages) so consumers without a separate `mdxPages`
778
+ // path can colocate .mdx docs alongside Puck pages under
779
+ // `{contentRoot}/{site}/{collection}/...`. When `mdxPages` IS set
780
+ // on a site in sites.json, .mdx files are served from that
781
+ // separate path (handled in the `absoluteMdxPagesRoot` branch
782
+ // above) and won't reach this branch.
783
+ const pathParts = parts.slice(2); // Remove site/collection
784
+ const filename = pathParts[pathParts.length - 1];
785
+ // One grammar with the header parser and every other reader (content-path.ts).
786
+ // A page file with no parseable locale suffix is NOT content: indexing it
787
+ // under the fallback locale filed it with no pathname at all, invisible to
788
+ // every pathname lookup while still occupying that locale slot. parseFilePath
789
+ // (the reindex path) has always refused these — now both halves agree.
790
+ const localeSuffix = filename ? parseLocaleFilename(filename) : null;
791
+ if (!localeSuffix || localeSuffix.extension === 'json') {
792
+ console.warn(`Skipping page file without a locale suffix: ${filePath}`);
793
+ return null;
794
+ }
795
+ locale = localeSuffix.locale;
796
+ // Replace filename with basename
797
+ pathParts[pathParts.length - 1] = localeSuffix.base;
798
+ // index files map to parent: /index -> /, /foo/index -> /foo
799
+ pathname =
800
+ pathParts[pathParts.length - 1] === 'index'
801
+ ? `/${pathParts.slice(0, -1).join('/')}`
802
+ : `/${pathParts.join('/')}`;
803
+
804
+ // Parse format-appropriately. parse4KBMDX reads frontmatter from the
805
+ // MDX header; VXJSON.parse4KB reads the leading JSON metadata.
806
+ if (filePath.endsWith('.mdx')) {
807
+ parsedData = parse4KBMDX(buffer, bytesRead);
808
+ } else {
809
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
810
+ }
811
+ }
812
+
813
+ // Check if the file is missing required fields
814
+ const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
815
+
816
+ // Extract or generate ID
817
+ const id = parsedData.id || generateContentId();
818
+
819
+ // Build LocaleManifest for this specific locale
820
+ const localeVersion: LocaleVersion = {
821
+ locale,
822
+ etag: '', // Will be filled below
823
+ created: parsedData.created || new Date().toISOString(),
824
+ modified: parsedData.modified || new Date().toISOString(),
825
+ ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),
826
+ ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),
827
+ ...(pathname && { pathname }),
828
+ ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),
829
+ ...(name && { name }),
830
+ meta: parsedData.meta || { title: name || 'Untitled' },
831
+ sourcePath: filePath,
832
+ };
833
+
834
+ // Build ContentManifest (without content)
835
+ const manifest: ContentManifest = {
836
+ id,
837
+ type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),
838
+ kind,
839
+ site,
840
+ collection,
841
+ locales: {
842
+ [locale]: localeVersion,
843
+ },
844
+ };
845
+
846
+ // If we have full content, parse it and compute etags
847
+ let content: ContentData | undefined;
848
+
849
+ // Check if we need to repair the file first (missing required fields)
850
+ if (needsRepair) {
851
+ // Perform repair and get the repaired content
852
+ const repairedData = await this.performReadRepair(filePath, manifest);
853
+ if (repairedData) {
854
+ content = repairedData.content;
855
+ localeVersion.etag = repairedData.etag;
856
+ localeVersion.modified = repairedData.modified;
857
+ return { manifest, locale, localeVersion, bytesRead, content };
858
+ }
859
+ // Repair failed, skip this file
860
+ console.error(`Failed to repair ${filePath}, skipping`);
861
+ this.recordIndexProblem(filePath, 'repair-failed', 'Read-repair failed');
862
+ return null;
863
+ }
864
+
865
+ if (
866
+ bytesRead < 4096 ||
867
+ (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||
868
+ (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)
869
+ ) {
870
+ // We have the full content
871
+ if (filePath.endsWith('.mdx')) {
872
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
873
+ const { content: mdx } = matter(fullContent, {});
874
+ content = { mdx };
875
+ } else if (filePath.endsWith('.json')) {
876
+ // Data collection JSON file
877
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
878
+ const jsonData = JSON.parse(fullContent);
879
+ content = { data: jsonData.data };
880
+ } else {
881
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
882
+ const data = JSON.parse(fullContent);
883
+ content = data.content || {};
884
+ }
885
+
886
+ // Calculate etags from the buffer (only use valid bytes)
887
+ const validBuffer = buffer.subarray(0, bytesRead);
888
+
889
+ if (filePath.endsWith('.mdx')) {
890
+ const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
891
+ localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
892
+ } else if (filePath.endsWith('.json')) {
893
+ // For data files, use simple etag (hash entire buffer)
894
+ // Data files are typically small and don't need separate meta/content etags
895
+ localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
896
+ } else {
897
+ const etagResult = VXJSON.calculateETags(validBuffer);
898
+
899
+ if (!etagResult.success) {
900
+ // Content field is not last or invalid JSON - repair immediately
901
+
902
+ // Perform repair and get the repaired content
903
+ const repairedData = await this.performReadRepair(filePath, manifest);
904
+ if (repairedData) {
905
+ content = repairedData.content;
906
+ localeVersion.etag = repairedData.etag;
907
+ localeVersion.modified = repairedData.modified;
908
+ return { manifest, locale, localeVersion, bytesRead, content };
909
+ }
910
+ // Repair failed, skip this file
911
+ console.error(`Failed to repair ${filePath}, skipping`);
912
+ this.recordIndexProblem(filePath, 'repair-failed', 'Read-repair failed');
913
+ return null;
914
+ }
915
+ localeVersion.etag = etagResult.contentEtag
916
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
917
+ : etagResult.metaEtag;
918
+ }
919
+ }
920
+
921
+ // Return both for indexing
922
+ return { manifest, locale, localeVersion, bytesRead, content };
923
+ } catch (error) {
924
+ console.error(`Error indexing ${originalFilePath}: ${messageOf(error)}`);
925
+ this.recordIndexProblem(originalFilePath, 'parse-failed', messageOf(error));
926
+ return null;
927
+ }
928
+ }
929
+
930
+ /**
931
+ * Perform read-repair by writing back the file with missing fields
932
+ * This ensures stable IDs and timestamps across restarts
933
+ */
934
+ private async performReadRepair(
935
+ filePath: string,
936
+ manifest: ContentManifest,
937
+ ): Promise<{
938
+ content: ContentData;
939
+ etag: string;
940
+ modified: string;
941
+ } | null> {
942
+ try {
943
+ const now = new Date().toISOString();
944
+ let needsWrite = false;
945
+
946
+ if (manifest.type === 'mdx') {
947
+ // Read the full MDX file
948
+ const content = await readFile(filePath, 'utf-8');
949
+ const parsed = matter(content, {});
950
+
951
+ // Check for missing fields
952
+ if (!parsed.data.id) {
953
+ parsed.data.id = manifest.id;
954
+ needsWrite = true;
955
+ }
956
+ if (!parsed.data.created) {
957
+ parsed.data.created = now;
958
+ needsWrite = true;
959
+ }
960
+ if (!parsed.data.modified) {
961
+ parsed.data.modified = now;
962
+ needsWrite = true;
963
+ }
964
+
965
+ if (needsWrite) {
966
+ // Write back with updated frontmatter. Pass the parsed file
967
+ // object, not the body string: stringify re-parses string inputs
968
+ // through gray-matter's memo cache, which is a plain object — a
969
+ // body equal to an Object.prototype member name ('toString',
970
+ // 'valueOf', …) reads the prototype function back and crashes.
971
+ // Same cache-opt-out rule as the matter(..., {}) calls above.
972
+ const updatedContent = matter.stringify(parsed, parsed.data);
973
+ await writeFile(filePath, updatedContent);
974
+ console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
975
+
976
+ // Calculate ETags for the repaired MDX file
977
+ const repairedBuffer = Buffer.from(updatedContent, 'utf-8') as Uint8Array;
978
+ const contentStartPos = updatedContent.indexOf('\n---\n') + 5; // Position after frontmatter
979
+ const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);
980
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
981
+
982
+ // Return the repaired data. Strip leading newlines so the
983
+ // body matches what the author wrote — see `readLocaleFile`.
984
+ return {
985
+ content: { mdx: parsed.content.replace(/^\n+/, '') },
986
+ etag,
987
+ modified: parsed.data.modified || now,
988
+ };
989
+ }
990
+ } else {
991
+ // Read the full JSON file
992
+ const content = await readFile(filePath, 'utf-8');
993
+ const data: VXJSONFile = JSON.parse(content);
994
+
995
+ // Check for missing fields
996
+ if (!data.id) {
997
+ data.id = manifest.id;
998
+ needsWrite = true;
999
+ }
1000
+ if (!data.created) {
1001
+ data.created = now;
1002
+ needsWrite = true;
1003
+ }
1004
+ if (!data.modified) {
1005
+ data.modified = now;
1006
+ needsWrite = true;
1007
+ }
1008
+
1009
+ // Always rewrite VXJSON files during repair to ensure correct field order
1010
+ needsWrite = true;
1011
+
1012
+ if (needsWrite) {
1013
+ // Write back with VXJSON format
1014
+ const vxjsonData: VXJSONFile = {
1015
+ id: data.id,
1016
+ type: data.type,
1017
+ created: data.created,
1018
+ modified: data.modified,
1019
+ publishAt: data.publishAt,
1020
+ unpublishAt: data.unpublishAt,
1021
+ previousPathnames: data.previousPathnames,
1022
+ meta: data.meta || {},
1023
+ content: data.content || {},
1024
+ };
1025
+ const repairedJson = VXJSON.serialize(vxjsonData);
1026
+ await writeFile(filePath, repairedJson);
1027
+ console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
1028
+ // Return the repaired data
1029
+
1030
+ // Calculate ETags from the repaired JSON
1031
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;
1032
+ const etagResult = VXJSON.calculateETags(repairedBuffer);
1033
+
1034
+ if (!etagResult.success) {
1035
+ console.error(`Failed to calculate ETags after repair: ${filePath}`);
1036
+ return null;
1037
+ }
1038
+
1039
+ const etag = etagResult.contentEtag
1040
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
1041
+ : etagResult.metaEtag;
1042
+
1043
+ // Return the complete repaired data
1044
+ return {
1045
+ content: vxjsonData.content,
1046
+ etag,
1047
+ modified: vxjsonData.modified,
1048
+ };
1049
+ }
1050
+ }
1051
+
1052
+ // For MDX or no repair needed, return null
1053
+ return null;
1054
+ } catch (error) {
1055
+ console.error(`Failed to perform read-repair on ${filePath}:`, error);
1056
+ return null;
1057
+ }
1058
+ }
1059
+
1060
+ private async scanContentFiles(): Promise<string[]> {
1061
+ const files: string[] = [];
1062
+ const contentRoot = this.absoluteContentRoot;
1063
+
1064
+ async function scan(dir: string, inDataDir = false) {
1065
+ try {
1066
+ const entries = await readdir(dir, { withFileTypes: true });
1067
+ for (const entry of entries) {
1068
+ const fullPath = join(dir, entry.name);
1069
+ if (entry.isDirectory()) {
1070
+ // Check if we're entering the data/ directory
1071
+ const isDataDir = dir === contentRoot && entry.name === 'data';
1072
+ await scan(fullPath, inDataDir || isDataDir);
1073
+ } else if (entry.isFile()) {
1074
+ // Include .vxjson and .mdx files everywhere
1075
+ // Include .json files only in the data/ directory
1076
+ if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {
1077
+ files.push(fullPath);
1078
+ } else if (inDataDir && entry.name.endsWith('.json')) {
1079
+ files.push(fullPath);
1080
+ }
1081
+ }
1082
+ }
1083
+ } catch {
1084
+ // Directory doesn't exist yet
1085
+ }
1086
+ }
1087
+
1088
+ await scan(this.absoluteContentRoot);
1089
+
1090
+ // Also scan mdxPagesRoot for .mdx files when the second root is configured.
1091
+ // Supports projects that store mdx-type pages outside the main content
1092
+ // tree (the rendering pipeline that consumes them is the project's choice).
1093
+ //
1094
+ // Skip the second scan when mdxPagesRoot is the same as contentRoot OR
1095
+ // nested inside it — the first scan already walked those files, and a
1096
+ // second pass would push every `.mdx` onto `files` twice. The nested case
1097
+ // is the documented Starlight pattern (`contentRoot: './src/content'`,
1098
+ // `mdxPagesRoot: './src/content/docs'`), so the prefix check matters in
1099
+ // practice.
1100
+ if (
1101
+ this.absoluteMdxPagesRoot &&
1102
+ this.absoluteMdxPagesRoot !== this.absoluteContentRoot &&
1103
+ !this.absoluteMdxPagesRoot.startsWith(`${this.absoluteContentRoot}/`)
1104
+ ) {
1105
+ async function scanMdxPages(dir: string) {
1106
+ try {
1107
+ const entries = await readdir(dir, { withFileTypes: true });
1108
+ for (const entry of entries) {
1109
+ const fullPath = join(dir, entry.name);
1110
+ if (entry.isDirectory()) {
1111
+ await scanMdxPages(fullPath);
1112
+ } else if (entry.isFile() && entry.name.endsWith('.mdx')) {
1113
+ files.push(fullPath);
1114
+ }
1115
+ }
1116
+ } catch {
1117
+ // Directory doesn't exist yet
1118
+ }
1119
+ }
1120
+ await scanMdxPages(this.absoluteMdxPagesRoot);
1121
+ }
1122
+
1123
+ return files;
1124
+ }
1125
+
1126
+ /**
1127
+ * Why a page of `type` cannot have `pathname` in `locale` where `getFilePath` puts it: an mdx
1128
+ * page lives in the MDX pages folder when one is configured, where a default-language path may
1129
+ * not start with a language folder (see `checkMdxPagesPathname`).
1130
+ */
1131
+ private mdxPagesPathnameRefusal(type: ContentType, pathname: string, locale: string): PathnameRefusal | null {
1132
+ if (type !== 'mdx' || !this.absoluteMdxPagesRoot) return null;
1133
+ return checkMdxPagesPathname(pathname, locale, {
1134
+ defaultLocale: this.mdxPagesDefaultLocale,
1135
+ locales: this.availableLocales,
1136
+ });
1137
+ }
1138
+
1139
+ private getFilePath(manifest: ContentIdentity, { locale, name, pathname }: LocalePathData): string {
1140
+ if (manifest.kind === 'fragment') {
1141
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
1142
+ return join(this.absoluteContentRoot, 'fragments', manifest.collection, `${name}.${locale}.${ext}`);
1143
+ }
1144
+ if (manifest.kind === 'data') {
1145
+ return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);
1146
+ }
1147
+ if (manifest.kind === 'page' && pathname) {
1148
+ // For pages, derive path from pathname
1149
+ const basePath = pathname.replace(/^\//, '').replace(/\/$/, '') || 'index';
1150
+
1151
+ // mdx-type pages live under absoluteMdxPagesRoot when configured.
1152
+ // The locale appears as a directory segment for non-default locales;
1153
+ // the default locale's files live at the root with no locale prefix.
1154
+ if (manifest.type === 'mdx' && this.absoluteMdxPagesRoot) {
1155
+ return locale === this.mdxPagesDefaultLocale
1156
+ ? join(this.absoluteMdxPagesRoot, `${basePath}.mdx`)
1157
+ : join(this.absoluteMdxPagesRoot, locale, `${basePath}.mdx`);
1158
+ }
1159
+
1160
+ // Pages live under contentRoot/{site}/{collection}. When type:'mdx'
1161
+ // and no `mdxPages` path is configured for the site, the .mdx files
1162
+ // sit here alongside the .vxjson Puck pages — the layout chosen
1163
+ // when sites.json doesn't declare a separate `mdxPages` path.
1164
+ if (manifest.site) {
1165
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
1166
+ return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.${ext}`);
1167
+ }
1168
+ }
1169
+ throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
1170
+ }
1171
+
1172
+ /**
1173
+ * Parse a file path back into its components for checking against the path index
1174
+ * Returns null if the path doesn't match expected patterns
1175
+ */
1176
+ parseFilePath(filePath: string): ContentPathLayout | null {
1177
+ // Files under mdxPagesRoot are kind:'page' + type:'mdx' regardless of
1178
+ // their position relative to absoluteContentRoot. Mirror the parsing
1179
+ // performed in parseFileHeaderWithRepair so both code paths agree on
1180
+ // the derived (pathname, locale) tuple.
1181
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(`${this.absoluteMdxPagesRoot}/`)) {
1182
+ const mdxRelativePath = filePath.replace(`${this.absoluteMdxPagesRoot}/`, '');
1183
+ const mdxParts = mdxRelativePath.split('/');
1184
+ const mdxFilename = mdxParts[mdxParts.length - 1];
1185
+ let locale: string;
1186
+ let pathname: string;
1187
+
1188
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
1189
+ if (!noLocaleMatch) return null;
1190
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
1191
+
1192
+ // Membership-based locale detection — mirrors parseFileHeaderWithRepair
1193
+ // so both paths classify the same file identically.
1194
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
1195
+ locale = mdxParts[0];
1196
+ const slugParts = mdxParts.slice(1);
1197
+ pathname =
1198
+ slugParts[slugParts.length - 1] === 'index'
1199
+ ? `/${slugParts.slice(0, -1).join('/')}`
1200
+ : `/${slugParts.join('/')}`;
1201
+ } else {
1202
+ locale = this.mdxPagesDefaultLocale;
1203
+ pathname =
1204
+ mdxParts[mdxParts.length - 1] === 'index' ? `/${mdxParts.slice(0, -1).join('/')}` : `/${mdxParts.join('/')}`;
1205
+ }
1206
+
1207
+ return {
1208
+ kind: 'page',
1209
+ site: this.mdxPagesSite,
1210
+ collection: this.mdxPagesCollection,
1211
+ pathname,
1212
+ locale,
1213
+ };
1214
+ }
1215
+
1216
+ // Everything under the primary content root shares ONE grammar with the
1217
+ // header parser and every other reader (content-path.ts) — including the
1218
+ // `index` -> parent-pathname rule this method used to skip. Missing it made
1219
+ // reindex look up `/index`, never find the entry the indexer had filed under
1220
+ // `/`, and leave a deleted index page in the index forever.
1221
+ return parseContentPathLayout(filePath.replace(`${this.absoluteContentRoot}/`, ''));
1222
+ }
1223
+
1224
+ async getContent(id: string): Promise<ContentEntry | null> {
1225
+ // Get manifest for this ID
1226
+ const manifest = this.contentIndex.getManifest(id);
1227
+ if (!manifest) {
1228
+ return null;
1229
+ }
1230
+
1231
+ // Read all locale files in parallel
1232
+ const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
1233
+ const filePath = this.getFilePath(manifest, localeVersion);
1234
+ const content = await this.readLocaleFile(filePath, localeVersion.locale);
1235
+ return { localeVersion, content };
1236
+ });
1237
+
1238
+ const results = await Promise.all(readPromises);
1239
+
1240
+ // Build locales with content
1241
+ const locales: Record<string, LocaleVersion & ContentProp> = {};
1242
+ for (const { localeVersion, content } of results) {
1243
+ if (content) {
1244
+ locales[localeVersion.locale] = {
1245
+ ...localeVersion,
1246
+ etag: content.etag, // Use fresh etag from file, not stale manifest etag
1247
+ content: content.content,
1248
+ };
1249
+ }
1250
+ }
1251
+
1252
+ return {
1253
+ id: manifest.id,
1254
+ site: manifest.site,
1255
+ collection: manifest.collection,
1256
+ type: manifest.type,
1257
+ kind: manifest.kind,
1258
+ locales,
1259
+ };
1260
+ }
1261
+
1262
+ async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {
1263
+ // Get manifest for this ID
1264
+ const manifest = this.contentIndex.getManifest(id);
1265
+ if (!manifest) {
1266
+ // File might have been added after indexing - try reindexing
1267
+ await this.reindex();
1268
+
1269
+ // Try again with updated index
1270
+ const updatedManifest = this.contentIndex.getManifest(id);
1271
+ if (!updatedManifest?.locales[locale]) {
1272
+ return null;
1273
+ }
1274
+
1275
+ return this.getLocalized(id, locale);
1276
+ }
1277
+
1278
+ // Check if this locale exists
1279
+ const localeVersion = manifest.locales[locale];
1280
+ if (!localeVersion) {
1281
+ return null;
1282
+ }
1283
+
1284
+ // Read the locale-specific file
1285
+ const filePath = this.getFilePath(manifest, localeVersion);
1286
+ const localeData = await this.readLocaleFile(filePath, locale);
1287
+ if (!localeData) {
1288
+ return null;
1289
+ }
1290
+
1291
+ // Build LocalizedEntry
1292
+ return {
1293
+ id: manifest.id,
1294
+ site: manifest.site,
1295
+ collection: manifest.collection,
1296
+ type: manifest.type,
1297
+ kind: manifest.kind,
1298
+ localized: {
1299
+ ...localeVersion,
1300
+ etag: localeData.etag, // Use fresh etag from file, not stale manifest etag
1301
+ content: localeData.content,
1302
+ },
1303
+ };
1304
+ }
1305
+
1306
+ private async readLocaleFile(filePath: string, locale: string): Promise<LocaleFileData | null> {
1307
+ try {
1308
+ const buffer = (await readFile(filePath)) as Uint8Array;
1309
+ const content = textDecoder.decode(buffer);
1310
+
1311
+ if (filePath.endsWith('.mdx')) {
1312
+ const { data: frontmatter, content: rawBody } = matter(content, {});
1313
+ // gray-matter leaves the blank line after the closing `---` on
1314
+ // the body. Strip leading newlines so the round-trip matches the
1315
+ // body the author wrote.
1316
+ const body = rawBody.replace(/^\n+/, '');
1317
+
1318
+ // Calculate etags from the file buffer
1319
+ const contentPos = findMdxContentStartPosition(buffer);
1320
+
1321
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
1322
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
1323
+
1324
+ // Extract special fields from frontmatter, everything else is metadata
1325
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
1326
+
1327
+ // Body-only — frontmatter is server-owned and surfaced separately
1328
+ // via `meta` / `created` / `modified`. Returning the full file here
1329
+ // would let the editor round-trip the YAML block as body text, which
1330
+ // duplicates the frontmatter on disk when content is inserted above
1331
+ // it (proven on assets.mdx, 2026-05-11).
1332
+ const result: LocaleFileData = {
1333
+ locale,
1334
+ etag,
1335
+ created: created,
1336
+ modified: modified,
1337
+ meta: metaFields as ContentMeta,
1338
+ content: { mdx: body },
1339
+ };
1340
+
1341
+ // Only add publish dates if they exist
1342
+ if (frontmatter.publishAt !== undefined) {
1343
+ result.publishAt = frontmatter.publishAt;
1344
+ }
1345
+ if (frontmatter.unpublishAt !== undefined) {
1346
+ result.unpublishAt = frontmatter.unpublishAt;
1347
+ }
1348
+
1349
+ return result;
1350
+ }
1351
+
1352
+ // Parse JSON data first to determine type
1353
+ const data = JSON.parse(content);
1354
+
1355
+ // Handle JSON data files (type: 'json') separately - they use simple etag
1356
+ if (data.type === 'json') {
1357
+ const etag = VXJSON.calculateSimpleEtag(buffer);
1358
+
1359
+ const result: LocaleFileData = {
1360
+ locale,
1361
+ etag,
1362
+ created: data.created,
1363
+ modified: data.modified,
1364
+ meta: data.meta || {},
1365
+ content: { data: data.data || {} },
1366
+ };
1367
+
1368
+ // Only add optional fields if they exist
1369
+ if (data.publishAt !== undefined) {
1370
+ result.publishAt = data.publishAt;
1371
+ }
1372
+ if (data.unpublishAt !== undefined) {
1373
+ result.unpublishAt = data.unpublishAt;
1374
+ }
1375
+
1376
+ return result;
1377
+ }
1378
+
1379
+ // For VXJSON (puck pages), calculate ETags with meta/content split
1380
+ const etagResult = VXJSON.calculateETags(buffer);
1381
+
1382
+ if (!etagResult.success) {
1383
+ // File needs repair - parse it and rewrite in correct format
1384
+ const repairedData: VXJSONFile = {
1385
+ id: data.id,
1386
+ type: data.type,
1387
+ created: data.created,
1388
+ modified: data.modified,
1389
+ publishAt: data.publishAt,
1390
+ unpublishAt: data.unpublishAt,
1391
+ previousPathnames: data.previousPathnames,
1392
+ meta: data.meta || {},
1393
+ content: data.content || {},
1394
+ };
1395
+
1396
+ // Rewrite file with correct format
1397
+ const repairedJson = VXJSON.serialize(repairedData);
1398
+ await writeFile(filePath, repairedJson);
1399
+
1400
+ // Recalculate ETags from repaired buffer
1401
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;
1402
+ const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
1403
+
1404
+ if (!repairedEtagResult.success) {
1405
+ throw new Error(`Failed to repair VXJSON file: ${filePath}`);
1406
+ }
1407
+
1408
+ const etag = repairedEtagResult.contentEtag
1409
+ ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`
1410
+ : repairedEtagResult.metaEtag;
1411
+
1412
+ console.log(`Repaired VXJSON file: ${filePath}`);
1413
+
1414
+ const result: LocaleFileData = {
1415
+ locale,
1416
+ etag,
1417
+ created: data.created,
1418
+ modified: data.modified,
1419
+ meta: data.meta || {},
1420
+ content: data.content || {},
1421
+ };
1422
+
1423
+ // Only add optional fields if they exist
1424
+ if (data.publishAt !== undefined) {
1425
+ result.publishAt = data.publishAt;
1426
+ }
1427
+ if (data.unpublishAt !== undefined) {
1428
+ result.unpublishAt = data.unpublishAt;
1429
+ }
1430
+ if (data.previousPathnames !== undefined) {
1431
+ result.previousPathnames = data.previousPathnames;
1432
+ }
1433
+
1434
+ return result;
1435
+ }
1436
+
1437
+ const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1438
+
1439
+ const result: LocaleFileData = {
1440
+ locale,
1441
+ etag,
1442
+ created: data.created,
1443
+ modified: data.modified,
1444
+ meta: data.meta || {},
1445
+ content: data.content || {},
1446
+ };
1447
+
1448
+ // Only add optional fields if they exist
1449
+ if (data.publishAt !== undefined) {
1450
+ result.publishAt = data.publishAt;
1451
+ }
1452
+ if (data.unpublishAt !== undefined) {
1453
+ result.unpublishAt = data.unpublishAt;
1454
+ }
1455
+ if (data.previousPathnames !== undefined) {
1456
+ result.previousPathnames = data.previousPathnames;
1457
+ }
1458
+
1459
+ return result;
1460
+ } catch {
1461
+ return null;
1462
+ }
1463
+ }
1464
+
1465
+ async createContent(data: CreateContentInput): Promise<CreateResult> {
1466
+ // Use shared validation
1467
+ const validation = validateCreateContent(data, this.sites, this.fragments, this.data);
1468
+ if (!validation.valid) {
1469
+ return {
1470
+ success: false,
1471
+ reason: validation.reason,
1472
+ error: validation.error ? new Error(validation.error) : undefined,
1473
+ existingId: validation.existingId,
1474
+ field: validation.field,
1475
+ };
1476
+ }
1477
+
1478
+ if (data.kind === 'page') {
1479
+ for (const [locale, localeData] of Object.entries(data.locales)) {
1480
+ const refused = this.mdxPagesPathnameRefusal(data.type, localeData.pathname ?? '', locale);
1481
+ if (refused) {
1482
+ return { success: false, reason: refused.reason, error: new Error(refused.error), field: 'pathname' };
1483
+ }
1484
+ }
1485
+ }
1486
+
1487
+ const id = generateContentId();
1488
+ const now = data.created || new Date().toISOString();
1489
+
1490
+ try {
1491
+ // Build the manifest with all locales
1492
+ const manifest: ContentManifest = {
1493
+ id,
1494
+ type: data.type,
1495
+ kind: data.kind,
1496
+ site: data.site,
1497
+ collection: data.collection,
1498
+ locales: {},
1499
+ };
1500
+
1501
+ const contentCache: Record<string, ContentData> = {};
1502
+
1503
+ // Create files for each locale
1504
+ for (const [locale, localeData] of Object.entries(data.locales)) {
1505
+ const content = localeData.content;
1506
+
1507
+ // Build metadata with required title
1508
+ const title = localeData.meta?.title || data.meta?.title;
1509
+ if (!title) {
1510
+ return {
1511
+ success: false,
1512
+ reason: 'write_error',
1513
+ error: new Error('Title is required in metadata'),
1514
+ };
1515
+ }
1516
+
1517
+ // Build complete metadata
1518
+ const meta: ContentMeta = {
1519
+ title,
1520
+ ...data.meta,
1521
+ ...localeData.meta,
1522
+ };
1523
+
1524
+ const fileData: VXJSONFile = {
1525
+ id,
1526
+ type: data.type,
1527
+ created: now,
1528
+ modified: now,
1529
+ publishAt:
1530
+ localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1531
+ unpublishAt:
1532
+ localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1533
+ meta,
1534
+ content,
1535
+ };
1536
+
1537
+ // Use the proper getFilePath method
1538
+ const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });
1539
+
1540
+ // Ensure directory exists
1541
+ await mkdir(dirname(filePath), { recursive: true });
1542
+
1543
+ // Write file and calculate etag from the serialized content
1544
+ let etag: string;
1545
+
1546
+ if (data.type === 'mdx') {
1547
+ // Write MDX with frontmatter - flatten metadata fields
1548
+ const frontmatterData = {
1549
+ id,
1550
+ created: now,
1551
+ modified: now,
1552
+ ...(localeData.publishAt && { publishAt: localeData.publishAt }),
1553
+ ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),
1554
+ ...meta, // Spread metadata fields directly, not nested
1555
+ };
1556
+
1557
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');
1558
+ await writeFile(filePath, mdxContent);
1559
+
1560
+ // For MDX, calculate etags from the serialized content
1561
+ const mdxBuffer = new TextEncoder().encode(mdxContent);
1562
+ // For MDX, all frontmatter is metadata, content starts after ---
1563
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
1564
+ let contentPos = -1;
1565
+ for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
1566
+ let match = true;
1567
+ for (let j = 0; j < contentStartMarker.length; j++) {
1568
+ if (mdxBuffer[i + j] !== contentStartMarker[j]) {
1569
+ match = false;
1570
+ break;
1571
+ }
1572
+ }
1573
+ if (match) {
1574
+ contentPos = i + contentStartMarker.length;
1575
+ break;
1576
+ }
1577
+ }
1578
+ const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
1579
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
1580
+ } else if (data.type === 'json') {
1581
+ // Data files use "data" field instead of "content"
1582
+ const dataFileContent = {
1583
+ id,
1584
+ type: 'json',
1585
+ created: now,
1586
+ modified: now,
1587
+ ...(localeData.publishAt &&
1588
+ typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),
1589
+ ...(localeData.unpublishAt &&
1590
+ typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),
1591
+ meta,
1592
+ data: content.data || {},
1593
+ };
1594
+
1595
+ const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\t');
1596
+ await writeFile(filePath, jsonContent);
1597
+
1598
+ // For data files, use simple etag (hash entire buffer)
1599
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1600
+ etag = VXJSON.calculateSimpleEtag(jsonBuffer);
1601
+ } else {
1602
+ // VXJSON for pages (puck)
1603
+ const jsonContent = VXJSON.serialize(fileData);
1604
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1605
+
1606
+ // Calculate etags from the buffer
1607
+ const etagResult = VXJSON.calculateETags(jsonBuffer);
1608
+
1609
+ if (!etagResult.success) {
1610
+ throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
1611
+ }
1612
+
1613
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1614
+
1615
+ // Write the file
1616
+ await writeFile(filePath, jsonContent);
1617
+ }
1618
+
1619
+ // Build locale manifest using shared function
1620
+ const localeVersion = buildLocaleVersion({
1621
+ locale,
1622
+ etag,
1623
+ created: now,
1624
+ modified: now,
1625
+ meta,
1626
+ kind: data.kind,
1627
+ pathname: data.kind === 'page' ? localeData.pathname : undefined,
1628
+ name: data.kind === 'fragment' || data.kind === 'data' ? data.name : undefined,
1629
+ publishAt:
1630
+ localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1631
+ unpublishAt:
1632
+ localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1633
+ });
1634
+
1635
+ // Add locale to manifest
1636
+ manifest.locales[locale] = localeVersion;
1637
+ contentCache[locale] = content;
1638
+ }
1639
+
1640
+ // Add each locale to the index
1641
+ for (const localeVersion of localesOf(manifest)) {
1642
+ const { locale } = localeVersion;
1643
+ this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
1644
+ }
1645
+
1646
+ return { success: true, id };
1647
+ } catch (error) {
1648
+ return {
1649
+ success: false,
1650
+ reason: 'write_error',
1651
+ error: ensureError(error),
1652
+ };
1653
+ }
1654
+ }
1655
+
1656
+ async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {
1657
+ const { id, locale, data, etag } = input;
1658
+
1659
+ // Get the manifest
1660
+ const manifest = this.contentIndex.getManifest(id);
1661
+ if (!manifest) {
1662
+ return {
1663
+ success: false,
1664
+ reason: 'not_found',
1665
+ };
1666
+ }
1667
+
1668
+ // Get the specific locale manifest
1669
+ const localeVersion = manifest.locales[locale];
1670
+ if (!localeVersion) {
1671
+ return {
1672
+ success: false,
1673
+ reason: 'not_found',
1674
+ };
1675
+ }
1676
+
1677
+ // Get file path and read current content FIRST to get fresh etag
1678
+ const filePath = this.getFilePath(manifest, localeVersion);
1679
+ const current = await this.readLocaleFile(filePath, locale);
1680
+ if (!current) {
1681
+ return {
1682
+ success: false,
1683
+ reason: 'not_found',
1684
+ };
1685
+ }
1686
+
1687
+ // Use fresh etag from file, not stale manifest etag
1688
+ const currentEtag = current.etag;
1689
+
1690
+ // Check etag - data files use simple etags, others use dual etags
1691
+ if (manifest.kind === 'data') {
1692
+ // Data files use simple etag (single hash, no dot separator)
1693
+ // Just compare the full etag directly
1694
+ if (etag !== currentEtag) {
1695
+ return {
1696
+ success: false,
1697
+ reason: 'stale_write',
1698
+ currentEtag,
1699
+ };
1700
+ }
1701
+ } else {
1702
+ // Non-data files use dual etags (meta.content format)
1703
+ const etagParts = parseDualEtag(etag);
1704
+ const currentParts = parseDualEtag(currentEtag);
1705
+
1706
+ if (!etagParts || !currentParts) {
1707
+ return {
1708
+ success: false,
1709
+ reason: 'stale_write',
1710
+ currentEtag,
1711
+ };
1712
+ }
1713
+
1714
+ // Check which parts are being updated
1715
+ const updateScope = analyzeUpdateScope(data);
1716
+ const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
1717
+ const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
1718
+
1719
+ // Validate etags for parts being updated
1720
+ if (updatingMeta && etagParts.meta !== currentParts.meta) {
1721
+ return {
1722
+ success: false,
1723
+ reason: 'stale_write',
1724
+ currentEtag,
1725
+ };
1726
+ }
1727
+
1728
+ if (updatingContent && etagParts.content !== currentParts.content) {
1729
+ return {
1730
+ success: false,
1731
+ reason: 'stale_write',
1732
+ currentEtag,
1733
+ };
1734
+ }
1735
+ }
1736
+
1737
+ // Update modified timestamp for any change (metadata or content)
1738
+ let modified: string;
1739
+ if (shouldUpdateModifiedTimestamp(data)) {
1740
+ // Use provided modified timestamp or current time
1741
+ modified = data.modified || new Date().toISOString();
1742
+ } else if (data.modified) {
1743
+ // If modified timestamp is explicitly provided, always use it
1744
+ modified = data.modified;
1745
+ } else {
1746
+ // No changes and no explicit timestamp, keep current
1747
+ modified = current.modified;
1748
+ }
1749
+
1750
+ const {
1751
+ sortedMeta: newMeta,
1752
+ valid: metaValid,
1753
+ error: metaError,
1754
+ } = validateAndPrepareMetadata(applyMetaPatch(current.meta, data.meta ?? {}));
1755
+
1756
+ // Validate new metadata
1757
+ if (!newMeta || !metaValid) {
1758
+ return {
1759
+ success: false,
1760
+ reason: 'write_error',
1761
+ error: new Error(metaError),
1762
+ };
1763
+ }
1764
+
1765
+ // Merge updates
1766
+ const newContent = data.content ? { ...current.content, ...data.content } : current.content;
1767
+
1768
+ // A page's new path is tidied, and refused when it is malformed or another page has it, as a
1769
+ // create's is; the tidied form names the file and keys the page in the site index. An unchanged
1770
+ // path is left alone, so a page keeps a path from before the checks.
1771
+ let pathname = data.pathname;
1772
+ if (pathname !== undefined && pathname !== localeVersion.pathname && manifest.kind === 'page') {
1773
+ // Own-key only: the manifest's site name comes from the on-disk layout
1774
+ // and is never checked against the configured sites, so an inherited key
1775
+ // would reach the calls below.
1776
+ const site = manifest.site && Object.hasOwn(this.sites, manifest.site) ? this.sites[manifest.site] : undefined;
1777
+ const checked = checkPagePathname(site, pathname, locale, id);
1778
+ if (!checked.valid) {
1779
+ return { success: false, reason: checked.reason, error: new Error(checked.error) };
1780
+ }
1781
+ const refused = this.mdxPagesPathnameRefusal(manifest.type, checked.pathname, locale);
1782
+ if (refused) {
1783
+ return { success: false, reason: refused.reason, error: new Error(refused.error) };
1784
+ }
1785
+ pathname = checked.pathname;
1786
+ }
1787
+
1788
+ // A new fragment or data name passes the create's checks. An unchanged name is left alone, so
1789
+ // an entry keeps a name from before the checks.
1790
+ if (
1791
+ data.name !== undefined &&
1792
+ data.name !== localeVersion.name &&
1793
+ (manifest.kind === 'fragment' || manifest.kind === 'data')
1794
+ ) {
1795
+ const entries = manifest.kind === 'fragment' ? this.fragments : this.data;
1796
+ const refused = checkEntryName(
1797
+ manifest.kind,
1798
+ manifest.collection,
1799
+ data.name,
1800
+ (name) =>
1801
+ manifest.kind === 'fragment' ? this.fragments.isFragmentNameValid(name) : this.data.isDataNameValid(name),
1802
+ (name) => entries.getNameConflict(manifest.collection, name, id),
1803
+ );
1804
+ if (refused) {
1805
+ return { success: false, reason: refused.reason, error: new Error(refused.error) };
1806
+ }
1807
+ }
1808
+
1809
+ // Handle pathname changes - track history only for published content
1810
+ const pathnameHistory = buildPathnameHistory(
1811
+ localeVersion.pathname,
1812
+ pathname,
1813
+ isContentPublished({
1814
+ publishAt: resolvePublishDate(data.publishAt, current.publishAt),
1815
+ unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),
1816
+ }),
1817
+ new Date().toISOString(),
1818
+ );
1819
+
1820
+ try {
1821
+ // Determine the target file path (may be different if pathname or name changed)
1822
+ let targetFilePath = filePath;
1823
+ if (pathname && localeVersion.pathname && pathname !== localeVersion.pathname && manifest.site) {
1824
+ // For pages, calculate new file path based on new pathname
1825
+ const newLocaleVersion: LocaleVersion = {
1826
+ ...localeVersion,
1827
+ pathname,
1828
+ };
1829
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1830
+
1831
+ // Ensure target directory exists
1832
+ await mkdir(dirname(targetFilePath), { recursive: true });
1833
+ } else if (
1834
+ data.name &&
1835
+ localeVersion.name &&
1836
+ data.name !== localeVersion.name &&
1837
+ (manifest.kind === 'fragment' || manifest.kind === 'data')
1838
+ ) {
1839
+ // A fragment's or data entry's name is part of its file path, so a rename moves the file
1840
+ const newLocaleVersion: LocaleVersion = {
1841
+ ...localeVersion,
1842
+ name: data.name,
1843
+ };
1844
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1845
+
1846
+ // Ensure target directory exists
1847
+ await mkdir(dirname(targetFilePath), { recursive: true });
1848
+ }
1849
+
1850
+ // Write updated content
1851
+ if (targetFilePath.endsWith('.mdx')) {
1852
+ // Build frontmatter with special fields and metadata
1853
+ const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
1854
+ const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
1855
+ const frontmatterData = {
1856
+ id: manifest.id,
1857
+ created: current.created,
1858
+ modified,
1859
+ ...(publishAt && { publishAt }),
1860
+ ...(unpublishAt && { unpublishAt }),
1861
+ ...newMeta, // Spread metadata fields directly
1862
+ };
1863
+
1864
+ // Extract just the content part from MDX (remove frontmatter if present)
1865
+ let mdxContentPart = newContent.mdx || '';
1866
+ if (mdxContentPart.startsWith('---')) {
1867
+ // Remove frontmatter if it exists
1868
+ const { content: contentOnly } = matter(mdxContentPart, {});
1869
+ mdxContentPart = contentOnly;
1870
+ }
1871
+
1872
+ // Defensive guard: warn when a frontmatter-shaped block appears
1873
+ // mid-body. The load path strips frontmatter before it reaches the
1874
+ // editor, so this should never occur — if it does, surface it for
1875
+ // investigation instead of silently writing a file with stacked
1876
+ // frontmatter blocks.
1877
+ if (/\n---\r?\n[\s\S]*?\r?\n---(\r?\n|$)/.test(mdxContentPart)) {
1878
+ console.warn(
1879
+ `[content-api] Embedded frontmatter-shaped block detected in body for ${targetFilePath}. ` +
1880
+ 'This indicates a load-path regression or client-side leak.',
1881
+ );
1882
+ }
1883
+
1884
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
1885
+
1886
+ // Atomic write for MDX files
1887
+ await atomicWriteFile(targetFilePath, mdxContent);
1888
+ } else if (targetFilePath.endsWith('.json')) {
1889
+ // Data files use "data" field instead of "content"
1890
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1891
+
1892
+ // Build updated data file structure
1893
+ const updatedFile = {
1894
+ id: fileContent.id,
1895
+ type: 'json' as const,
1896
+ created: fileContent.created,
1897
+ modified,
1898
+ ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),
1899
+ ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),
1900
+ meta: newMeta,
1901
+ data: sortKeys(newContent.data || {}, { deep: true }),
1902
+ };
1903
+
1904
+ // Handle publish date updates
1905
+ if ('publishAt' in data) {
1906
+ if (data.publishAt) {
1907
+ (updatedFile as Record<string, unknown>).publishAt = data.publishAt;
1908
+ } else {
1909
+ delete (updatedFile as Record<string, unknown>).publishAt;
1910
+ }
1911
+ }
1912
+
1913
+ if ('unpublishAt' in data) {
1914
+ if (data.unpublishAt) {
1915
+ (updatedFile as Record<string, unknown>).unpublishAt = data.unpublishAt;
1916
+ } else {
1917
+ delete (updatedFile as Record<string, unknown>).unpublishAt;
1918
+ }
1919
+ }
1920
+
1921
+ // Serialize data file
1922
+ const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\t');
1923
+
1924
+ // Atomic write for JSON data files
1925
+ await atomicWriteFile(targetFilePath, serializedContent);
1926
+ } else {
1927
+ // VXJSON for pages (puck)
1928
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1929
+
1930
+ // Build updated VXJSONFile structure
1931
+ const updatedFile: VXJSONFile = {
1932
+ id: fileContent.id,
1933
+ type: fileContent.type,
1934
+ created: fileContent.created,
1935
+ modified,
1936
+ publishAt: fileContent.publishAt,
1937
+ unpublishAt: fileContent.unpublishAt,
1938
+ previousPathnames: fileContent.previousPathnames,
1939
+ meta: newMeta,
1940
+ content: sortKeys(newContent, { deep: true }),
1941
+ };
1942
+
1943
+ // Handle pathname changes and track history
1944
+ if (pathname && localeVersion.pathname && pathname !== localeVersion.pathname) {
1945
+ // Only add to history if content is published
1946
+ if (isContentPublished(current)) {
1947
+ if (!updatedFile.previousPathnames) {
1948
+ updatedFile.previousPathnames = {};
1949
+ }
1950
+ updatedFile.previousPathnames[localeVersion.pathname] = modified;
1951
+ }
1952
+ }
1953
+
1954
+ // Handle publish date updates
1955
+ if ('publishAt' in data) {
1956
+ if (data.publishAt) {
1957
+ updatedFile.publishAt = data.publishAt;
1958
+ } else {
1959
+ delete updatedFile.publishAt;
1960
+ }
1961
+ }
1962
+
1963
+ if ('unpublishAt' in data) {
1964
+ if (data.unpublishAt) {
1965
+ updatedFile.unpublishAt = data.unpublishAt;
1966
+ } else {
1967
+ delete updatedFile.unpublishAt;
1968
+ }
1969
+ }
1970
+
1971
+ // Serialize using VXJSON format to ensure content is last
1972
+ const serializedContent = VXJSON.serialize(updatedFile);
1973
+
1974
+ // Atomic write for VXJSON page files
1975
+ await atomicWriteFile(targetFilePath, serializedContent);
1976
+ }
1977
+
1978
+ // Calculate new etag from the written file
1979
+ const writtenBuffer = (await readFile(targetFilePath)) as Uint8Array;
1980
+ let newEtag: string;
1981
+
1982
+ if (targetFilePath.endsWith('.mdx')) {
1983
+ // Find content position in MDX
1984
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
1985
+ let contentPos = -1;
1986
+ for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
1987
+ let match = true;
1988
+ for (let j = 0; j < contentStartMarker.length; j++) {
1989
+ if (writtenBuffer[i + j] !== contentStartMarker[j]) {
1990
+ match = false;
1991
+ break;
1992
+ }
1993
+ }
1994
+ if (match) {
1995
+ contentPos = i + contentStartMarker.length;
1996
+ break;
1997
+ }
1998
+ }
1999
+ const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
2000
+ newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
2001
+ } else if (targetFilePath.endsWith('.json')) {
2002
+ // For data files, use simple etag (hash entire buffer)
2003
+ newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
2004
+ } else {
2005
+ // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally
2006
+ const etagResult = VXJSON.calculateETags(writtenBuffer);
2007
+
2008
+ if (!etagResult.success) {
2009
+ throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
2010
+ }
2011
+
2012
+ newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2013
+ }
2014
+
2015
+ // Build updated locale manifest with current publish data
2016
+ const updatedLocaleVersion: LocaleVersion = {
2017
+ ...localeVersion,
2018
+ etag: newEtag,
2019
+ modified,
2020
+ meta: newMeta,
2021
+ ...(pathname && { pathname }),
2022
+ ...(data.name && { name: data.name }),
2023
+ };
2024
+
2025
+ // Handle publish dates using shared function
2026
+ // First preserve current values if not updating
2027
+ if (current.publishAt && !('publishAt' in data)) {
2028
+ updatedLocaleVersion.publishAt = current.publishAt;
2029
+ }
2030
+ if (current.unpublishAt && !('unpublishAt' in data)) {
2031
+ updatedLocaleVersion.unpublishAt = current.unpublishAt;
2032
+ }
2033
+
2034
+ // Then apply updates
2035
+ updatePublishDates(updatedLocaleVersion, data);
2036
+
2037
+ // Update pathname history if changed
2038
+ if (Object.keys(pathnameHistory).length > 0) {
2039
+ updatedLocaleVersion.previousPathnames = {
2040
+ ...localeVersion.previousPathnames,
2041
+ ...pathnameHistory,
2042
+ };
2043
+ } else {
2044
+ // Preserve existing previousPathnames if no change, but only if it has content
2045
+ const existingPreviousPathnames = localeVersion.previousPathnames;
2046
+ if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {
2047
+ updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
2048
+ } else {
2049
+ // Remove empty previousPathnames object
2050
+ delete updatedLocaleVersion.previousPathnames;
2051
+ }
2052
+ }
2053
+
2054
+ // Store the old locale manifest for rollback if needed
2055
+ const oldLocaleVersion = localeVersion;
2056
+
2057
+ try {
2058
+ // Replace the locale so its old path/name mappings are removed first.
2059
+ this.contentIndex.removeLocale(id, locale);
2060
+ this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
2061
+
2062
+ // If pathname changed, delete the old file
2063
+ if (targetFilePath !== filePath) {
2064
+ try {
2065
+ // A name changed only in letter case is the same file on a case-insensitive disk: the
2066
+ // write went into it, so deleting the old path would delete the entry. Renaming it
2067
+ // gives the file its new name's case.
2068
+ if (await isSameFile(filePath, targetFilePath)) await rename(filePath, targetFilePath);
2069
+ else await unlink(filePath);
2070
+ } catch (error) {
2071
+ // Log but don't fail if old file deletion fails
2072
+ console.warn(`Failed to delete old file ${filePath}:`, error);
2073
+ }
2074
+ }
2075
+ } catch (error) {
2076
+ // Rollback on error to maintain the original locale and name mapping.
2077
+ this.contentIndex.removeLocale(id, locale);
2078
+ this.contentIndex.addContent(manifest, oldLocaleVersion, current.content);
2079
+
2080
+ // If we wrote to a new file, try to clean it up. A name changed only in letter case wrote
2081
+ // into the entry's own file on a case-insensitive disk, and that file is kept.
2082
+ if (targetFilePath !== filePath && !(await isSameFile(filePath, targetFilePath))) {
2083
+ try {
2084
+ await unlink(targetFilePath);
2085
+ } catch {
2086
+ // Ignore cleanup errors
2087
+ }
2088
+ }
2089
+
2090
+ throw error;
2091
+ }
2092
+
2093
+ return {
2094
+ success: true,
2095
+ etag: newEtag,
2096
+ modified: new Date(),
2097
+ };
2098
+ } catch (error) {
2099
+ return {
2100
+ success: false,
2101
+ reason: 'write_error',
2102
+ error: ensureError(error),
2103
+ };
2104
+ }
2105
+ }
2106
+
2107
+ async deleteContent(id: string, etag: string): Promise<DeleteResult> {
2108
+ // Get manifest for this ID
2109
+ const manifest = this.contentIndex.getManifest(id);
2110
+ if (!manifest) {
2111
+ return {
2112
+ success: false,
2113
+ reason: 'not_found',
2114
+ error: new Error('Content not found'),
2115
+ };
2116
+ }
2117
+
2118
+ // For deleteContent, we require the etag to match ANY locale (indicating user has current data)
2119
+ // But this is still a design flaw - we should probably require all etags or a master etag
2120
+ let matchingLocale: LocaleVersion | undefined;
2121
+ for (const localeVersion of localesOf(manifest)) {
2122
+ if (localeVersion.etag === etag) {
2123
+ matchingLocale = localeVersion;
2124
+ break;
2125
+ }
2126
+ }
2127
+ if (!matchingLocale) {
2128
+ return {
2129
+ success: false,
2130
+ reason: 'stale_write',
2131
+ currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',
2132
+ error: new Error('Invalid etag - must match at least one locale'),
2133
+ };
2134
+ }
2135
+
2136
+ // Settled, not all: Promise.all let one rejection abandon the others
2137
+ // AFTER they had already unlinked, so the caller was told the delete
2138
+ // failed while the content was gone and the index still listed it. A file
2139
+ // already absent (git checkout, a manual rm) is the common cause, and for
2140
+ // a delete that is the desired end state, not an error.
2141
+ const localeVersions = Array.from(localesOf(manifest));
2142
+ const outcomes = await Promise.allSettled(
2143
+ localeVersions.map(async (localeVersion) => {
2144
+ await rm(this.getFilePath(manifest, localeVersion), { force: true });
2145
+ }),
2146
+ );
2147
+
2148
+ const failures = outcomes.filter((outcome) => outcome.status === 'rejected');
2149
+ if (failures.length === 0) {
2150
+ this.contentIndex.removeEntry(id);
2151
+ return { success: true };
2152
+ }
2153
+
2154
+ // Some files are gone and some are not. Drop exactly what was removed so
2155
+ // the index still describes what is on disk; the survivors stay indexed
2156
+ // rather than becoming unreachable orphans.
2157
+ for (const [position, outcome] of outcomes.entries()) {
2158
+ if (outcome.status === 'fulfilled') {
2159
+ this.contentIndex.removeLocale(id, localeVersions[position].locale);
2160
+ }
2161
+ }
2162
+
2163
+ return {
2164
+ success: false,
2165
+ error: ensureError(failures[0].reason),
2166
+ };
2167
+ }
2168
+
2169
+ async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {
2170
+ const { id, locale, etag } = input;
2171
+
2172
+ // Get manifest for this ID
2173
+ const manifest = this.contentIndex.getManifest(id);
2174
+ if (!manifest) {
2175
+ return {
2176
+ success: false,
2177
+ reason: 'not_found',
2178
+ error: new Error('Content not found'),
2179
+ };
2180
+ }
2181
+
2182
+ // Check if this locale exists
2183
+ const localeVersion = manifest.locales[locale];
2184
+ if (!localeVersion) {
2185
+ return {
2186
+ success: false,
2187
+ reason: 'not_found',
2188
+ error: new Error('Locale not found'),
2189
+ };
2190
+ }
2191
+
2192
+ // Verify etag matches this locale
2193
+ if (localeVersion.etag !== etag) {
2194
+ return {
2195
+ success: false,
2196
+ reason: 'stale_write',
2197
+ currentEtag: localeVersion.etag,
2198
+ error: new Error('Invalid etag for locale'),
2199
+ };
2200
+ }
2201
+
2202
+ // Don't allow deleting the last locale. Count actual locales, not
2203
+ // manifest keys — removeLocale clears a locale by assigning undefined
2204
+ // and keeping the key, so after an earlier translation delete the key
2205
+ // count still includes the dead slot and the guard would wave the
2206
+ // genuinely last locale through.
2207
+ if (Array.from(localesOf(manifest)).length === 1) {
2208
+ return {
2209
+ success: false,
2210
+ error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),
2211
+ };
2212
+ }
2213
+
2214
+ try {
2215
+ // Delete the locale file. A file already absent (git checkout, a
2216
+ // manual rm) is the desired end state of a delete, not an error —
2217
+ // same stance deleteContent takes. Failing on it left the deleted
2218
+ // translation routable and cached while reporting failure.
2219
+ await rm(this.getFilePath(manifest, localeVersion), { force: true });
2220
+
2221
+ // Remove locale from manifest and index. removeLocale clears the
2222
+ // manifest field itself, and returns early if it is already cleared —
2223
+ // clearing it here first skipped the pathname-index and content-cache
2224
+ // cleanup, leaving the deleted translation routable and cached.
2225
+ this.contentIndex.removeLocale(manifest.id, locale);
2226
+
2227
+ return { success: true };
2228
+ } catch (error) {
2229
+ return {
2230
+ success: false,
2231
+ error: ensureError(error),
2232
+ };
2233
+ }
2234
+ }
2235
+
2236
+ getSite(siteName: string): Site | null {
2237
+ if (siteName === 'fragments') {
2238
+ throw new Error('Use `fragments` property instead of getSite("fragments")');
2239
+ }
2240
+
2241
+ // Own-key only: the name is caller-supplied, and an inherited key like
2242
+ // `constructor` would resolve to a truthy non-Site.
2243
+ return Object.hasOwn(this.sites, siteName) ? this.sites[siteName] : null;
2244
+ }
2245
+
2246
+ *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {
2247
+ yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
2248
+ }
2249
+ *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {
2250
+ yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
2251
+ }
2252
+
2253
+ /**
2254
+ * Reindex files that were added or changed after initial creation
2255
+ *
2256
+ * This method:
2257
+ * 1. Either scans for all content files or processes specific paths
2258
+ * 2. Uses the path index to check if files are already indexed
2259
+ * 3. Indexes new files or force-reindexes specified files
2260
+ * 4. Optionally handles file deletions
2261
+ *
2262
+ * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
2263
+ * @param options - Options for reindexing behavior
2264
+ * @returns Statistics about the reindexing operation
2265
+ */
2266
+ async reindex(paths?: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResult> {
2267
+ const filesToProcess = paths || (await this.scanContentFiles());
2268
+ let filesSkipped = 0;
2269
+ let filesProcessed = 0;
2270
+ let filesDeleted = 0;
2271
+ let errors = 0;
2272
+ const filesToIndex: string[] = [];
2273
+ const updated: LocalizedManifest[] = [];
2274
+ const deleted: Array<{ id: string; locale: string; kind: 'page' | 'fragment' | 'data' }> = [];
2275
+
2276
+ // Check each file
2277
+ for (const filePath of filesToProcess) {
2278
+ // Check if file exists (for deletion handling)
2279
+ if (options?.handleDeletions && paths) {
2280
+ try {
2281
+ await readFile(filePath);
2282
+ } catch {
2283
+ // File doesn't exist - remove from index
2284
+ const parsed = this.parseFilePath(filePath);
2285
+ if (parsed) {
2286
+ // Find the content ID to remove
2287
+ let manifest: ContentManifest | null = null;
2288
+ if (parsed.kind === 'fragment' && parsed.name) {
2289
+ manifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2290
+ } else if (parsed.kind === 'data' && parsed.name) {
2291
+ manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2292
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2293
+ manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2294
+ }
2295
+ // A name finds an entry when any of its locales has it. A save that renames one locale
2296
+ // writes its new file and then deletes the old one, whose name the other locales still
2297
+ // carry: only a locale whose own name is the deleted file's has lost its file.
2298
+ if (parsed.kind !== 'page' && manifest?.locales[parsed.locale]?.name !== parsed.name) {
2299
+ manifest = null;
2300
+ }
2301
+
2302
+ if (manifest) {
2303
+ // Track the deletion
2304
+ deleted.push({
2305
+ id: manifest.id,
2306
+ locale: parsed.locale,
2307
+ kind: parsed.kind,
2308
+ });
2309
+
2310
+ // Remove the specific locale or entire entry if it's the last locale
2311
+ if (Object.keys(manifest.locales).length === 1) {
2312
+ this.contentIndex.removeEntry(manifest.id);
2313
+ } else {
2314
+ // Remove just this locale. removeLocale clears the manifest field itself and returns early
2315
+ // if it is already cleared, so clearing it here first left the locale's name taken.
2316
+ this.contentIndex.removeLocale(manifest.id, parsed.locale);
2317
+ }
2318
+ filesDeleted++;
2319
+ }
2320
+ }
2321
+ continue;
2322
+ }
2323
+ }
2324
+
2325
+ const parsed = this.parseFilePath(filePath);
2326
+ if (!parsed) {
2327
+ console.warn(`Skipping unrecognized file pattern: ${filePath}`);
2328
+ errors++;
2329
+ continue;
2330
+ }
2331
+
2332
+ // Check if this path is already indexed
2333
+ let isIndexed = false;
2334
+ if (parsed.kind === 'fragment' && parsed.name) {
2335
+ // Check fragment index by name
2336
+ const manifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2337
+ isIndexed = !!manifest;
2338
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2339
+ // Check site index by pathname
2340
+ const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2341
+ isIndexed = !!manifest;
2342
+ } else if (parsed.kind === 'data' && parsed.name) {
2343
+ // Check data index by name
2344
+ const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2345
+ isIndexed = !!manifest;
2346
+ }
2347
+
2348
+ if (isIndexed) {
2349
+ if (!paths) {
2350
+ // Skip already indexed files when doing a full scan
2351
+ filesSkipped++;
2352
+ } else {
2353
+ // For specific paths, check if the file has changed
2354
+ const fileStats = await readFile(filePath);
2355
+ let currentManifest: ContentManifest | null = null;
2356
+ if (parsed.kind === 'fragment' && parsed.name) {
2357
+ currentManifest = this.contentIndex.getFragmentByName(parsed.collection, parsed.name, parsed.locale);
2358
+ } else if (parsed.kind === 'data' && parsed.name) {
2359
+ currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
2360
+ } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
2361
+ currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
2362
+ }
2363
+
2364
+ if (currentManifest) {
2365
+ // Calculate current file etag
2366
+ const buffer = fileStats as Uint8Array;
2367
+ let currentEtag: string;
2368
+
2369
+ if (filePath.endsWith('.mdx')) {
2370
+ const contentPos = findMdxContentStartPosition(buffer);
2371
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
2372
+ currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
2373
+ } else if (filePath.endsWith('.vxjson')) {
2374
+ const etagResult = VXJSON.calculateETags(buffer);
2375
+ if (!etagResult.success) {
2376
+ // File needs repair - add to filesToIndex for repair
2377
+ filesToIndex.push(filePath);
2378
+ continue;
2379
+ }
2380
+ currentEtag = etagResult.contentEtag
2381
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
2382
+ : etagResult.metaEtag;
2383
+ } else if (filePath.endsWith('.json')) {
2384
+ // For JSON data files, use content hash as etag
2385
+ currentEtag = xxh64(buffer).toString(16);
2386
+ } else {
2387
+ // Unknown file type, skip
2388
+ filesSkipped++;
2389
+ continue;
2390
+ }
2391
+
2392
+ // Only reindex if etag changed
2393
+ const existingEtag = currentManifest.locales[parsed.locale]?.etag;
2394
+
2395
+ if (existingEtag === currentEtag) {
2396
+ const relativePath = filePath.replace(`${this.absoluteContentRoot}/`, '');
2397
+ console.log(`[Content] skip ${relativePath} (unchanged)`);
2398
+ filesSkipped++;
2399
+ } else {
2400
+ filesToIndex.push(filePath);
2401
+ }
2402
+ } else {
2403
+ // Not indexed yet
2404
+ filesToIndex.push(filePath);
2405
+ }
2406
+ }
2407
+ } else {
2408
+ // Not indexed yet
2409
+ filesToIndex.push(filePath);
2410
+ }
2411
+ }
2412
+
2413
+ // Index the files
2414
+ const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
2415
+
2416
+ // Drop the previous verdicts for every file this pass re-examines, so
2417
+ // problems do not pile up across reindexes. A full scan re-examines every
2418
+ // file that is not already indexed — and a file with a problem is never
2419
+ // indexed — so it can start from an empty slate.
2420
+ if (paths) {
2421
+ this.contentIndex.dropProblems(new Set(filesToIndex));
2422
+ } else {
2423
+ this.contentIndex.clearProblems();
2424
+ }
2425
+
2426
+ for (let i = 0; i < filesToIndex.length; i++) {
2427
+ const filePath = filesToIndex[i];
2428
+ const bufferIndex = i % buffers.length;
2429
+
2430
+ try {
2431
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
2432
+ if (result) {
2433
+ const { manifest, localeVersion, content } = result;
2434
+
2435
+ // A different file already claims this id+locale. Its file still
2436
+ // being on disk is what tells a stray copy (refuse, or it merges
2437
+ // over the original and a page silently stops existing) apart from
2438
+ // an out-of-band rename (the old path is gone — this file is the
2439
+ // entry's new home and must keep merging).
2440
+ const claimant = this.contentIndex.getManifest(manifest.id);
2441
+ const claimedLocale = claimant?.locales[localeVersion.locale];
2442
+ if (claimant && claimedLocale) {
2443
+ const claimantPath = this.getFilePath(claimant, claimedLocale);
2444
+ const claimantOnDisk = await access(claimantPath).then(
2445
+ () => true,
2446
+ () => false,
2447
+ );
2448
+ if (claimantPath !== filePath && claimantOnDisk) {
2449
+ this.recordIndexProblem(
2450
+ filePath,
2451
+ 'duplicate-id',
2452
+ duplicateIdMessage(manifest.id, localeVersion.locale, claimantPath),
2453
+ );
2454
+ filesSkipped++;
2455
+ continue;
2456
+ }
2457
+ }
2458
+
2459
+ // Add to index
2460
+ this.contentIndex.addContent(manifest, localeVersion, content);
2461
+ filesProcessed++;
2462
+
2463
+ // Create LocalizedManifest for the updated list
2464
+ const localizedManifest: LocalizedManifest = {
2465
+ id: manifest.id,
2466
+ type: manifest.type,
2467
+ kind: manifest.kind,
2468
+ site: manifest.site,
2469
+ collection: manifest.collection,
2470
+ localized: localeVersion,
2471
+ };
2472
+ updated.push(localizedManifest);
2473
+ }
2474
+ } catch (error) {
2475
+ console.error(`Failed to reindex ${filePath}: ${messageOf(error)}`);
2476
+ this.recordIndexProblem(filePath, 'index-error', messageOf(error));
2477
+ errors++;
2478
+ }
2479
+ }
2480
+
2481
+ const result: ReindexResult = {
2482
+ filesProcessed,
2483
+ filesSkipped,
2484
+ updated,
2485
+ };
2486
+
2487
+ if (options?.handleDeletions && deleted.length > 0) {
2488
+ result.filesDeleted = filesDeleted;
2489
+ result.deleted = deleted;
2490
+ }
2491
+
2492
+ if (errors > 0) {
2493
+ result.errors = errors;
2494
+ }
2495
+
2496
+ return result;
2497
+ }
2498
+
2499
+ /**
2500
+ * Read content directly from cache
2501
+ * For testing purposes - returns null if not cached
2502
+ */
2503
+ async readFromCache(id: string, locale: string): Promise<ContentData | null> {
2504
+ return this.contentIndex.getCachedContent(id, locale);
2505
+ }
2506
+
2507
+ async getContentAsBuffer(
2508
+ id: string,
2509
+ locale: string,
2510
+ ): Promise<{
2511
+ buffer: Uint8Array;
2512
+ etag: string;
2513
+ contentType: 'application/json' | 'text/mdx';
2514
+ } | null> {
2515
+ const manifest = this.contentIndex.getManifest(id);
2516
+ if (!manifest?.locales[locale]) {
2517
+ return null;
2518
+ }
2519
+
2520
+ const localeVersion = manifest.locales[locale];
2521
+ const filePath = this.getFilePath(manifest, localeVersion);
2522
+ const buffer = (await readFile(filePath)) as Uint8Array;
2523
+ const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';
2524
+
2525
+ // Calculate ETag based on file type
2526
+ let etag: string;
2527
+ if (contentType === 'text/mdx') {
2528
+ // Find content start position for MDX
2529
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
2530
+ let contentPos = -1;
2531
+ for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
2532
+ let match = true;
2533
+ for (let j = 0; j < contentStartMarker.length; j++) {
2534
+ if (buffer[i + j] !== contentStartMarker[j]) {
2535
+ match = false;
2536
+ break;
2537
+ }
2538
+ }
2539
+ if (match) {
2540
+ contentPos = i + contentStartMarker.length;
2541
+ break;
2542
+ }
2543
+ }
2544
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
2545
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
2546
+ } else {
2547
+ // Calculate ETags for JSON
2548
+ const etagResult = VXJSON.calculateETags(buffer);
2549
+
2550
+ if (!etagResult.success) {
2551
+ throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
2552
+ }
2553
+
2554
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2555
+ }
2556
+
2557
+ return { buffer, etag, contentType };
2558
+ }
2559
+
2560
+ async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {
2561
+ // First, validate all operations can succeed
2562
+ const validationResults: Array<{
2563
+ op: UpdateLocaleInput;
2564
+ manifest: ContentManifest;
2565
+ localeVersion: LocaleVersion;
2566
+ current?: LocaleFileData;
2567
+ }> = [];
2568
+
2569
+ for (const op of operations) {
2570
+ const manifest = this.contentIndex.getManifest(op.id);
2571
+ if (!manifest) {
2572
+ // Content not found
2573
+ return {
2574
+ operations: operations.map((o) => ({
2575
+ id: o.id,
2576
+ locale: o.locale,
2577
+ updated: false,
2578
+ error: new Error('Content not found'),
2579
+ })),
2580
+ success: false,
2581
+ updated: 0,
2582
+ failed: operations.length,
2583
+ };
2584
+ }
2585
+
2586
+ const localeVersion = manifest.locales[op.locale];
2587
+ if (!localeVersion) {
2588
+ // Locale not found
2589
+ return {
2590
+ operations: operations.map((o) => ({
2591
+ id: o.id,
2592
+ locale: o.locale,
2593
+ updated: false,
2594
+ error: new Error('Locale not found'),
2595
+ })),
2596
+ success: false,
2597
+ updated: 0,
2598
+ failed: operations.length,
2599
+ };
2600
+ }
2601
+
2602
+ // Check etag
2603
+ if (localeVersion.etag !== op.etag) {
2604
+ // Stale write detected
2605
+ return {
2606
+ operations: operations.map((o) => ({
2607
+ id: o.id,
2608
+ locale: o.locale,
2609
+ updated: false,
2610
+ error: new Error('Stale write'),
2611
+ })),
2612
+ success: false,
2613
+ updated: 0,
2614
+ failed: operations.length,
2615
+ };
2616
+ }
2617
+
2618
+ // Read current content for validation
2619
+ const filePath = this.getFilePath(manifest, localeVersion);
2620
+ const current = await this.readLocaleFile(filePath, op.locale);
2621
+ if (!current) {
2622
+ return {
2623
+ operations: operations.map((o) => ({
2624
+ id: o.id,
2625
+ locale: o.locale,
2626
+ updated: false,
2627
+ error: new Error('Failed to read content'),
2628
+ })),
2629
+ success: false,
2630
+ updated: 0,
2631
+ failed: operations.length,
2632
+ };
2633
+ }
2634
+
2635
+ // Validate metadata size if updating
2636
+ if (op.data.meta) {
2637
+ const newMeta = applyMetaPatch(current.meta, op.data.meta);
2638
+ const validation = validateAndPrepareMetadata(newMeta);
2639
+ if (!validation.valid) {
2640
+ return {
2641
+ operations: operations.map((o) => ({
2642
+ id: o.id,
2643
+ locale: o.locale,
2644
+ updated: false,
2645
+ error: new Error(validation.error!),
2646
+ })),
2647
+ success: false,
2648
+ updated: 0,
2649
+ failed: operations.length,
2650
+ };
2651
+ }
2652
+ }
2653
+
2654
+ validationResults.push({ op, manifest, localeVersion, current });
2655
+ }
2656
+
2657
+ // All validations passed, now perform updates
2658
+ const results: BatchOperationResult[] = [];
2659
+ let updated = 0;
2660
+
2661
+ for (const { op } of validationResults) {
2662
+ const result = await this.updateLocalized(op);
2663
+ if (result.success) {
2664
+ updated++;
2665
+ results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });
2666
+ } else {
2667
+ // This shouldn't happen if validation was correct
2668
+ results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });
2669
+ }
2670
+ }
2671
+
2672
+ return {
2673
+ operations: results,
2674
+ success: updated === operations.length,
2675
+ updated,
2676
+ failed: operations.length - updated,
2677
+ };
2678
+ }
2679
+ }
2680
+
2681
+ /** Whether two paths name one file, as 'hero.en.mdx' and 'Hero.en.mdx' do on a case-insensitive disk. */
2682
+ async function isSameFile(a: string, b: string): Promise<boolean> {
2683
+ const [statA, statB] = await Promise.all([stat(a), stat(b)]).catch(() => [null, null]);
2684
+ return statA !== null && statB !== null && statA.dev === statB.dev && statA.ino === statB.ino;
2685
+ }