@conloca/content-api 0.1.15 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/asset-manifest.d.ts +23 -0
  2. package/dist/asset-manifest.d.ts.map +1 -0
  3. package/dist/asset-manifest.js +73 -0
  4. package/dist/asset-operations.d.ts +159 -0
  5. package/dist/asset-operations.d.ts.map +1 -0
  6. package/dist/asset-operations.js +736 -0
  7. package/dist/asset-types.d.ts +56 -0
  8. package/dist/asset-types.d.ts.map +1 -0
  9. package/dist/asset-types.js +7 -0
  10. package/dist/base-content-index.d.ts +57 -0
  11. package/dist/base-content-index.d.ts.map +1 -0
  12. package/dist/base-content-index.js +179 -0
  13. package/dist/block-index.d.ts +9 -0
  14. package/dist/block-index.d.ts.map +1 -0
  15. package/dist/block-index.js +11 -0
  16. package/dist/blocks.d.ts +16 -0
  17. package/dist/blocks.d.ts.map +1 -0
  18. package/dist/blocks.js +103 -0
  19. package/dist/cf-access.d.ts +31 -0
  20. package/dist/cf-access.d.ts.map +1 -0
  21. package/dist/cf-access.js +66 -0
  22. package/dist/component-registry.d.ts +50 -0
  23. package/dist/component-registry.d.ts.map +1 -0
  24. package/dist/component-registry.js +120 -0
  25. package/dist/{component-registry.types-CBGONnYn.d.mts → component-registry.types-C0ctF9nh.d.mts} +1 -1
  26. package/dist/component-registry.types-C0ctF9nh.d.mts.map +1 -0
  27. package/dist/component-registry.types.d.ts +11 -0
  28. package/dist/component-registry.types.d.ts.map +1 -0
  29. package/dist/component-registry.types.js +1 -0
  30. package/dist/content-api.interface.d.ts +64 -0
  31. package/dist/content-api.interface.d.ts.map +1 -0
  32. package/dist/content-api.interface.js +1 -0
  33. package/dist/content-filters.d.ts +31 -0
  34. package/dist/content-filters.d.ts.map +1 -0
  35. package/dist/content-filters.js +246 -0
  36. package/dist/content-index-D092_vk1.mjs +629 -0
  37. package/dist/content-index-D092_vk1.mjs.map +1 -0
  38. package/dist/content-index-D6IVMmAB.d.mts +127 -0
  39. package/dist/content-index-D6IVMmAB.d.mts.map +1 -0
  40. package/dist/content-index.d.ts +126 -0
  41. package/dist/content-index.d.ts.map +1 -0
  42. package/dist/content-index.js +418 -0
  43. package/dist/content-operations-DIbsxG5A.d.mts +354 -0
  44. package/dist/content-operations-DIbsxG5A.d.mts.map +1 -0
  45. package/dist/content-operations.d.ts +93 -0
  46. package/dist/content-operations.d.ts.map +1 -0
  47. package/dist/content-operations.js +275 -0
  48. package/dist/content-reader.d.ts +10 -0
  49. package/dist/content-reader.d.ts.map +1 -0
  50. package/dist/content-reader.js +13 -0
  51. package/dist/content-utils-fWNHTrPy.mjs +280 -0
  52. package/dist/content-utils-fWNHTrPy.mjs.map +1 -0
  53. package/dist/content-utils.d.ts +132 -0
  54. package/dist/content-utils.d.ts.map +1 -0
  55. package/dist/content-utils.js +352 -0
  56. package/dist/content-watcher.d.ts +43 -0
  57. package/dist/content-watcher.d.ts.map +1 -0
  58. package/dist/content-watcher.js +83 -0
  59. package/dist/{data-Db1Iv9T0.mjs → data-DquNIEnQ.mjs} +4 -2
  60. package/dist/{data-Db1Iv9T0.mjs.map → data-DquNIEnQ.mjs.map} +1 -1
  61. package/dist/data-index.d.ts +8 -0
  62. package/dist/data-index.d.ts.map +1 -0
  63. package/dist/data-index.js +7 -0
  64. package/dist/data.d.ts +43 -0
  65. package/dist/data.d.ts.map +1 -0
  66. package/dist/data.js +103 -0
  67. package/dist/etag-utils.d.ts +77 -0
  68. package/dist/etag-utils.d.ts.map +1 -0
  69. package/dist/etag-utils.js +160 -0
  70. package/dist/filesystem-content-api-B1KIQJfk.mjs +2 -0
  71. package/dist/{filesystem-content-api-kxKY5IUw.mjs → filesystem-content-api-C0HIhqZi.mjs} +172 -1230
  72. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +1 -0
  73. package/dist/{filesystem-content-api-C1TM0GLo.d.mts → filesystem-content-api-DCdNi-co.d.mts} +19 -4
  74. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +1 -0
  75. package/dist/filesystem-content-api.d.ts +135 -0
  76. package/dist/filesystem-content-api.d.ts.map +1 -0
  77. package/dist/filesystem-content-api.js +2181 -0
  78. package/dist/git-operations.d.ts +49 -0
  79. package/dist/git-operations.d.ts.map +1 -0
  80. package/dist/git-operations.js +252 -0
  81. package/dist/header-parser.d.ts +37 -0
  82. package/dist/header-parser.d.ts.map +1 -0
  83. package/dist/header-parser.js +286 -0
  84. package/dist/in-memory-content-api.d.ts +35 -0
  85. package/dist/in-memory-content-api.d.ts.map +1 -0
  86. package/dist/in-memory-content-api.js +591 -0
  87. package/dist/index-DxVTFK66.d.mts +105 -0
  88. package/dist/index-DxVTFK66.d.mts.map +1 -0
  89. package/dist/index.d.mts +6 -5
  90. package/dist/index.d.mts.map +1 -1
  91. package/dist/index.d.ts +19 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +16 -0
  94. package/dist/index.mjs +37 -6
  95. package/dist/index.mjs.map +1 -1
  96. package/dist/indexing.d.mts +152 -0
  97. package/dist/indexing.d.mts.map +1 -0
  98. package/dist/indexing.d.ts +5 -0
  99. package/dist/indexing.d.ts.map +1 -0
  100. package/dist/indexing.js +7 -0
  101. package/dist/indexing.mjs +255 -0
  102. package/dist/indexing.mjs.map +1 -0
  103. package/dist/json-whitespace-view.d.ts +32 -0
  104. package/dist/json-whitespace-view.d.ts.map +1 -0
  105. package/dist/json-whitespace-view.js +152 -0
  106. package/dist/middleware.d.ts +20 -0
  107. package/dist/middleware.d.ts.map +1 -0
  108. package/dist/middleware.js +1031 -0
  109. package/dist/node.d.mts +10 -15
  110. package/dist/node.d.mts.map +1 -1
  111. package/dist/node.d.ts +25 -0
  112. package/dist/node.d.ts.map +1 -0
  113. package/dist/node.js +24 -0
  114. package/dist/node.mjs +89 -135
  115. package/dist/node.mjs.map +1 -1
  116. package/dist/reader.d.mts +5 -8
  117. package/dist/reader.d.mts.map +1 -1
  118. package/dist/reader.d.ts +15 -0
  119. package/dist/reader.d.ts.map +1 -0
  120. package/dist/reader.js +13 -0
  121. package/dist/reader.mjs +8 -8
  122. package/dist/reader.mjs.map +1 -1
  123. package/dist/schemas/index.d.mts +2 -90
  124. package/dist/schemas/index.d.ts +102 -0
  125. package/dist/schemas/index.d.ts.map +1 -0
  126. package/dist/schemas/index.js +87 -0
  127. package/dist/schemas/index.mjs +2 -70
  128. package/dist/schemas-CFRD0FIQ.mjs +84 -0
  129. package/dist/schemas-CFRD0FIQ.mjs.map +1 -0
  130. package/dist/{site-vNtJ5jCh.mjs → site-8oaj1Q60.mjs} +21 -193
  131. package/dist/site-8oaj1Q60.mjs.map +1 -0
  132. package/dist/site-index-B_254bCc.d.mts +136 -0
  133. package/dist/site-index-B_254bCc.d.mts.map +1 -0
  134. package/dist/site-index.d.ts +60 -0
  135. package/dist/site-index.d.ts.map +1 -0
  136. package/dist/site-index.js +287 -0
  137. package/dist/site.d.ts +21 -0
  138. package/dist/site.d.ts.map +1 -0
  139. package/dist/site.js +168 -0
  140. package/dist/{types-DWt912tu.mjs → types-DOdldbfD.mjs} +3 -2
  141. package/dist/types-DOdldbfD.mjs.map +1 -0
  142. package/dist/types-DjfhS272.d.mts +456 -0
  143. package/dist/types-DjfhS272.d.mts.map +1 -0
  144. package/dist/types.d.ts +453 -0
  145. package/dist/types.d.ts.map +1 -0
  146. package/dist/types.js +36 -0
  147. package/dist/url-safe-base64.d.ts +12 -0
  148. package/dist/url-safe-base64.d.ts.map +1 -0
  149. package/dist/url-safe-base64.js +40 -0
  150. package/dist/url-validation.d.ts +14 -0
  151. package/dist/url-validation.d.ts.map +1 -0
  152. package/dist/url-validation.js +81 -0
  153. package/dist/utils/atomic-write.d.ts +6 -0
  154. package/dist/utils/atomic-write.d.ts.map +1 -0
  155. package/dist/utils/atomic-write.js +20 -0
  156. package/dist/utils.d.ts +46 -0
  157. package/dist/utils.d.ts.map +1 -0
  158. package/dist/utils.js +70 -0
  159. package/dist/vite-plugin.d.ts +12 -0
  160. package/dist/vite-plugin.d.ts.map +1 -0
  161. package/dist/vite-plugin.js +29 -0
  162. package/dist/vxjson-qHrgLGip.mjs +555 -0
  163. package/dist/vxjson-qHrgLGip.mjs.map +1 -0
  164. package/dist/vxjson-serialize-geF6qvpn.mjs +34 -0
  165. package/dist/vxjson-serialize-geF6qvpn.mjs.map +1 -0
  166. package/dist/vxjson-serialize.d.mts +17 -0
  167. package/dist/vxjson-serialize.d.mts.map +1 -0
  168. package/dist/vxjson-serialize.d.ts +14 -0
  169. package/dist/vxjson-serialize.d.ts.map +1 -0
  170. package/dist/vxjson-serialize.js +50 -0
  171. package/dist/vxjson-serialize.mjs +2 -0
  172. package/dist/vxjson.d.ts +112 -0
  173. package/dist/vxjson.d.ts.map +1 -0
  174. package/dist/vxjson.js +391 -0
  175. package/dist/xxhash.d.ts +10 -0
  176. package/dist/xxhash.d.ts.map +1 -0
  177. package/dist/xxhash.js +31 -0
  178. package/package.json +79 -17
  179. package/dist/component-registry.types-CBGONnYn.d.mts.map +0 -1
  180. package/dist/content-operations-Dv67amz3.d.mts +0 -852
  181. package/dist/content-operations-Dv67amz3.d.mts.map +0 -1
  182. package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +0 -1
  183. package/dist/filesystem-content-api-kxKY5IUw.mjs.map +0 -1
  184. package/dist/schemas/index.d.mts.map +0 -1
  185. package/dist/schemas/index.mjs.map +0 -1
  186. package/dist/site-vNtJ5jCh.mjs.map +0 -1
  187. package/dist/types-DWt912tu.mjs.map +0 -1
