@conloca/content-api 0.1.16 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +18 -13
  10. package/dist/asset-operations.d.ts.map +1 -1
  11. package/dist/asset-operations.js +302 -254
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +23 -7
  14. package/dist/asset-types.d.ts.map +1 -1
  15. package/dist/asset-types.js +8 -2
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +8 -2
  22. package/dist/base-content-index.d.ts.map +1 -1
  23. package/dist/base-content-index.js +24 -3
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.js +1 -0
  26. package/dist/cf-access.js.map +1 -0
  27. package/dist/component-registry.d.ts +1 -1
  28. package/dist/component-registry.d.ts.map +1 -1
  29. package/dist/component-registry.js +2 -1
  30. package/dist/component-registry.js.map +1 -0
  31. package/dist/component-registry.types.js +1 -0
  32. package/dist/component-registry.types.js.map +1 -0
  33. package/dist/component-vocabulary.d.ts +33 -0
  34. package/dist/component-vocabulary.d.ts.map +1 -0
  35. package/dist/component-vocabulary.js +105 -0
  36. package/dist/component-vocabulary.js.map +1 -0
  37. package/dist/content-api.interface.d.ts +5 -5
  38. package/dist/content-api.interface.d.ts.map +1 -1
  39. package/dist/content-api.interface.js +1 -0
  40. package/dist/content-api.interface.js.map +1 -0
  41. package/dist/content-filters.d.ts +2 -2
  42. package/dist/content-filters.d.ts.map +1 -1
  43. package/dist/content-filters.js +9 -8
  44. package/dist/content-filters.js.map +1 -0
  45. package/dist/content-index.d.ts +74 -16
  46. package/dist/content-index.d.ts.map +1 -1
  47. package/dist/content-index.js +183 -55
  48. package/dist/content-index.js.map +1 -0
  49. package/dist/content-operations.d.ts +71 -7
  50. package/dist/content-operations.d.ts.map +1 -1
  51. package/dist/content-operations.js +166 -82
  52. package/dist/content-operations.js.map +1 -0
  53. package/dist/content-path.d.ts +59 -0
  54. package/dist/content-path.d.ts.map +1 -0
  55. package/dist/content-path.js +88 -0
  56. package/dist/content-path.js.map +1 -0
  57. package/dist/content-reader.d.ts +2 -2
  58. package/dist/content-reader.d.ts.map +1 -1
  59. package/dist/content-reader.js +2 -1
  60. package/dist/content-reader.js.map +1 -0
  61. package/dist/content-utils.d.ts +53 -10
  62. package/dist/content-utils.d.ts.map +1 -1
  63. package/dist/content-utils.js +103 -34
  64. package/dist/content-utils.js.map +1 -0
  65. package/dist/content-watcher.d.ts +3 -3
  66. package/dist/content-watcher.d.ts.map +1 -1
  67. package/dist/content-watcher.js +13 -10
  68. package/dist/content-watcher.js.map +1 -0
  69. package/dist/data-index.d.ts +1 -1
  70. package/dist/data-index.d.ts.map +1 -1
  71. package/dist/data-index.js +2 -1
  72. package/dist/data-index.js.map +1 -0
  73. package/dist/data.d.ts +5 -13
  74. package/dist/data.d.ts.map +1 -1
  75. package/dist/data.js +7 -6
  76. package/dist/data.js.map +1 -0
  77. package/dist/editor-data-bindings.d.ts +10 -0
  78. package/dist/editor-data-bindings.d.ts.map +1 -0
  79. package/dist/editor-data-bindings.js +67 -0
  80. package/dist/editor-data-bindings.js.map +1 -0
  81. package/dist/etag-utils.d.ts.map +1 -1
  82. package/dist/etag-utils.js +5 -4
  83. package/dist/etag-utils.js.map +1 -0
  84. package/dist/filesystem-content-api.d.ts +45 -18
  85. package/dist/filesystem-content-api.d.ts.map +1 -1
  86. package/dist/filesystem-content-api.js +407 -281
  87. package/dist/filesystem-content-api.js.map +1 -0
  88. package/dist/filesystem-reader-backend.d.ts +46 -0
  89. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  90. package/dist/filesystem-reader-backend.js +119 -0
  91. package/dist/filesystem-reader-backend.js.map +1 -0
  92. package/dist/fragment-index.d.ts +8 -0
  93. package/dist/fragment-index.d.ts.map +1 -0
  94. package/dist/fragment-index.js +8 -0
  95. package/dist/fragment-index.js.map +1 -0
  96. package/dist/fragments.d.ts +16 -0
  97. package/dist/fragments.d.ts.map +1 -0
  98. package/dist/fragments.js +104 -0
  99. package/dist/fragments.js.map +1 -0
  100. package/dist/git-operations.d.ts.map +1 -1
  101. package/dist/git-operations.js +5 -1
  102. package/dist/git-operations.js.map +1 -0
  103. package/dist/header-parser.d.ts +4 -4
  104. package/dist/header-parser.d.ts.map +1 -1
  105. package/dist/header-parser.js +8 -61
  106. package/dist/header-parser.js.map +1 -0
  107. package/dist/in-memory-content-api.d.ts +7 -7
  108. package/dist/in-memory-content-api.d.ts.map +1 -1
  109. package/dist/in-memory-content-api.js +74 -56
  110. package/dist/in-memory-content-api.js.map +1 -0
  111. package/dist/index.d.ts +19 -12
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.js +21 -9
  114. package/dist/index.js.map +1 -0
  115. package/dist/indexing.d.ts +4 -4
  116. package/dist/indexing.d.ts.map +1 -1
  117. package/dist/indexing.js +6 -5
  118. package/dist/indexing.js.map +1 -0
  119. package/dist/json-whitespace-view.js +1 -0
  120. package/dist/json-whitespace-view.js.map +1 -0
  121. package/dist/middleware.d.ts +6 -6
  122. package/dist/middleware.d.ts.map +1 -1
  123. package/dist/middleware.js +170 -119
  124. package/dist/middleware.js.map +1 -0
  125. package/dist/node.d.ts +24 -17
  126. package/dist/node.d.ts.map +1 -1
  127. package/dist/node.js +17 -14
  128. package/dist/node.js.map +1 -0
  129. package/dist/page-references.d.ts +21 -0
  130. package/dist/page-references.d.ts.map +1 -0
  131. package/dist/page-references.js +50 -0
  132. package/dist/page-references.js.map +1 -0
  133. package/dist/read-date.d.ts +3 -0
  134. package/dist/read-date.d.ts.map +1 -0
  135. package/dist/read-date.js +9 -0
  136. package/dist/read-date.js.map +1 -0
  137. package/dist/reader-backend.d.ts +54 -0
  138. package/dist/reader-backend.d.ts.map +1 -0
  139. package/dist/reader-backend.js +2 -0
  140. package/dist/reader-backend.js.map +1 -0
  141. package/dist/reader.d.ts +8 -8
  142. package/dist/reader.d.ts.map +1 -1
  143. package/dist/reader.js +8 -7
  144. package/dist/reader.js.map +1 -0
  145. package/dist/schemas/index.d.ts +6 -6
  146. package/dist/schemas/index.d.ts.map +1 -1
  147. package/dist/schemas/index.js +9 -8
  148. package/dist/schemas/index.js.map +1 -0
  149. package/dist/site-index.d.ts +3 -3
  150. package/dist/site-index.d.ts.map +1 -1
  151. package/dist/site-index.js +9 -5
  152. package/dist/site-index.js.map +1 -0
  153. package/dist/site.d.ts +5 -3
  154. package/dist/site.d.ts.map +1 -1
  155. package/dist/site.js +14 -2
  156. package/dist/site.js.map +1 -0
  157. package/dist/types.d.ts +203 -15
  158. package/dist/types.d.ts.map +1 -1
  159. package/dist/types.js +9 -0
  160. package/dist/types.js.map +1 -0
  161. package/dist/url-safe-base64.js +1 -0
  162. package/dist/url-safe-base64.js.map +1 -0
  163. package/dist/url-validation.d.ts +14 -0
  164. package/dist/url-validation.d.ts.map +1 -1
  165. package/dist/url-validation.js +56 -14
  166. package/dist/url-validation.js.map +1 -0
  167. package/dist/utils/atomic-write.js +1 -0
  168. package/dist/utils/atomic-write.js.map +1 -0
  169. package/dist/utils.d.ts +1 -1
  170. package/dist/utils.js +2 -1
  171. package/dist/utils.js.map +1 -0
  172. package/dist/vite-plugin.d.ts +2 -2
  173. package/dist/vite-plugin.js +5 -4
  174. package/dist/vite-plugin.js.map +1 -0
  175. package/dist/vxjson-serialize.d.ts +5 -6
  176. package/dist/vxjson-serialize.d.ts.map +1 -1
  177. package/dist/vxjson-serialize.js +13 -10
  178. package/dist/vxjson-serialize.js.map +1 -0
  179. package/dist/vxjson.d.ts +4 -3
  180. package/dist/vxjson.d.ts.map +1 -1
  181. package/dist/vxjson.js +10 -20
  182. package/dist/vxjson.js.map +1 -0
  183. package/dist/xxhash.d.ts.map +1 -1
  184. package/dist/xxhash.js +6 -2
  185. package/dist/xxhash.js.map +1 -0
  186. package/package.json +92 -56
  187. package/src/asset-constraints.ts +33 -0
  188. package/src/asset-metadata-store.ts +401 -0
  189. package/src/asset-operations.ts +914 -0
  190. package/src/asset-types.ts +74 -0
  191. package/src/asset-usage.ts +47 -0
  192. package/src/base-content-index.ts +227 -0
  193. package/src/cf-access.ts +85 -0
  194. package/src/component-registry.ts +145 -0
  195. package/src/component-registry.types.ts +12 -0
  196. package/src/component-vocabulary.ts +87 -0
  197. package/src/content-api.interface.ts +94 -0
  198. package/src/content-filters.ts +278 -0
  199. package/src/content-index.ts +642 -0
  200. package/src/content-operations.ts +497 -0
  201. package/src/content-path.ts +113 -0
  202. package/src/content-reader.ts +18 -0
  203. package/src/content-utils.ts +474 -0
  204. package/src/content-watcher.ts +122 -0
  205. package/src/data-index.ts +7 -0
  206. package/src/data.ts +134 -0
  207. package/src/editor-data-bindings.ts +66 -0
  208. package/src/etag-utils.ts +204 -0
  209. package/src/filesystem-content-api.ts +2685 -0
  210. package/src/filesystem-reader-backend.ts +135 -0
  211. package/src/fragment-index.ts +7 -0
  212. package/src/fragments.ts +113 -0
  213. package/src/git-operations.ts +340 -0
  214. package/src/header-parser.ts +272 -0
  215. package/src/in-memory-content-api.ts +760 -0
  216. package/src/index.ts +45 -0
  217. package/src/indexing.ts +8 -0
  218. package/src/json-whitespace-view.ts +155 -0
  219. package/src/middleware.ts +1341 -0
  220. package/src/node.ts +40 -0
  221. package/src/page-references.ts +76 -0
  222. package/src/read-date.ts +7 -0
  223. package/src/reader-backend.ts +54 -0
  224. package/src/reader.ts +15 -0
  225. package/src/schemas/index.ts +113 -0
  226. package/src/site-index.ts +330 -0
  227. package/src/site.ts +198 -0
  228. package/src/types.ts +759 -0
  229. package/src/url-safe-base64.ts +38 -0
  230. package/src/url-validation.ts +121 -0
  231. package/src/utils/atomic-write.ts +20 -0
  232. package/src/utils.ts +84 -0
  233. package/src/vite-plugin.ts +45 -0
  234. package/src/vxjson-serialize.ts +66 -0
  235. package/src/vxjson.ts +442 -0
  236. package/src/xxhash.ts +43 -0
  237. package/dist/asset-manifest.d.ts +0 -23
  238. package/dist/asset-manifest.d.ts.map +0 -1
  239. package/dist/asset-manifest.js +0 -73
  240. package/dist/block-index.d.ts +0 -9
  241. package/dist/block-index.d.ts.map +0 -1
  242. package/dist/block-index.js +0 -11
  243. package/dist/blocks.d.ts +0 -16
  244. package/dist/blocks.d.ts.map +0 -1
  245. package/dist/blocks.js +0 -103
  246. package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
  247. package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
  248. package/dist/content-index-D092_vk1.mjs +0 -629
  249. package/dist/content-index-D092_vk1.mjs.map +0 -1
  250. package/dist/content-index-D6IVMmAB.d.mts +0 -127
  251. package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
  252. package/dist/content-operations-DIbsxG5A.d.mts +0 -354
  253. package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
  254. package/dist/content-utils-fWNHTrPy.mjs +0 -280
  255. package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
  256. package/dist/data-DquNIEnQ.mjs +0 -62
  257. package/dist/data-DquNIEnQ.mjs.map +0 -1
  258. package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
  259. package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
  260. package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
  261. package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
  262. package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
  263. package/dist/index-DxVTFK66.d.mts +0 -105
  264. package/dist/index-DxVTFK66.d.mts.map +0 -1
  265. package/dist/index.d.mts +0 -80
  266. package/dist/index.d.mts.map +0 -1
  267. package/dist/index.mjs +0 -78
  268. package/dist/index.mjs.map +0 -1
  269. package/dist/indexing.d.mts +0 -152
  270. package/dist/indexing.d.mts.map +0 -1
  271. package/dist/indexing.mjs +0 -255
  272. package/dist/indexing.mjs.map +0 -1
  273. package/dist/node.d.mts +0 -373
  274. package/dist/node.d.mts.map +0 -1
  275. package/dist/node.mjs +0 -2572
  276. package/dist/node.mjs.map +0 -1
  277. package/dist/reader.d.mts +0 -15
  278. package/dist/reader.d.mts.map +0 -1
  279. package/dist/reader.mjs +0 -22
  280. package/dist/reader.mjs.map +0 -1
  281. package/dist/schemas/index.d.mts +0 -2
  282. package/dist/schemas/index.mjs +0 -2
  283. package/dist/schemas-CFRD0FIQ.mjs +0 -84
  284. package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
  285. package/dist/site-8oaj1Q60.mjs +0 -366
  286. package/dist/site-8oaj1Q60.mjs.map +0 -1
  287. package/dist/site-index-B_254bCc.d.mts +0 -136
  288. package/dist/site-index-B_254bCc.d.mts.map +0 -1
  289. package/dist/types-DOdldbfD.mjs +0 -34
  290. package/dist/types-DOdldbfD.mjs.map +0 -1
  291. package/dist/types-DjfhS272.d.mts +0 -456
  292. package/dist/types-DjfhS272.d.mts.map +0 -1
  293. package/dist/vxjson-qHrgLGip.mjs +0 -555
  294. package/dist/vxjson-qHrgLGip.mjs.map +0 -1
  295. package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
  296. package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
  297. package/dist/vxjson-serialize.d.mts +0 -17
  298. package/dist/vxjson-serialize.d.mts.map +0 -1
  299. package/dist/vxjson-serialize.mjs +0 -2