@@ -0,0 +1,2181 @@
1
+ import { mkdir, open, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
2
+ import { xxh64 } from './xxhash';
3
+ import matter from 'gray-matter';
4
+ import { dirname, join, resolve } from 'path';
5
+ import sortKeys from 'sort-keys';
6
+ import { Blocks } from './blocks';
7
+ import { filterContentWithIndexes } from './content-filters';
8
+ import { ContentIndex } from './content-index';
9
+ import { analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, generateContentId, isContentPublished, shouldUpdateModifiedTimestamp, UPDATE_SCOPE, updatePublishDates, validateAndPrepareMetadata, validateCreateContent, } from './content-operations';
10
+ import { localesOf, mapSiteNames, resolvePublishDate, serializeMdxWithFrontmatter } from './content-utils';
11
+ import { Data } from './data';
12
+ import { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils';
13
+ import { Site } from './site';
14
+ import { atomicWriteFile } from './utils/atomic-write';
15
+ import { VXJSON } from './vxjson';
16
+ // Helper to ensure we have an Error object
17
+ function ensureError(error) {
18
+ if (error instanceof Error) {
19
+ return error;
20
+ }
21
+ return new Error(String(error));
22
+ }
23
+ // Reusable TextDecoder instance - safe to reuse as it's stateless
24
+ const textDecoder = new TextDecoder();
25
+ // Parse 4KB MDX content - extracts frontmatter from buffer
26
+ function parse4KBMDX(buffer, bytesRead) {
27
+ // Only convert to string what we need
28
+ const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));
29
+ const { data: frontmatter } = matter(partialContent, {});
30
+ // Find where content starts (after second ---)
31
+ const delimiter = new TextEncoder().encode('---');
32
+ let delimiterCount = 0;
33
+ let contentStartPos = -1;
34
+ for (let i = 0; i <= bytesRead - delimiter.length; i++) {
35
+ let match = true;
36
+ for (let j = 0; j < delimiter.length; j++) {
37
+ if (buffer[i + j] !== delimiter[j]) {
38
+ match = false;
39
+ break;
40
+ }
41
+ }
42
+ if (match) {
43
+ delimiterCount++;
44
+ if (delimiterCount === 2) {
45
+ // Skip past --- and newline
46
+ contentStartPos = i + delimiter.length;
47
+ while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {
48
+ contentStartPos++;
49
+ }
50
+ break;
51
+ }
52
+ }
53
+ }
54
+ // Extract special fields and treat the rest as metadata
55
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
56
+ return {
57
+ id,
58
+ created,
59
+ modified,
60
+ publishAt,
61
+ unpublishAt,
62
+ meta: metaFields, // All other fields are metadata
63
+ contentStartPos,
64
+ };
65
+ }
66
+ /**
67
+ * FileSystem-based Content API Implementation
68
+ *
69
+ * Stores content as files on disk in a git-friendly format:
70
+ * - Pages: /{site}/pages/{filename}.{locale}.vxjson
71
+ * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
72
+ *
73
+ * ## Indexing
74
+ *
75
+ * Content is indexed at startup for performance. The index is cached per
76
+ * content root path and cleared when the process restarts.
77
+ *
78
+ * ## Read-Repair
79
+ *
80
+ * Since files can be modified externally (git, editors), this implementation:
81
+ *
82
+ * 1. Repairs invalid VXJSON files (ensures "content" field is last)
83
+ * 2. Adds missing required fields (id, created, modified)
84
+ * 3. Handles files added after initial indexing
85
+ * 4. Updates the index when files are repaired or discovered
86
+ *
87
+ * ## Performance
88
+ *
89
+ * - Initial indexing reads only first 4KB of each file
90
+ * - Full content is loaded on demand
91
+ * - ETags are calculated using streaming for efficiency
92
+ */
93
+ /**
94
+ * Read and validate `<contentRoot>/sites.json`. Returns a safe default
95
+ * (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
96
+ * has invalid structure, with a warning logged in each case.
97
+ *
98
+ * Exported standalone so the Astro integration (and any other tooling
99
+ * that needs to inspect per-site config at startup time) can read the
100
+ * config without spinning up a full content-api instance.
101
+ */
102
+ export async function readSitesConfig(contentRoot) {
103
+ const absoluteContentRoot = resolve(contentRoot);
104
+ const sitesPath = join(absoluteContentRoot, 'sites.json');
105
+ try {
106
+ const content = await readFile(sitesPath, 'utf-8');
107
+ const parsed = JSON.parse(content);
108
+ // Validate the structure
109
+ if (!parsed.sites || typeof parsed.sites !== 'object') {
110
+ console.warn(`Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`);
111
+ return { sites: {}, globalLocales: ['en'] };
112
+ }
113
+ if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
114
+ console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
115
+ return {
116
+ sites: parsed.sites,
117
+ globalLocales: ['en'],
118
+ };
119
+ }
120
+ return parsed;
121
+ }
122
+ catch {
123
+ // Handle missing sites.json gracefully
124
+ console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
125
+ return { sites: {}, globalLocales: ['en'] };
126
+ }
127
+ }
128
+ export class FileSystemContentAPI {
129
+ contentRoot;
130
+ absoluteContentRoot;
131
+ contentIndex;
132
+ sitesConfig;
133
+ blocks;
134
+ data;
135
+ sites;
136
+ // mdx-page support: optional second filesystem root for kind:'page'+type:'mdx'.
137
+ // Canonical source is the resolved site's `mdxPages` in sites.json; the
138
+ // ContentAPIOptions.mdxPagesRoot option exists as a test/programmatic
139
+ // override. See ContentAPIOptions.mdxPagesRoot for the design rationale.
140
+ absoluteMdxPagesRoot;
141
+ mdxPagesDefaultLocale = 'en';
142
+ mdxPagesSite = 'default';
143
+ mdxPagesCollection = 'pages';
144
+ // Resolved locale list used to decide whether a path segment that
145
+ // looks locale-shaped (e.g. `de`, `en-US`) is actually a configured
146
+ // locale. Source-of-truth resolution (option > sites.json) happens in
147
+ // the constructor; parsers read this set directly.
148
+ availableLocales;
149
+ // Getter for testing purposes
150
+ get normalizedContentRoot() {
151
+ return this.contentRoot;
152
+ }
153
+ constructor(contentRoot, canvasDir, sitesConfig, contentIndex, mdxPagesOptions, localeOptions) {
154
+ // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is
155
+ if (contentRoot.startsWith('./')) {
156
+ this.contentRoot = contentRoot.slice(2);
157
+ }
158
+ else if (contentRoot.startsWith('/')) {
159
+ // Absolute path, keep as-is
160
+ this.contentRoot = contentRoot;
161
+ }
162
+ else {
163
+ // Already normalized relative path
164
+ this.contentRoot = contentRoot;
165
+ }
166
+ // Store absolute path for file operations
167
+ this.absoluteContentRoot = resolve(this.contentRoot);
168
+ // TODO: Use canvasDir for canvas/unlinked components
169
+ this.sitesConfig = sitesConfig;
170
+ this.contentIndex = contentIndex;
171
+ // Resolve which site owns mdx-type pages. Resolution order:
172
+ // 1. Explicit `mdxPagesOptions.site` (test / programmatic override)
173
+ // 2. First site in sites.json that declares an `mdxPages` path
174
+ // 3. First configured site (any)
175
+ // 4. Literal 'default'
176
+ const siteNames = Object.keys(sitesConfig.sites);
177
+ const firstSiteName = siteNames[0];
178
+ const firstSiteWithMdxPages = siteNames.find((name) => sitesConfig.sites[name]?.mdxPages);
179
+ this.mdxPagesSite = mdxPagesOptions?.site ?? firstSiteWithMdxPages ?? firstSiteName ?? 'default';
180
+ // Resolve the mdx-pages path. Option wins over sites.json so tests and
181
+ // programmatic callers can supply a path without writing a sites.json
182
+ // file. When neither is set, .mdx files fall back to living alongside
183
+ // Puck pages under `{contentRoot}/{site}/pages/`.
184
+ const sitesJsonMdxPages = sitesConfig.sites[this.mdxPagesSite]?.mdxPages;
185
+ const resolvedMdxPages = mdxPagesOptions?.root ?? sitesJsonMdxPages;
186
+ if (resolvedMdxPages) {
187
+ const normalizedMdxPages = resolvedMdxPages.startsWith('./') ? resolvedMdxPages.slice(2) : resolvedMdxPages;
188
+ this.absoluteMdxPagesRoot = resolve(normalizedMdxPages);
189
+ }
190
+ // Default locale: top-level option > mdxPages option > resolved-site's
191
+ // defaultLocale > first global locale > 'en'. The top-level option wins
192
+ // because it represents an explicit framework-level declaration (e.g.
193
+ // forwarded from Astro's i18n block via localesFromAstroI18n).
194
+ const siteConfig = sitesConfig.sites[this.mdxPagesSite];
195
+ this.mdxPagesDefaultLocale =
196
+ localeOptions?.defaultLocale ??
197
+ mdxPagesOptions?.defaultLocale ??
198
+ siteConfig?.defaultLocale ??
199
+ sitesConfig.globalLocales[0] ??
200
+ 'en';
201
+ // Resolve the available-locales set. The top-level option is
202
+ // authoritative when present; otherwise we merge sites.json's global
203
+ // locales with the resolved-site's per-site locales. The default
204
+ // locale is always added so getFilePath round-trips work.
205
+ const merged = new Set();
206
+ if (localeOptions?.availableLocales && localeOptions.availableLocales.length > 0) {
207
+ for (const loc of localeOptions.availableLocales)
208
+ merged.add(loc);
209
+ }
210
+ else {
211
+ for (const loc of sitesConfig.globalLocales)
212
+ merged.add(loc);
213
+ if (siteConfig?.locales) {
214
+ for (const loc of siteConfig.locales)
215
+ merged.add(loc);
216
+ }
217
+ }
218
+ merged.add(this.mdxPagesDefaultLocale);
219
+ this.availableLocales = merged;
220
+ // Initialize blocks
221
+ this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
222
+ // Initialize data
223
+ this.data = new Data(this, this.contentIndex.getDataIndex());
224
+ // Initialize all sites
225
+ this.sites = mapSiteNames(sitesConfig, (siteName) => {
226
+ const siteIndex = this.contentIndex.getSiteIndex(siteName);
227
+ if (!siteIndex) {
228
+ throw new Error(`Site index not found for ${siteName}`);
229
+ }
230
+ return new Site(siteName, this, siteIndex);
231
+ });
232
+ }
233
+ static async create(options) {
234
+ const { canvasDir } = options;
235
+ // Keep contentRoot as provided (will be normalized in constructor)
236
+ const contentRoot = options.contentRoot;
237
+ // Load sites config (canonical home for per-site fields including mdxPages).
238
+ let sitesConfig = await readSitesConfig(contentRoot);
239
+ // Apply the top-level locales option as the authoritative source.
240
+ // We expand sitesConfig so that the BlockIndex (which keys on
241
+ // globalLocales) and the resolved SiteIndex (which keys on the
242
+ // site's locales array) both have slots for every option-declared
243
+ // locale. Without this, the parser would correctly identify a file's
244
+ // locale but `addContent` would crash on a missing index bucket.
245
+ // We preserve the resolved site's existing `mdxPages` and `domains`
246
+ // through the rewrite so the locale-override doesn't clobber the
247
+ // per-site content config.
248
+ if (options.availableLocales && options.availableLocales.length > 0) {
249
+ const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
250
+ const optionSite = options.mdxPagesSite ?? Object.keys(sitesConfig.sites)[0] ?? 'default';
251
+ const existingSite = sitesConfig.sites[optionSite];
252
+ sitesConfig = {
253
+ sites: {
254
+ ...sitesConfig.sites,
255
+ [optionSite]: {
256
+ locales: options.availableLocales,
257
+ defaultLocale: optionDefaultLocale,
258
+ ...(existingSite?.domains && { domains: existingSite.domains }),
259
+ ...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),
260
+ },
261
+ },
262
+ globalLocales: Array.from(new Set([...sitesConfig.globalLocales, ...options.availableLocales])),
263
+ };
264
+ }
265
+ // Get cached content index or create new one
266
+ // Use the normalized contentRoot for cache key
267
+ const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;
268
+ const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
269
+ // Create instance (not cached)
270
+ const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex, {
271
+ root: options.mdxPagesRoot,
272
+ defaultLocale: options.mdxPagesDefaultLocale,
273
+ site: options.mdxPagesSite,
274
+ }, {
275
+ availableLocales: options.availableLocales,
276
+ defaultLocale: options.defaultLocale,
277
+ });
278
+ // Index all content files (only if index is empty)
279
+ if (contentIndex.entryCount === 0) {
280
+ await api.indexAllContent();
281
+ }
282
+ return api;
283
+ }
284
+ /**
285
+ * Clear all caches - useful for testing
286
+ */
287
+ static clearCaches() {
288
+ ContentIndex.clearCache();
289
+ // TODO: CanvasIndex.clearCache() when implemented
290
+ }
291
+ async indexAllContent() {
292
+ // Clear existing indexes
293
+ this.contentIndex.clear();
294
+ // Scan content directory
295
+ const files = await this.scanContentFiles();
296
+ // Use optimized batch size based on benchmarks
297
+ const OPTIMAL_BATCH_SIZE = 1000;
298
+ console.debug(`Indexing ${files.length} content files...`);
299
+ // Pre-allocate reusable buffers for the entire indexing operation
300
+ // Only allocate as many as we need (up to batch size)
301
+ const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);
302
+ const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));
303
+ for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
304
+ const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
305
+ // Process batch in parallel - winner of benchmarks
306
+ await Promise.all(batch.map(async (filePath, index) => {
307
+ try {
308
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);
309
+ if (result) {
310
+ const { manifest, localeVersion, content } = result;
311
+ // Add to index with content if we have it
312
+ this.contentIndex.addContent(manifest, localeVersion, content);
313
+ }
314
+ }
315
+ catch (error) {
316
+ console.error(`Failed to index ${filePath}:`, error);
317
+ }
318
+ }));
319
+ }
320
+ }
321
+ async parseFileHeaderWithRepair(originalFilePath, buffer) {
322
+ let handle;
323
+ let bytesRead = 0;
324
+ let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed
325
+ try {
326
+ handle = await open(filePath, 'r');
327
+ bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
328
+ }
329
+ catch (error) {
330
+ console.error(`Error reading ${filePath}:`, error);
331
+ throw error;
332
+ }
333
+ finally {
334
+ await handle?.close();
335
+ }
336
+ try {
337
+ // Now parse the buffer content
338
+ // Parse file to extract metadata
339
+ let relativePath = filePath.replace(this.absoluteContentRoot + '/', '');
340
+ let parts = relativePath.split('/');
341
+ // Determine site/collection structure
342
+ let site;
343
+ let collection;
344
+ let locale = 'en';
345
+ let name;
346
+ let pathname;
347
+ let parsedData = {};
348
+ let kind;
349
+ // Files under the optional mdxPagesRoot are kind:'page' + type:'mdx',
350
+ // independent of the directory tree rooted at absoluteContentRoot. The
351
+ // leading prefix is stripped here; locale lives as a directory segment
352
+ // ({locale}/{slug}.mdx for non-default locales, {slug}.mdx at the root
353
+ // for the default locale).
354
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + '/')) {
355
+ kind = 'page';
356
+ site = this.mdxPagesSite;
357
+ collection = this.mdxPagesCollection;
358
+ const mdxRelativePath = filePath.replace(this.absoluteMdxPagesRoot + '/', '');
359
+ const mdxParts = mdxRelativePath.split('/');
360
+ const mdxFilename = mdxParts[mdxParts.length - 1];
361
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
362
+ if (!noLocaleMatch)
363
+ return null;
364
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
365
+ // A leading folder counts as a locale only when it's a configured
366
+ // locale. A two-letter folder like `qa/` or `id/` is therefore
367
+ // left in the slug, not silently classified as a language.
368
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
369
+ locale = mdxParts[0];
370
+ const slugParts = mdxParts.slice(1);
371
+ pathname =
372
+ slugParts[slugParts.length - 1] === 'index'
373
+ ? '/' + slugParts.slice(0, -1).join('/') || '/'
374
+ : '/' + slugParts.join('/');
375
+ }
376
+ else {
377
+ locale = this.mdxPagesDefaultLocale;
378
+ pathname =
379
+ mdxParts[mdxParts.length - 1] === 'index'
380
+ ? '/' + mdxParts.slice(0, -1).join('/') || '/'
381
+ : '/' + mdxParts.join('/');
382
+ }
383
+ parsedData = parse4KBMDX(buffer, bytesRead);
384
+ }
385
+ else if (parts[0] === 'blocks') {
386
+ kind = 'block';
387
+ // Check if block is directly in blocks/ directory (no collection subdirectory)
388
+ if (parts.length === 2) {
389
+ // Block is directly in blocks/ directory, needs to be moved to 'general' collection
390
+ collection = 'general';
391
+ const filename = parts[1];
392
+ // Create the general directory if it doesn't exist
393
+ const generalDir = join(this.absoluteContentRoot, 'blocks', 'general');
394
+ try {
395
+ await mkdir(generalDir, { recursive: true });
396
+ }
397
+ catch (error) {
398
+ // Directory might already exist, that's fine
399
+ }
400
+ // Move the file to the general collection
401
+ const newFilePath = join(generalDir, filename);
402
+ try {
403
+ await handle?.close(); // Close the current file handle before moving
404
+ handle = undefined;
405
+ // Check if target file already exists
406
+ try {
407
+ const targetHandle = await open(newFilePath, 'r');
408
+ await targetHandle.close();
409
+ console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);
410
+ }
411
+ catch (error) {
412
+ // Target doesn't exist, safe to move
413
+ await rename(filePath, newFilePath);
414
+ console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);
415
+ // Update filePath to the new path for further processing
416
+ filePath = newFilePath;
417
+ // Update relativePath and parts for the new file path
418
+ relativePath = filePath.replace(this.absoluteContentRoot + '/', '');
419
+ parts = relativePath.split('/');
420
+ // Re-open the file with the new path
421
+ handle = await open(filePath, 'r');
422
+ bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
423
+ }
424
+ }
425
+ catch (moveError) {
426
+ console.error(`Failed to move ${filename} to general collection:`, moveError);
427
+ // Continue processing with original file
428
+ handle = await open(filePath, 'r');
429
+ bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
430
+ }
431
+ }
432
+ else {
433
+ // Block is in a collection subdirectory
434
+ collection = parts[1];
435
+ }
436
+ const filename = parts[parts.length - 1];
437
+ // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en
438
+ // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json
439
+ const matchWithLocale = filename.match(/^(.+)\.(\w+)\.(mdx|vxjson)$/);
440
+ const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
441
+ if (matchWithLocale) {
442
+ name = matchWithLocale[1];
443
+ locale = matchWithLocale[2];
444
+ }
445
+ else if (matchWithoutLocale) {
446
+ name = matchWithoutLocale[1];
447
+ // Use default locale from sites config instead of hardcoded 'en'
448
+ locale = this.contentIndex.getDefaultLocale('');
449
+ console.log(`Found file without locale suffix: ${filename}`);
450
+ // Rename file to include locale suffix
451
+ const extension = matchWithoutLocale[2];
452
+ const newFilename = `${name}.${locale}.${extension}`;
453
+ const newFilePath = join(dirname(filePath), newFilename);
454
+ console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
455
+ // Check if target file already exists
456
+ try {
457
+ await handle?.close(); // Close the current file handle before renaming
458
+ handle = undefined;
459
+ // Try to open the target file to check if it exists
460
+ const targetHandle = await open(newFilePath, 'r');
461
+ await targetHandle.close();
462
+ // Target file exists, skip renaming to avoid conflict
463
+ console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
464
+ }
465
+ catch (error) {
466
+ // Target file doesn't exist, safe to rename
467
+ console.log(`Target file doesn't exist, proceeding with rename`);
468
+ try {
469
+ await rename(filePath, newFilePath);
470
+ console.log(`Successfully renamed ${filename} to ${newFilename}`);
471
+ // Update filePath to the new path for further processing
472
+ filePath = newFilePath;
473
+ // Update relativePath and parts for the new file path
474
+ relativePath = filePath.replace(this.absoluteContentRoot + '/', '');
475
+ parts = relativePath.split('/');
476
+ // Re-open the file with the new path
477
+ handle = await open(filePath, 'r');
478
+ bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
479
+ }
480
+ catch (renameError) {
481
+ console.error(`Failed to rename ${filename}:`, renameError);
482
+ // Continue processing with original file
483
+ handle = await open(filePath, 'r');
484
+ bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
485
+ }
486
+ }
487
+ }
488
+ // Parse content based on file type
489
+ if (filePath.endsWith('.mdx')) {
490
+ parsedData = parse4KBMDX(buffer, bytesRead);
491
+ }
492
+ else {
493
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
494
+ }
495
+ }
496
+ else if (parts[0] === 'data') {
497
+ // Data collection entry: data/{collection}/{name}.{locale}.json
498
+ kind = 'data';
499
+ collection = parts[1];
500
+ const filename = parts[parts.length - 1];
501
+ // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en
502
+ // Use strict locale pattern matching blocks: 2-letter code with optional region (en, en-US)
503
+ const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
504
+ if (match) {
505
+ name = match[1];
506
+ locale = match[2];
507
+ }
508
+ // Parse JSON to get ID, metadata, and data
509
+ const content = textDecoder.decode(buffer.subarray(0, bytesRead));
510
+ try {
511
+ const jsonData = JSON.parse(content);
512
+ parsedData = {
513
+ id: jsonData.id,
514
+ type: 'json',
515
+ created: jsonData.created,
516
+ modified: jsonData.modified,
517
+ publishAt: jsonData.publishAt,
518
+ unpublishAt: jsonData.unpublishAt,
519
+ meta: jsonData.meta || { title: name || 'Untitled' },
520
+ data: jsonData.data,
521
+ name,
522
+ };
523
+ }
524
+ catch (error) {
525
+ console.error(`Failed to parse JSON data file ${filePath}:`, error);
526
+ return null;
527
+ }
528
+ }
529
+ else {
530
+ kind = 'page';
531
+ site = parts[0];
532
+ collection = parts[1];
533
+ // Build pathname from file path. Accepts both .vxjson (Puck pages) and
534
+ // .mdx (mdx-type pages) so consumers without a separate `mdxPages`
535
+ // path can colocate .mdx docs alongside Puck pages under
536
+ // `{contentRoot}/{site}/{collection}/...`. When `mdxPages` IS set
537
+ // on a site in sites.json, .mdx files are served from that
538
+ // separate path (handled in the `absoluteMdxPagesRoot` branch
539
+ // above) and won't reach this branch.
540
+ const pathParts = parts.slice(2); // Remove site/collection
541
+ const filename = pathParts[pathParts.length - 1];
542
+ const match = filename.match(/^(.+)\.(\w+)\.(vxjson|mdx)$/);
543
+ if (match) {
544
+ locale = match[2];
545
+ // Replace filename with basename
546
+ pathParts[pathParts.length - 1] = match[1];
547
+ // index files map to parent: /index -> /, /foo/index -> /foo
548
+ pathname =
549
+ pathParts[pathParts.length - 1] === 'index'
550
+ ? '/' + pathParts.slice(0, -1).join('/') || '/'
551
+ : '/' + pathParts.join('/');
552
+ }
553
+ // Parse format-appropriately. parse4KBMDX reads frontmatter from the
554
+ // MDX header; VXJSON.parse4KB reads the leading JSON metadata.
555
+ if (filePath.endsWith('.mdx')) {
556
+ parsedData = parse4KBMDX(buffer, bytesRead);
557
+ }
558
+ else {
559
+ parsedData = VXJSON.parse4KB(buffer, bytesRead);
560
+ }
561
+ }
562
+ // Check if the file is missing required fields
563
+ const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
564
+ // Extract or generate ID
565
+ const id = parsedData.id || generateContentId();
566
+ // Build LocaleManifest for this specific locale
567
+ const localeVersion = {
568
+ locale,
569
+ etag: '', // Will be filled below
570
+ created: parsedData.created || new Date().toISOString(),
571
+ modified: parsedData.modified || new Date().toISOString(),
572
+ ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),
573
+ ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),
574
+ ...(pathname && { pathname }),
575
+ ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),
576
+ ...(name && { name }),
577
+ meta: parsedData.meta || { title: name || 'Untitled' },
578
+ };
579
+ // Build ContentManifest (without content)
580
+ const manifest = {
581
+ id,
582
+ type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),
583
+ kind,
584
+ site,
585
+ collection,
586
+ locales: {
587
+ [locale]: localeVersion,
588
+ },
589
+ };
590
+ // If we have full content, parse it and compute etags
591
+ let content;
592
+ // Check if we need to repair the file first (missing required fields)
593
+ if (needsRepair) {
594
+ // Perform repair and get the repaired content
595
+ const repairedData = await this.performReadRepair(filePath, manifest, locale);
596
+ if (repairedData) {
597
+ content = repairedData.content;
598
+ localeVersion.etag = repairedData.etag;
599
+ localeVersion.modified = repairedData.modified;
600
+ return { manifest, locale, localeVersion, bytesRead, content };
601
+ }
602
+ // Repair failed, skip this file
603
+ console.error(`Failed to repair ${filePath}, skipping`);
604
+ return null;
605
+ }
606
+ if (bytesRead < 4096 ||
607
+ (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||
608
+ (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)) {
609
+ // We have the full content
610
+ if (filePath.endsWith('.mdx')) {
611
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
612
+ const { content: mdx } = matter(fullContent, {});
613
+ content = { mdx };
614
+ }
615
+ else if (filePath.endsWith('.json')) {
616
+ // Data collection JSON file
617
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
618
+ const jsonData = JSON.parse(fullContent);
619
+ content = { data: jsonData.data };
620
+ }
621
+ else {
622
+ const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
623
+ const data = JSON.parse(fullContent);
624
+ content = data.content || {};
625
+ }
626
+ // Calculate etags from the buffer (only use valid bytes)
627
+ const validBuffer = buffer.subarray(0, bytesRead);
628
+ if (filePath.endsWith('.mdx')) {
629
+ const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
630
+ localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
631
+ }
632
+ else if (filePath.endsWith('.json')) {
633
+ // For data files, use simple etag (hash entire buffer)
634
+ // Data files are typically small and don't need separate meta/content etags
635
+ localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
636
+ }
637
+ else {
638
+ const etagResult = VXJSON.calculateETags(validBuffer);
639
+ if (!etagResult.success) {
640
+ // Content field is not last or invalid JSON - repair immediately
641
+ // Perform repair and get the repaired content
642
+ const repairedData = await this.performReadRepair(filePath, manifest, locale);
643
+ if (repairedData) {
644
+ content = repairedData.content;
645
+ localeVersion.etag = repairedData.etag;
646
+ localeVersion.modified = repairedData.modified;
647
+ return { manifest, locale, localeVersion, bytesRead, content };
648
+ }
649
+ // Repair failed, skip this file
650
+ console.error(`Failed to repair ${filePath}, skipping`);
651
+ return null;
652
+ }
653
+ localeVersion.etag = etagResult.contentEtag
654
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
655
+ : etagResult.metaEtag;
656
+ }
657
+ }
658
+ // Return both for indexing
659
+ return { manifest, locale, localeVersion, bytesRead, content };
660
+ }
661
+ catch (error) {
662
+ console.error(`Error indexing ${originalFilePath}:`, error);
663
+ return null;
664
+ }
665
+ }
666
+ /**
667
+ * Perform read-repair by writing back the file with missing fields
668
+ * This ensures stable IDs and timestamps across restarts
669
+ */
670
+ async performReadRepair(filePath, manifest, locale) {
671
+ try {
672
+ const now = new Date().toISOString();
673
+ let needsWrite = false;
674
+ if (manifest.type === 'mdx') {
675
+ // Read the full MDX file
676
+ const content = await readFile(filePath, 'utf-8');
677
+ const parsed = matter(content, {});
678
+ // Check for missing fields
679
+ if (!parsed.data.id) {
680
+ parsed.data.id = manifest.id;
681
+ needsWrite = true;
682
+ }
683
+ if (!parsed.data.created) {
684
+ parsed.data.created = now;
685
+ needsWrite = true;
686
+ }
687
+ if (!parsed.data.modified) {
688
+ parsed.data.modified = now;
689
+ needsWrite = true;
690
+ }
691
+ if (needsWrite) {
692
+ // Write back with updated frontmatter. Pass the parsed file
693
+ // object, not the body string: stringify re-parses string inputs
694
+ // through gray-matter's memo cache, which is a plain object — a
695
+ // body equal to an Object.prototype member name ('toString',
696
+ // 'valueOf', …) reads the prototype function back and crashes.
697
+ // Same cache-opt-out rule as the matter(..., {}) calls above.
698
+ const updatedContent = matter.stringify(parsed, parsed.data);
699
+ await writeFile(filePath, updatedContent);
700
+ console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
701
+ // Calculate ETags for the repaired MDX file
702
+ const repairedBuffer = Buffer.from(updatedContent, 'utf-8');
703
+ const contentStartPos = updatedContent.indexOf('\n---\n') + 5; // Position after frontmatter
704
+ const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);
705
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
706
+ // Return the repaired data. Strip leading newlines so the
707
+ // body matches what the author wrote — see `readLocaleFile`.
708
+ return {
709
+ content: { mdx: parsed.content.replace(/^\n+/, '') },
710
+ etag,
711
+ modified: parsed.data.modified || now,
712
+ };
713
+ }
714
+ }
715
+ else {
716
+ // Read the full JSON file
717
+ const content = await readFile(filePath, 'utf-8');
718
+ const data = JSON.parse(content);
719
+ // Check for missing fields
720
+ if (!data.id) {
721
+ data.id = manifest.id;
722
+ needsWrite = true;
723
+ }
724
+ if (!data.created) {
725
+ data.created = now;
726
+ needsWrite = true;
727
+ }
728
+ if (!data.modified) {
729
+ data.modified = now;
730
+ needsWrite = true;
731
+ }
732
+ // Always rewrite VXJSON files during repair to ensure correct field order
733
+ needsWrite = true;
734
+ if (needsWrite) {
735
+ // Write back with VXJSON format
736
+ const vxjsonData = {
737
+ id: data.id,
738
+ type: data.type,
739
+ created: data.created,
740
+ modified: data.modified,
741
+ publishAt: data.publishAt,
742
+ unpublishAt: data.unpublishAt,
743
+ previousPathnames: data.previousPathnames,
744
+ meta: data.meta || {},
745
+ content: data.content || {},
746
+ };
747
+ const repairedJson = VXJSON.serialize(vxjsonData);
748
+ await writeFile(filePath, repairedJson);
749
+ console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
750
+ // Return the repaired data
751
+ // Calculate ETags from the repaired JSON
752
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8');
753
+ const etagResult = VXJSON.calculateETags(repairedBuffer);
754
+ if (!etagResult.success) {
755
+ console.error(`Failed to calculate ETags after repair: ${filePath}`);
756
+ return null;
757
+ }
758
+ const etag = etagResult.contentEtag
759
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
760
+ : etagResult.metaEtag;
761
+ // Return the complete repaired data
762
+ return {
763
+ content: vxjsonData.content,
764
+ etag,
765
+ modified: vxjsonData.modified,
766
+ };
767
+ }
768
+ }
769
+ // For MDX or no repair needed, return null
770
+ return null;
771
+ }
772
+ catch (error) {
773
+ console.error(`Failed to perform read-repair on ${filePath}:`, error);
774
+ return null;
775
+ }
776
+ }
777
+ async scanContentFiles() {
778
+ const files = [];
779
+ const contentRoot = this.absoluteContentRoot;
780
+ async function scan(dir, inDataDir = false) {
781
+ try {
782
+ const entries = await readdir(dir, { withFileTypes: true });
783
+ for (const entry of entries) {
784
+ const fullPath = join(dir, entry.name);
785
+ if (entry.isDirectory()) {
786
+ // Check if we're entering the data/ directory
787
+ const isDataDir = dir === contentRoot && entry.name === 'data';
788
+ await scan(fullPath, inDataDir || isDataDir);
789
+ }
790
+ else if (entry.isFile()) {
791
+ // Include .vxjson and .mdx files everywhere
792
+ // Include .json files only in the data/ directory
793
+ if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {
794
+ files.push(fullPath);
795
+ }
796
+ else if (inDataDir && entry.name.endsWith('.json')) {
797
+ files.push(fullPath);
798
+ }
799
+ }
800
+ }
801
+ }
802
+ catch (error) {
803
+ // Directory doesn't exist yet
804
+ }
805
+ }
806
+ await scan(this.absoluteContentRoot);
807
+ // Also scan mdxPagesRoot for .mdx files when the second root is configured.
808
+ // Supports projects that store mdx-type pages outside the main content
809
+ // tree (the rendering pipeline that consumes them is the project's choice).
810
+ //
811
+ // Skip the second scan when mdxPagesRoot is the same as contentRoot OR
812
+ // nested inside it — the first scan already walked those files, and a
813
+ // second pass would push every `.mdx` onto `files` twice. The nested case
814
+ // is the documented Starlight pattern (`contentRoot: './src/content'`,
815
+ // `mdxPagesRoot: './src/content/docs'`), so the prefix check matters in
816
+ // practice.
817
+ if (this.absoluteMdxPagesRoot &&
818
+ this.absoluteMdxPagesRoot !== this.absoluteContentRoot &&
819
+ !this.absoluteMdxPagesRoot.startsWith(this.absoluteContentRoot + '/')) {
820
+ async function scanMdxPages(dir) {
821
+ try {
822
+ const entries = await readdir(dir, { withFileTypes: true });
823
+ for (const entry of entries) {
824
+ const fullPath = join(dir, entry.name);
825
+ if (entry.isDirectory()) {
826
+ await scanMdxPages(fullPath);
827
+ }
828
+ else if (entry.isFile() && entry.name.endsWith('.mdx')) {
829
+ files.push(fullPath);
830
+ }
831
+ }
832
+ }
833
+ catch (error) {
834
+ // Directory doesn't exist yet
835
+ }
836
+ }
837
+ await scanMdxPages(this.absoluteMdxPagesRoot);
838
+ }
839
+ return files;
840
+ }
841
+ getFilePath(manifest, { locale, name, pathname }) {
842
+ if (manifest.kind === 'block') {
843
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
844
+ return join(this.absoluteContentRoot, 'blocks', manifest.collection, `${name}.${locale}.${ext}`);
845
+ }
846
+ if (manifest.kind === 'data') {
847
+ return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);
848
+ }
849
+ if (manifest.kind === 'page' && pathname) {
850
+ // For pages, derive path from pathname
851
+ const basePath = pathname.replace(/^\//, '').replace(/\/$/, '') || 'index';
852
+ // mdx-type pages live under absoluteMdxPagesRoot when configured.
853
+ // The locale appears as a directory segment for non-default locales;
854
+ // the default locale's files live at the root with no locale prefix.
855
+ if (manifest.type === 'mdx' && this.absoluteMdxPagesRoot) {
856
+ return locale === this.mdxPagesDefaultLocale
857
+ ? join(this.absoluteMdxPagesRoot, `${basePath}.mdx`)
858
+ : join(this.absoluteMdxPagesRoot, locale, `${basePath}.mdx`);
859
+ }
860
+ // Pages live under contentRoot/{site}/{collection}. When type:'mdx'
861
+ // and no `mdxPages` path is configured for the site, the .mdx files
862
+ // sit here alongside the .vxjson Puck pages — the layout chosen
863
+ // when sites.json doesn't declare a separate `mdxPages` path.
864
+ if (manifest.site) {
865
+ const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';
866
+ return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.${ext}`);
867
+ }
868
+ }
869
+ throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
870
+ }
871
+ /**
872
+ * Parse a file path back into its components for checking against the path index
873
+ * Returns null if the path doesn't match expected patterns
874
+ */
875
+ parseFilePath(filePath) {
876
+ // Files under mdxPagesRoot are kind:'page' + type:'mdx' regardless of
877
+ // their position relative to absoluteContentRoot. Mirror the parsing
878
+ // performed in parseFileHeaderWithRepair so both code paths agree on
879
+ // the derived (pathname, locale) tuple.
880
+ if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + '/')) {
881
+ const mdxRelativePath = filePath.replace(this.absoluteMdxPagesRoot + '/', '');
882
+ const mdxParts = mdxRelativePath.split('/');
883
+ const mdxFilename = mdxParts[mdxParts.length - 1];
884
+ let locale;
885
+ let pathname;
886
+ const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
887
+ if (!noLocaleMatch)
888
+ return null;
889
+ mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
890
+ // Membership-based locale detection — mirrors parseFileHeaderWithRepair
891
+ // so both paths classify the same file identically.
892
+ if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
893
+ locale = mdxParts[0];
894
+ const slugParts = mdxParts.slice(1);
895
+ pathname =
896
+ slugParts[slugParts.length - 1] === 'index'
897
+ ? '/' + slugParts.slice(0, -1).join('/') || '/'
898
+ : '/' + slugParts.join('/');
899
+ }
900
+ else {
901
+ locale = this.mdxPagesDefaultLocale;
902
+ pathname =
903
+ mdxParts[mdxParts.length - 1] === 'index'
904
+ ? '/' + mdxParts.slice(0, -1).join('/') || '/'
905
+ : '/' + mdxParts.join('/');
906
+ }
907
+ return {
908
+ kind: 'page',
909
+ site: this.mdxPagesSite,
910
+ collection: this.mdxPagesCollection,
911
+ pathname,
912
+ locale,
913
+ };
914
+ }
915
+ // Remove contentRoot prefix
916
+ const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');
917
+ const parts = relativePath.split('/');
918
+ // Match locale.ext pattern at the end
919
+ const filename = parts[parts.length - 1];
920
+ // Handle data files: data/{collection}/{name}.{locale}.json
921
+ if (parts[0] === 'data' && parts.length === 3) {
922
+ const dataMatch = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
923
+ if (!dataMatch)
924
+ return null;
925
+ const [, name, locale] = dataMatch;
926
+ return {
927
+ kind: 'data',
928
+ collection: parts[1],
929
+ name,
930
+ locale,
931
+ };
932
+ }
933
+ // Match locale.ext pattern for non-data files (vxjson, mdx)
934
+ const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.(?:vxjson|mdx)$/);
935
+ if (!match)
936
+ return null;
937
+ const [, nameOrPath, locale] = match;
938
+ if (parts[0] === 'blocks' && parts.length === 3) {
939
+ // blocks/collection/name.locale.ext
940
+ return {
941
+ kind: 'block',
942
+ collection: parts[1],
943
+ name: nameOrPath,
944
+ locale,
945
+ };
946
+ }
947
+ if (parts.length >= 3 && parts[0] !== 'blocks') {
948
+ // site/collection/pathname.locale.vxjson
949
+ const site = parts[0];
950
+ const collection = parts[1];
951
+ // Reconstruct pathname from remaining parts
952
+ const pathParts = parts.slice(2, -1); // All dirs between collection and filename
953
+ pathParts.push(nameOrPath); // Add the filename part (without locale.ext)
954
+ const pathname = '/' + pathParts.join('/');
955
+ return {
956
+ kind: 'page',
957
+ site,
958
+ collection,
959
+ pathname,
960
+ locale,
961
+ };
962
+ }
963
+ return null;
964
+ }
965
+ async getContent(id) {
966
+ // Get manifest for this ID
967
+ const manifest = this.contentIndex.getManifest(id);
968
+ if (!manifest) {
969
+ return null;
970
+ }
971
+ // Read all locale files in parallel
972
+ const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
973
+ const filePath = this.getFilePath(manifest, localeVersion);
974
+ const content = await this.readLocaleFile(filePath, localeVersion.locale);
975
+ return { localeVersion, content };
976
+ });
977
+ const results = await Promise.all(readPromises);
978
+ // Build locales with content
979
+ const locales = {};
980
+ for (const { localeVersion, content } of results) {
981
+ if (content) {
982
+ locales[localeVersion.locale] = {
983
+ ...localeVersion,
984
+ etag: content.etag, // Use fresh etag from file, not stale manifest etag
985
+ content: content.content,
986
+ };
987
+ }
988
+ }
989
+ return {
990
+ id: manifest.id,
991
+ site: manifest.site,
992
+ collection: manifest.collection,
993
+ type: manifest.type,
994
+ kind: manifest.kind,
995
+ locales,
996
+ };
997
+ }
998
+ async getLocalized(id, locale) {
999
+ // Get manifest for this ID
1000
+ const manifest = this.contentIndex.getManifest(id);
1001
+ if (!manifest) {
1002
+ // File might have been added after indexing - try reindexing
1003
+ await this.reindex();
1004
+ // Try again with updated index
1005
+ const updatedManifest = this.contentIndex.getManifest(id);
1006
+ if (!updatedManifest || !updatedManifest.locales[locale]) {
1007
+ return null;
1008
+ }
1009
+ return this.getLocalized(id, locale);
1010
+ }
1011
+ // Check if this locale exists
1012
+ const localeVersion = manifest.locales[locale];
1013
+ if (!localeVersion) {
1014
+ return null;
1015
+ }
1016
+ // Read the locale-specific file
1017
+ const filePath = this.getFilePath(manifest, localeVersion);
1018
+ const localeData = await this.readLocaleFile(filePath, locale);
1019
+ if (!localeData) {
1020
+ return null;
1021
+ }
1022
+ // Build LocalizedEntry
1023
+ return {
1024
+ id: manifest.id,
1025
+ site: manifest.site,
1026
+ collection: manifest.collection,
1027
+ type: manifest.type,
1028
+ kind: manifest.kind,
1029
+ localized: {
1030
+ ...localeVersion,
1031
+ etag: localeData.etag, // Use fresh etag from file, not stale manifest etag
1032
+ content: localeData.content,
1033
+ },
1034
+ };
1035
+ }
1036
+ async readLocaleFile(filePath, locale) {
1037
+ try {
1038
+ const buffer = (await readFile(filePath));
1039
+ const content = textDecoder.decode(buffer);
1040
+ if (filePath.endsWith('.mdx')) {
1041
+ const { data: frontmatter, content: rawBody } = matter(content, {});
1042
+ // gray-matter leaves the blank line after the closing `---` on
1043
+ // the body. Strip leading newlines so the round-trip matches the
1044
+ // body the author wrote.
1045
+ const body = rawBody.replace(/^\n+/, '');
1046
+ // Calculate etags from the file buffer
1047
+ const contentPos = findMdxContentStartPosition(buffer);
1048
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
1049
+ const etag = `${etags.metaEtag}.${etags.contentEtag}`;
1050
+ // Extract special fields from frontmatter, everything else is metadata
1051
+ const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
1052
+ // Body-only — frontmatter is server-owned and surfaced separately
1053
+ // via `meta` / `created` / `modified`. Returning the full file here
1054
+ // would let the editor round-trip the YAML block as body text, which
1055
+ // duplicates the frontmatter on disk when content is inserted above
1056
+ // it (proven on assets.mdx, 2026-05-11).
1057
+ const result = {
1058
+ locale,
1059
+ etag,
1060
+ created: created,
1061
+ modified: modified,
1062
+ meta: metaFields,
1063
+ content: { mdx: body },
1064
+ };
1065
+ // Only add publish dates if they exist
1066
+ if (frontmatter.publishAt !== undefined) {
1067
+ result.publishAt = frontmatter.publishAt;
1068
+ }
1069
+ if (frontmatter.unpublishAt !== undefined) {
1070
+ result.unpublishAt = frontmatter.unpublishAt;
1071
+ }
1072
+ return result;
1073
+ }
1074
+ // Parse JSON data first to determine type
1075
+ const data = JSON.parse(content);
1076
+ // Handle JSON data files (type: 'json') separately - they use simple etag
1077
+ if (data.type === 'json') {
1078
+ const etag = VXJSON.calculateSimpleEtag(buffer);
1079
+ const result = {
1080
+ locale,
1081
+ etag,
1082
+ created: data.created,
1083
+ modified: data.modified,
1084
+ meta: data.meta || {},
1085
+ content: { data: data.data || {} },
1086
+ };
1087
+ // Only add optional fields if they exist
1088
+ if (data.publishAt !== undefined) {
1089
+ result.publishAt = data.publishAt;
1090
+ }
1091
+ if (data.unpublishAt !== undefined) {
1092
+ result.unpublishAt = data.unpublishAt;
1093
+ }
1094
+ return result;
1095
+ }
1096
+ // For VXJSON (puck pages), calculate ETags with meta/content split
1097
+ const etagResult = VXJSON.calculateETags(buffer);
1098
+ if (!etagResult.success) {
1099
+ // File needs repair - parse it and rewrite in correct format
1100
+ const repairedData = {
1101
+ id: data.id,
1102
+ type: data.type,
1103
+ created: data.created,
1104
+ modified: data.modified,
1105
+ publishAt: data.publishAt,
1106
+ unpublishAt: data.unpublishAt,
1107
+ previousPathnames: data.previousPathnames,
1108
+ meta: data.meta || {},
1109
+ content: data.content || {},
1110
+ };
1111
+ // Rewrite file with correct format
1112
+ const repairedJson = VXJSON.serialize(repairedData);
1113
+ await writeFile(filePath, repairedJson);
1114
+ // Recalculate ETags from repaired buffer
1115
+ const repairedBuffer = Buffer.from(repairedJson, 'utf-8');
1116
+ const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
1117
+ if (!repairedEtagResult.success) {
1118
+ throw new Error(`Failed to repair VXJSON file: ${filePath}`);
1119
+ }
1120
+ const etag = repairedEtagResult.contentEtag
1121
+ ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`
1122
+ : repairedEtagResult.metaEtag;
1123
+ console.log(`Repaired VXJSON file: ${filePath}`);
1124
+ const result = {
1125
+ locale,
1126
+ etag,
1127
+ created: data.created,
1128
+ modified: data.modified,
1129
+ meta: data.meta || {},
1130
+ content: data.content || {},
1131
+ };
1132
+ // Only add optional fields if they exist
1133
+ if (data.publishAt !== undefined) {
1134
+ result.publishAt = data.publishAt;
1135
+ }
1136
+ if (data.unpublishAt !== undefined) {
1137
+ result.unpublishAt = data.unpublishAt;
1138
+ }
1139
+ if (data.previousPathnames !== undefined) {
1140
+ result.previousPathnames = data.previousPathnames;
1141
+ }
1142
+ return result;
1143
+ }
1144
+ const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1145
+ const result = {
1146
+ locale,
1147
+ etag,
1148
+ created: data.created,
1149
+ modified: data.modified,
1150
+ meta: data.meta || {},
1151
+ content: data.content || {},
1152
+ };
1153
+ // Only add optional fields if they exist
1154
+ if (data.publishAt !== undefined) {
1155
+ result.publishAt = data.publishAt;
1156
+ }
1157
+ if (data.unpublishAt !== undefined) {
1158
+ result.unpublishAt = data.unpublishAt;
1159
+ }
1160
+ if (data.previousPathnames !== undefined) {
1161
+ result.previousPathnames = data.previousPathnames;
1162
+ }
1163
+ return result;
1164
+ }
1165
+ catch (error) {
1166
+ return null;
1167
+ }
1168
+ }
1169
+ async createContent(data) {
1170
+ // Use shared validation
1171
+ const validation = validateCreateContent(data, this.sites, this.blocks, this.data);
1172
+ if (!validation.valid) {
1173
+ return {
1174
+ success: false,
1175
+ reason: validation.reason,
1176
+ error: validation.error ? new Error(validation.error) : undefined,
1177
+ existingId: validation.existingId,
1178
+ };
1179
+ }
1180
+ const id = generateContentId();
1181
+ const now = data.created || new Date().toISOString();
1182
+ try {
1183
+ // Build the manifest with all locales
1184
+ const manifest = {
1185
+ id,
1186
+ type: data.type,
1187
+ kind: data.kind,
1188
+ site: data.site,
1189
+ collection: data.collection,
1190
+ locales: {},
1191
+ };
1192
+ const contentCache = {};
1193
+ // Create files for each locale
1194
+ for (const [locale, localeData] of Object.entries(data.locales)) {
1195
+ const content = localeData.content;
1196
+ // Build metadata with required title
1197
+ const title = localeData.meta?.title || data.meta?.title;
1198
+ if (!title) {
1199
+ return {
1200
+ success: false,
1201
+ reason: 'write_error',
1202
+ error: new Error('Title is required in metadata'),
1203
+ };
1204
+ }
1205
+ // Build complete metadata
1206
+ const meta = {
1207
+ title,
1208
+ ...data.meta,
1209
+ ...localeData.meta,
1210
+ };
1211
+ const fileData = {
1212
+ id,
1213
+ type: data.type,
1214
+ created: now,
1215
+ modified: now,
1216
+ publishAt: localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1217
+ unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1218
+ meta,
1219
+ content,
1220
+ };
1221
+ // Use the proper getFilePath method
1222
+ const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });
1223
+ // Ensure directory exists
1224
+ await mkdir(dirname(filePath), { recursive: true });
1225
+ // Write file and calculate etag from the serialized content
1226
+ let etag;
1227
+ if (data.type === 'mdx') {
1228
+ // Write MDX with frontmatter - flatten metadata fields
1229
+ const frontmatterData = {
1230
+ id,
1231
+ created: now,
1232
+ modified: now,
1233
+ ...(localeData.publishAt && { publishAt: localeData.publishAt }),
1234
+ ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),
1235
+ ...meta, // Spread metadata fields directly, not nested
1236
+ };
1237
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');
1238
+ await writeFile(filePath, mdxContent);
1239
+ // For MDX, calculate etags from the serialized content
1240
+ const mdxBuffer = new TextEncoder().encode(mdxContent);
1241
+ // For MDX, all frontmatter is metadata, content starts after ---
1242
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
1243
+ let contentPos = -1;
1244
+ for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
1245
+ let match = true;
1246
+ for (let j = 0; j < contentStartMarker.length; j++) {
1247
+ if (mdxBuffer[i + j] !== contentStartMarker[j]) {
1248
+ match = false;
1249
+ break;
1250
+ }
1251
+ }
1252
+ if (match) {
1253
+ contentPos = i + contentStartMarker.length;
1254
+ break;
1255
+ }
1256
+ }
1257
+ const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
1258
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
1259
+ }
1260
+ else if (data.type === 'json') {
1261
+ // Data files use "data" field instead of "content"
1262
+ const dataFileContent = {
1263
+ id,
1264
+ type: 'json',
1265
+ created: now,
1266
+ modified: now,
1267
+ ...(localeData.publishAt &&
1268
+ typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),
1269
+ ...(localeData.unpublishAt &&
1270
+ typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),
1271
+ meta,
1272
+ data: content.data || {},
1273
+ };
1274
+ const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\t');
1275
+ await writeFile(filePath, jsonContent);
1276
+ // For data files, use simple etag (hash entire buffer)
1277
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1278
+ etag = VXJSON.calculateSimpleEtag(jsonBuffer);
1279
+ }
1280
+ else {
1281
+ // VXJSON for pages (puck)
1282
+ const jsonContent = VXJSON.serialize(fileData);
1283
+ const jsonBuffer = new TextEncoder().encode(jsonContent);
1284
+ // Calculate etags from the buffer
1285
+ const etagResult = VXJSON.calculateETags(jsonBuffer);
1286
+ if (!etagResult.success) {
1287
+ throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
1288
+ }
1289
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1290
+ // Write the file
1291
+ await writeFile(filePath, jsonContent);
1292
+ }
1293
+ // Build locale manifest using shared function
1294
+ const localeVersion = buildLocaleVersion({
1295
+ locale,
1296
+ etag,
1297
+ created: now,
1298
+ modified: now,
1299
+ meta,
1300
+ kind: data.kind,
1301
+ pathname: data.kind === 'page' ? localeData.pathname : undefined,
1302
+ name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,
1303
+ publishAt: localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,
1304
+ unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,
1305
+ });
1306
+ // Add locale to manifest
1307
+ manifest.locales[locale] = localeVersion;
1308
+ contentCache[locale] = content;
1309
+ }
1310
+ // Add each locale to the index
1311
+ for (const localeVersion of localesOf(manifest)) {
1312
+ const { locale } = localeVersion;
1313
+ this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
1314
+ }
1315
+ return { success: true, id };
1316
+ }
1317
+ catch (error) {
1318
+ return {
1319
+ success: false,
1320
+ reason: 'write_error',
1321
+ error: ensureError(error),
1322
+ };
1323
+ }
1324
+ }
1325
+ async updateLocalized(input) {
1326
+ const { id, locale, data, etag } = input;
1327
+ // Get the manifest
1328
+ const manifest = this.contentIndex.getManifest(id);
1329
+ if (!manifest) {
1330
+ return {
1331
+ success: false,
1332
+ reason: 'not_found',
1333
+ };
1334
+ }
1335
+ // Get the specific locale manifest
1336
+ const localeVersion = manifest.locales[locale];
1337
+ if (!localeVersion) {
1338
+ return {
1339
+ success: false,
1340
+ reason: 'not_found',
1341
+ };
1342
+ }
1343
+ // Get file path and read current content FIRST to get fresh etag
1344
+ const filePath = this.getFilePath(manifest, localeVersion);
1345
+ const current = await this.readLocaleFile(filePath, locale);
1346
+ if (!current) {
1347
+ return {
1348
+ success: false,
1349
+ reason: 'not_found',
1350
+ };
1351
+ }
1352
+ // Use fresh etag from file, not stale manifest etag
1353
+ const currentEtag = current.etag;
1354
+ // Check etag - data files use simple etags, others use dual etags
1355
+ if (manifest.kind === 'data') {
1356
+ // Data files use simple etag (single hash, no dot separator)
1357
+ // Just compare the full etag directly
1358
+ if (etag !== currentEtag) {
1359
+ return {
1360
+ success: false,
1361
+ reason: 'stale_write',
1362
+ currentEtag,
1363
+ };
1364
+ }
1365
+ }
1366
+ else {
1367
+ // Non-data files use dual etags (meta.content format)
1368
+ const etagParts = parseDualEtag(etag);
1369
+ const currentParts = parseDualEtag(currentEtag);
1370
+ if (!etagParts || !currentParts) {
1371
+ return {
1372
+ success: false,
1373
+ reason: 'stale_write',
1374
+ currentEtag,
1375
+ };
1376
+ }
1377
+ // Check which parts are being updated
1378
+ const updateScope = analyzeUpdateScope(data);
1379
+ const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
1380
+ const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
1381
+ // Validate etags for parts being updated
1382
+ if (updatingMeta && etagParts.meta !== currentParts.meta) {
1383
+ return {
1384
+ success: false,
1385
+ reason: 'stale_write',
1386
+ currentEtag,
1387
+ };
1388
+ }
1389
+ if (updatingContent && etagParts.content !== currentParts.content) {
1390
+ return {
1391
+ success: false,
1392
+ reason: 'stale_write',
1393
+ currentEtag,
1394
+ };
1395
+ }
1396
+ }
1397
+ // Update modified timestamp for any change (metadata or content)
1398
+ let modified;
1399
+ if (shouldUpdateModifiedTimestamp(data)) {
1400
+ // Use provided modified timestamp or current time
1401
+ modified = data.modified || new Date().toISOString();
1402
+ }
1403
+ else if (data.modified) {
1404
+ // If modified timestamp is explicitly provided, always use it
1405
+ modified = data.modified;
1406
+ }
1407
+ else {
1408
+ // No changes and no explicit timestamp, keep current
1409
+ modified = current.modified;
1410
+ }
1411
+ const { sortedMeta: newMeta, valid: metaValid, error: metaError, } = validateAndPrepareMetadata({ ...current.meta, ...(data.meta ? data.meta : {}) });
1412
+ // Validate new metadata
1413
+ if (!newMeta || !metaValid) {
1414
+ return {
1415
+ success: false,
1416
+ reason: 'write_error',
1417
+ error: new Error(metaError),
1418
+ };
1419
+ }
1420
+ // Merge updates
1421
+ const newContent = data.content ? { ...current.content, ...data.content } : current.content;
1422
+ // Validate pathname change if updating pathname for pages
1423
+ if (data.pathname && manifest.kind === 'page' && manifest.site) {
1424
+ const site = this.sites[manifest.site];
1425
+ if (site) {
1426
+ // Check if new pathname is already taken by another content
1427
+ const existingId = site.getPathnameConflict(data.pathname, locale, id);
1428
+ if (existingId) {
1429
+ return {
1430
+ success: false,
1431
+ reason: 'write_error',
1432
+ error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),
1433
+ };
1434
+ }
1435
+ }
1436
+ }
1437
+ // Validate name change if updating name for blocks or data
1438
+ if (data.name && (manifest.kind === 'block' || manifest.kind === 'data')) {
1439
+ // Check if new name is already taken by another entry in the same collection
1440
+ const index = manifest.kind === 'block' ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex();
1441
+ const existing = index.getByName(manifest.collection, data.name);
1442
+ if (existing && existing.id !== id) {
1443
+ // Get title from the existing entry for a better error message
1444
+ const existingLocale = Object.values(existing.locales).find((lv) => lv !== undefined);
1445
+ const existingTitle = existingLocale?.meta?.title;
1446
+ const kindLabel = manifest.kind === 'block' ? 'Block' : 'Data';
1447
+ return {
1448
+ success: false,
1449
+ reason: 'write_error',
1450
+ error: new Error(`${kindLabel} name "${data.name}" is already in use${existingTitle ? ` by "${existingTitle}"` : ''}`),
1451
+ };
1452
+ }
1453
+ }
1454
+ // Handle pathname changes - track history only for published content
1455
+ const pathnameHistory = buildPathnameHistory(localeVersion.pathname, data.pathname, isContentPublished({
1456
+ publishAt: resolvePublishDate(data.publishAt, current.publishAt),
1457
+ unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),
1458
+ }), new Date().toISOString());
1459
+ try {
1460
+ // Determine the target file path (may be different if pathname or name changed)
1461
+ let targetFilePath = filePath;
1462
+ if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {
1463
+ // For pages, calculate new file path based on new pathname
1464
+ const newLocaleVersion = {
1465
+ ...localeVersion,
1466
+ pathname: data.pathname,
1467
+ };
1468
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1469
+ // Ensure target directory exists
1470
+ await mkdir(dirname(targetFilePath), { recursive: true });
1471
+ }
1472
+ else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === 'block') {
1473
+ // For blocks, calculate new file path based on new name
1474
+ const newLocaleVersion = {
1475
+ ...localeVersion,
1476
+ name: data.name,
1477
+ };
1478
+ targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1479
+ // Ensure target directory exists
1480
+ await mkdir(dirname(targetFilePath), { recursive: true });
1481
+ }
1482
+ // Write updated content
1483
+ if (targetFilePath.endsWith('.mdx')) {
1484
+ // Build frontmatter with special fields and metadata
1485
+ const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
1486
+ const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
1487
+ const frontmatterData = {
1488
+ id: manifest.id,
1489
+ created: current.created,
1490
+ modified,
1491
+ ...(publishAt && { publishAt }),
1492
+ ...(unpublishAt && { unpublishAt }),
1493
+ ...newMeta, // Spread metadata fields directly
1494
+ };
1495
+ // Extract just the content part from MDX (remove frontmatter if present)
1496
+ let mdxContentPart = newContent.mdx || '';
1497
+ if (mdxContentPart.startsWith('---')) {
1498
+ // Remove frontmatter if it exists
1499
+ const { content: contentOnly } = matter(mdxContentPart, {});
1500
+ mdxContentPart = contentOnly;
1501
+ }
1502
+ // Defensive guard: warn when a frontmatter-shaped block appears
1503
+ // mid-body. The load path strips frontmatter before it reaches the
1504
+ // editor, so this should never occur — if it does, surface it for
1505
+ // investigation instead of silently writing a file with stacked
1506
+ // frontmatter blocks.
1507
+ if (/\n---\r?\n[\s\S]*?\r?\n---(\r?\n|$)/.test(mdxContentPart)) {
1508
+ console.warn(`[content-api] Embedded frontmatter-shaped block detected in body for ${targetFilePath}. ` +
1509
+ 'This indicates a load-path regression or client-side leak.');
1510
+ }
1511
+ const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
1512
+ // Atomic write for MDX files
1513
+ await atomicWriteFile(targetFilePath, mdxContent);
1514
+ }
1515
+ else if (targetFilePath.endsWith('.json')) {
1516
+ // Data files use "data" field instead of "content"
1517
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1518
+ // Build updated data file structure
1519
+ const updatedFile = {
1520
+ id: fileContent.id,
1521
+ type: 'json',
1522
+ created: fileContent.created,
1523
+ modified,
1524
+ ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),
1525
+ ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),
1526
+ meta: newMeta,
1527
+ data: sortKeys(newContent.data || {}, { deep: true }),
1528
+ };
1529
+ // Handle publish date updates
1530
+ if ('publishAt' in data) {
1531
+ if (data.publishAt) {
1532
+ updatedFile.publishAt = data.publishAt;
1533
+ }
1534
+ else {
1535
+ delete updatedFile.publishAt;
1536
+ }
1537
+ }
1538
+ if ('unpublishAt' in data) {
1539
+ if (data.unpublishAt) {
1540
+ updatedFile.unpublishAt = data.unpublishAt;
1541
+ }
1542
+ else {
1543
+ delete updatedFile.unpublishAt;
1544
+ }
1545
+ }
1546
+ // Serialize data file
1547
+ const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\t');
1548
+ // Atomic write for JSON data files
1549
+ await atomicWriteFile(targetFilePath, serializedContent);
1550
+ }
1551
+ else {
1552
+ // VXJSON for pages (puck)
1553
+ const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));
1554
+ // Build updated VXJSONFile structure
1555
+ const updatedFile = {
1556
+ id: fileContent.id,
1557
+ type: fileContent.type,
1558
+ created: fileContent.created,
1559
+ modified,
1560
+ publishAt: fileContent.publishAt,
1561
+ unpublishAt: fileContent.unpublishAt,
1562
+ previousPathnames: fileContent.previousPathnames,
1563
+ meta: newMeta,
1564
+ content: sortKeys(newContent, { deep: true }),
1565
+ };
1566
+ // Handle pathname changes and track history
1567
+ if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {
1568
+ // Only add to history if content is published
1569
+ if (isContentPublished(current)) {
1570
+ if (!updatedFile.previousPathnames) {
1571
+ updatedFile.previousPathnames = {};
1572
+ }
1573
+ updatedFile.previousPathnames[localeVersion.pathname] = modified;
1574
+ }
1575
+ }
1576
+ // Handle publish date updates
1577
+ if ('publishAt' in data) {
1578
+ if (data.publishAt) {
1579
+ updatedFile.publishAt = data.publishAt;
1580
+ }
1581
+ else {
1582
+ delete updatedFile.publishAt;
1583
+ }
1584
+ }
1585
+ if ('unpublishAt' in data) {
1586
+ if (data.unpublishAt) {
1587
+ updatedFile.unpublishAt = data.unpublishAt;
1588
+ }
1589
+ else {
1590
+ delete updatedFile.unpublishAt;
1591
+ }
1592
+ }
1593
+ // Serialize using VXJSON format to ensure content is last
1594
+ const serializedContent = VXJSON.serialize(updatedFile);
1595
+ // Atomic write for VXJSON page files
1596
+ await atomicWriteFile(targetFilePath, serializedContent);
1597
+ }
1598
+ // Calculate new etag from the written file
1599
+ const writtenBuffer = (await readFile(targetFilePath));
1600
+ let newEtag;
1601
+ if (targetFilePath.endsWith('.mdx')) {
1602
+ // Find content position in MDX
1603
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
1604
+ let contentPos = -1;
1605
+ for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
1606
+ let match = true;
1607
+ for (let j = 0; j < contentStartMarker.length; j++) {
1608
+ if (writtenBuffer[i + j] !== contentStartMarker[j]) {
1609
+ match = false;
1610
+ break;
1611
+ }
1612
+ }
1613
+ if (match) {
1614
+ contentPos = i + contentStartMarker.length;
1615
+ break;
1616
+ }
1617
+ }
1618
+ const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
1619
+ newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
1620
+ }
1621
+ else if (targetFilePath.endsWith('.json')) {
1622
+ // For data files, use simple etag (hash entire buffer)
1623
+ newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
1624
+ }
1625
+ else {
1626
+ // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally
1627
+ const etagResult = VXJSON.calculateETags(writtenBuffer);
1628
+ if (!etagResult.success) {
1629
+ throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
1630
+ }
1631
+ newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1632
+ }
1633
+ // Build updated locale manifest with current publish data
1634
+ const updatedLocaleVersion = {
1635
+ ...localeVersion,
1636
+ etag: newEtag,
1637
+ modified,
1638
+ meta: newMeta,
1639
+ ...(data.pathname && { pathname: data.pathname }),
1640
+ ...(data.name && { name: data.name }),
1641
+ };
1642
+ // Handle publish dates using shared function
1643
+ // First preserve current values if not updating
1644
+ if (current.publishAt && !('publishAt' in data)) {
1645
+ updatedLocaleVersion.publishAt = current.publishAt;
1646
+ }
1647
+ if (current.unpublishAt && !('unpublishAt' in data)) {
1648
+ updatedLocaleVersion.unpublishAt = current.unpublishAt;
1649
+ }
1650
+ // Then apply updates
1651
+ updatePublishDates(updatedLocaleVersion, data);
1652
+ // Update pathname history if changed
1653
+ if (Object.keys(pathnameHistory).length > 0) {
1654
+ updatedLocaleVersion.previousPathnames = {
1655
+ ...localeVersion.previousPathnames,
1656
+ ...pathnameHistory,
1657
+ };
1658
+ }
1659
+ else {
1660
+ // Preserve existing previousPathnames if no change, but only if it has content
1661
+ const existingPreviousPathnames = localeVersion.previousPathnames;
1662
+ if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {
1663
+ updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
1664
+ }
1665
+ else {
1666
+ // Remove empty previousPathnames object
1667
+ delete updatedLocaleVersion.previousPathnames;
1668
+ }
1669
+ }
1670
+ // Store the old locale manifest for rollback if needed
1671
+ const oldLocaleVersion = manifest.locales[locale];
1672
+ try {
1673
+ // Update the locale in the existing manifest directly (avoids allocation)
1674
+ manifest.locales[locale] = updatedLocaleVersion;
1675
+ // Update index with the updated locale
1676
+ this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
1677
+ // If pathname changed, delete the old file
1678
+ if (targetFilePath !== filePath) {
1679
+ try {
1680
+ await unlink(filePath);
1681
+ }
1682
+ catch (error) {
1683
+ // Log but don't fail if old file deletion fails
1684
+ console.warn(`Failed to delete old file ${filePath}:`, error);
1685
+ }
1686
+ }
1687
+ }
1688
+ catch (error) {
1689
+ // Rollback on error to maintain consistency
1690
+ manifest.locales[locale] = oldLocaleVersion;
1691
+ // If we wrote to a new file, try to clean it up
1692
+ if (targetFilePath !== filePath) {
1693
+ try {
1694
+ await unlink(targetFilePath);
1695
+ }
1696
+ catch {
1697
+ // Ignore cleanup errors
1698
+ }
1699
+ }
1700
+ throw error;
1701
+ }
1702
+ return {
1703
+ success: true,
1704
+ etag: newEtag,
1705
+ modified: new Date(),
1706
+ };
1707
+ }
1708
+ catch (error) {
1709
+ return {
1710
+ success: false,
1711
+ reason: 'write_error',
1712
+ error: ensureError(error),
1713
+ };
1714
+ }
1715
+ }
1716
+ async deleteContent(id, etag) {
1717
+ // Get manifest for this ID
1718
+ const manifest = this.contentIndex.getManifest(id);
1719
+ if (!manifest) {
1720
+ return {
1721
+ success: false,
1722
+ reason: 'not_found',
1723
+ error: new Error('Content not found'),
1724
+ };
1725
+ }
1726
+ // For deleteContent, we require the etag to match ANY locale (indicating user has current data)
1727
+ // But this is still a design flaw - we should probably require all etags or a master etag
1728
+ let matchingLocale;
1729
+ for (const localeVersion of localesOf(manifest)) {
1730
+ if (localeVersion.etag === etag) {
1731
+ matchingLocale = localeVersion;
1732
+ break;
1733
+ }
1734
+ }
1735
+ if (!matchingLocale) {
1736
+ return {
1737
+ success: false,
1738
+ reason: 'stale_write',
1739
+ currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',
1740
+ error: new Error('Invalid etag - must match at least one locale'),
1741
+ };
1742
+ }
1743
+ try {
1744
+ // Delete all locale files in parallel
1745
+ const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
1746
+ const filePath = this.getFilePath(manifest, localeVersion);
1747
+ await unlink(filePath);
1748
+ });
1749
+ await Promise.all(deletePromises);
1750
+ // Remove from index
1751
+ this.contentIndex.removeEntry(id);
1752
+ return { success: true };
1753
+ }
1754
+ catch (error) {
1755
+ return {
1756
+ success: false,
1757
+ error: ensureError(error),
1758
+ };
1759
+ }
1760
+ }
1761
+ async deleteLocalized(input) {
1762
+ const { id, locale, etag } = input;
1763
+ // Get manifest for this ID
1764
+ const manifest = this.contentIndex.getManifest(id);
1765
+ if (!manifest) {
1766
+ return {
1767
+ success: false,
1768
+ reason: 'not_found',
1769
+ error: new Error('Content not found'),
1770
+ };
1771
+ }
1772
+ // Check if this locale exists
1773
+ const localeVersion = manifest.locales[locale];
1774
+ if (!localeVersion) {
1775
+ return {
1776
+ success: false,
1777
+ reason: 'not_found',
1778
+ error: new Error('Locale not found'),
1779
+ };
1780
+ }
1781
+ // Verify etag matches this locale
1782
+ if (localeVersion.etag !== etag) {
1783
+ return {
1784
+ success: false,
1785
+ reason: 'stale_write',
1786
+ currentEtag: localeVersion.etag,
1787
+ error: new Error('Invalid etag for locale'),
1788
+ };
1789
+ }
1790
+ // Don't allow deleting the last locale
1791
+ if (Object.keys(manifest.locales).length === 1) {
1792
+ return {
1793
+ success: false,
1794
+ error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),
1795
+ };
1796
+ }
1797
+ try {
1798
+ // Delete the locale file
1799
+ const filePath = this.getFilePath(manifest, localeVersion);
1800
+ await unlink(filePath);
1801
+ // Remove locale from manifest and index
1802
+ manifest.locales[locale] = undefined;
1803
+ this.contentIndex.removeLocale(manifest.id, locale);
1804
+ return { success: true };
1805
+ }
1806
+ catch (error) {
1807
+ return {
1808
+ success: false,
1809
+ error: ensureError(error),
1810
+ };
1811
+ }
1812
+ }
1813
+ getSite(siteName) {
1814
+ if (siteName === 'blocks') {
1815
+ throw new Error('Use `blocks` property instead of getSite("blocks")');
1816
+ }
1817
+ const site = this.sites[siteName];
1818
+ return site || null;
1819
+ }
1820
+ *listAllContent(filters) {
1821
+ yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
1822
+ }
1823
+ *findUntranslatedContent(targetLocale, options) {
1824
+ yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
1825
+ }
1826
+ /**
1827
+ * Reindex files that were added or changed after initial creation
1828
+ *
1829
+ * This method:
1830
+ * 1. Either scans for all content files or processes specific paths
1831
+ * 2. Uses the path index to check if files are already indexed
1832
+ * 3. Indexes new files or force-reindexes specified files
1833
+ * 4. Optionally handles file deletions
1834
+ *
1835
+ * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
1836
+ * @param options - Options for reindexing behavior
1837
+ * @returns Statistics about the reindexing operation
1838
+ */
1839
+ async reindex(paths, options) {
1840
+ const filesToProcess = paths || (await this.scanContentFiles());
1841
+ let filesSkipped = 0;
1842
+ let filesProcessed = 0;
1843
+ let filesDeleted = 0;
1844
+ let errors = 0;
1845
+ const filesToIndex = [];
1846
+ const updated = [];
1847
+ const deleted = [];
1848
+ // Check each file
1849
+ for (const filePath of filesToProcess) {
1850
+ // Check if file exists (for deletion handling)
1851
+ if (options?.handleDeletions && paths) {
1852
+ try {
1853
+ await readFile(filePath);
1854
+ }
1855
+ catch (error) {
1856
+ // File doesn't exist - remove from index
1857
+ const parsed = this.parseFilePath(filePath);
1858
+ if (parsed) {
1859
+ // Find the content ID to remove
1860
+ let manifest = null;
1861
+ if (parsed.kind === 'block' && parsed.name) {
1862
+ manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1863
+ }
1864
+ else if (parsed.kind === 'data' && parsed.name) {
1865
+ manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1866
+ }
1867
+ else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
1868
+ manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1869
+ }
1870
+ if (manifest) {
1871
+ // Track the deletion
1872
+ deleted.push({
1873
+ id: manifest.id,
1874
+ locale: parsed.locale,
1875
+ kind: parsed.kind,
1876
+ });
1877
+ // Remove the specific locale or entire entry if it's the last locale
1878
+ if (Object.keys(manifest.locales).length === 1) {
1879
+ this.contentIndex.removeEntry(manifest.id);
1880
+ }
1881
+ else {
1882
+ // Remove just this locale
1883
+ manifest.locales[parsed.locale] = undefined;
1884
+ this.contentIndex.removeLocale(manifest.id, parsed.locale);
1885
+ }
1886
+ filesDeleted++;
1887
+ }
1888
+ }
1889
+ continue;
1890
+ }
1891
+ }
1892
+ const parsed = this.parseFilePath(filePath);
1893
+ if (!parsed) {
1894
+ console.warn(`Skipping unrecognized file pattern: ${filePath}`);
1895
+ errors++;
1896
+ continue;
1897
+ }
1898
+ // Check if this path is already indexed
1899
+ let isIndexed = false;
1900
+ if (parsed.kind === 'block' && parsed.name) {
1901
+ // Check block index by name
1902
+ const manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1903
+ isIndexed = !!manifest;
1904
+ }
1905
+ else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
1906
+ // Check site index by pathname
1907
+ const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1908
+ isIndexed = !!manifest;
1909
+ }
1910
+ else if (parsed.kind === 'data' && parsed.name) {
1911
+ // Check data index by name
1912
+ const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1913
+ isIndexed = !!manifest;
1914
+ }
1915
+ if (isIndexed) {
1916
+ if (!paths) {
1917
+ // Skip already indexed files when doing a full scan
1918
+ filesSkipped++;
1919
+ }
1920
+ else {
1921
+ // For specific paths, check if the file has changed
1922
+ const fileStats = await readFile(filePath);
1923
+ let currentManifest = null;
1924
+ if (parsed.kind === 'block' && parsed.name) {
1925
+ currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1926
+ }
1927
+ else if (parsed.kind === 'data' && parsed.name) {
1928
+ currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1929
+ }
1930
+ else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {
1931
+ currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1932
+ }
1933
+ if (currentManifest) {
1934
+ // Calculate current file etag
1935
+ const buffer = fileStats;
1936
+ let currentEtag;
1937
+ if (filePath.endsWith('.mdx')) {
1938
+ const contentPos = findMdxContentStartPosition(buffer);
1939
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
1940
+ currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
1941
+ }
1942
+ else if (filePath.endsWith('.vxjson')) {
1943
+ const etagResult = VXJSON.calculateETags(buffer);
1944
+ if (!etagResult.success) {
1945
+ // File needs repair - add to filesToIndex for repair
1946
+ filesToIndex.push(filePath);
1947
+ continue;
1948
+ }
1949
+ currentEtag = etagResult.contentEtag
1950
+ ? `${etagResult.metaEtag}.${etagResult.contentEtag}`
1951
+ : etagResult.metaEtag;
1952
+ }
1953
+ else if (filePath.endsWith('.json')) {
1954
+ // For JSON data files, use content hash as etag
1955
+ currentEtag = xxh64(buffer).toString(16);
1956
+ }
1957
+ else {
1958
+ // Unknown file type, skip
1959
+ filesSkipped++;
1960
+ continue;
1961
+ }
1962
+ // Only reindex if etag changed
1963
+ const existingEtag = currentManifest.locales[parsed.locale]?.etag;
1964
+ if (existingEtag === currentEtag) {
1965
+ const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');
1966
+ console.log(`[Content] skip ${relativePath} (unchanged)`);
1967
+ filesSkipped++;
1968
+ }
1969
+ else {
1970
+ filesToIndex.push(filePath);
1971
+ }
1972
+ }
1973
+ else {
1974
+ // Not indexed yet
1975
+ filesToIndex.push(filePath);
1976
+ }
1977
+ }
1978
+ }
1979
+ else {
1980
+ // Not indexed yet
1981
+ filesToIndex.push(filePath);
1982
+ }
1983
+ }
1984
+ // Index the files
1985
+ const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
1986
+ for (let i = 0; i < filesToIndex.length; i++) {
1987
+ const filePath = filesToIndex[i];
1988
+ const bufferIndex = i % buffers.length;
1989
+ try {
1990
+ const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
1991
+ if (result) {
1992
+ const { manifest, localeVersion, content } = result;
1993
+ // Add to index
1994
+ this.contentIndex.addContent(manifest, localeVersion, content);
1995
+ filesProcessed++;
1996
+ // Create LocalizedManifest for the updated list
1997
+ const localizedManifest = {
1998
+ id: manifest.id,
1999
+ type: manifest.type,
2000
+ kind: manifest.kind,
2001
+ site: manifest.site,
2002
+ collection: manifest.collection,
2003
+ localized: localeVersion,
2004
+ };
2005
+ updated.push(localizedManifest);
2006
+ }
2007
+ }
2008
+ catch (error) {
2009
+ console.error(`Failed to reindex ${filePath}:`, error);
2010
+ errors++;
2011
+ }
2012
+ }
2013
+ const result = {
2014
+ filesProcessed,
2015
+ filesSkipped,
2016
+ updated,
2017
+ };
2018
+ if (options?.handleDeletions && deleted.length > 0) {
2019
+ result.filesDeleted = filesDeleted;
2020
+ result.deleted = deleted;
2021
+ }
2022
+ if (errors > 0) {
2023
+ result.errors = errors;
2024
+ }
2025
+ return result;
2026
+ }
2027
+ /**
2028
+ * Read content directly from cache
2029
+ * For testing purposes - returns null if not cached
2030
+ */
2031
+ async readFromCache(id, locale) {
2032
+ return this.contentIndex.getCachedContent(id, locale);
2033
+ }
2034
+ async getContentAsBuffer(id, locale) {
2035
+ const manifest = this.contentIndex.getManifest(id);
2036
+ if (!manifest || !manifest.locales[locale]) {
2037
+ return null;
2038
+ }
2039
+ const localeVersion = manifest.locales[locale];
2040
+ const filePath = this.getFilePath(manifest, localeVersion);
2041
+ const buffer = (await readFile(filePath));
2042
+ const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';
2043
+ // Calculate ETag based on file type
2044
+ let etag;
2045
+ if (contentType === 'text/mdx') {
2046
+ // Find content start position for MDX
2047
+ const contentStartMarker = new TextEncoder().encode('---\n\n');
2048
+ let contentPos = -1;
2049
+ for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
2050
+ let match = true;
2051
+ for (let j = 0; j < contentStartMarker.length; j++) {
2052
+ if (buffer[i + j] !== contentStartMarker[j]) {
2053
+ match = false;
2054
+ break;
2055
+ }
2056
+ }
2057
+ if (match) {
2058
+ contentPos = i + contentStartMarker.length;
2059
+ break;
2060
+ }
2061
+ }
2062
+ const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
2063
+ etag = `${etags.metaEtag}.${etags.contentEtag}`;
2064
+ }
2065
+ else {
2066
+ // Calculate ETags for JSON
2067
+ const etagResult = VXJSON.calculateETags(buffer);
2068
+ if (!etagResult.success) {
2069
+ throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
2070
+ }
2071
+ etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
2072
+ }
2073
+ return { buffer, etag, contentType };
2074
+ }
2075
+ async batchUpdate(operations) {
2076
+ // First, validate all operations can succeed
2077
+ const validationResults = [];
2078
+ for (const op of operations) {
2079
+ const manifest = this.contentIndex.getManifest(op.id);
2080
+ if (!manifest) {
2081
+ // Content not found
2082
+ return {
2083
+ operations: operations.map((o) => ({
2084
+ id: o.id,
2085
+ locale: o.locale,
2086
+ updated: false,
2087
+ error: new Error('Content not found'),
2088
+ })),
2089
+ success: false,
2090
+ updated: 0,
2091
+ failed: operations.length,
2092
+ };
2093
+ }
2094
+ const localeVersion = manifest.locales[op.locale];
2095
+ if (!localeVersion) {
2096
+ // Locale not found
2097
+ return {
2098
+ operations: operations.map((o) => ({
2099
+ id: o.id,
2100
+ locale: o.locale,
2101
+ updated: false,
2102
+ error: new Error('Locale not found'),
2103
+ })),
2104
+ success: false,
2105
+ updated: 0,
2106
+ failed: operations.length,
2107
+ };
2108
+ }
2109
+ // Check etag
2110
+ if (localeVersion.etag !== op.etag) {
2111
+ // Stale write detected
2112
+ return {
2113
+ operations: operations.map((o) => ({
2114
+ id: o.id,
2115
+ locale: o.locale,
2116
+ updated: false,
2117
+ error: new Error('Stale write'),
2118
+ })),
2119
+ success: false,
2120
+ updated: 0,
2121
+ failed: operations.length,
2122
+ };
2123
+ }
2124
+ // Read current content for validation
2125
+ const filePath = this.getFilePath(manifest, localeVersion);
2126
+ const current = await this.readLocaleFile(filePath, op.locale);
2127
+ if (!current) {
2128
+ return {
2129
+ operations: operations.map((o) => ({
2130
+ id: o.id,
2131
+ locale: o.locale,
2132
+ updated: false,
2133
+ error: new Error('Failed to read content'),
2134
+ })),
2135
+ success: false,
2136
+ updated: 0,
2137
+ failed: operations.length,
2138
+ };
2139
+ }
2140
+ // Validate metadata size if updating
2141
+ if (op.data.meta) {
2142
+ const newMeta = { ...current.meta, ...op.data.meta };
2143
+ const validation = validateAndPrepareMetadata(newMeta);
2144
+ if (!validation.valid) {
2145
+ return {
2146
+ operations: operations.map((o) => ({
2147
+ id: o.id,
2148
+ locale: o.locale,
2149
+ updated: false,
2150
+ error: new Error(validation.error),
2151
+ })),
2152
+ success: false,
2153
+ updated: 0,
2154
+ failed: operations.length,
2155
+ };
2156
+ }
2157
+ }
2158
+ validationResults.push({ op, manifest, localeVersion, current });
2159
+ }
2160
+ // All validations passed, now perform updates
2161
+ const results = [];
2162
+ let updated = 0;
2163
+ for (const { op } of validationResults) {
2164
+ const result = await this.updateLocalized(op);
2165
+ if (result.success) {
2166
+ updated++;
2167
+ results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });
2168
+ }
2169
+ else {
2170
+ // This shouldn't happen if validation was correct
2171
+ results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });
2172
+ }
2173
+ }
2174
+ return {
2175
+ operations: results,
2176
+ success: updated === operations.length,
2177
+ updated,
2178
+ failed: operations.length - updated,
2179
+ };
2180
+ }
2181
+ }