@@ -1,1620 +0,0 @@
1
- import { a as buildPathnameHistory, c as validateAndPrepareMetadata, i as buildLocaleVersion, l as validateCreateContent, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, r as analyzeUpdateScope, s as updatePublishDates, t as Site, u as Blocks } from "./site-8oaj1Q60.mjs";
2
- import { _ as serializeMdxWithFrontmatter, f as mapSiteNames, g as resolvePublishDate, o as isContentPublished, r as generateContentId, u as localesOf } from "./content-utils-fWNHTrPy.mjs";
3
- import { t as ContentIndex } from "./content-index-D092_vk1.mjs";
4
- import { a as xxh64, i as parseDualEtag, n as calculateEtagsFromMdxBuffer, r as findMdxContentStartPosition, t as VXJSON } from "./vxjson-qHrgLGip.mjs";
5
- import { t as Data } from "./data-DquNIEnQ.mjs";
6
- import sortKeys from "sort-keys";
7
- import matter from "gray-matter";
8
- import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
9
- import { dirname, join, resolve } from "path";
10
- //#region src/utils/atomic-write.ts
11
- /**
12
- * Write file atomically via temp file + rename to prevent corruption on crash.
13
- * Callers are responsible for ensuring the parent directory exists.
14
- */
15
- async function atomicWriteFile(filePath, content) {
16
- const hrtime = process.hrtime.bigint();
17
- const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;
18
- try {
19
- await writeFile(tempFile, content);
20
- await rename(tempFile, filePath);
21
- } catch (error) {
22
- try {
23
- await unlink(tempFile);
24
- } catch {}
25
- throw error;
26
- }
27
- }
28
- //#endregion
29
- //#region src/content-filters.ts
30
- /**
31
- * Apply filters to a single content manifest
32
- * Pure function that checks if a manifest matches all provided filters
33
- */
34
- function applyContentFilters(manifest, filters) {
35
- if (filters.site && manifest.site !== filters.site) return false;
36
- if (filters.collection && manifest.collection !== filters.collection) return false;
37
- if (filters.type && manifest.type !== filters.type) return false;
38
- if (filters.kind && manifest.kind !== filters.kind) return false;
39
- if (filters.locales && filters.locales.length > 0) {
40
- if (!filters.locales.some((locale) => manifest.locales[locale])) return false;
41
- }
42
- if (filters.missingLocales && filters.missingLocales.length > 0) {
43
- if (filters.missingLocales.some((locale) => manifest.locales[locale])) return false;
44
- }
45
- if (filters.published !== void 0) {
46
- let hasPublishedLocale = false;
47
- for (const localeVersion of localesOf(manifest)) {
48
- if (!localeVersion.unpublishAt) {
49
- hasPublishedLocale = true;
50
- break;
51
- }
52
- if (new Date(localeVersion.unpublishAt) > /* @__PURE__ */ new Date()) {
53
- hasPublishedLocale = true;
54
- break;
55
- }
56
- }
57
- if (filters.published !== hasPublishedLocale) return false;
58
- }
59
- return true;
60
- }
61
- /**
62
- * Generator that yields manifests after applying all filters
63
- * This is the main entry point for filtering content using indexes efficiently
64
- */
65
- function* filterContentWithIndexes(contentIndex, filters, sitesConfig) {
66
- if (!filters) {
67
- yield* contentIndex.listAllContent();
68
- return;
69
- }
70
- if (filters.kind === "page" && filters.site && filters.collection) {
71
- if (!contentIndex.getCollectionsForSite(filters.site).has(filters.collection)) return;
72
- } else if (filters.kind === "block" && filters.collection) {
73
- if (!contentIndex.getBlockCollections().has(filters.collection)) return;
74
- }
75
- let generator;
76
- if (filters.kind === "page" && filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
77
- else if (filters.kind === "block" && filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
78
- else if (filters.kind) generator = contentIndex.getManifestsForKind(filters.kind);
79
- else if (filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
80
- else if (filters.site && filters.locales?.length === 1) generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);
81
- else if (filters.site) generator = contentIndex.getManifestsForSite(filters.site);
82
- else if (filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
83
- else if (filters.locales?.length === 1) generator = contentIndex.getManifestsForLocale(filters.locales[0]);
84
- else generator = contentIndex.listAllContent();
85
- for (const manifest of generator) {
86
- if (!applyContentFilters(manifest, filters)) continue;
87
- if (filters.localization) {
88
- if (filters.localization === "complete" && filters.missingLocales?.length) continue;
89
- const siteLocales = filters.site && manifest.kind === "page" ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales : sitesConfig.globalLocales;
90
- const localeCount = Object.keys(manifest.locales).length;
91
- const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;
92
- const totalLocales = siteLocales.length;
93
- if (filters.localization === "complete" && hasLocales !== totalLocales) continue;
94
- if (filters.localization === "partial" && (localeCount <= 1 || hasLocales === totalLocales)) continue;
95
- if (filters.localization === "one" && localeCount !== 1) continue;
96
- }
97
- yield manifest;
98
- }
99
- }
100
- //#endregion
101
- //#region src/filesystem-content-api.ts
102
- function ensureError(error) {
103
- if (error instanceof Error) return error;
104
- return new Error(String(error));
105
- }
106
- const textDecoder = new TextDecoder();
107
- function parse4KBMDX(buffer, bytesRead) {
108
- const { data: frontmatter } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)), {});
109
- const delimiter = new TextEncoder().encode("---");
110
- let delimiterCount = 0;
111
- let contentStartPos = -1;
112
- for (let i = 0; i <= bytesRead - delimiter.length; i++) {
113
- let match = true;
114
- for (let j = 0; j < delimiter.length; j++) if (buffer[i + j] !== delimiter[j]) {
115
- match = false;
116
- break;
117
- }
118
- if (match) {
119
- delimiterCount++;
120
- if (delimiterCount === 2) {
121
- contentStartPos = i + delimiter.length;
122
- while (contentStartPos < bytesRead && (buffer[contentStartPos] === 10 || buffer[contentStartPos] === 13)) contentStartPos++;
123
- break;
124
- }
125
- }
126
- }
127
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
128
- return {
129
- id,
130
- created,
131
- modified,
132
- publishAt,
133
- unpublishAt,
134
- meta: metaFields,
135
- contentStartPos
136
- };
137
- }
138
- /**
139
- * FileSystem-based Content API Implementation
140
- *
141
- * Stores content as files on disk in a git-friendly format:
142
- * - Pages: /{site}/pages/{filename}.{locale}.vxjson
143
- * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
144
- *
145
- * ## Indexing
146
- *
147
- * Content is indexed at startup for performance. The index is cached per
148
- * content root path and cleared when the process restarts.
149
- *
150
- * ## Read-Repair
151
- *
152
- * Since files can be modified externally (git, editors), this implementation:
153
- *
154
- * 1. Repairs invalid VXJSON files (ensures "content" field is last)
155
- * 2. Adds missing required fields (id, created, modified)
156
- * 3. Handles files added after initial indexing
157
- * 4. Updates the index when files are repaired or discovered
158
- *
159
- * ## Performance
160
- *
161
- * - Initial indexing reads only first 4KB of each file
162
- * - Full content is loaded on demand
163
- * - ETags are calculated using streaming for efficiency
164
- */
165
- /**
166
- * Read and validate `<contentRoot>/sites.json`. Returns a safe default
167
- * (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
168
- * has invalid structure, with a warning logged in each case.
169
- *
170
- * Exported standalone so the Astro integration (and any other tooling
171
- * that needs to inspect per-site config at startup time) can read the
172
- * config without spinning up a full content-api instance.
173
- */
174
- async function readSitesConfig(contentRoot) {
175
- const sitesPath = join(resolve(contentRoot), "sites.json");
176
- try {
177
- const content = await readFile(sitesPath, "utf-8");
178
- const parsed = JSON.parse(content);
179
- if (!parsed.sites || typeof parsed.sites !== "object") {
180
- console.warn(`Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`);
181
- return {
182
- sites: {},
183
- globalLocales: ["en"]
184
- };
185
- }
186
- if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
187
- console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
188
- return {
189
- sites: parsed.sites,
190
- globalLocales: ["en"]
191
- };
192
- }
193
- return parsed;
194
- } catch {
195
- console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
196
- return {
197
- sites: {},
198
- globalLocales: ["en"]
199
- };
200
- }
201
- }
202
- var FileSystemContentAPI = class FileSystemContentAPI {
203
- contentRoot;
204
- absoluteContentRoot;
205
- contentIndex;
206
- sitesConfig;
207
- blocks;
208
- data;
209
- sites;
210
- absoluteMdxPagesRoot;
211
- mdxPagesDefaultLocale = "en";
212
- mdxPagesSite = "default";
213
- mdxPagesCollection = "pages";
214
- availableLocales;
215
- get normalizedContentRoot() {
216
- return this.contentRoot;
217
- }
218
- constructor(contentRoot, canvasDir, sitesConfig, contentIndex, mdxPagesOptions, localeOptions) {
219
- if (contentRoot.startsWith("./")) this.contentRoot = contentRoot.slice(2);
220
- else if (contentRoot.startsWith("/")) this.contentRoot = contentRoot;
221
- else this.contentRoot = contentRoot;
222
- this.absoluteContentRoot = resolve(this.contentRoot);
223
- this.sitesConfig = sitesConfig;
224
- this.contentIndex = contentIndex;
225
- const siteNames = Object.keys(sitesConfig.sites);
226
- const firstSiteName = siteNames[0];
227
- const firstSiteWithMdxPages = siteNames.find((name) => sitesConfig.sites[name]?.mdxPages);
228
- this.mdxPagesSite = mdxPagesOptions?.site ?? firstSiteWithMdxPages ?? firstSiteName ?? "default";
229
- const sitesJsonMdxPages = sitesConfig.sites[this.mdxPagesSite]?.mdxPages;
230
- const resolvedMdxPages = mdxPagesOptions?.root ?? sitesJsonMdxPages;
231
- if (resolvedMdxPages) {
232
- const normalizedMdxPages = resolvedMdxPages.startsWith("./") ? resolvedMdxPages.slice(2) : resolvedMdxPages;
233
- this.absoluteMdxPagesRoot = resolve(normalizedMdxPages);
234
- }
235
- const siteConfig = sitesConfig.sites[this.mdxPagesSite];
236
- this.mdxPagesDefaultLocale = localeOptions?.defaultLocale ?? mdxPagesOptions?.defaultLocale ?? siteConfig?.defaultLocale ?? sitesConfig.globalLocales[0] ?? "en";
237
- const merged = /* @__PURE__ */ new Set();
238
- if (localeOptions?.availableLocales && localeOptions.availableLocales.length > 0) for (const loc of localeOptions.availableLocales) merged.add(loc);
239
- else {
240
- for (const loc of sitesConfig.globalLocales) merged.add(loc);
241
- if (siteConfig?.locales) for (const loc of siteConfig.locales) merged.add(loc);
242
- }
243
- merged.add(this.mdxPagesDefaultLocale);
244
- this.availableLocales = merged;
245
- this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
246
- this.data = new Data(this, this.contentIndex.getDataIndex());
247
- this.sites = mapSiteNames(sitesConfig, (siteName) => {
248
- const siteIndex = this.contentIndex.getSiteIndex(siteName);
249
- if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
250
- return new Site(siteName, this, siteIndex);
251
- });
252
- }
253
- static async create(options) {
254
- const { canvasDir } = options;
255
- const contentRoot = options.contentRoot;
256
- let sitesConfig = await readSitesConfig(contentRoot);
257
- if (options.availableLocales && options.availableLocales.length > 0) {
258
- const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
259
- const optionSite = options.mdxPagesSite ?? Object.keys(sitesConfig.sites)[0] ?? "default";
260
- const existingSite = sitesConfig.sites[optionSite];
261
- sitesConfig = {
262
- sites: {
263
- ...sitesConfig.sites,
264
- [optionSite]: {
265
- locales: options.availableLocales,
266
- defaultLocale: optionDefaultLocale,
267
- ...existingSite?.domains && { domains: existingSite.domains },
268
- ...existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }
269
- }
270
- },
271
- globalLocales: Array.from(/* @__PURE__ */ new Set([...sitesConfig.globalLocales, ...options.availableLocales]))
272
- };
273
- }
274
- const normalizedContentRoot = contentRoot.startsWith("./") ? contentRoot.slice(2) : contentRoot;
275
- const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
276
- const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex, {
277
- root: options.mdxPagesRoot,
278
- defaultLocale: options.mdxPagesDefaultLocale,
279
- site: options.mdxPagesSite
280
- }, {
281
- availableLocales: options.availableLocales,
282
- defaultLocale: options.defaultLocale
283
- });
284
- if (contentIndex.entryCount === 0) await api.indexAllContent();
285
- return api;
286
- }
287
- /**
288
- * Clear all caches - useful for testing
289
- */
290
- static clearCaches() {
291
- ContentIndex.clearCache();
292
- }
293
- async indexAllContent() {
294
- this.contentIndex.clear();
295
- const files = await this.scanContentFiles();
296
- const OPTIMAL_BATCH_SIZE = 1e3;
297
- console.debug(`Indexing ${files.length} content files...`);
298
- const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);
299
- const buffers = Array.from({ length: bufferCount }, () => /* @__PURE__ */ new Uint8Array(4096));
300
- for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
301
- const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
302
- await Promise.all(batch.map(async (filePath, index) => {
303
- try {
304
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);
305
- if (result) {
306
- const { manifest, localeVersion, content } = result;
307
- this.contentIndex.addContent(manifest, localeVersion, content);
308
- }
309
- } catch (error) {
310
- console.error(`Failed to index ${filePath}:`, error);
311
- }
312
- }));
313
- }
314
- }
315
- async parseFileHeaderWithRepair(originalFilePath, buffer) {
316
- let handle;
317
- let bytesRead = 0;
318
- let filePath = originalFilePath;
319
- try {
320
- handle = await open(filePath, "r");
321
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
322
- } catch (error) {
323
- console.error(`Error reading ${filePath}:`, error);
324
- throw error;
325
- } finally {
326
- await handle?.close();
327
- }
328
- try {
329
- let relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
330
- let parts = relativePath.split("/");
331
- let site;
332
- let collection;
333
- let locale = "en";
334
- let name;
335
- let pathname;
336
- let parsedData = {};
337
- let kind;
338
- if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + "/")) {
339
- kind = "page";
340
- site = this.mdxPagesSite;
341
- collection = this.mdxPagesCollection;
342
- const mdxParts = filePath.replace(this.absoluteMdxPagesRoot + "/", "").split("/");
343
- const noLocaleMatch = mdxParts[mdxParts.length - 1].match(/^(.+)\.mdx$/);
344
- if (!noLocaleMatch) return null;
345
- mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
346
- if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
347
- locale = mdxParts[0];
348
- const slugParts = mdxParts.slice(1);
349
- pathname = slugParts[slugParts.length - 1] === "index" ? "/" + slugParts.slice(0, -1).join("/") || "/" : "/" + slugParts.join("/");
350
- } else {
351
- locale = this.mdxPagesDefaultLocale;
352
- pathname = mdxParts[mdxParts.length - 1] === "index" ? "/" + mdxParts.slice(0, -1).join("/") || "/" : "/" + mdxParts.join("/");
353
- }
354
- parsedData = parse4KBMDX(buffer, bytesRead);
355
- } else if (parts[0] === "blocks") {
356
- kind = "block";
357
- if (parts.length === 2) {
358
- collection = "general";
359
- const filename = parts[1];
360
- const generalDir = join(this.absoluteContentRoot, "blocks", "general");
361
- try {
362
- await mkdir(generalDir, { recursive: true });
363
- } catch (error) {}
364
- const newFilePath = join(generalDir, filename);
365
- try {
366
- await handle?.close();
367
- handle = void 0;
368
- try {
369
- await (await open(newFilePath, "r")).close();
370
- console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);
371
- } catch (error) {
372
- await rename(filePath, newFilePath);
373
- console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);
374
- filePath = newFilePath;
375
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
376
- parts = relativePath.split("/");
377
- handle = await open(filePath, "r");
378
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
379
- }
380
- } catch (moveError) {
381
- console.error(`Failed to move ${filename} to general collection:`, moveError);
382
- handle = await open(filePath, "r");
383
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
384
- }
385
- } else collection = parts[1];
386
- const filename = parts[parts.length - 1];
387
- const matchWithLocale = filename.match(/^(.+)\.(\w+)\.(mdx|vxjson)$/);
388
- const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
389
- if (matchWithLocale) {
390
- name = matchWithLocale[1];
391
- locale = matchWithLocale[2];
392
- } else if (matchWithoutLocale) {
393
- name = matchWithoutLocale[1];
394
- locale = this.contentIndex.getDefaultLocale("");
395
- console.log(`Found file without locale suffix: ${filename}`);
396
- const extension = matchWithoutLocale[2];
397
- const newFilename = `${name}.${locale}.${extension}`;
398
- const newFilePath = join(dirname(filePath), newFilename);
399
- console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
400
- try {
401
- await handle?.close();
402
- handle = void 0;
403
- await (await open(newFilePath, "r")).close();
404
- console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
405
- } catch (error) {
406
- console.log(`Target file doesn't exist, proceeding with rename`);
407
- try {
408
- await rename(filePath, newFilePath);
409
- console.log(`Successfully renamed ${filename} to ${newFilename}`);
410
- filePath = newFilePath;
411
- relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
412
- parts = relativePath.split("/");
413
- handle = await open(filePath, "r");
414
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
415
- } catch (renameError) {
416
- console.error(`Failed to rename ${filename}:`, renameError);
417
- handle = await open(filePath, "r");
418
- bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
419
- }
420
- }
421
- }
422
- if (filePath.endsWith(".mdx")) parsedData = parse4KBMDX(buffer, bytesRead);
423
- else parsedData = VXJSON.parse4KB(buffer, bytesRead);
424
- } else if (parts[0] === "data") {
425
- kind = "data";
426
- collection = parts[1];
427
- const match = parts[parts.length - 1].match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
428
- if (match) {
429
- name = match[1];
430
- locale = match[2];
431
- }
432
- const content = textDecoder.decode(buffer.subarray(0, bytesRead));
433
- try {
434
- const jsonData = JSON.parse(content);
435
- parsedData = {
436
- id: jsonData.id,
437
- type: "json",
438
- created: jsonData.created,
439
- modified: jsonData.modified,
440
- publishAt: jsonData.publishAt,
441
- unpublishAt: jsonData.unpublishAt,
442
- meta: jsonData.meta || { title: name || "Untitled" },
443
- data: jsonData.data,
444
- name
445
- };
446
- } catch (error) {
447
- console.error(`Failed to parse JSON data file ${filePath}:`, error);
448
- return null;
449
- }
450
- } else {
451
- kind = "page";
452
- site = parts[0];
453
- collection = parts[1];
454
- const pathParts = parts.slice(2);
455
- const match = pathParts[pathParts.length - 1].match(/^(.+)\.(\w+)\.(vxjson|mdx)$/);
456
- if (match) {
457
- locale = match[2];
458
- pathParts[pathParts.length - 1] = match[1];
459
- pathname = pathParts[pathParts.length - 1] === "index" ? "/" + pathParts.slice(0, -1).join("/") || "/" : "/" + pathParts.join("/");
460
- }
461
- if (filePath.endsWith(".mdx")) parsedData = parse4KBMDX(buffer, bytesRead);
462
- else parsedData = VXJSON.parse4KB(buffer, bytesRead);
463
- }
464
- const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
465
- const id = parsedData.id || generateContentId();
466
- const localeVersion = {
467
- locale,
468
- etag: "",
469
- created: parsedData.created || (/* @__PURE__ */ new Date()).toISOString(),
470
- modified: parsedData.modified || (/* @__PURE__ */ new Date()).toISOString(),
471
- ...parsedData.publishAt && { publishAt: parsedData.publishAt },
472
- ...parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt },
473
- ...pathname && { pathname },
474
- ...parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames },
475
- ...name && { name },
476
- meta: parsedData.meta || { title: name || "Untitled" }
477
- };
478
- const manifest = {
479
- id,
480
- type: parsedData.type || (filePath.endsWith(".mdx") ? "mdx" : filePath.endsWith(".json") ? "json" : "puck"),
481
- kind,
482
- site,
483
- collection,
484
- locales: { [locale]: localeVersion }
485
- };
486
- let content;
487
- if (needsRepair) {
488
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
489
- if (repairedData) {
490
- content = repairedData.content;
491
- localeVersion.etag = repairedData.etag;
492
- localeVersion.modified = repairedData.modified;
493
- return {
494
- manifest,
495
- locale,
496
- localeVersion,
497
- bytesRead,
498
- content
499
- };
500
- }
501
- console.error(`Failed to repair ${filePath}, skipping`);
502
- return null;
503
- }
504
- if (bytesRead < 4096 || filePath.endsWith(".vxjson") && buffer[bytesRead - 1] === 125 || filePath.endsWith(".json") && buffer[bytesRead - 1] === 125) {
505
- if (filePath.endsWith(".mdx")) {
506
- const { content: mdx } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)), {});
507
- content = { mdx };
508
- } else if (filePath.endsWith(".json")) {
509
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
510
- content = { data: JSON.parse(fullContent).data };
511
- } else {
512
- const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
513
- content = JSON.parse(fullContent).content || {};
514
- }
515
- const validBuffer = buffer.subarray(0, bytesRead);
516
- if (filePath.endsWith(".mdx")) {
517
- const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
518
- localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
519
- } else if (filePath.endsWith(".json")) localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
520
- else {
521
- const etagResult = VXJSON.calculateETags(validBuffer);
522
- if (!etagResult.success) {
523
- const repairedData = await this.performReadRepair(filePath, manifest, locale);
524
- if (repairedData) {
525
- content = repairedData.content;
526
- localeVersion.etag = repairedData.etag;
527
- localeVersion.modified = repairedData.modified;
528
- return {
529
- manifest,
530
- locale,
531
- localeVersion,
532
- bytesRead,
533
- content
534
- };
535
- }
536
- console.error(`Failed to repair ${filePath}, skipping`);
537
- return null;
538
- }
539
- localeVersion.etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
540
- }
541
- }
542
- return {
543
- manifest,
544
- locale,
545
- localeVersion,
546
- bytesRead,
547
- content
548
- };
549
- } catch (error) {
550
- console.error(`Error indexing ${originalFilePath}:`, error);
551
- return null;
552
- }
553
- }
554
- /**
555
- * Perform read-repair by writing back the file with missing fields
556
- * This ensures stable IDs and timestamps across restarts
557
- */
558
- async performReadRepair(filePath, manifest, locale) {
559
- try {
560
- const now = (/* @__PURE__ */ new Date()).toISOString();
561
- let needsWrite = false;
562
- if (manifest.type === "mdx") {
563
- const parsed = matter(await readFile(filePath, "utf-8"), {});
564
- if (!parsed.data.id) {
565
- parsed.data.id = manifest.id;
566
- needsWrite = true;
567
- }
568
- if (!parsed.data.created) {
569
- parsed.data.created = now;
570
- needsWrite = true;
571
- }
572
- if (!parsed.data.modified) {
573
- parsed.data.modified = now;
574
- needsWrite = true;
575
- }
576
- if (needsWrite) {
577
- const updatedContent = matter.stringify(parsed, parsed.data);
578
- await writeFile(filePath, updatedContent);
579
- console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
580
- const etags = calculateEtagsFromMdxBuffer(Buffer.from(updatedContent, "utf-8"), updatedContent.indexOf("\n---\n") + 5);
581
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
582
- return {
583
- content: { mdx: parsed.content.replace(/^\n+/, "") },
584
- etag,
585
- modified: parsed.data.modified || now
586
- };
587
- }
588
- } else {
589
- const content = await readFile(filePath, "utf-8");
590
- const data = JSON.parse(content);
591
- if (!data.id) {
592
- data.id = manifest.id;
593
- needsWrite = true;
594
- }
595
- if (!data.created) {
596
- data.created = now;
597
- needsWrite = true;
598
- }
599
- if (!data.modified) {
600
- data.modified = now;
601
- needsWrite = true;
602
- }
603
- needsWrite = true;
604
- if (needsWrite) {
605
- const vxjsonData = {
606
- id: data.id,
607
- type: data.type,
608
- created: data.created,
609
- modified: data.modified,
610
- publishAt: data.publishAt,
611
- unpublishAt: data.unpublishAt,
612
- previousPathnames: data.previousPathnames,
613
- meta: data.meta || {},
614
- content: data.content || {}
615
- };
616
- const repairedJson = VXJSON.serialize(vxjsonData);
617
- await writeFile(filePath, repairedJson);
618
- console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
619
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
620
- const etagResult = VXJSON.calculateETags(repairedBuffer);
621
- if (!etagResult.success) {
622
- console.error(`Failed to calculate ETags after repair: ${filePath}`);
623
- return null;
624
- }
625
- const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
626
- return {
627
- content: vxjsonData.content,
628
- etag,
629
- modified: vxjsonData.modified
630
- };
631
- }
632
- }
633
- return null;
634
- } catch (error) {
635
- console.error(`Failed to perform read-repair on ${filePath}:`, error);
636
- return null;
637
- }
638
- }
639
- async scanContentFiles() {
640
- const files = [];
641
- const contentRoot = this.absoluteContentRoot;
642
- async function scan(dir, inDataDir = false) {
643
- try {
644
- const entries = await readdir(dir, { withFileTypes: true });
645
- for (const entry of entries) {
646
- const fullPath = join(dir, entry.name);
647
- if (entry.isDirectory()) {
648
- const isDataDir = dir === contentRoot && entry.name === "data";
649
- await scan(fullPath, inDataDir || isDataDir);
650
- } else if (entry.isFile()) {
651
- if (entry.name.endsWith(".vxjson") || entry.name.endsWith(".mdx")) files.push(fullPath);
652
- else if (inDataDir && entry.name.endsWith(".json")) files.push(fullPath);
653
- }
654
- }
655
- } catch (error) {}
656
- }
657
- await scan(this.absoluteContentRoot);
658
- if (this.absoluteMdxPagesRoot && this.absoluteMdxPagesRoot !== this.absoluteContentRoot && !this.absoluteMdxPagesRoot.startsWith(this.absoluteContentRoot + "/")) {
659
- async function scanMdxPages(dir) {
660
- try {
661
- const entries = await readdir(dir, { withFileTypes: true });
662
- for (const entry of entries) {
663
- const fullPath = join(dir, entry.name);
664
- if (entry.isDirectory()) await scanMdxPages(fullPath);
665
- else if (entry.isFile() && entry.name.endsWith(".mdx")) files.push(fullPath);
666
- }
667
- } catch (error) {}
668
- }
669
- await scanMdxPages(this.absoluteMdxPagesRoot);
670
- }
671
- return files;
672
- }
673
- getFilePath(manifest, { locale, name, pathname }) {
674
- if (manifest.kind === "block") {
675
- const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
676
- return join(this.absoluteContentRoot, "blocks", manifest.collection, `${name}.${locale}.${ext}`);
677
- }
678
- if (manifest.kind === "data") return join(this.absoluteContentRoot, "data", manifest.collection, `${name}.${locale}.json`);
679
- if (manifest.kind === "page" && pathname) {
680
- const basePath = pathname.replace(/^\//, "").replace(/\/$/, "") || "index";
681
- if (manifest.type === "mdx" && this.absoluteMdxPagesRoot) return locale === this.mdxPagesDefaultLocale ? join(this.absoluteMdxPagesRoot, `${basePath}.mdx`) : join(this.absoluteMdxPagesRoot, locale, `${basePath}.mdx`);
682
- if (manifest.site) {
683
- const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
684
- return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.${ext}`);
685
- }
686
- }
687
- throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
688
- }
689
- /**
690
- * Parse a file path back into its components for checking against the path index
691
- * Returns null if the path doesn't match expected patterns
692
- */
693
- parseFilePath(filePath) {
694
- if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + "/")) {
695
- const mdxParts = filePath.replace(this.absoluteMdxPagesRoot + "/", "").split("/");
696
- const mdxFilename = mdxParts[mdxParts.length - 1];
697
- let locale;
698
- let pathname;
699
- const noLocaleMatch = mdxFilename.match(/^(.+)\.mdx$/);
700
- if (!noLocaleMatch) return null;
701
- mdxParts[mdxParts.length - 1] = noLocaleMatch[1];
702
- if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {
703
- locale = mdxParts[0];
704
- const slugParts = mdxParts.slice(1);
705
- pathname = slugParts[slugParts.length - 1] === "index" ? "/" + slugParts.slice(0, -1).join("/") || "/" : "/" + slugParts.join("/");
706
- } else {
707
- locale = this.mdxPagesDefaultLocale;
708
- pathname = mdxParts[mdxParts.length - 1] === "index" ? "/" + mdxParts.slice(0, -1).join("/") || "/" : "/" + mdxParts.join("/");
709
- }
710
- return {
711
- kind: "page",
712
- site: this.mdxPagesSite,
713
- collection: this.mdxPagesCollection,
714
- pathname,
715
- locale
716
- };
717
- }
718
- const parts = filePath.replace(this.absoluteContentRoot + "/", "").split("/");
719
- const filename = parts[parts.length - 1];
720
- if (parts[0] === "data" && parts.length === 3) {
721
- const dataMatch = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
722
- if (!dataMatch) return null;
723
- const [, name, locale] = dataMatch;
724
- return {
725
- kind: "data",
726
- collection: parts[1],
727
- name,
728
- locale
729
- };
730
- }
731
- const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.(?:vxjson|mdx)$/);
732
- if (!match) return null;
733
- const [, nameOrPath, locale] = match;
734
- if (parts[0] === "blocks" && parts.length === 3) return {
735
- kind: "block",
736
- collection: parts[1],
737
- name: nameOrPath,
738
- locale
739
- };
740
- if (parts.length >= 3 && parts[0] !== "blocks") {
741
- const site = parts[0];
742
- const collection = parts[1];
743
- const pathParts = parts.slice(2, -1);
744
- pathParts.push(nameOrPath);
745
- return {
746
- kind: "page",
747
- site,
748
- collection,
749
- pathname: "/" + pathParts.join("/"),
750
- locale
751
- };
752
- }
753
- return null;
754
- }
755
- async getContent(id) {
756
- const manifest = this.contentIndex.getManifest(id);
757
- if (!manifest) return null;
758
- const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
759
- const filePath = this.getFilePath(manifest, localeVersion);
760
- return {
761
- localeVersion,
762
- content: await this.readLocaleFile(filePath, localeVersion.locale)
763
- };
764
- });
765
- const results = await Promise.all(readPromises);
766
- const locales = {};
767
- for (const { localeVersion, content } of results) if (content) locales[localeVersion.locale] = {
768
- ...localeVersion,
769
- etag: content.etag,
770
- content: content.content
771
- };
772
- return {
773
- id: manifest.id,
774
- site: manifest.site,
775
- collection: manifest.collection,
776
- type: manifest.type,
777
- kind: manifest.kind,
778
- locales
779
- };
780
- }
781
- async getLocalized(id, locale) {
782
- const manifest = this.contentIndex.getManifest(id);
783
- if (!manifest) {
784
- await this.reindex();
785
- const updatedManifest = this.contentIndex.getManifest(id);
786
- if (!updatedManifest || !updatedManifest.locales[locale]) return null;
787
- return this.getLocalized(id, locale);
788
- }
789
- const localeVersion = manifest.locales[locale];
790
- if (!localeVersion) return null;
791
- const filePath = this.getFilePath(manifest, localeVersion);
792
- const localeData = await this.readLocaleFile(filePath, locale);
793
- if (!localeData) return null;
794
- return {
795
- id: manifest.id,
796
- site: manifest.site,
797
- collection: manifest.collection,
798
- type: manifest.type,
799
- kind: manifest.kind,
800
- localized: {
801
- ...localeVersion,
802
- etag: localeData.etag,
803
- content: localeData.content
804
- }
805
- };
806
- }
807
- async readLocaleFile(filePath, locale) {
808
- try {
809
- const buffer = await readFile(filePath);
810
- const content = textDecoder.decode(buffer);
811
- if (filePath.endsWith(".mdx")) {
812
- const { data: frontmatter, content: rawBody } = matter(content, {});
813
- const body = rawBody.replace(/^\n+/, "");
814
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
815
- const etag = `${etags.metaEtag}.${etags.contentEtag}`;
816
- const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
817
- const result = {
818
- locale,
819
- etag,
820
- created,
821
- modified,
822
- meta: metaFields,
823
- content: { mdx: body }
824
- };
825
- if (frontmatter.publishAt !== void 0) result.publishAt = frontmatter.publishAt;
826
- if (frontmatter.unpublishAt !== void 0) result.unpublishAt = frontmatter.unpublishAt;
827
- return result;
828
- }
829
- const data = JSON.parse(content);
830
- if (data.type === "json") {
831
- const result = {
832
- locale,
833
- etag: VXJSON.calculateSimpleEtag(buffer),
834
- created: data.created,
835
- modified: data.modified,
836
- meta: data.meta || {},
837
- content: { data: data.data || {} }
838
- };
839
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
840
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
841
- return result;
842
- }
843
- const etagResult = VXJSON.calculateETags(buffer);
844
- if (!etagResult.success) {
845
- const repairedData = {
846
- id: data.id,
847
- type: data.type,
848
- created: data.created,
849
- modified: data.modified,
850
- publishAt: data.publishAt,
851
- unpublishAt: data.unpublishAt,
852
- previousPathnames: data.previousPathnames,
853
- meta: data.meta || {},
854
- content: data.content || {}
855
- };
856
- const repairedJson = VXJSON.serialize(repairedData);
857
- await writeFile(filePath, repairedJson);
858
- const repairedBuffer = Buffer.from(repairedJson, "utf-8");
859
- const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
860
- if (!repairedEtagResult.success) throw new Error(`Failed to repair VXJSON file: ${filePath}`);
861
- const etag = repairedEtagResult.contentEtag ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}` : repairedEtagResult.metaEtag;
862
- console.log(`Repaired VXJSON file: ${filePath}`);
863
- const result = {
864
- locale,
865
- etag,
866
- created: data.created,
867
- modified: data.modified,
868
- meta: data.meta || {},
869
- content: data.content || {}
870
- };
871
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
872
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
873
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
874
- return result;
875
- }
876
- const result = {
877
- locale,
878
- etag: etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag,
879
- created: data.created,
880
- modified: data.modified,
881
- meta: data.meta || {},
882
- content: data.content || {}
883
- };
884
- if (data.publishAt !== void 0) result.publishAt = data.publishAt;
885
- if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
886
- if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
887
- return result;
888
- } catch (error) {
889
- return null;
890
- }
891
- }
892
- async createContent(data) {
893
- const validation = validateCreateContent(data, this.sites, this.blocks, this.data);
894
- if (!validation.valid) return {
895
- success: false,
896
- reason: validation.reason,
897
- error: validation.error ? new Error(validation.error) : void 0,
898
- existingId: validation.existingId
899
- };
900
- const id = generateContentId();
901
- const now = data.created || (/* @__PURE__ */ new Date()).toISOString();
902
- try {
903
- const manifest = {
904
- id,
905
- type: data.type,
906
- kind: data.kind,
907
- site: data.site,
908
- collection: data.collection,
909
- locales: {}
910
- };
911
- const contentCache = {};
912
- for (const [locale, localeData] of Object.entries(data.locales)) {
913
- const content = localeData.content;
914
- const title = localeData.meta?.title || data.meta?.title;
915
- if (!title) return {
916
- success: false,
917
- reason: "write_error",
918
- error: /* @__PURE__ */ new Error("Title is required in metadata")
919
- };
920
- const meta = {
921
- title,
922
- ...data.meta,
923
- ...localeData.meta
924
- };
925
- const fileData = {
926
- id,
927
- type: data.type,
928
- created: now,
929
- modified: now,
930
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
931
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
932
- meta,
933
- content
934
- };
935
- const filePath = this.getFilePath(manifest, {
936
- locale,
937
- name: data.name,
938
- pathname: localeData.pathname
939
- });
940
- await mkdir(dirname(filePath), { recursive: true });
941
- let etag;
942
- if (data.type === "mdx") {
943
- const mdxContent = serializeMdxWithFrontmatter({
944
- id,
945
- created: now,
946
- modified: now,
947
- ...localeData.publishAt && { publishAt: localeData.publishAt },
948
- ...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
949
- ...meta
950
- }, content.mdx || "");
951
- await writeFile(filePath, mdxContent);
952
- const mdxBuffer = new TextEncoder().encode(mdxContent);
953
- const contentStartMarker = new TextEncoder().encode("---\n\n");
954
- let contentPos = -1;
955
- for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
956
- let match = true;
957
- for (let j = 0; j < contentStartMarker.length; j++) if (mdxBuffer[i + j] !== contentStartMarker[j]) {
958
- match = false;
959
- break;
960
- }
961
- if (match) {
962
- contentPos = i + contentStartMarker.length;
963
- break;
964
- }
965
- }
966
- const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
967
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
968
- } else if (data.type === "json") {
969
- const dataFileContent = {
970
- id,
971
- type: "json",
972
- created: now,
973
- modified: now,
974
- ...localeData.publishAt && typeof localeData.publishAt === "string" && { publishAt: localeData.publishAt },
975
- ...localeData.unpublishAt && typeof localeData.unpublishAt === "string" && { unpublishAt: localeData.unpublishAt },
976
- meta,
977
- data: content.data || {}
978
- };
979
- const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, " ");
980
- await writeFile(filePath, jsonContent);
981
- const jsonBuffer = new TextEncoder().encode(jsonContent);
982
- etag = VXJSON.calculateSimpleEtag(jsonBuffer);
983
- } else {
984
- const jsonContent = VXJSON.serialize(fileData);
985
- const jsonBuffer = new TextEncoder().encode(jsonContent);
986
- const etagResult = VXJSON.calculateETags(jsonBuffer);
987
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
988
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
989
- await writeFile(filePath, jsonContent);
990
- }
991
- const localeVersion = buildLocaleVersion({
992
- locale,
993
- etag,
994
- created: now,
995
- modified: now,
996
- meta,
997
- kind: data.kind,
998
- pathname: data.kind === "page" ? localeData.pathname : void 0,
999
- name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
1000
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
1001
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
1002
- });
1003
- manifest.locales[locale] = localeVersion;
1004
- contentCache[locale] = content;
1005
- }
1006
- for (const localeVersion of localesOf(manifest)) {
1007
- const { locale } = localeVersion;
1008
- this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
1009
- }
1010
- return {
1011
- success: true,
1012
- id
1013
- };
1014
- } catch (error) {
1015
- return {
1016
- success: false,
1017
- reason: "write_error",
1018
- error: ensureError(error)
1019
- };
1020
- }
1021
- }
1022
- async updateLocalized(input) {
1023
- const { id, locale, data, etag } = input;
1024
- const manifest = this.contentIndex.getManifest(id);
1025
- if (!manifest) return {
1026
- success: false,
1027
- reason: "not_found"
1028
- };
1029
- const localeVersion = manifest.locales[locale];
1030
- if (!localeVersion) return {
1031
- success: false,
1032
- reason: "not_found"
1033
- };
1034
- const filePath = this.getFilePath(manifest, localeVersion);
1035
- const current = await this.readLocaleFile(filePath, locale);
1036
- if (!current) return {
1037
- success: false,
1038
- reason: "not_found"
1039
- };
1040
- const currentEtag = current.etag;
1041
- if (manifest.kind === "data") {
1042
- if (etag !== currentEtag) return {
1043
- success: false,
1044
- reason: "stale_write",
1045
- currentEtag
1046
- };
1047
- } else {
1048
- const etagParts = parseDualEtag(etag);
1049
- const currentParts = parseDualEtag(currentEtag);
1050
- if (!etagParts || !currentParts) return {
1051
- success: false,
1052
- reason: "stale_write",
1053
- currentEtag
1054
- };
1055
- const updateScope = analyzeUpdateScope(data);
1056
- const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
1057
- const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
1058
- if (updatingMeta && etagParts.meta !== currentParts.meta) return {
1059
- success: false,
1060
- reason: "stale_write",
1061
- currentEtag
1062
- };
1063
- if (updatingContent && etagParts.content !== currentParts.content) return {
1064
- success: false,
1065
- reason: "stale_write",
1066
- currentEtag
1067
- };
1068
- }
1069
- let modified;
1070
- if (shouldUpdateModifiedTimestamp(data)) modified = data.modified || (/* @__PURE__ */ new Date()).toISOString();
1071
- else if (data.modified) modified = data.modified;
1072
- else modified = current.modified;
1073
- const { sortedMeta: newMeta, valid: metaValid, error: metaError } = validateAndPrepareMetadata({
1074
- ...current.meta,
1075
- ...data.meta ? data.meta : {}
1076
- });
1077
- if (!newMeta || !metaValid) return {
1078
- success: false,
1079
- reason: "write_error",
1080
- error: new Error(metaError)
1081
- };
1082
- const newContent = data.content ? {
1083
- ...current.content,
1084
- ...data.content
1085
- } : current.content;
1086
- if (data.pathname && manifest.kind === "page" && manifest.site) {
1087
- const site = this.sites[manifest.site];
1088
- if (site) {
1089
- const existingId = site.getPathnameConflict(data.pathname, locale, id);
1090
- if (existingId) return {
1091
- success: false,
1092
- reason: "write_error",
1093
- error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
1094
- };
1095
- }
1096
- }
1097
- if (data.name && (manifest.kind === "block" || manifest.kind === "data")) {
1098
- const existing = (manifest.kind === "block" ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex()).getByName(manifest.collection, data.name);
1099
- if (existing && existing.id !== id) {
1100
- const existingTitle = Object.values(existing.locales).find((lv) => lv !== void 0)?.meta?.title;
1101
- const kindLabel = manifest.kind === "block" ? "Block" : "Data";
1102
- return {
1103
- success: false,
1104
- reason: "write_error",
1105
- error: /* @__PURE__ */ new Error(`${kindLabel} name "${data.name}" is already in use${existingTitle ? ` by "${existingTitle}"` : ""}`)
1106
- };
1107
- }
1108
- }
1109
- const pathnameHistory = buildPathnameHistory(localeVersion.pathname, data.pathname, isContentPublished({
1110
- publishAt: resolvePublishDate(data.publishAt, current.publishAt),
1111
- unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt)
1112
- }), (/* @__PURE__ */ new Date()).toISOString());
1113
- try {
1114
- let targetFilePath = filePath;
1115
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {
1116
- const newLocaleVersion = {
1117
- ...localeVersion,
1118
- pathname: data.pathname
1119
- };
1120
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1121
- await mkdir(dirname(targetFilePath), { recursive: true });
1122
- } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === "block") {
1123
- const newLocaleVersion = {
1124
- ...localeVersion,
1125
- name: data.name
1126
- };
1127
- targetFilePath = this.getFilePath(manifest, newLocaleVersion);
1128
- await mkdir(dirname(targetFilePath), { recursive: true });
1129
- }
1130
- if (targetFilePath.endsWith(".mdx")) {
1131
- const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
1132
- const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
1133
- const frontmatterData = {
1134
- id: manifest.id,
1135
- created: current.created,
1136
- modified,
1137
- ...publishAt && { publishAt },
1138
- ...unpublishAt && { unpublishAt },
1139
- ...newMeta
1140
- };
1141
- let mdxContentPart = newContent.mdx || "";
1142
- if (mdxContentPart.startsWith("---")) {
1143
- const { content: contentOnly } = matter(mdxContentPart, {});
1144
- mdxContentPart = contentOnly;
1145
- }
1146
- if (/\n---\r?\n[\s\S]*?\r?\n---(\r?\n|$)/.test(mdxContentPart)) console.warn(`[content-api] Embedded frontmatter-shaped block detected in body for ${targetFilePath}. This indicates a load-path regression or client-side leak.`);
1147
- const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
1148
- await atomicWriteFile(targetFilePath, mdxContent);
1149
- } else if (targetFilePath.endsWith(".json")) {
1150
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
1151
- const updatedFile = {
1152
- id: fileContent.id,
1153
- type: "json",
1154
- created: fileContent.created,
1155
- modified,
1156
- ...fileContent.publishAt && { publishAt: fileContent.publishAt },
1157
- ...fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt },
1158
- meta: newMeta,
1159
- data: sortKeys(newContent.data || {}, { deep: true })
1160
- };
1161
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
1162
- else delete updatedFile.publishAt;
1163
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
1164
- else delete updatedFile.unpublishAt;
1165
- const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
1166
- await atomicWriteFile(targetFilePath, serializedContent);
1167
- } else {
1168
- const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
1169
- const updatedFile = {
1170
- id: fileContent.id,
1171
- type: fileContent.type,
1172
- created: fileContent.created,
1173
- modified,
1174
- publishAt: fileContent.publishAt,
1175
- unpublishAt: fileContent.unpublishAt,
1176
- previousPathnames: fileContent.previousPathnames,
1177
- meta: newMeta,
1178
- content: sortKeys(newContent, { deep: true })
1179
- };
1180
- if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {
1181
- if (isContentPublished(current)) {
1182
- if (!updatedFile.previousPathnames) updatedFile.previousPathnames = {};
1183
- updatedFile.previousPathnames[localeVersion.pathname] = modified;
1184
- }
1185
- }
1186
- if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
1187
- else delete updatedFile.publishAt;
1188
- if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
1189
- else delete updatedFile.unpublishAt;
1190
- const serializedContent = VXJSON.serialize(updatedFile);
1191
- await atomicWriteFile(targetFilePath, serializedContent);
1192
- }
1193
- const writtenBuffer = await readFile(targetFilePath);
1194
- let newEtag;
1195
- if (targetFilePath.endsWith(".mdx")) {
1196
- const contentStartMarker = new TextEncoder().encode("---\n\n");
1197
- let contentPos = -1;
1198
- for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
1199
- let match = true;
1200
- for (let j = 0; j < contentStartMarker.length; j++) if (writtenBuffer[i + j] !== contentStartMarker[j]) {
1201
- match = false;
1202
- break;
1203
- }
1204
- if (match) {
1205
- contentPos = i + contentStartMarker.length;
1206
- break;
1207
- }
1208
- }
1209
- const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
1210
- newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
1211
- } else if (targetFilePath.endsWith(".json")) newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
1212
- else {
1213
- const etagResult = VXJSON.calculateETags(writtenBuffer);
1214
- if (!etagResult.success) throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
1215
- newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1216
- }
1217
- const updatedLocaleVersion = {
1218
- ...localeVersion,
1219
- etag: newEtag,
1220
- modified,
1221
- meta: newMeta,
1222
- ...data.pathname && { pathname: data.pathname },
1223
- ...data.name && { name: data.name }
1224
- };
1225
- if (current.publishAt && !("publishAt" in data)) updatedLocaleVersion.publishAt = current.publishAt;
1226
- if (current.unpublishAt && !("unpublishAt" in data)) updatedLocaleVersion.unpublishAt = current.unpublishAt;
1227
- updatePublishDates(updatedLocaleVersion, data);
1228
- if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
1229
- ...localeVersion.previousPathnames,
1230
- ...pathnameHistory
1231
- };
1232
- else {
1233
- const existingPreviousPathnames = localeVersion.previousPathnames;
1234
- if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
1235
- else delete updatedLocaleVersion.previousPathnames;
1236
- }
1237
- const oldLocaleVersion = manifest.locales[locale];
1238
- try {
1239
- manifest.locales[locale] = updatedLocaleVersion;
1240
- this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
1241
- if (targetFilePath !== filePath) try {
1242
- await unlink(filePath);
1243
- } catch (error) {
1244
- console.warn(`Failed to delete old file ${filePath}:`, error);
1245
- }
1246
- } catch (error) {
1247
- manifest.locales[locale] = oldLocaleVersion;
1248
- if (targetFilePath !== filePath) try {
1249
- await unlink(targetFilePath);
1250
- } catch {}
1251
- throw error;
1252
- }
1253
- return {
1254
- success: true,
1255
- etag: newEtag,
1256
- modified: /* @__PURE__ */ new Date()
1257
- };
1258
- } catch (error) {
1259
- return {
1260
- success: false,
1261
- reason: "write_error",
1262
- error: ensureError(error)
1263
- };
1264
- }
1265
- }
1266
- async deleteContent(id, etag) {
1267
- const manifest = this.contentIndex.getManifest(id);
1268
- if (!manifest) return {
1269
- success: false,
1270
- reason: "not_found",
1271
- error: /* @__PURE__ */ new Error("Content not found")
1272
- };
1273
- let matchingLocale;
1274
- for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
1275
- matchingLocale = localeVersion;
1276
- break;
1277
- }
1278
- if (!matchingLocale) return {
1279
- success: false,
1280
- reason: "stale_write",
1281
- currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
1282
- error: /* @__PURE__ */ new Error("Invalid etag - must match at least one locale")
1283
- };
1284
- try {
1285
- const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
1286
- await unlink(this.getFilePath(manifest, localeVersion));
1287
- });
1288
- await Promise.all(deletePromises);
1289
- this.contentIndex.removeEntry(id);
1290
- return { success: true };
1291
- } catch (error) {
1292
- return {
1293
- success: false,
1294
- error: ensureError(error)
1295
- };
1296
- }
1297
- }
1298
- async deleteLocalized(input) {
1299
- const { id, locale, etag } = input;
1300
- const manifest = this.contentIndex.getManifest(id);
1301
- if (!manifest) return {
1302
- success: false,
1303
- reason: "not_found",
1304
- error: /* @__PURE__ */ new Error("Content not found")
1305
- };
1306
- const localeVersion = manifest.locales[locale];
1307
- if (!localeVersion) return {
1308
- success: false,
1309
- reason: "not_found",
1310
- error: /* @__PURE__ */ new Error("Locale not found")
1311
- };
1312
- if (localeVersion.etag !== etag) return {
1313
- success: false,
1314
- reason: "stale_write",
1315
- currentEtag: localeVersion.etag,
1316
- error: /* @__PURE__ */ new Error("Invalid etag for locale")
1317
- };
1318
- if (Object.keys(manifest.locales).length === 1) return {
1319
- success: false,
1320
- error: /* @__PURE__ */ new Error("Cannot delete the last locale. Use deleteContent to delete all content.")
1321
- };
1322
- try {
1323
- await unlink(this.getFilePath(manifest, localeVersion));
1324
- manifest.locales[locale] = void 0;
1325
- this.contentIndex.removeLocale(manifest.id, locale);
1326
- return { success: true };
1327
- } catch (error) {
1328
- return {
1329
- success: false,
1330
- error: ensureError(error)
1331
- };
1332
- }
1333
- }
1334
- getSite(siteName) {
1335
- if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
1336
- return this.sites[siteName] || null;
1337
- }
1338
- *listAllContent(filters) {
1339
- yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
1340
- }
1341
- *findUntranslatedContent(targetLocale, options) {
1342
- yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
1343
- }
1344
- /**
1345
- * Reindex files that were added or changed after initial creation
1346
- *
1347
- * This method:
1348
- * 1. Either scans for all content files or processes specific paths
1349
- * 2. Uses the path index to check if files are already indexed
1350
- * 3. Indexes new files or force-reindexes specified files
1351
- * 4. Optionally handles file deletions
1352
- *
1353
- * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
1354
- * @param options - Options for reindexing behavior
1355
- * @returns Statistics about the reindexing operation
1356
- */
1357
- async reindex(paths, options) {
1358
- const filesToProcess = paths || await this.scanContentFiles();
1359
- let filesSkipped = 0;
1360
- let filesProcessed = 0;
1361
- let filesDeleted = 0;
1362
- let errors = 0;
1363
- const filesToIndex = [];
1364
- const updated = [];
1365
- const deleted = [];
1366
- for (const filePath of filesToProcess) {
1367
- if (options?.handleDeletions && paths) try {
1368
- await readFile(filePath);
1369
- } catch (error) {
1370
- const parsed = this.parseFilePath(filePath);
1371
- if (parsed) {
1372
- let manifest = null;
1373
- if (parsed.kind === "block" && parsed.name) manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1374
- else if (parsed.kind === "data" && parsed.name) manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1375
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1376
- if (manifest) {
1377
- deleted.push({
1378
- id: manifest.id,
1379
- locale: parsed.locale,
1380
- kind: parsed.kind
1381
- });
1382
- if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(manifest.id);
1383
- else {
1384
- manifest.locales[parsed.locale] = void 0;
1385
- this.contentIndex.removeLocale(manifest.id, parsed.locale);
1386
- }
1387
- filesDeleted++;
1388
- }
1389
- }
1390
- continue;
1391
- }
1392
- const parsed = this.parseFilePath(filePath);
1393
- if (!parsed) {
1394
- console.warn(`Skipping unrecognized file pattern: ${filePath}`);
1395
- errors++;
1396
- continue;
1397
- }
1398
- let isIndexed = false;
1399
- if (parsed.kind === "block" && parsed.name) isIndexed = !!this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1400
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) isIndexed = !!this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1401
- else if (parsed.kind === "data" && parsed.name) isIndexed = !!this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1402
- if (isIndexed) if (!paths) filesSkipped++;
1403
- else {
1404
- const fileStats = await readFile(filePath);
1405
- let currentManifest = null;
1406
- if (parsed.kind === "block" && parsed.name) currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
1407
- else if (parsed.kind === "data" && parsed.name) currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
1408
- else if (parsed.kind === "page" && parsed.site && parsed.pathname) currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
1409
- if (currentManifest) {
1410
- const buffer = fileStats;
1411
- let currentEtag;
1412
- if (filePath.endsWith(".mdx")) {
1413
- const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
1414
- currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
1415
- } else if (filePath.endsWith(".vxjson")) {
1416
- const etagResult = VXJSON.calculateETags(buffer);
1417
- if (!etagResult.success) {
1418
- filesToIndex.push(filePath);
1419
- continue;
1420
- }
1421
- currentEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1422
- } else if (filePath.endsWith(".json")) currentEtag = xxh64(buffer).toString(16);
1423
- else {
1424
- filesSkipped++;
1425
- continue;
1426
- }
1427
- if (currentManifest.locales[parsed.locale]?.etag === currentEtag) {
1428
- const relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
1429
- console.log(`[Content] skip ${relativePath} (unchanged)`);
1430
- filesSkipped++;
1431
- } else filesToIndex.push(filePath);
1432
- } else filesToIndex.push(filePath);
1433
- }
1434
- else filesToIndex.push(filePath);
1435
- }
1436
- const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => /* @__PURE__ */ new Uint8Array(4096));
1437
- for (let i = 0; i < filesToIndex.length; i++) {
1438
- const filePath = filesToIndex[i];
1439
- const bufferIndex = i % buffers.length;
1440
- try {
1441
- const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
1442
- if (result) {
1443
- const { manifest, localeVersion, content } = result;
1444
- this.contentIndex.addContent(manifest, localeVersion, content);
1445
- filesProcessed++;
1446
- const localizedManifest = {
1447
- id: manifest.id,
1448
- type: manifest.type,
1449
- kind: manifest.kind,
1450
- site: manifest.site,
1451
- collection: manifest.collection,
1452
- localized: localeVersion
1453
- };
1454
- updated.push(localizedManifest);
1455
- }
1456
- } catch (error) {
1457
- console.error(`Failed to reindex ${filePath}:`, error);
1458
- errors++;
1459
- }
1460
- }
1461
- const result = {
1462
- filesProcessed,
1463
- filesSkipped,
1464
- updated
1465
- };
1466
- if (options?.handleDeletions && deleted.length > 0) {
1467
- result.filesDeleted = filesDeleted;
1468
- result.deleted = deleted;
1469
- }
1470
- if (errors > 0) result.errors = errors;
1471
- return result;
1472
- }
1473
- /**
1474
- * Read content directly from cache
1475
- * For testing purposes - returns null if not cached
1476
- */
1477
- async readFromCache(id, locale) {
1478
- return this.contentIndex.getCachedContent(id, locale);
1479
- }
1480
- async getContentAsBuffer(id, locale) {
1481
- const manifest = this.contentIndex.getManifest(id);
1482
- if (!manifest || !manifest.locales[locale]) return null;
1483
- const localeVersion = manifest.locales[locale];
1484
- const filePath = this.getFilePath(manifest, localeVersion);
1485
- const buffer = await readFile(filePath);
1486
- const contentType = filePath.endsWith(".mdx") ? "text/mdx" : "application/json";
1487
- let etag;
1488
- if (contentType === "text/mdx") {
1489
- const contentStartMarker = new TextEncoder().encode("---\n\n");
1490
- let contentPos = -1;
1491
- for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
1492
- let match = true;
1493
- for (let j = 0; j < contentStartMarker.length; j++) if (buffer[i + j] !== contentStartMarker[j]) {
1494
- match = false;
1495
- break;
1496
- }
1497
- if (match) {
1498
- contentPos = i + contentStartMarker.length;
1499
- break;
1500
- }
1501
- }
1502
- const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
1503
- etag = `${etags.metaEtag}.${etags.contentEtag}`;
1504
- } else {
1505
- const etagResult = VXJSON.calculateETags(buffer);
1506
- if (!etagResult.success) throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
1507
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1508
- }
1509
- return {
1510
- buffer,
1511
- etag,
1512
- contentType
1513
- };
1514
- }
1515
- async batchUpdate(operations) {
1516
- const validationResults = [];
1517
- for (const op of operations) {
1518
- const manifest = this.contentIndex.getManifest(op.id);
1519
- if (!manifest) return {
1520
- operations: operations.map((o) => ({
1521
- id: o.id,
1522
- locale: o.locale,
1523
- updated: false,
1524
- error: /* @__PURE__ */ new Error("Content not found")
1525
- })),
1526
- success: false,
1527
- updated: 0,
1528
- failed: operations.length
1529
- };
1530
- const localeVersion = manifest.locales[op.locale];
1531
- if (!localeVersion) return {
1532
- operations: operations.map((o) => ({
1533
- id: o.id,
1534
- locale: o.locale,
1535
- updated: false,
1536
- error: /* @__PURE__ */ new Error("Locale not found")
1537
- })),
1538
- success: false,
1539
- updated: 0,
1540
- failed: operations.length
1541
- };
1542
- if (localeVersion.etag !== op.etag) return {
1543
- operations: operations.map((o) => ({
1544
- id: o.id,
1545
- locale: o.locale,
1546
- updated: false,
1547
- error: /* @__PURE__ */ new Error("Stale write")
1548
- })),
1549
- success: false,
1550
- updated: 0,
1551
- failed: operations.length
1552
- };
1553
- const filePath = this.getFilePath(manifest, localeVersion);
1554
- const current = await this.readLocaleFile(filePath, op.locale);
1555
- if (!current) return {
1556
- operations: operations.map((o) => ({
1557
- id: o.id,
1558
- locale: o.locale,
1559
- updated: false,
1560
- error: /* @__PURE__ */ new Error("Failed to read content")
1561
- })),
1562
- success: false,
1563
- updated: 0,
1564
- failed: operations.length
1565
- };
1566
- if (op.data.meta) {
1567
- const validation = validateAndPrepareMetadata({
1568
- ...current.meta,
1569
- ...op.data.meta
1570
- });
1571
- if (!validation.valid) return {
1572
- operations: operations.map((o) => ({
1573
- id: o.id,
1574
- locale: o.locale,
1575
- updated: false,
1576
- error: new Error(validation.error)
1577
- })),
1578
- success: false,
1579
- updated: 0,
1580
- failed: operations.length
1581
- };
1582
- }
1583
- validationResults.push({
1584
- op,
1585
- manifest,
1586
- localeVersion,
1587
- current
1588
- });
1589
- }
1590
- const results = [];
1591
- let updated = 0;
1592
- for (const { op } of validationResults) {
1593
- const result = await this.updateLocalized(op);
1594
- if (result.success) {
1595
- updated++;
1596
- results.push({
1597
- id: op.id,
1598
- locale: op.locale,
1599
- updated: true,
1600
- etag: result.etag
1601
- });
1602
- } else results.push({
1603
- id: op.id,
1604
- locale: op.locale,
1605
- updated: false,
1606
- error: result.error
1607
- });
1608
- }
1609
- return {
1610
- operations: results,
1611
- success: updated === operations.length,
1612
- updated,
1613
- failed: operations.length - updated
1614
- };
1615
- }
1616
- };
1617
- //#endregion
1618
- export { atomicWriteFile as i, readSitesConfig as n, filterContentWithIndexes as r, FileSystemContentAPI as t };
1619
-
1620
- //# sourceMappingURL=filesystem-content-api-C0HIhqZi.mjs.map