@conloca/content-api 0.1.14 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-manifest.d.ts +23 -0
- package/dist/asset-manifest.d.ts.map +1 -0
- package/dist/asset-manifest.js +73 -0
- package/dist/asset-operations.d.ts +159 -0
- package/dist/asset-operations.d.ts.map +1 -0
- package/dist/asset-operations.js +736 -0
- package/dist/asset-types.d.ts +56 -0
- package/dist/asset-types.d.ts.map +1 -0
- package/dist/asset-types.js +7 -0
- package/dist/base-content-index.d.ts +57 -0
- package/dist/base-content-index.d.ts.map +1 -0
- package/dist/base-content-index.js +179 -0
- package/dist/block-index.d.ts +9 -0
- package/dist/block-index.d.ts.map +1 -0
- package/dist/block-index.js +11 -0
- package/dist/blocks.d.ts +16 -0
- package/dist/blocks.d.ts.map +1 -0
- package/dist/blocks.js +103 -0
- package/dist/cf-access.d.ts +31 -0
- package/dist/cf-access.d.ts.map +1 -0
- package/dist/cf-access.js +66 -0
- package/dist/component-registry.d.ts +50 -0
- package/dist/component-registry.d.ts.map +1 -0
- package/dist/component-registry.js +120 -0
- package/dist/component-registry.types-C0ctF9nh.d.mts +71 -0
- package/dist/component-registry.types-C0ctF9nh.d.mts.map +1 -0
- package/dist/component-registry.types.d.ts +11 -0
- package/dist/component-registry.types.d.ts.map +1 -0
- package/dist/component-registry.types.js +1 -0
- package/dist/content-api.interface.d.ts +64 -0
- package/dist/content-api.interface.d.ts.map +1 -0
- package/dist/content-api.interface.js +1 -0
- package/dist/content-filters.d.ts +31 -0
- package/dist/content-filters.d.ts.map +1 -0
- package/dist/content-filters.js +246 -0
- package/dist/content-index-D092_vk1.mjs +629 -0
- package/dist/content-index-D092_vk1.mjs.map +1 -0
- package/dist/content-index-D6IVMmAB.d.mts +127 -0
- package/dist/content-index-D6IVMmAB.d.mts.map +1 -0
- package/dist/content-index.d.ts +126 -0
- package/dist/content-index.d.ts.map +1 -0
- package/dist/content-index.js +418 -0
- package/dist/content-operations-DIbsxG5A.d.mts +354 -0
- package/dist/content-operations-DIbsxG5A.d.mts.map +1 -0
- package/dist/content-operations.d.ts +93 -0
- package/dist/content-operations.d.ts.map +1 -0
- package/dist/content-operations.js +275 -0
- package/dist/content-reader.d.ts +10 -0
- package/dist/content-reader.d.ts.map +1 -0
- package/dist/content-reader.js +13 -0
- package/dist/content-utils-fWNHTrPy.mjs +280 -0
- package/dist/content-utils-fWNHTrPy.mjs.map +1 -0
- package/dist/content-utils.d.ts +132 -0
- package/dist/content-utils.d.ts.map +1 -0
- package/dist/content-utils.js +352 -0
- package/dist/content-watcher.d.ts +43 -0
- package/dist/content-watcher.d.ts.map +1 -0
- package/dist/content-watcher.js +83 -0
- package/dist/data-DquNIEnQ.mjs +62 -0
- package/dist/data-DquNIEnQ.mjs.map +1 -0
- package/dist/data-index.d.ts +8 -0
- package/dist/data-index.d.ts.map +1 -0
- package/dist/data-index.js +7 -0
- package/dist/data.d.ts +43 -0
- package/dist/data.d.ts.map +1 -0
- package/dist/data.js +103 -0
- package/dist/etag-utils.d.ts +77 -0
- package/dist/etag-utils.d.ts.map +1 -0
- package/dist/etag-utils.js +160 -0
- package/dist/filesystem-content-api-B1KIQJfk.mjs +2 -0
- package/dist/filesystem-content-api-C0HIhqZi.mjs +1620 -0
- package/dist/filesystem-content-api-C0HIhqZi.mjs.map +1 -0
- package/dist/filesystem-content-api-DCdNi-co.d.mts +134 -0
- package/dist/filesystem-content-api-DCdNi-co.d.mts.map +1 -0
- package/dist/filesystem-content-api.d.ts +135 -0
- package/dist/filesystem-content-api.d.ts.map +1 -0
- package/dist/filesystem-content-api.js +2181 -0
- package/dist/git-operations.d.ts +49 -0
- package/dist/git-operations.d.ts.map +1 -0
- package/dist/git-operations.js +252 -0
- package/dist/header-parser.d.ts +37 -0
- package/dist/header-parser.d.ts.map +1 -0
- package/dist/header-parser.js +286 -0
- package/dist/in-memory-content-api.d.ts +35 -0
- package/dist/in-memory-content-api.d.ts.map +1 -0
- package/dist/in-memory-content-api.js +591 -0
- package/dist/index-DxVTFK66.d.mts +105 -0
- package/dist/index-DxVTFK66.d.mts.map +1 -0
- package/dist/index.d.mts +6 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.mjs +37 -5
- package/dist/index.mjs.map +1 -1
- package/dist/indexing.d.mts +152 -0
- package/dist/indexing.d.mts.map +1 -0
- package/dist/indexing.d.ts +5 -0
- package/dist/indexing.d.ts.map +1 -0
- package/dist/indexing.js +7 -0
- package/dist/indexing.mjs +255 -0
- package/dist/indexing.mjs.map +1 -0
- package/dist/json-whitespace-view.d.ts +32 -0
- package/dist/json-whitespace-view.d.ts.map +1 -0
- package/dist/json-whitespace-view.js +152 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +1031 -0
- package/dist/node.d.mts +28 -126
- package/dist/node.d.mts.map +1 -1
- package/dist/node.d.ts +25 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +24 -0
- package/dist/node.mjs +199 -2890
- package/dist/node.mjs.map +1 -1
- package/dist/reader.d.mts +15 -0
- package/dist/reader.d.mts.map +1 -0
- package/dist/reader.d.ts +15 -0
- package/dist/reader.d.ts.map +1 -0
- package/dist/reader.js +13 -0
- package/dist/reader.mjs +22 -0
- package/dist/reader.mjs.map +1 -0
- package/dist/schemas/index.d.mts +2 -90
- package/dist/schemas/index.d.ts +102 -0
- package/dist/schemas/index.d.ts.map +1 -0
- package/dist/schemas/index.js +87 -0
- package/dist/schemas/index.mjs +2 -70
- package/dist/schemas-CFRD0FIQ.mjs +84 -0
- package/dist/schemas-CFRD0FIQ.mjs.map +1 -0
- package/dist/{types-BUG0Cfkg.mjs → site-8oaj1Q60.mjs} +20 -222
- package/dist/site-8oaj1Q60.mjs.map +1 -0
- package/dist/site-index-B_254bCc.d.mts +136 -0
- package/dist/site-index-B_254bCc.d.mts.map +1 -0
- package/dist/site-index.d.ts +60 -0
- package/dist/site-index.d.ts.map +1 -0
- package/dist/site-index.js +287 -0
- package/dist/site.d.ts +21 -0
- package/dist/site.d.ts.map +1 -0
- package/dist/site.js +168 -0
- package/dist/types-DOdldbfD.mjs +34 -0
- package/dist/types-DOdldbfD.mjs.map +1 -0
- package/dist/types-DjfhS272.d.mts +456 -0
- package/dist/types-DjfhS272.d.mts.map +1 -0
- package/dist/types.d.ts +453 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +36 -0
- package/dist/url-safe-base64.d.ts +12 -0
- package/dist/url-safe-base64.d.ts.map +1 -0
- package/dist/url-safe-base64.js +40 -0
- package/dist/url-validation.d.ts +14 -0
- package/dist/url-validation.d.ts.map +1 -0
- package/dist/url-validation.js +81 -0
- package/dist/utils/atomic-write.d.ts +6 -0
- package/dist/utils/atomic-write.d.ts.map +1 -0
- package/dist/utils/atomic-write.js +20 -0
- package/dist/utils.d.ts +46 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +70 -0
- package/dist/vite-plugin.d.ts +12 -0
- package/dist/vite-plugin.d.ts.map +1 -0
- package/dist/vite-plugin.js +29 -0
- package/dist/vxjson-qHrgLGip.mjs +555 -0
- package/dist/vxjson-qHrgLGip.mjs.map +1 -0
- package/dist/vxjson-serialize-geF6qvpn.mjs +34 -0
- package/dist/vxjson-serialize-geF6qvpn.mjs.map +1 -0
- package/dist/vxjson-serialize.d.mts +17 -0
- package/dist/vxjson-serialize.d.mts.map +1 -0
- package/dist/vxjson-serialize.d.ts +14 -0
- package/dist/vxjson-serialize.d.ts.map +1 -0
- package/dist/vxjson-serialize.js +50 -0
- package/dist/vxjson-serialize.mjs +2 -0
- package/dist/vxjson.d.ts +112 -0
- package/dist/vxjson.d.ts.map +1 -0
- package/dist/vxjson.js +391 -0
- package/dist/xxhash.d.ts +10 -0
- package/dist/xxhash.d.ts.map +1 -0
- package/dist/xxhash.js +31 -0
- package/package.json +88 -17
- package/dist/content-operations-BZLfJWqT.d.mts +0 -916
- package/dist/content-operations-BZLfJWqT.d.mts.map +0 -1
- package/dist/schemas/index.d.mts.map +0 -1
- package/dist/schemas/index.mjs.map +0 -1
- package/dist/types-BUG0Cfkg.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filesystem-content-api-C0HIhqZi.mjs","names":[],"sources":["../src/utils/atomic-write.ts","../src/content-filters.ts","../src/filesystem-content-api.ts"],"sourcesContent":["import { rename, unlink, writeFile } from 'node:fs/promises';\n\n/**\n * Write file atomically via temp file + rename to prevent corruption on crash.\n * Callers are responsible for ensuring the parent directory exists.\n */\nexport async function atomicWriteFile(filePath: string, content: string): Promise<void> {\n const hrtime = process.hrtime.bigint();\n const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;\n\n try {\n await writeFile(tempFile, content);\n await rename(tempFile, filePath);\n } catch (error) {\n try {\n await unlink(tempFile);\n } catch {}\n throw error;\n }\n}\n","import type { ContentIndex } from './content-index';\nimport { localesOf } from './content-utils';\nimport type { ContentManifest, GlobalFilters, SitesConfig } from './types';\n\n/**\n * Apply filters to a single content manifest\n * Pure function that checks if a manifest matches all provided filters\n */\nexport function applyContentFilters(manifest: ContentManifest, filters: GlobalFilters): boolean {\n // Site filter\n if (filters.site && manifest.site !== filters.site) return false;\n\n // Collection filter\n if (filters.collection && manifest.collection !== filters.collection) return false;\n\n // Type filter\n if (filters.type && manifest.type !== filters.type) return false;\n\n // Kind filter\n if (filters.kind && manifest.kind !== filters.kind) return false;\n\n // Locales filter - check if manifest has any of the requested locales\n if (filters.locales && filters.locales.length > 0) {\n const hasAnyLocale = filters.locales.some((locale) => manifest.locales[locale]);\n if (!hasAnyLocale) return false;\n }\n\n // Missing locales filter - content must NOT have any of these locales\n if (filters.missingLocales && filters.missingLocales.length > 0) {\n const hasAnyMissingLocale = filters.missingLocales.some((locale) => manifest.locales[locale]);\n if (hasAnyMissingLocale) return false;\n }\n\n // Published status filter - check all locales\n if (filters.published !== undefined) {\n let hasPublishedLocale = false;\n for (const localeVersion of localesOf(manifest)) {\n if (!localeVersion.unpublishAt) {\n hasPublishedLocale = true;\n break;\n }\n if (new Date(localeVersion.unpublishAt) > new Date()) {\n hasPublishedLocale = true;\n break;\n }\n }\n if (filters.published !== hasPublishedLocale) return false;\n }\n\n // All filters passed\n return true;\n}\n\n/**\n * Filter a collection of content manifests based on localization status\n * Returns manifests that match the specified localization criteria\n */\nexport function filterByLocalization(\n allManifests: ContentManifest[],\n filters: GlobalFilters,\n siteLocales: string[],\n): ContentManifest[] {\n const results: ContentManifest[] = [];\n\n if (!filters.localization) {\n // No localization filter - return all manifests that match other filters\n for (const manifest of allManifests) {\n if (applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n return results;\n }\n\n // Apply localization-specific filtering\n switch (filters.localization) {\n case 'one':\n // Find content with exactly one locale\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n if (localeCount === 1 && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'complete':\n // Find content with all expected locales\n for (const manifest of allManifests) {\n const hasAllLocales = siteLocales.every((loc) => manifest.locales[loc]);\n if (hasAllLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n\n case 'partial':\n // Find content with some but not all translations\n for (const manifest of allManifests) {\n const localeCount = Object.keys(manifest.locales).length;\n const hasPartialLocales = localeCount > 0 && localeCount < siteLocales.length;\n if (hasPartialLocales && applyContentFilters(manifest, filters)) {\n results.push(manifest);\n }\n }\n break;\n }\n\n return results;\n}\n\n/**\n * Generator that yields manifests after applying all filters\n */\nexport function* filteredContentGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n for (const manifest of getFilteredManifestsGenerator(contentIndex, filters)) {\n if (applyContentFilters(manifest, filters)) {\n yield manifest;\n }\n }\n}\n\n/**\n * Generator that yields manifests using the most efficient index path\n */\nexport function* getFilteredManifestsGenerator(\n contentIndex: ContentIndex,\n filters: GlobalFilters,\n): Generator<ContentManifest> {\n // Choose the most efficient index path based on available filters\n\n // Most specific: site + locale + collection\n if (filters.site && filters.locales?.length === 1 && filters.collection) {\n for (const manifest of contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0])) {\n if (manifest.collection === filters.collection) {\n yield manifest;\n }\n }\n return;\n }\n\n // Site + collection (use optimized method)\n if (filters.site && filters.collection) {\n yield* contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n return;\n }\n\n // Site + single locale (use optimized method)\n if (filters.site && filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n return;\n }\n\n // Just single locale\n if (filters.locales?.length === 1) {\n yield* contentIndex.getManifestsForLocale(filters.locales[0]);\n return;\n }\n\n // Just site\n if (filters.site) {\n yield* contentIndex.getManifestsForSite(filters.site);\n return;\n }\n\n // Just collection\n if (filters.collection) {\n yield* contentIndex.getManifestsForCollection(filters.collection);\n return;\n }\n\n // Kind filter\n if (filters.kind) {\n yield* contentIndex.getManifestsForKind(filters.kind);\n return;\n }\n\n // No specific filters - yield all manifests\n yield* contentIndex.listAllContent();\n}\n\n/**\n * Get filtered manifests using indexes where possible for performance\n * This function leverages ContentIndex's specialized indexes to avoid full scans\n */\nexport function getFilteredManifests(contentIndex: ContentIndex, filters: GlobalFilters): ContentManifest[] {\n return Array.from(getFilteredManifestsGenerator(contentIndex, filters));\n}\n\n/**\n * Generator that yields manifests after applying all filters\n * This is the main entry point for filtering content using indexes efficiently\n */\nexport function* filterContentWithIndexes(\n contentIndex: ContentIndex,\n filters: GlobalFilters | undefined,\n sitesConfig: SitesConfig,\n): Generator<ContentManifest> {\n if (!filters) {\n // No filters - return all content\n yield* contentIndex.listAllContent();\n return;\n }\n\n // Special optimization for kind + site + collection\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Check if the site even has this collection\n const siteCollections = contentIndex.getCollectionsForSite(filters.site);\n if (!siteCollections.has(filters.collection)) {\n return; // Early exit - no pages in this collection for this site\n }\n } else if (filters.kind === 'block' && filters.collection) {\n // Check if blocks have this collection\n const blockCollections = contentIndex.getBlockCollections();\n if (!blockCollections.has(filters.collection)) {\n return; // Early exit - no blocks in this collection\n }\n }\n\n // Use the most efficient generator based on filters\n let generator: Generator<ContentManifest>;\n\n // Optimal filter ordering for most specific queries first\n if (filters.kind === 'page' && filters.site && filters.collection) {\n // Most specific for pages: site + collection\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.kind === 'block' && filters.collection) {\n // Most specific for blocks: kind + collection\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.kind) {\n generator = contentIndex.getManifestsForKind(filters.kind);\n } else if (filters.site && filters.collection) {\n generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);\n } else if (filters.site && filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);\n } else if (filters.site) {\n generator = contentIndex.getManifestsForSite(filters.site);\n } else if (filters.collection) {\n generator = contentIndex.getManifestsForCollection(filters.collection);\n } else if (filters.locales?.length === 1) {\n // Single locale optimization\n generator = contentIndex.getManifestsForLocale(filters.locales[0]);\n } else {\n generator = contentIndex.listAllContent();\n }\n\n // Apply additional filters\n for (const manifest of generator) {\n if (!applyContentFilters(manifest, filters)) continue;\n\n // Localization filter\n if (filters.localization) {\n // Early exit optimization: if complete + missingLocales, no results possible\n if (filters.localization === 'complete' && filters.missingLocales?.length) {\n continue; // Complete means has all locales, can't be missing any\n }\n\n const siteLocales =\n filters.site && manifest.kind === 'page'\n ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales\n : sitesConfig.globalLocales;\n\n const localeCount = Object.keys(manifest.locales).length;\n const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;\n const totalLocales = siteLocales.length;\n\n if (filters.localization === 'complete' && hasLocales !== totalLocales) continue;\n if (filters.localization === 'partial' && (localeCount <= 1 || hasLocales === totalLocales)) continue;\n if (filters.localization === 'one' && localeCount !== 1) continue;\n }\n\n yield manifest;\n }\n}\n","import { type FileHandle, mkdir, open, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { xxh64 } from './xxhash';\nimport matter from 'gray-matter';\nimport { dirname, join, resolve } from 'path';\nimport sortKeys from 'sort-keys';\nimport { Blocks } from './blocks';\nimport type { ContentAPI } from './content-api.interface';\nimport { filterContentWithIndexes } from './content-filters';\nimport { ContentIndex } from './content-index';\nimport {\n analyzeUpdateScope,\n buildLocaleVersion,\n buildPathnameHistory,\n generateContentId,\n isContentPublished,\n shouldUpdateModifiedTimestamp,\n UPDATE_SCOPE,\n updatePublishDates,\n validateAndPrepareMetadata,\n validateCreateContent,\n} from './content-operations';\nimport { localesOf, mapSiteNames, resolvePublishDate, serializeMdxWithFrontmatter } from './content-utils';\nimport { Data } from './data';\nimport { calculateEtagsFromMdxBuffer, findMdxContentStartPosition, parseDualEtag } from './etag-utils';\nimport { Site } from './site';\nimport type {\n BatchOperationResult,\n BatchResult,\n ContentAPIOptions,\n ContentData,\n ContentEntry,\n ContentIdentity,\n ContentManifest,\n ContentMeta,\n ContentProp,\n CreateContentInput,\n CreateResult,\n DeleteLocaleInput,\n DeleteResult,\n FindOptions,\n GlobalFilters,\n LocaleFileData,\n LocalePathData,\n LocaleVersion,\n LocalizedEntry,\n LocalizedManifest,\n SitesConfig,\n UpdateLocaleInput,\n UpdateResult,\n VXJSONFile,\n} from './types';\nimport { atomicWriteFile } from './utils/atomic-write';\n\ninterface ReindexResult {\n filesProcessed: number;\n filesSkipped: number;\n filesDeleted?: number;\n errors?: number;\n // Return manifests of updated locales (without content)\n updated: LocalizedManifest[];\n deleted?: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }>;\n}\n\nimport { VXJSON } from './vxjson';\n\n// Helper to ensure we have an Error object\nfunction ensureError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n// Reusable TextDecoder instance - safe to reuse as it's stateless\nconst textDecoder = new TextDecoder();\n\n// Parse 4KB MDX content - extracts frontmatter from buffer\nfunction parse4KBMDX(\n buffer: Uint8Array,\n bytesRead: number,\n): {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n meta: ContentMeta;\n contentStartPos?: number; // Position where content starts (after second ---)\n} {\n // Only convert to string what we need\n const partialContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { data: frontmatter } = matter(partialContent, {});\n\n // Find where content starts (after second ---)\n const delimiter = new TextEncoder().encode('---');\n let delimiterCount = 0;\n let contentStartPos = -1;\n\n for (let i = 0; i <= bytesRead - delimiter.length; i++) {\n let match = true;\n for (let j = 0; j < delimiter.length; j++) {\n if (buffer[i + j] !== delimiter[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n delimiterCount++;\n if (delimiterCount === 2) {\n // Skip past --- and newline\n contentStartPos = i + delimiter.length;\n while (contentStartPos < bytesRead && (buffer[contentStartPos] === 0x0a || buffer[contentStartPos] === 0x0d)) {\n contentStartPos++;\n }\n break;\n }\n }\n }\n\n // Extract special fields and treat the rest as metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n return {\n id,\n created,\n modified,\n publishAt,\n unpublishAt,\n meta: metaFields as ContentMeta, // All other fields are metadata\n contentStartPos,\n };\n}\n\n/**\n * FileSystem-based Content API Implementation\n *\n * Stores content as files on disk in a git-friendly format:\n * - Pages: /{site}/pages/{filename}.{locale}.vxjson\n * - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}\n *\n * ## Indexing\n *\n * Content is indexed at startup for performance. The index is cached per\n * content root path and cleared when the process restarts.\n *\n * ## Read-Repair\n *\n * Since files can be modified externally (git, editors), this implementation:\n *\n * 1. Repairs invalid VXJSON files (ensures \"content\" field is last)\n * 2. Adds missing required fields (id, created, modified)\n * 3. Handles files added after initial indexing\n * 4. Updates the index when files are repaired or discovered\n *\n * ## Performance\n *\n * - Initial indexing reads only first 4KB of each file\n * - Full content is loaded on demand\n * - ETags are calculated using streaming for efficiency\n */\n/**\n * Read and validate `<contentRoot>/sites.json`. Returns a safe default\n * (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or\n * has invalid structure, with a warning logged in each case.\n *\n * Exported standalone so the Astro integration (and any other tooling\n * that needs to inspect per-site config at startup time) can read the\n * config without spinning up a full content-api instance.\n */\nexport async function readSitesConfig(contentRoot: string): Promise<SitesConfig> {\n const absoluteContentRoot = resolve(contentRoot);\n const sitesPath = join(absoluteContentRoot, 'sites.json');\n try {\n const content = await readFile(sitesPath, 'utf-8');\n const parsed = JSON.parse(content);\n\n // Validate the structure\n if (!parsed.sites || typeof parsed.sites !== 'object') {\n console.warn(\n `Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`,\n );\n return { sites: {}, globalLocales: ['en'] };\n }\n if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {\n console.warn(\n `Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`,\n );\n return {\n sites: parsed.sites,\n globalLocales: ['en'],\n };\n }\n return parsed;\n } catch {\n // Handle missing sites.json gracefully\n console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);\n return { sites: {}, globalLocales: ['en'] };\n }\n}\n\nexport class FileSystemContentAPI implements ContentAPI {\n private contentRoot: string;\n private absoluteContentRoot: string;\n private contentIndex: ContentIndex;\n readonly sitesConfig: SitesConfig;\n readonly blocks: Blocks;\n readonly data: Data;\n private readonly sites: Record<string, Site>;\n\n // mdx-page support: optional second filesystem root for kind:'page'+type:'mdx'.\n // Canonical source is the resolved site's `mdxPages` in sites.json; the\n // ContentAPIOptions.mdxPagesRoot option exists as a test/programmatic\n // override. See ContentAPIOptions.mdxPagesRoot for the design rationale.\n private absoluteMdxPagesRoot?: string;\n private mdxPagesDefaultLocale = 'en';\n private mdxPagesSite = 'default';\n private mdxPagesCollection = 'pages';\n\n // Resolved locale list used to decide whether a path segment that\n // looks locale-shaped (e.g. `de`, `en-US`) is actually a configured\n // locale. Source-of-truth resolution (option > sites.json) happens in\n // the constructor; parsers read this set directly.\n private readonly availableLocales: ReadonlySet<string>;\n\n // Getter for testing purposes\n get normalizedContentRoot(): string {\n return this.contentRoot;\n }\n\n private constructor(\n contentRoot: string,\n canvasDir: string | undefined,\n sitesConfig: SitesConfig,\n contentIndex: ContentIndex,\n mdxPagesOptions?: {\n root?: string;\n defaultLocale?: string;\n site?: string;\n },\n localeOptions?: {\n availableLocales?: string[];\n defaultLocale?: string;\n },\n ) {\n // Normalize contentRoot: remove ./ prefix for relative paths, keep absolute paths as-is\n if (contentRoot.startsWith('./')) {\n this.contentRoot = contentRoot.slice(2);\n } else if (contentRoot.startsWith('/')) {\n // Absolute path, keep as-is\n this.contentRoot = contentRoot;\n } else {\n // Already normalized relative path\n this.contentRoot = contentRoot;\n }\n\n // Store absolute path for file operations\n this.absoluteContentRoot = resolve(this.contentRoot);\n\n // TODO: Use canvasDir for canvas/unlinked components\n this.sitesConfig = sitesConfig;\n this.contentIndex = contentIndex;\n\n // Resolve which site owns mdx-type pages. Resolution order:\n // 1. Explicit `mdxPagesOptions.site` (test / programmatic override)\n // 2. First site in sites.json that declares an `mdxPages` path\n // 3. First configured site (any)\n // 4. Literal 'default'\n const siteNames = Object.keys(sitesConfig.sites);\n const firstSiteName = siteNames[0];\n const firstSiteWithMdxPages = siteNames.find((name) => sitesConfig.sites[name]?.mdxPages);\n this.mdxPagesSite = mdxPagesOptions?.site ?? firstSiteWithMdxPages ?? firstSiteName ?? 'default';\n\n // Resolve the mdx-pages path. Option wins over sites.json so tests and\n // programmatic callers can supply a path without writing a sites.json\n // file. When neither is set, .mdx files fall back to living alongside\n // Puck pages under `{contentRoot}/{site}/pages/`.\n const sitesJsonMdxPages = sitesConfig.sites[this.mdxPagesSite]?.mdxPages;\n const resolvedMdxPages = mdxPagesOptions?.root ?? sitesJsonMdxPages;\n if (resolvedMdxPages) {\n const normalizedMdxPages = resolvedMdxPages.startsWith('./') ? resolvedMdxPages.slice(2) : resolvedMdxPages;\n this.absoluteMdxPagesRoot = resolve(normalizedMdxPages);\n }\n // Default locale: top-level option > mdxPages option > resolved-site's\n // defaultLocale > first global locale > 'en'. The top-level option wins\n // because it represents an explicit framework-level declaration (e.g.\n // forwarded from Astro's i18n block via localesFromAstroI18n).\n const siteConfig = sitesConfig.sites[this.mdxPagesSite];\n this.mdxPagesDefaultLocale =\n localeOptions?.defaultLocale ??\n mdxPagesOptions?.defaultLocale ??\n siteConfig?.defaultLocale ??\n sitesConfig.globalLocales[0] ??\n 'en';\n\n // Resolve the available-locales set. The top-level option is\n // authoritative when present; otherwise we merge sites.json's global\n // locales with the resolved-site's per-site locales. The default\n // locale is always added so getFilePath round-trips work.\n const merged = new Set<string>();\n if (localeOptions?.availableLocales && localeOptions.availableLocales.length > 0) {\n for (const loc of localeOptions.availableLocales) merged.add(loc);\n } else {\n for (const loc of sitesConfig.globalLocales) merged.add(loc);\n if (siteConfig?.locales) {\n for (const loc of siteConfig.locales) merged.add(loc);\n }\n }\n merged.add(this.mdxPagesDefaultLocale);\n this.availableLocales = merged;\n\n // Initialize blocks\n this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());\n\n // Initialize data\n this.data = new Data(this, this.contentIndex.getDataIndex());\n\n // Initialize all sites\n this.sites = mapSiteNames(sitesConfig, (siteName) => {\n const siteIndex = this.contentIndex.getSiteIndex(siteName);\n if (!siteIndex) {\n throw new Error(`Site index not found for ${siteName}`);\n }\n return new Site(siteName, this, siteIndex);\n });\n }\n\n static async create(options: ContentAPIOptions): Promise<FileSystemContentAPI> {\n const { canvasDir } = options;\n // Keep contentRoot as provided (will be normalized in constructor)\n const contentRoot = options.contentRoot;\n\n // Load sites config (canonical home for per-site fields including mdxPages).\n let sitesConfig = await readSitesConfig(contentRoot);\n\n // Apply the top-level locales option as the authoritative source.\n // We expand sitesConfig so that the BlockIndex (which keys on\n // globalLocales) and the resolved SiteIndex (which keys on the\n // site's locales array) both have slots for every option-declared\n // locale. Without this, the parser would correctly identify a file's\n // locale but `addContent` would crash on a missing index bucket.\n // We preserve the resolved site's existing `mdxPages` and `domains`\n // through the rewrite so the locale-override doesn't clobber the\n // per-site content config.\n if (options.availableLocales && options.availableLocales.length > 0) {\n const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];\n const optionSite = options.mdxPagesSite ?? Object.keys(sitesConfig.sites)[0] ?? 'default';\n const existingSite = sitesConfig.sites[optionSite];\n sitesConfig = {\n sites: {\n ...sitesConfig.sites,\n [optionSite]: {\n locales: options.availableLocales,\n defaultLocale: optionDefaultLocale,\n ...(existingSite?.domains && { domains: existingSite.domains }),\n ...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),\n },\n },\n globalLocales: Array.from(new Set([...sitesConfig.globalLocales, ...options.availableLocales])),\n };\n }\n\n // Get cached content index or create new one\n // Use the normalized contentRoot for cache key\n const normalizedContentRoot = contentRoot.startsWith('./') ? contentRoot.slice(2) : contentRoot;\n const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);\n\n // Create instance (not cached)\n const api = new FileSystemContentAPI(\n contentRoot,\n canvasDir,\n sitesConfig,\n contentIndex,\n {\n root: options.mdxPagesRoot,\n defaultLocale: options.mdxPagesDefaultLocale,\n site: options.mdxPagesSite,\n },\n {\n availableLocales: options.availableLocales,\n defaultLocale: options.defaultLocale,\n },\n );\n\n // Index all content files (only if index is empty)\n if (contentIndex.entryCount === 0) {\n await api.indexAllContent();\n }\n\n return api;\n }\n\n /**\n * Clear all caches - useful for testing\n */\n static clearCaches(): void {\n ContentIndex.clearCache();\n // TODO: CanvasIndex.clearCache() when implemented\n }\n\n private async indexAllContent(): Promise<void> {\n // Clear existing indexes\n this.contentIndex.clear();\n\n // Scan content directory\n const files = await this.scanContentFiles();\n\n // Use optimized batch size based on benchmarks\n const OPTIMAL_BATCH_SIZE = 1000;\n\n console.debug(`Indexing ${files.length} content files...`);\n\n // Pre-allocate reusable buffers for the entire indexing operation\n // Only allocate as many as we need (up to batch size)\n const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);\n const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));\n\n for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {\n const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);\n\n // Process batch in parallel - winner of benchmarks\n await Promise.all(\n batch.map(async (filePath, index) => {\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index with content if we have it\n this.contentIndex.addContent(manifest, localeVersion, content);\n }\n } catch (error) {\n console.error(`Failed to index ${filePath}:`, error);\n }\n }),\n );\n }\n }\n\n private async parseFileHeaderWithRepair(\n originalFilePath: string,\n buffer: Uint8Array,\n ): Promise<{\n manifest: ContentManifest;\n locale: string;\n localeVersion: LocaleVersion;\n bytesRead: number;\n content?: ContentData;\n } | null> {\n let handle: FileHandle | undefined;\n let bytesRead = 0;\n let filePath = originalFilePath; // Use a local variable that can be updated if file is renamed\n\n try {\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (error) {\n console.error(`Error reading ${filePath}:`, error);\n throw error;\n } finally {\n await handle?.close();\n }\n\n try {\n // Now parse the buffer content\n\n // Parse file to extract metadata\n let relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n let parts = relativePath.split('/');\n\n // Determine site/collection structure\n let site: string | undefined;\n let collection: string;\n let locale = 'en';\n let name: string | undefined;\n let pathname: string | undefined;\n // Type for parsed metadata from files\n interface ParsedMetadata {\n id?: string;\n created?: string;\n modified?: string;\n publishAt?: string;\n unpublishAt?: string;\n pathname?: string;\n name?: string;\n previousPathnames?: Record<string, string>;\n meta?: ContentMeta;\n type?: 'puck' | 'mdx' | 'json';\n contentStartPos?: number;\n data?: Record<string, unknown>; // For data collection entries\n }\n let parsedData: ParsedMetadata = {};\n let kind: 'block' | 'page' | 'data';\n\n // Files under the optional mdxPagesRoot are kind:'page' + type:'mdx',\n // independent of the directory tree rooted at absoluteContentRoot. The\n // leading prefix is stripped here; locale lives as a directory segment\n // ({locale}/{slug}.mdx for non-default locales, {slug}.mdx at the root\n // for the default locale).\n if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + '/')) {\n kind = 'page';\n site = this.mdxPagesSite;\n collection = this.mdxPagesCollection;\n const mdxRelativePath = filePath.replace(this.absoluteMdxPagesRoot + '/', '');\n const mdxParts = mdxRelativePath.split('/');\n const mdxFilename = mdxParts[mdxParts.length - 1];\n\n const noLocaleMatch = mdxFilename.match(/^(.+)\\.mdx$/);\n if (!noLocaleMatch) return null;\n mdxParts[mdxParts.length - 1] = noLocaleMatch[1];\n\n // A leading folder counts as a locale only when it's a configured\n // locale. A two-letter folder like `qa/` or `id/` is therefore\n // left in the slug, not silently classified as a language.\n if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {\n locale = mdxParts[0];\n const slugParts = mdxParts.slice(1);\n pathname =\n slugParts[slugParts.length - 1] === 'index'\n ? '/' + slugParts.slice(0, -1).join('/') || '/'\n : '/' + slugParts.join('/');\n } else {\n locale = this.mdxPagesDefaultLocale;\n pathname =\n mdxParts[mdxParts.length - 1] === 'index'\n ? '/' + mdxParts.slice(0, -1).join('/') || '/'\n : '/' + mdxParts.join('/');\n }\n\n parsedData = parse4KBMDX(buffer, bytesRead);\n } else if (parts[0] === 'blocks') {\n kind = 'block';\n\n // Check if block is directly in blocks/ directory (no collection subdirectory)\n if (parts.length === 2) {\n // Block is directly in blocks/ directory, needs to be moved to 'general' collection\n collection = 'general';\n const filename = parts[1];\n\n // Create the general directory if it doesn't exist\n const generalDir = join(this.absoluteContentRoot, 'blocks', 'general');\n try {\n await mkdir(generalDir, { recursive: true });\n } catch (error) {\n // Directory might already exist, that's fine\n }\n\n // Move the file to the general collection\n const newFilePath = join(generalDir, filename);\n\n try {\n await handle?.close(); // Close the current file handle before moving\n handle = undefined;\n\n // Check if target file already exists\n try {\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);\n } catch (error) {\n // Target doesn't exist, safe to move\n await rename(filePath, newFilePath);\n console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } catch (moveError) {\n console.error(`Failed to move ${filename} to general collection:`, moveError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n } else {\n // Block is in a collection subdirectory\n collection = parts[1];\n }\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: hero.en.mdx -> name: hero, locale: en\n // Also handle files without locale: hero.mdx -> name: hero, locale: default from sites.json\n const matchWithLocale = filename.match(/^(.+)\\.(\\w+)\\.(mdx|vxjson)$/);\n const matchWithoutLocale = filename.match(/^(.+)\\.(mdx|vxjson)$/);\n\n if (matchWithLocale) {\n name = matchWithLocale[1];\n locale = matchWithLocale[2];\n } else if (matchWithoutLocale) {\n name = matchWithoutLocale[1];\n // Use default locale from sites config instead of hardcoded 'en'\n locale = this.contentIndex.getDefaultLocale('');\n\n console.log(`Found file without locale suffix: ${filename}`);\n // Rename file to include locale suffix\n const extension = matchWithoutLocale[2];\n const newFilename = `${name}.${locale}.${extension}`;\n const newFilePath = join(dirname(filePath), newFilename);\n console.log(`Will rename to: ${newFilename} at ${newFilePath}`);\n\n // Check if target file already exists\n try {\n await handle?.close(); // Close the current file handle before renaming\n handle = undefined;\n\n // Try to open the target file to check if it exists\n const targetHandle = await open(newFilePath, 'r');\n await targetHandle.close();\n\n // Target file exists, skip renaming to avoid conflict\n console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);\n } catch (error) {\n // Target file doesn't exist, safe to rename\n console.log(`Target file doesn't exist, proceeding with rename`);\n try {\n await rename(filePath, newFilePath);\n console.log(`Successfully renamed ${filename} to ${newFilename}`);\n\n // Update filePath to the new path for further processing\n filePath = newFilePath;\n\n // Update relativePath and parts for the new file path\n relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n parts = relativePath.split('/');\n\n // Re-open the file with the new path\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n } catch (renameError) {\n console.error(`Failed to rename ${filename}:`, renameError);\n // Continue processing with original file\n handle = await open(filePath, 'r');\n bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;\n }\n }\n }\n\n // Parse content based on file type\n if (filePath.endsWith('.mdx')) {\n parsedData = parse4KBMDX(buffer, bytesRead);\n } else {\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n } else if (parts[0] === 'data') {\n // Data collection entry: data/{collection}/{name}.{locale}.json\n kind = 'data';\n collection = parts[1];\n\n const filename = parts[parts.length - 1];\n // Extract name and locale from filename: testimonial.en.json -> name: testimonial, locale: en\n // Use strict locale pattern matching blocks: 2-letter code with optional region (en, en-US)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (match) {\n name = match[1];\n locale = match[2];\n }\n\n // Parse JSON to get ID, metadata, and data\n const content = textDecoder.decode(buffer.subarray(0, bytesRead));\n try {\n const jsonData = JSON.parse(content);\n parsedData = {\n id: jsonData.id,\n type: 'json',\n created: jsonData.created,\n modified: jsonData.modified,\n publishAt: jsonData.publishAt,\n unpublishAt: jsonData.unpublishAt,\n meta: jsonData.meta || { title: name || 'Untitled' },\n data: jsonData.data,\n name,\n };\n } catch (error) {\n console.error(`Failed to parse JSON data file ${filePath}:`, error);\n return null;\n }\n } else {\n kind = 'page';\n site = parts[0];\n collection = parts[1];\n\n // Build pathname from file path. Accepts both .vxjson (Puck pages) and\n // .mdx (mdx-type pages) so consumers without a separate `mdxPages`\n // path can colocate .mdx docs alongside Puck pages under\n // `{contentRoot}/{site}/{collection}/...`. When `mdxPages` IS set\n // on a site in sites.json, .mdx files are served from that\n // separate path (handled in the `absoluteMdxPagesRoot` branch\n // above) and won't reach this branch.\n const pathParts = parts.slice(2); // Remove site/collection\n const filename = pathParts[pathParts.length - 1];\n const match = filename.match(/^(.+)\\.(\\w+)\\.(vxjson|mdx)$/);\n if (match) {\n locale = match[2];\n // Replace filename with basename\n pathParts[pathParts.length - 1] = match[1];\n // index files map to parent: /index -> /, /foo/index -> /foo\n pathname =\n pathParts[pathParts.length - 1] === 'index'\n ? '/' + pathParts.slice(0, -1).join('/') || '/'\n : '/' + pathParts.join('/');\n }\n\n // Parse format-appropriately. parse4KBMDX reads frontmatter from the\n // MDX header; VXJSON.parse4KB reads the leading JSON metadata.\n if (filePath.endsWith('.mdx')) {\n parsedData = parse4KBMDX(buffer, bytesRead);\n } else {\n parsedData = VXJSON.parse4KB(buffer, bytesRead);\n }\n }\n\n // Check if the file is missing required fields\n const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;\n\n // Extract or generate ID\n const id = parsedData.id || generateContentId();\n\n // Build LocaleManifest for this specific locale\n const localeVersion: LocaleVersion = {\n locale,\n etag: '', // Will be filled below\n created: parsedData.created || new Date().toISOString(),\n modified: parsedData.modified || new Date().toISOString(),\n ...(parsedData.publishAt && { publishAt: parsedData.publishAt }),\n ...(parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt }),\n ...(pathname && { pathname }),\n ...(parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames }),\n ...(name && { name }),\n meta: parsedData.meta || { title: name || 'Untitled' },\n };\n\n // Build ContentManifest (without content)\n const manifest: ContentManifest = {\n id,\n type: parsedData.type || (filePath.endsWith('.mdx') ? 'mdx' : filePath.endsWith('.json') ? 'json' : 'puck'),\n kind,\n site,\n collection,\n locales: {\n [locale]: localeVersion,\n },\n };\n\n // If we have full content, parse it and compute etags\n let content: ContentData | undefined;\n\n // Check if we need to repair the file first (missing required fields)\n if (needsRepair) {\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n\n if (\n bytesRead < 4096 ||\n (filePath.endsWith('.vxjson') && buffer[bytesRead - 1] === 0x7d) ||\n (filePath.endsWith('.json') && buffer[bytesRead - 1] === 0x7d)\n ) {\n // We have the full content\n if (filePath.endsWith('.mdx')) {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const { content: mdx } = matter(fullContent, {});\n content = { mdx };\n } else if (filePath.endsWith('.json')) {\n // Data collection JSON file\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const jsonData = JSON.parse(fullContent);\n content = { data: jsonData.data };\n } else {\n const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));\n const data = JSON.parse(fullContent);\n content = data.content || {};\n }\n\n // Calculate etags from the buffer (only use valid bytes)\n const validBuffer = buffer.subarray(0, bytesRead);\n\n if (filePath.endsWith('.mdx')) {\n const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);\n localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n // Data files are typically small and don't need separate meta/content etags\n localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);\n } else {\n const etagResult = VXJSON.calculateETags(validBuffer);\n\n if (!etagResult.success) {\n // Content field is not last or invalid JSON - repair immediately\n\n // Perform repair and get the repaired content\n const repairedData = await this.performReadRepair(filePath, manifest, locale);\n if (repairedData) {\n content = repairedData.content;\n localeVersion.etag = repairedData.etag;\n localeVersion.modified = repairedData.modified;\n return { manifest, locale, localeVersion, bytesRead, content };\n }\n // Repair failed, skip this file\n console.error(`Failed to repair ${filePath}, skipping`);\n return null;\n }\n localeVersion.etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n }\n }\n\n // Return both for indexing\n return { manifest, locale, localeVersion, bytesRead, content };\n } catch (error) {\n console.error(`Error indexing ${originalFilePath}:`, error);\n return null;\n }\n }\n\n /**\n * Perform read-repair by writing back the file with missing fields\n * This ensures stable IDs and timestamps across restarts\n */\n private async performReadRepair(\n filePath: string,\n manifest: ContentManifest,\n locale: string,\n ): Promise<{\n content: ContentData;\n etag: string;\n modified: string;\n } | null> {\n try {\n const now = new Date().toISOString();\n let needsWrite = false;\n\n if (manifest.type === 'mdx') {\n // Read the full MDX file\n const content = await readFile(filePath, 'utf-8');\n const parsed = matter(content, {});\n\n // Check for missing fields\n if (!parsed.data.id) {\n parsed.data.id = manifest.id;\n needsWrite = true;\n }\n if (!parsed.data.created) {\n parsed.data.created = now;\n needsWrite = true;\n }\n if (!parsed.data.modified) {\n parsed.data.modified = now;\n needsWrite = true;\n }\n\n if (needsWrite) {\n // Write back with updated frontmatter. Pass the parsed file\n // object, not the body string: stringify re-parses string inputs\n // through gray-matter's memo cache, which is a plain object — a\n // body equal to an Object.prototype member name ('toString',\n // 'valueOf', …) reads the prototype function back and crashes.\n // Same cache-opt-out rule as the matter(..., {}) calls above.\n const updatedContent = matter.stringify(parsed, parsed.data);\n await writeFile(filePath, updatedContent);\n console.log(`Repaired MDX file: ${filePath} (added missing fields)`);\n\n // Calculate ETags for the repaired MDX file\n const repairedBuffer = Buffer.from(updatedContent, 'utf-8') as Uint8Array;\n const contentStartPos = updatedContent.indexOf('\\n---\\n') + 5; // Position after frontmatter\n const etags = calculateEtagsFromMdxBuffer(repairedBuffer, contentStartPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Return the repaired data. Strip leading newlines so the\n // body matches what the author wrote — see `readLocaleFile`.\n return {\n content: { mdx: parsed.content.replace(/^\\n+/, '') },\n etag,\n modified: parsed.data.modified || now,\n };\n }\n } else {\n // Read the full JSON file\n const content = await readFile(filePath, 'utf-8');\n const data: VXJSONFile = JSON.parse(content);\n\n // Check for missing fields\n if (!data.id) {\n data.id = manifest.id;\n needsWrite = true;\n }\n if (!data.created) {\n data.created = now;\n needsWrite = true;\n }\n if (!data.modified) {\n data.modified = now;\n needsWrite = true;\n }\n\n // Always rewrite VXJSON files during repair to ensure correct field order\n needsWrite = true;\n\n if (needsWrite) {\n // Write back with VXJSON format\n const vxjsonData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n const repairedJson = VXJSON.serialize(vxjsonData);\n await writeFile(filePath, repairedJson);\n console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);\n // Return the repaired data\n\n // Calculate ETags from the repaired JSON\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const etagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!etagResult.success) {\n console.error(`Failed to calculate ETags after repair: ${filePath}`);\n return null;\n }\n\n const etag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n\n // Return the complete repaired data\n return {\n content: vxjsonData.content,\n etag,\n modified: vxjsonData.modified,\n };\n }\n }\n\n // For MDX or no repair needed, return null\n return null;\n } catch (error) {\n console.error(`Failed to perform read-repair on ${filePath}:`, error);\n return null;\n }\n }\n\n private async scanContentFiles(): Promise<string[]> {\n const files: string[] = [];\n const contentRoot = this.absoluteContentRoot;\n\n async function scan(dir: string, inDataDir = false) {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n // Check if we're entering the data/ directory\n const isDataDir = dir === contentRoot && entry.name === 'data';\n await scan(fullPath, inDataDir || isDataDir);\n } else if (entry.isFile()) {\n // Include .vxjson and .mdx files everywhere\n // Include .json files only in the data/ directory\n if (entry.name.endsWith('.vxjson') || entry.name.endsWith('.mdx')) {\n files.push(fullPath);\n } else if (inDataDir && entry.name.endsWith('.json')) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Directory doesn't exist yet\n }\n }\n\n await scan(this.absoluteContentRoot);\n\n // Also scan mdxPagesRoot for .mdx files when the second root is configured.\n // Supports projects that store mdx-type pages outside the main content\n // tree (the rendering pipeline that consumes them is the project's choice).\n //\n // Skip the second scan when mdxPagesRoot is the same as contentRoot OR\n // nested inside it — the first scan already walked those files, and a\n // second pass would push every `.mdx` onto `files` twice. The nested case\n // is the documented Starlight pattern (`contentRoot: './src/content'`,\n // `mdxPagesRoot: './src/content/docs'`), so the prefix check matters in\n // practice.\n if (\n this.absoluteMdxPagesRoot &&\n this.absoluteMdxPagesRoot !== this.absoluteContentRoot &&\n !this.absoluteMdxPagesRoot.startsWith(this.absoluteContentRoot + '/')\n ) {\n async function scanMdxPages(dir: string) {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n await scanMdxPages(fullPath);\n } else if (entry.isFile() && entry.name.endsWith('.mdx')) {\n files.push(fullPath);\n }\n }\n } catch (error) {\n // Directory doesn't exist yet\n }\n }\n await scanMdxPages(this.absoluteMdxPagesRoot);\n }\n\n return files;\n }\n\n private getFilePath(manifest: ContentIdentity, { locale, name, pathname }: LocalePathData): string {\n if (manifest.kind === 'block') {\n const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';\n return join(this.absoluteContentRoot, 'blocks', manifest.collection, `${name}.${locale}.${ext}`);\n }\n if (manifest.kind === 'data') {\n return join(this.absoluteContentRoot, 'data', manifest.collection, `${name}.${locale}.json`);\n }\n if (manifest.kind === 'page' && pathname) {\n // For pages, derive path from pathname\n const basePath = pathname.replace(/^\\//, '').replace(/\\/$/, '') || 'index';\n\n // mdx-type pages live under absoluteMdxPagesRoot when configured.\n // The locale appears as a directory segment for non-default locales;\n // the default locale's files live at the root with no locale prefix.\n if (manifest.type === 'mdx' && this.absoluteMdxPagesRoot) {\n return locale === this.mdxPagesDefaultLocale\n ? join(this.absoluteMdxPagesRoot, `${basePath}.mdx`)\n : join(this.absoluteMdxPagesRoot, locale, `${basePath}.mdx`);\n }\n\n // Pages live under contentRoot/{site}/{collection}. When type:'mdx'\n // and no `mdxPages` path is configured for the site, the .mdx files\n // sit here alongside the .vxjson Puck pages — the layout chosen\n // when sites.json doesn't declare a separate `mdxPages` path.\n if (manifest.site) {\n const ext = manifest.type === 'mdx' ? 'mdx' : 'vxjson';\n return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.${ext}`);\n }\n }\n throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);\n }\n\n /**\n * Parse a file path back into its components for checking against the path index\n * Returns null if the path doesn't match expected patterns\n */\n parseFilePath(filePath: string): {\n kind: 'page' | 'block' | 'data';\n site?: string;\n collection: string;\n pathname?: string;\n name?: string;\n locale: string;\n } | null {\n // Files under mdxPagesRoot are kind:'page' + type:'mdx' regardless of\n // their position relative to absoluteContentRoot. Mirror the parsing\n // performed in parseFileHeaderWithRepair so both code paths agree on\n // the derived (pathname, locale) tuple.\n if (this.absoluteMdxPagesRoot && filePath.startsWith(this.absoluteMdxPagesRoot + '/')) {\n const mdxRelativePath = filePath.replace(this.absoluteMdxPagesRoot + '/', '');\n const mdxParts = mdxRelativePath.split('/');\n const mdxFilename = mdxParts[mdxParts.length - 1];\n let locale: string;\n let pathname: string;\n\n const noLocaleMatch = mdxFilename.match(/^(.+)\\.mdx$/);\n if (!noLocaleMatch) return null;\n mdxParts[mdxParts.length - 1] = noLocaleMatch[1];\n\n // Membership-based locale detection — mirrors parseFileHeaderWithRepair\n // so both paths classify the same file identically.\n if (mdxParts.length > 1 && this.availableLocales.has(mdxParts[0])) {\n locale = mdxParts[0];\n const slugParts = mdxParts.slice(1);\n pathname =\n slugParts[slugParts.length - 1] === 'index'\n ? '/' + slugParts.slice(0, -1).join('/') || '/'\n : '/' + slugParts.join('/');\n } else {\n locale = this.mdxPagesDefaultLocale;\n pathname =\n mdxParts[mdxParts.length - 1] === 'index'\n ? '/' + mdxParts.slice(0, -1).join('/') || '/'\n : '/' + mdxParts.join('/');\n }\n\n return {\n kind: 'page',\n site: this.mdxPagesSite,\n collection: this.mdxPagesCollection,\n pathname,\n locale,\n };\n }\n\n // Remove contentRoot prefix\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n const parts = relativePath.split('/');\n\n // Match locale.ext pattern at the end\n const filename = parts[parts.length - 1];\n\n // Handle data files: data/{collection}/{name}.{locale}.json\n if (parts[0] === 'data' && parts.length === 3) {\n const dataMatch = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.json$/);\n if (!dataMatch) return null;\n const [, name, locale] = dataMatch;\n return {\n kind: 'data',\n collection: parts[1],\n name,\n locale,\n };\n }\n\n // Match locale.ext pattern for non-data files (vxjson, mdx)\n const match = filename.match(/^(.+)\\.([a-z]{2}(?:-[A-Z]{2})?)\\.(?:vxjson|mdx)$/);\n if (!match) return null;\n\n const [, nameOrPath, locale] = match;\n\n if (parts[0] === 'blocks' && parts.length === 3) {\n // blocks/collection/name.locale.ext\n return {\n kind: 'block',\n collection: parts[1],\n name: nameOrPath,\n locale,\n };\n }\n if (parts.length >= 3 && parts[0] !== 'blocks') {\n // site/collection/pathname.locale.vxjson\n const site = parts[0];\n const collection = parts[1];\n // Reconstruct pathname from remaining parts\n const pathParts = parts.slice(2, -1); // All dirs between collection and filename\n pathParts.push(nameOrPath); // Add the filename part (without locale.ext)\n const pathname = '/' + pathParts.join('/');\n\n return {\n kind: 'page',\n site,\n collection,\n pathname,\n locale,\n };\n }\n\n return null;\n }\n\n async getContent(id: string): Promise<ContentEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return null;\n }\n\n // Read all locale files in parallel\n const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n const content = await this.readLocaleFile(filePath, localeVersion.locale);\n return { localeVersion, content };\n });\n\n const results = await Promise.all(readPromises);\n\n // Build locales with content\n const locales: Record<string, LocaleVersion & ContentProp> = {};\n for (const { localeVersion, content } of results) {\n if (content) {\n locales[localeVersion.locale] = {\n ...localeVersion,\n etag: content.etag, // Use fresh etag from file, not stale manifest etag\n content: content.content,\n };\n }\n }\n\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n locales,\n };\n }\n\n async getLocalized(id: string, locale: string): Promise<LocalizedEntry | null> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n // File might have been added after indexing - try reindexing\n await this.reindex();\n\n // Try again with updated index\n const updatedManifest = this.contentIndex.getManifest(id);\n if (!updatedManifest || !updatedManifest.locales[locale]) {\n return null;\n }\n\n return this.getLocalized(id, locale);\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return null;\n }\n\n // Read the locale-specific file\n const filePath = this.getFilePath(manifest, localeVersion);\n const localeData = await this.readLocaleFile(filePath, locale);\n if (!localeData) {\n return null;\n }\n\n // Build LocalizedEntry\n return {\n id: manifest.id,\n site: manifest.site,\n collection: manifest.collection,\n type: manifest.type,\n kind: manifest.kind,\n localized: {\n ...localeVersion,\n etag: localeData.etag, // Use fresh etag from file, not stale manifest etag\n content: localeData.content,\n },\n };\n }\n\n private async readLocaleFile(filePath: string, locale: string): Promise<LocaleFileData | null> {\n try {\n const buffer = (await readFile(filePath)) as Uint8Array;\n const content = textDecoder.decode(buffer);\n\n if (filePath.endsWith('.mdx')) {\n const { data: frontmatter, content: rawBody } = matter(content, {});\n // gray-matter leaves the blank line after the closing `---` on\n // the body. Strip leading newlines so the round-trip matches the\n // body the author wrote.\n const body = rawBody.replace(/^\\n+/, '');\n\n // Calculate etags from the file buffer\n const contentPos = findMdxContentStartPosition(buffer);\n\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n const etag = `${etags.metaEtag}.${etags.contentEtag}`;\n\n // Extract special fields from frontmatter, everything else is metadata\n const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;\n\n // Body-only — frontmatter is server-owned and surfaced separately\n // via `meta` / `created` / `modified`. Returning the full file here\n // would let the editor round-trip the YAML block as body text, which\n // duplicates the frontmatter on disk when content is inserted above\n // it (proven on assets.mdx, 2026-05-11).\n const result: LocaleFileData = {\n locale,\n etag,\n created: created,\n modified: modified,\n meta: metaFields as ContentMeta,\n content: { mdx: body },\n };\n\n // Only add publish dates if they exist\n if (frontmatter.publishAt !== undefined) {\n result.publishAt = frontmatter.publishAt;\n }\n if (frontmatter.unpublishAt !== undefined) {\n result.unpublishAt = frontmatter.unpublishAt;\n }\n\n return result;\n }\n\n // Parse JSON data first to determine type\n const data = JSON.parse(content);\n\n // Handle JSON data files (type: 'json') separately - they use simple etag\n if (data.type === 'json') {\n const etag = VXJSON.calculateSimpleEtag(buffer);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: { data: data.data || {} },\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n\n return result;\n }\n\n // For VXJSON (puck pages), calculate ETags with meta/content split\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n // File needs repair - parse it and rewrite in correct format\n const repairedData: VXJSONFile = {\n id: data.id,\n type: data.type,\n created: data.created,\n modified: data.modified,\n publishAt: data.publishAt,\n unpublishAt: data.unpublishAt,\n previousPathnames: data.previousPathnames,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Rewrite file with correct format\n const repairedJson = VXJSON.serialize(repairedData);\n await writeFile(filePath, repairedJson);\n\n // Recalculate ETags from repaired buffer\n const repairedBuffer = Buffer.from(repairedJson, 'utf-8') as Uint8Array;\n const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);\n\n if (!repairedEtagResult.success) {\n throw new Error(`Failed to repair VXJSON file: ${filePath}`);\n }\n\n const etag = repairedEtagResult.contentEtag\n ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}`\n : repairedEtagResult.metaEtag;\n\n console.log(`Repaired VXJSON file: ${filePath}`);\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n }\n\n const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n const result: LocaleFileData = {\n locale,\n etag,\n created: data.created,\n modified: data.modified,\n meta: data.meta || {},\n content: data.content || {},\n };\n\n // Only add optional fields if they exist\n if (data.publishAt !== undefined) {\n result.publishAt = data.publishAt;\n }\n if (data.unpublishAt !== undefined) {\n result.unpublishAt = data.unpublishAt;\n }\n if (data.previousPathnames !== undefined) {\n result.previousPathnames = data.previousPathnames;\n }\n\n return result;\n } catch (error) {\n return null;\n }\n }\n\n async createContent(data: CreateContentInput): Promise<CreateResult> {\n // Use shared validation\n const validation = validateCreateContent(data, this.sites, this.blocks, this.data);\n if (!validation.valid) {\n return {\n success: false,\n reason: validation.reason,\n error: validation.error ? new Error(validation.error) : undefined,\n existingId: validation.existingId,\n };\n }\n\n const id = generateContentId();\n const now = data.created || new Date().toISOString();\n\n try {\n // Build the manifest with all locales\n const manifest: ContentManifest = {\n id,\n type: data.type,\n kind: data.kind,\n site: data.site,\n collection: data.collection,\n locales: {},\n };\n\n const contentCache: Record<string, ContentData> = {};\n\n // Create files for each locale\n for (const [locale, localeData] of Object.entries(data.locales)) {\n const content = localeData.content;\n\n // Build metadata with required title\n const title = localeData.meta?.title || data.meta?.title;\n if (!title) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error('Title is required in metadata'),\n };\n }\n\n // Build complete metadata\n const meta: ContentMeta = {\n title,\n ...data.meta,\n ...localeData.meta,\n };\n\n const fileData: VXJSONFile = {\n id,\n type: data.type,\n created: now,\n modified: now,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n meta,\n content,\n };\n\n // Use the proper getFilePath method\n const filePath = this.getFilePath(manifest, { locale, name: data.name, pathname: localeData.pathname });\n\n // Ensure directory exists\n await mkdir(dirname(filePath), { recursive: true });\n\n // Write file and calculate etag from the serialized content\n let etag: string;\n\n if (data.type === 'mdx') {\n // Write MDX with frontmatter - flatten metadata fields\n const frontmatterData = {\n id,\n created: now,\n modified: now,\n ...(localeData.publishAt && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt && { unpublishAt: localeData.unpublishAt }),\n ...meta, // Spread metadata fields directly, not nested\n };\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, content.mdx || '');\n await writeFile(filePath, mdxContent);\n\n // For MDX, calculate etags from the serialized content\n const mdxBuffer = new TextEncoder().encode(mdxContent);\n // For MDX, all frontmatter is metadata, content starts after ---\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (mdxBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (data.type === 'json') {\n // Data files use \"data\" field instead of \"content\"\n const dataFileContent = {\n id,\n type: 'json',\n created: now,\n modified: now,\n ...(localeData.publishAt &&\n typeof localeData.publishAt === 'string' && { publishAt: localeData.publishAt }),\n ...(localeData.unpublishAt &&\n typeof localeData.unpublishAt === 'string' && { unpublishAt: localeData.unpublishAt }),\n meta,\n data: content.data || {},\n };\n\n const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, '\\t');\n await writeFile(filePath, jsonContent);\n\n // For data files, use simple etag (hash entire buffer)\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n etag = VXJSON.calculateSimpleEtag(jsonBuffer);\n } else {\n // VXJSON for pages (puck)\n const jsonContent = VXJSON.serialize(fileData);\n const jsonBuffer = new TextEncoder().encode(jsonContent);\n\n // Calculate etags from the buffer\n const etagResult = VXJSON.calculateETags(jsonBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n\n // Write the file\n await writeFile(filePath, jsonContent);\n }\n\n // Build locale manifest using shared function\n const localeVersion = buildLocaleVersion({\n locale,\n etag,\n created: now,\n modified: now,\n meta,\n kind: data.kind,\n pathname: data.kind === 'page' ? localeData.pathname : undefined,\n name: data.kind === 'block' || data.kind === 'data' ? data.name : undefined,\n publishAt:\n localeData.publishAt && typeof localeData.publishAt === 'string' ? localeData.publishAt : undefined,\n unpublishAt:\n localeData.unpublishAt && typeof localeData.unpublishAt === 'string' ? localeData.unpublishAt : undefined,\n });\n\n // Add locale to manifest\n manifest.locales[locale] = localeVersion;\n contentCache[locale] = content;\n }\n\n // Add each locale to the index\n for (const localeVersion of localesOf(manifest)) {\n const { locale } = localeVersion;\n this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);\n }\n\n return { success: true, id };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult> {\n const { id, locale, data, etag } = input;\n\n // Get the manifest\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get the specific locale manifest\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Get file path and read current content FIRST to get fresh etag\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, locale);\n if (!current) {\n return {\n success: false,\n reason: 'not_found',\n };\n }\n\n // Use fresh etag from file, not stale manifest etag\n const currentEtag = current.etag;\n\n // Check etag - data files use simple etags, others use dual etags\n if (manifest.kind === 'data') {\n // Data files use simple etag (single hash, no dot separator)\n // Just compare the full etag directly\n if (etag !== currentEtag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n } else {\n // Non-data files use dual etags (meta.content format)\n const etagParts = parseDualEtag(etag);\n const currentParts = parseDualEtag(currentEtag);\n\n if (!etagParts || !currentParts) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n // Check which parts are being updated\n const updateScope = analyzeUpdateScope(data);\n const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;\n const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;\n\n // Validate etags for parts being updated\n if (updatingMeta && etagParts.meta !== currentParts.meta) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n\n if (updatingContent && etagParts.content !== currentParts.content) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag,\n };\n }\n }\n\n // Update modified timestamp for any change (metadata or content)\n let modified: string;\n if (shouldUpdateModifiedTimestamp(data)) {\n // Use provided modified timestamp or current time\n modified = data.modified || new Date().toISOString();\n } else if (data.modified) {\n // If modified timestamp is explicitly provided, always use it\n modified = data.modified;\n } else {\n // No changes and no explicit timestamp, keep current\n modified = current.modified;\n }\n\n const {\n sortedMeta: newMeta,\n valid: metaValid,\n error: metaError,\n } = validateAndPrepareMetadata({ ...current.meta, ...(data.meta ? data.meta : {}) });\n\n // Validate new metadata\n if (!newMeta || !metaValid) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(metaError),\n };\n }\n\n // Merge updates\n const newContent = data.content ? { ...current.content, ...data.content } : current.content;\n\n // Validate pathname change if updating pathname for pages\n if (data.pathname && manifest.kind === 'page' && manifest.site) {\n const site = this.sites[manifest.site];\n if (site) {\n // Check if new pathname is already taken by another content\n const existingId = site.getPathnameConflict(data.pathname, locale, id);\n if (existingId) {\n return {\n success: false,\n reason: 'write_error',\n error: new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`),\n };\n }\n }\n }\n\n // Validate name change if updating name for blocks or data\n if (data.name && (manifest.kind === 'block' || manifest.kind === 'data')) {\n // Check if new name is already taken by another entry in the same collection\n const index = manifest.kind === 'block' ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex();\n const existing = index.getByName(manifest.collection, data.name);\n\n if (existing && existing.id !== id) {\n // Get title from the existing entry for a better error message\n const existingLocale = Object.values(existing.locales).find((lv) => lv !== undefined);\n const existingTitle = existingLocale?.meta?.title;\n const kindLabel = manifest.kind === 'block' ? 'Block' : 'Data';\n\n return {\n success: false,\n reason: 'write_error',\n error: new Error(\n `${kindLabel} name \"${data.name}\" is already in use${existingTitle ? ` by \"${existingTitle}\"` : ''}`,\n ),\n };\n }\n }\n\n // Handle pathname changes - track history only for published content\n const pathnameHistory = buildPathnameHistory(\n localeVersion.pathname,\n data.pathname,\n isContentPublished({\n publishAt: resolvePublishDate(data.publishAt, current.publishAt),\n unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt),\n }),\n new Date().toISOString(),\n );\n\n try {\n // Determine the target file path (may be different if pathname or name changed)\n let targetFilePath = filePath;\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {\n // For pages, calculate new file path based on new pathname\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n pathname: data.pathname,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n } else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === 'block') {\n // For blocks, calculate new file path based on new name\n const newLocaleVersion: LocaleVersion = {\n ...localeVersion,\n name: data.name,\n };\n targetFilePath = this.getFilePath(manifest, newLocaleVersion);\n\n // Ensure target directory exists\n await mkdir(dirname(targetFilePath), { recursive: true });\n }\n\n // Write updated content\n if (targetFilePath.endsWith('.mdx')) {\n // Build frontmatter with special fields and metadata\n const publishAt = resolvePublishDate(data.publishAt, current.publishAt);\n const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);\n const frontmatterData = {\n id: manifest.id,\n created: current.created,\n modified,\n ...(publishAt && { publishAt }),\n ...(unpublishAt && { unpublishAt }),\n ...newMeta, // Spread metadata fields directly\n };\n\n // Extract just the content part from MDX (remove frontmatter if present)\n let mdxContentPart = newContent.mdx || '';\n if (mdxContentPart.startsWith('---')) {\n // Remove frontmatter if it exists\n const { content: contentOnly } = matter(mdxContentPart, {});\n mdxContentPart = contentOnly;\n }\n\n // Defensive guard: warn when a frontmatter-shaped block appears\n // mid-body. The load path strips frontmatter before it reaches the\n // editor, so this should never occur — if it does, surface it for\n // investigation instead of silently writing a file with stacked\n // frontmatter blocks.\n if (/\\n---\\r?\\n[\\s\\S]*?\\r?\\n---(\\r?\\n|$)/.test(mdxContentPart)) {\n console.warn(\n `[content-api] Embedded frontmatter-shaped block detected in body for ${targetFilePath}. ` +\n 'This indicates a load-path regression or client-side leak.',\n );\n }\n\n const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);\n\n // Atomic write for MDX files\n await atomicWriteFile(targetFilePath, mdxContent);\n } else if (targetFilePath.endsWith('.json')) {\n // Data files use \"data\" field instead of \"content\"\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated data file structure\n const updatedFile = {\n id: fileContent.id,\n type: 'json' as const,\n created: fileContent.created,\n modified,\n ...(fileContent.publishAt && { publishAt: fileContent.publishAt }),\n ...(fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt }),\n meta: newMeta,\n data: sortKeys(newContent.data || {}, { deep: true }),\n };\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n (updatedFile as Record<string, unknown>).publishAt = data.publishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n (updatedFile as Record<string, unknown>).unpublishAt = data.unpublishAt;\n } else {\n delete (updatedFile as Record<string, unknown>).unpublishAt;\n }\n }\n\n // Serialize data file\n const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, '\\t');\n\n // Atomic write for JSON data files\n await atomicWriteFile(targetFilePath, serializedContent);\n } else {\n // VXJSON for pages (puck)\n const fileContent = JSON.parse(await readFile(filePath, 'utf-8'));\n\n // Build updated VXJSONFile structure\n const updatedFile: VXJSONFile = {\n id: fileContent.id,\n type: fileContent.type,\n created: fileContent.created,\n modified,\n publishAt: fileContent.publishAt,\n unpublishAt: fileContent.unpublishAt,\n previousPathnames: fileContent.previousPathnames,\n meta: newMeta,\n content: sortKeys(newContent, { deep: true }),\n };\n\n // Handle pathname changes and track history\n if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {\n // Only add to history if content is published\n if (isContentPublished(current)) {\n if (!updatedFile.previousPathnames) {\n updatedFile.previousPathnames = {};\n }\n updatedFile.previousPathnames[localeVersion.pathname] = modified;\n }\n }\n\n // Handle publish date updates\n if ('publishAt' in data) {\n if (data.publishAt) {\n updatedFile.publishAt = data.publishAt;\n } else {\n delete updatedFile.publishAt;\n }\n }\n\n if ('unpublishAt' in data) {\n if (data.unpublishAt) {\n updatedFile.unpublishAt = data.unpublishAt;\n } else {\n delete updatedFile.unpublishAt;\n }\n }\n\n // Serialize using VXJSON format to ensure content is last\n const serializedContent = VXJSON.serialize(updatedFile);\n\n // Atomic write for VXJSON page files\n await atomicWriteFile(targetFilePath, serializedContent);\n }\n\n // Calculate new etag from the written file\n const writtenBuffer = (await readFile(targetFilePath)) as Uint8Array;\n let newEtag: string;\n\n if (targetFilePath.endsWith('.mdx')) {\n // Find content position in MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (writtenBuffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);\n newEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (targetFilePath.endsWith('.json')) {\n // For data files, use simple etag (hash entire buffer)\n newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);\n } else {\n // For VXJSON, calculateEtagsFromVXJSONBuffer finds the content position internally\n const etagResult = VXJSON.calculateETags(writtenBuffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);\n }\n\n newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n // Build updated locale manifest with current publish data\n const updatedLocaleVersion: LocaleVersion = {\n ...localeVersion,\n etag: newEtag,\n modified,\n meta: newMeta,\n ...(data.pathname && { pathname: data.pathname }),\n ...(data.name && { name: data.name }),\n };\n\n // Handle publish dates using shared function\n // First preserve current values if not updating\n if (current.publishAt && !('publishAt' in data)) {\n updatedLocaleVersion.publishAt = current.publishAt;\n }\n if (current.unpublishAt && !('unpublishAt' in data)) {\n updatedLocaleVersion.unpublishAt = current.unpublishAt;\n }\n\n // Then apply updates\n updatePublishDates(updatedLocaleVersion, data);\n\n // Update pathname history if changed\n if (Object.keys(pathnameHistory).length > 0) {\n updatedLocaleVersion.previousPathnames = {\n ...localeVersion.previousPathnames,\n ...pathnameHistory,\n };\n } else {\n // Preserve existing previousPathnames if no change, but only if it has content\n const existingPreviousPathnames = localeVersion.previousPathnames;\n if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) {\n updatedLocaleVersion.previousPathnames = existingPreviousPathnames;\n } else {\n // Remove empty previousPathnames object\n delete updatedLocaleVersion.previousPathnames;\n }\n }\n\n // Store the old locale manifest for rollback if needed\n const oldLocaleVersion = manifest.locales[locale];\n\n try {\n // Update the locale in the existing manifest directly (avoids allocation)\n manifest.locales[locale] = updatedLocaleVersion;\n\n // Update index with the updated locale\n this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);\n\n // If pathname changed, delete the old file\n if (targetFilePath !== filePath) {\n try {\n await unlink(filePath);\n } catch (error) {\n // Log but don't fail if old file deletion fails\n console.warn(`Failed to delete old file ${filePath}:`, error);\n }\n }\n } catch (error) {\n // Rollback on error to maintain consistency\n manifest.locales[locale] = oldLocaleVersion;\n\n // If we wrote to a new file, try to clean it up\n if (targetFilePath !== filePath) {\n try {\n await unlink(targetFilePath);\n } catch {\n // Ignore cleanup errors\n }\n }\n\n throw error;\n }\n\n return {\n success: true,\n etag: newEtag,\n modified: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n reason: 'write_error',\n error: ensureError(error),\n };\n }\n }\n\n async deleteContent(id: string, etag: string): Promise<DeleteResult> {\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // For deleteContent, we require the etag to match ANY locale (indicating user has current data)\n // But this is still a design flaw - we should probably require all etags or a master etag\n let matchingLocale: LocaleVersion | undefined;\n for (const localeVersion of localesOf(manifest)) {\n if (localeVersion.etag === etag) {\n matchingLocale = localeVersion;\n break;\n }\n }\n if (!matchingLocale) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: Array.from(localesOf(manifest))[0]?.etag || '',\n error: new Error('Invalid etag - must match at least one locale'),\n };\n }\n\n try {\n // Delete all locale files in parallel\n const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n });\n\n await Promise.all(deletePromises);\n\n // Remove from index\n this.contentIndex.removeEntry(id);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n async deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult> {\n const { id, locale, etag } = input;\n\n // Get manifest for this ID\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Content not found'),\n };\n }\n\n // Check if this locale exists\n const localeVersion = manifest.locales[locale];\n if (!localeVersion) {\n return {\n success: false,\n reason: 'not_found',\n error: new Error('Locale not found'),\n };\n }\n\n // Verify etag matches this locale\n if (localeVersion.etag !== etag) {\n return {\n success: false,\n reason: 'stale_write',\n currentEtag: localeVersion.etag,\n error: new Error('Invalid etag for locale'),\n };\n }\n\n // Don't allow deleting the last locale\n if (Object.keys(manifest.locales).length === 1) {\n return {\n success: false,\n error: new Error('Cannot delete the last locale. Use deleteContent to delete all content.'),\n };\n }\n\n try {\n // Delete the locale file\n const filePath = this.getFilePath(manifest, localeVersion);\n await unlink(filePath);\n\n // Remove locale from manifest and index\n manifest.locales[locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, locale);\n\n return { success: true };\n } catch (error) {\n return {\n success: false,\n error: ensureError(error),\n };\n }\n }\n\n getSite(siteName: string): Site | null {\n if (siteName === 'blocks') {\n throw new Error('Use `blocks` property instead of getSite(\"blocks\")');\n }\n\n const site = this.sites[siteName];\n return site || null;\n }\n\n *listAllContent(filters?: GlobalFilters): Generator<ContentManifest> {\n yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);\n }\n *findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest> {\n yield* this.contentIndex.findUntranslatedContent(targetLocale, options);\n }\n\n /**\n * Reindex files that were added or changed after initial creation\n *\n * This method:\n * 1. Either scans for all content files or processes specific paths\n * 2. Uses the path index to check if files are already indexed\n * 3. Indexes new files or force-reindexes specified files\n * 4. Optionally handles file deletions\n *\n * @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.\n * @param options - Options for reindexing behavior\n * @returns Statistics about the reindexing operation\n */\n async reindex(paths?: string[], options?: { handleDeletions?: boolean }): Promise<ReindexResult> {\n const filesToProcess = paths || (await this.scanContentFiles());\n let filesSkipped = 0;\n let filesProcessed = 0;\n let filesDeleted = 0;\n let errors = 0;\n const filesToIndex: string[] = [];\n const updated: LocalizedManifest[] = [];\n const deleted: Array<{ id: string; locale: string; kind: 'page' | 'block' | 'data' }> = [];\n\n // Check each file\n for (const filePath of filesToProcess) {\n // Check if file exists (for deletion handling)\n if (options?.handleDeletions && paths) {\n try {\n await readFile(filePath);\n } catch (error) {\n // File doesn't exist - remove from index\n const parsed = this.parseFilePath(filePath);\n if (parsed) {\n // Find the content ID to remove\n let manifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (manifest) {\n // Track the deletion\n deleted.push({\n id: manifest.id,\n locale: parsed.locale,\n kind: parsed.kind,\n });\n\n // Remove the specific locale or entire entry if it's the last locale\n if (Object.keys(manifest.locales).length === 1) {\n this.contentIndex.removeEntry(manifest.id);\n } else {\n // Remove just this locale\n manifest.locales[parsed.locale] = undefined;\n this.contentIndex.removeLocale(manifest.id, parsed.locale);\n }\n filesDeleted++;\n }\n }\n continue;\n }\n }\n\n const parsed = this.parseFilePath(filePath);\n if (!parsed) {\n console.warn(`Skipping unrecognized file pattern: ${filePath}`);\n errors++;\n continue;\n }\n\n // Check if this path is already indexed\n let isIndexed = false;\n if (parsed.kind === 'block' && parsed.name) {\n // Check block index by name\n const manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n // Check site index by pathname\n const manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n isIndexed = !!manifest;\n } else if (parsed.kind === 'data' && parsed.name) {\n // Check data index by name\n const manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n isIndexed = !!manifest;\n }\n\n if (isIndexed) {\n if (!paths) {\n // Skip already indexed files when doing a full scan\n filesSkipped++;\n } else {\n // For specific paths, check if the file has changed\n const fileStats = await readFile(filePath);\n let currentManifest: ContentManifest | null = null;\n if (parsed.kind === 'block' && parsed.name) {\n currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'data' && parsed.name) {\n currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);\n } else if (parsed.kind === 'page' && parsed.site && parsed.pathname) {\n currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);\n }\n\n if (currentManifest) {\n // Calculate current file etag\n const buffer = fileStats as Uint8Array;\n let currentEtag: string;\n\n if (filePath.endsWith('.mdx')) {\n const contentPos = findMdxContentStartPosition(buffer);\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else if (filePath.endsWith('.vxjson')) {\n const etagResult = VXJSON.calculateETags(buffer);\n if (!etagResult.success) {\n // File needs repair - add to filesToIndex for repair\n filesToIndex.push(filePath);\n continue;\n }\n currentEtag = etagResult.contentEtag\n ? `${etagResult.metaEtag}.${etagResult.contentEtag}`\n : etagResult.metaEtag;\n } else if (filePath.endsWith('.json')) {\n // For JSON data files, use content hash as etag\n currentEtag = xxh64(buffer).toString(16);\n } else {\n // Unknown file type, skip\n filesSkipped++;\n continue;\n }\n\n // Only reindex if etag changed\n const existingEtag = currentManifest.locales[parsed.locale]?.etag;\n\n if (existingEtag === currentEtag) {\n const relativePath = filePath.replace(this.absoluteContentRoot + '/', '');\n console.log(`[Content] skip ${relativePath} (unchanged)`);\n filesSkipped++;\n } else {\n filesToIndex.push(filePath);\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n } else {\n // Not indexed yet\n filesToIndex.push(filePath);\n }\n }\n\n // Index the files\n const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));\n\n for (let i = 0; i < filesToIndex.length; i++) {\n const filePath = filesToIndex[i];\n const bufferIndex = i % buffers.length;\n\n try {\n const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);\n if (result) {\n const { manifest, localeVersion, content } = result;\n\n // Add to index\n this.contentIndex.addContent(manifest, localeVersion, content);\n filesProcessed++;\n\n // Create LocalizedManifest for the updated list\n const localizedManifest: LocalizedManifest = {\n id: manifest.id,\n type: manifest.type,\n kind: manifest.kind,\n site: manifest.site,\n collection: manifest.collection,\n localized: localeVersion,\n };\n updated.push(localizedManifest);\n }\n } catch (error) {\n console.error(`Failed to reindex ${filePath}:`, error);\n errors++;\n }\n }\n\n const result: ReindexResult = {\n filesProcessed,\n filesSkipped,\n updated,\n };\n\n if (options?.handleDeletions && deleted.length > 0) {\n result.filesDeleted = filesDeleted;\n result.deleted = deleted;\n }\n\n if (errors > 0) {\n result.errors = errors;\n }\n\n return result;\n }\n\n /**\n * Read content directly from cache\n * For testing purposes - returns null if not cached\n */\n async readFromCache(id: string, locale: string): Promise<ContentData | null> {\n return this.contentIndex.getCachedContent(id, locale);\n }\n\n async getContentAsBuffer(\n id: string,\n locale: string,\n ): Promise<{\n buffer: Uint8Array;\n etag: string;\n contentType: 'application/json' | 'text/mdx';\n } | null> {\n const manifest = this.contentIndex.getManifest(id);\n if (!manifest || !manifest.locales[locale]) {\n return null;\n }\n\n const localeVersion = manifest.locales[locale];\n const filePath = this.getFilePath(manifest, localeVersion);\n const buffer = (await readFile(filePath)) as Uint8Array;\n const contentType = filePath.endsWith('.mdx') ? 'text/mdx' : 'application/json';\n\n // Calculate ETag based on file type\n let etag: string;\n if (contentType === 'text/mdx') {\n // Find content start position for MDX\n const contentStartMarker = new TextEncoder().encode('---\\n\\n');\n let contentPos = -1;\n for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {\n let match = true;\n for (let j = 0; j < contentStartMarker.length; j++) {\n if (buffer[i + j] !== contentStartMarker[j]) {\n match = false;\n break;\n }\n }\n if (match) {\n contentPos = i + contentStartMarker.length;\n break;\n }\n }\n const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);\n etag = `${etags.metaEtag}.${etags.contentEtag}`;\n } else {\n // Calculate ETags for JSON\n const etagResult = VXJSON.calculateETags(buffer);\n\n if (!etagResult.success) {\n throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);\n }\n\n etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;\n }\n\n return { buffer, etag, contentType };\n }\n\n async batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult> {\n // First, validate all operations can succeed\n const validationResults: Array<{\n op: UpdateLocaleInput;\n manifest: ContentManifest;\n localeVersion: LocaleVersion;\n current?: LocaleFileData;\n }> = [];\n\n for (const op of operations) {\n const manifest = this.contentIndex.getManifest(op.id);\n if (!manifest) {\n // Content not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Content not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n const localeVersion = manifest.locales[op.locale];\n if (!localeVersion) {\n // Locale not found\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Locale not found'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Check etag\n if (localeVersion.etag !== op.etag) {\n // Stale write detected\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Stale write'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Read current content for validation\n const filePath = this.getFilePath(manifest, localeVersion);\n const current = await this.readLocaleFile(filePath, op.locale);\n if (!current) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error('Failed to read content'),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n\n // Validate metadata size if updating\n if (op.data.meta) {\n const newMeta = { ...current.meta, ...op.data.meta };\n const validation = validateAndPrepareMetadata(newMeta);\n if (!validation.valid) {\n return {\n operations: operations.map((o) => ({\n id: o.id,\n locale: o.locale,\n updated: false,\n error: new Error(validation.error!),\n })),\n success: false,\n updated: 0,\n failed: operations.length,\n };\n }\n }\n\n validationResults.push({ op, manifest, localeVersion, current });\n }\n\n // All validations passed, now perform updates\n const results: BatchOperationResult[] = [];\n let updated = 0;\n\n for (const { op } of validationResults) {\n const result = await this.updateLocalized(op);\n if (result.success) {\n updated++;\n results.push({ id: op.id, locale: op.locale, updated: true, etag: result.etag });\n } else {\n // This shouldn't happen if validation was correct\n results.push({ id: op.id, locale: op.locale, updated: false, error: result.error });\n }\n }\n\n return {\n operations: results,\n success: updated === operations.length,\n updated,\n failed: operations.length - updated,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,eAAsB,gBAAgB,UAAkB,SAAgC;CACtF,MAAM,SAAS,QAAQ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AgB,EAAE;GAC5C,IAAI,OAAO,SAAS;IAClB;IACA,QAAQ,KAAK;KAAE,IAAI,GAAG;KAAI,QAAQ,GAAG;KAAQ,SAAS;KAAM,MAAM,OAAO;IAAK,CAAC;GACjF,OAEE,QAAQ,KAAK;IAAE,IAAI,GAAG;IAAI,QAAQ,GAAG;IAAQ,SAAS;IAAO,OAAO,OAAO;GAAM,CAAC;EAEtF;EAEA,OAAO;GACL,YAAY;GACZ,SAAS,YAAY,WAAW;GAChC;GACA,QAAQ,WAAW,SAAS;EAC9B;CACF;AACF"}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { A as LocalizedEntry, L as SitesConfig, R as UpdateLocaleInput, T as GlobalFilters, _ as CreateResult, a as ContentAPIOptions, b as DeleteLocaleInput, h as CreateContentInput, j as LocalizedManifest, o as ContentData, r as BatchResult, s as ContentEntry, u as ContentManifest, w as FindOptions, x as DeleteResult, z as UpdateResult } from "./types-DjfhS272.mjs";
|
|
2
|
+
import { M as ContentAPI, N as Site, P as Data, j as Blocks } from "./content-operations-DIbsxG5A.mjs";
|
|
3
|
+
//#region src/filesystem-content-api.d.ts
|
|
4
|
+
interface ReindexResult {
|
|
5
|
+
filesProcessed: number;
|
|
6
|
+
filesSkipped: number;
|
|
7
|
+
filesDeleted?: number;
|
|
8
|
+
errors?: number;
|
|
9
|
+
updated: LocalizedManifest[];
|
|
10
|
+
deleted?: Array<{
|
|
11
|
+
id: string;
|
|
12
|
+
locale: string;
|
|
13
|
+
kind: 'page' | 'block' | 'data';
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* FileSystem-based Content API Implementation
|
|
18
|
+
*
|
|
19
|
+
* Stores content as files on disk in a git-friendly format:
|
|
20
|
+
* - Pages: /{site}/pages/{filename}.{locale}.vxjson
|
|
21
|
+
* - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
|
|
22
|
+
*
|
|
23
|
+
* ## Indexing
|
|
24
|
+
*
|
|
25
|
+
* Content is indexed at startup for performance. The index is cached per
|
|
26
|
+
* content root path and cleared when the process restarts.
|
|
27
|
+
*
|
|
28
|
+
* ## Read-Repair
|
|
29
|
+
*
|
|
30
|
+
* Since files can be modified externally (git, editors), this implementation:
|
|
31
|
+
*
|
|
32
|
+
* 1. Repairs invalid VXJSON files (ensures "content" field is last)
|
|
33
|
+
* 2. Adds missing required fields (id, created, modified)
|
|
34
|
+
* 3. Handles files added after initial indexing
|
|
35
|
+
* 4. Updates the index when files are repaired or discovered
|
|
36
|
+
*
|
|
37
|
+
* ## Performance
|
|
38
|
+
*
|
|
39
|
+
* - Initial indexing reads only first 4KB of each file
|
|
40
|
+
* - Full content is loaded on demand
|
|
41
|
+
* - ETags are calculated using streaming for efficiency
|
|
42
|
+
*/
|
|
43
|
+
/**
|
|
44
|
+
* Read and validate `<contentRoot>/sites.json`. Returns a safe default
|
|
45
|
+
* (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
|
|
46
|
+
* has invalid structure, with a warning logged in each case.
|
|
47
|
+
*
|
|
48
|
+
* Exported standalone so the Astro integration (and any other tooling
|
|
49
|
+
* that needs to inspect per-site config at startup time) can read the
|
|
50
|
+
* config without spinning up a full content-api instance.
|
|
51
|
+
*/
|
|
52
|
+
declare function readSitesConfig(contentRoot: string): Promise<SitesConfig>;
|
|
53
|
+
declare class FileSystemContentAPI implements ContentAPI {
|
|
54
|
+
private contentRoot;
|
|
55
|
+
private absoluteContentRoot;
|
|
56
|
+
private contentIndex;
|
|
57
|
+
readonly sitesConfig: SitesConfig;
|
|
58
|
+
readonly blocks: Blocks;
|
|
59
|
+
readonly data: Data;
|
|
60
|
+
private readonly sites;
|
|
61
|
+
private absoluteMdxPagesRoot?;
|
|
62
|
+
private mdxPagesDefaultLocale;
|
|
63
|
+
private mdxPagesSite;
|
|
64
|
+
private mdxPagesCollection;
|
|
65
|
+
private readonly availableLocales;
|
|
66
|
+
get normalizedContentRoot(): string;
|
|
67
|
+
private constructor();
|
|
68
|
+
static create(options: ContentAPIOptions): Promise<FileSystemContentAPI>;
|
|
69
|
+
/**
|
|
70
|
+
* Clear all caches - useful for testing
|
|
71
|
+
*/
|
|
72
|
+
static clearCaches(): void;
|
|
73
|
+
private indexAllContent;
|
|
74
|
+
private parseFileHeaderWithRepair;
|
|
75
|
+
/**
|
|
76
|
+
* Perform read-repair by writing back the file with missing fields
|
|
77
|
+
* This ensures stable IDs and timestamps across restarts
|
|
78
|
+
*/
|
|
79
|
+
private performReadRepair;
|
|
80
|
+
private scanContentFiles;
|
|
81
|
+
private getFilePath;
|
|
82
|
+
/**
|
|
83
|
+
* Parse a file path back into its components for checking against the path index
|
|
84
|
+
* Returns null if the path doesn't match expected patterns
|
|
85
|
+
*/
|
|
86
|
+
parseFilePath(filePath: string): {
|
|
87
|
+
kind: 'page' | 'block' | 'data';
|
|
88
|
+
site?: string;
|
|
89
|
+
collection: string;
|
|
90
|
+
pathname?: string;
|
|
91
|
+
name?: string;
|
|
92
|
+
locale: string;
|
|
93
|
+
} | null;
|
|
94
|
+
getContent(id: string): Promise<ContentEntry | null>;
|
|
95
|
+
getLocalized(id: string, locale: string): Promise<LocalizedEntry | null>;
|
|
96
|
+
private readLocaleFile;
|
|
97
|
+
createContent(data: CreateContentInput): Promise<CreateResult>;
|
|
98
|
+
updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult>;
|
|
99
|
+
deleteContent(id: string, etag: string): Promise<DeleteResult>;
|
|
100
|
+
deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult>;
|
|
101
|
+
getSite(siteName: string): Site | null;
|
|
102
|
+
listAllContent(filters?: GlobalFilters): Generator<ContentManifest>;
|
|
103
|
+
findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest>;
|
|
104
|
+
/**
|
|
105
|
+
* Reindex files that were added or changed after initial creation
|
|
106
|
+
*
|
|
107
|
+
* This method:
|
|
108
|
+
* 1. Either scans for all content files or processes specific paths
|
|
109
|
+
* 2. Uses the path index to check if files are already indexed
|
|
110
|
+
* 3. Indexes new files or force-reindexes specified files
|
|
111
|
+
* 4. Optionally handles file deletions
|
|
112
|
+
*
|
|
113
|
+
* @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
|
|
114
|
+
* @param options - Options for reindexing behavior
|
|
115
|
+
* @returns Statistics about the reindexing operation
|
|
116
|
+
*/
|
|
117
|
+
reindex(paths?: string[], options?: {
|
|
118
|
+
handleDeletions?: boolean;
|
|
119
|
+
}): Promise<ReindexResult>;
|
|
120
|
+
/**
|
|
121
|
+
* Read content directly from cache
|
|
122
|
+
* For testing purposes - returns null if not cached
|
|
123
|
+
*/
|
|
124
|
+
readFromCache(id: string, locale: string): Promise<ContentData | null>;
|
|
125
|
+
getContentAsBuffer(id: string, locale: string): Promise<{
|
|
126
|
+
buffer: Uint8Array;
|
|
127
|
+
etag: string;
|
|
128
|
+
contentType: 'application/json' | 'text/mdx';
|
|
129
|
+
} | null>;
|
|
130
|
+
batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult>;
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
export { readSitesConfig as n, FileSystemContentAPI as t };
|
|
134
|
+
//# sourceMappingURL=filesystem-content-api-DCdNi-co.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filesystem-content-api-DCdNi-co.d.mts","names":[],"sources":["../src/filesystem-content-api.ts"],"mappings":";;;UAqDU;EACR;EACA;EACA;EACA;EAEA,SAAS;EACT,UAAU;IAAQ;IAAY;IAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6G1B,gBAAgB,sBAAsB,QAAQ;cA+BvD,gCAAgC;UACnC;UACA;UACA;WACC,aAAa;WACb,QAAQ;WACR,MAAM;mBACE;UAMT;UACA;UACA;UACA;mBAMS;MAGb;UAIG;SAiGM,OAAO,SAAS,oBAAoB,QAAQ;;;;SAoElD;UAKO;UAuCA;;;;;UA4YA;UA+HA;UAkEN;;;;;EAqCR,cAAc;IACZ;IACA;IACA;IACA;IACA;IACA;;EAmGI,WAAW,aAAa,QAAQ;EAsChC,aAAa,YAAY,iBAAiB,QAAQ;UA4C1C;EA+JR,cAAc,MAAM,qBAAqB,QAAQ;EAqLjD,gBAAgB,OAAO,oBAAoB,QAAQ;EAubnD,cAAc,YAAY,eAAe,QAAQ;EAkDjD,gBAAgB,OAAO,oBAAoB,QAAQ;EA2DzD,QAAQ,mBAAmB;EAS1B,eAAe,UAAU,gBAAgB,UAAU;EAGnD,wBAAwB,sBAAsB,UAAU,cAAc,UAAU;;;;;;;;;;;;;;EAiB3E,QAAQ,kBAAkB;IAAY;MAA8B,QAAQ;;;;;EAoM5E,cAAc,YAAY,iBAAiB,QAAQ;EAInD,mBACJ,YACA,iBACC;IACD,QAAQ;IACR;IACA;;EA+CI,YAAY,YAAY,sBAAsB,QAAQ"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { Blocks } from './blocks';
|
|
2
|
+
import type { ContentAPI } from './content-api.interface';
|
|
3
|
+
import { Data } from './data';
|
|
4
|
+
import { Site } from './site';
|
|
5
|
+
import type { BatchResult, ContentAPIOptions, ContentData, ContentEntry, ContentManifest, CreateContentInput, CreateResult, DeleteLocaleInput, DeleteResult, FindOptions, GlobalFilters, LocalizedEntry, LocalizedManifest, SitesConfig, UpdateLocaleInput, UpdateResult } from './types';
|
|
6
|
+
interface ReindexResult {
|
|
7
|
+
filesProcessed: number;
|
|
8
|
+
filesSkipped: number;
|
|
9
|
+
filesDeleted?: number;
|
|
10
|
+
errors?: number;
|
|
11
|
+
updated: LocalizedManifest[];
|
|
12
|
+
deleted?: Array<{
|
|
13
|
+
id: string;
|
|
14
|
+
locale: string;
|
|
15
|
+
kind: 'page' | 'block' | 'data';
|
|
16
|
+
}>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* FileSystem-based Content API Implementation
|
|
20
|
+
*
|
|
21
|
+
* Stores content as files on disk in a git-friendly format:
|
|
22
|
+
* - Pages: /{site}/pages/{filename}.{locale}.vxjson
|
|
23
|
+
* - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
|
|
24
|
+
*
|
|
25
|
+
* ## Indexing
|
|
26
|
+
*
|
|
27
|
+
* Content is indexed at startup for performance. The index is cached per
|
|
28
|
+
* content root path and cleared when the process restarts.
|
|
29
|
+
*
|
|
30
|
+
* ## Read-Repair
|
|
31
|
+
*
|
|
32
|
+
* Since files can be modified externally (git, editors), this implementation:
|
|
33
|
+
*
|
|
34
|
+
* 1. Repairs invalid VXJSON files (ensures "content" field is last)
|
|
35
|
+
* 2. Adds missing required fields (id, created, modified)
|
|
36
|
+
* 3. Handles files added after initial indexing
|
|
37
|
+
* 4. Updates the index when files are repaired or discovered
|
|
38
|
+
*
|
|
39
|
+
* ## Performance
|
|
40
|
+
*
|
|
41
|
+
* - Initial indexing reads only first 4KB of each file
|
|
42
|
+
* - Full content is loaded on demand
|
|
43
|
+
* - ETags are calculated using streaming for efficiency
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* Read and validate `<contentRoot>/sites.json`. Returns a safe default
|
|
47
|
+
* (`{ sites: {}, globalLocales: ['en'] }`) when the file is missing or
|
|
48
|
+
* has invalid structure, with a warning logged in each case.
|
|
49
|
+
*
|
|
50
|
+
* Exported standalone so the Astro integration (and any other tooling
|
|
51
|
+
* that needs to inspect per-site config at startup time) can read the
|
|
52
|
+
* config without spinning up a full content-api instance.
|
|
53
|
+
*/
|
|
54
|
+
export declare function readSitesConfig(contentRoot: string): Promise<SitesConfig>;
|
|
55
|
+
export declare class FileSystemContentAPI implements ContentAPI {
|
|
56
|
+
private contentRoot;
|
|
57
|
+
private absoluteContentRoot;
|
|
58
|
+
private contentIndex;
|
|
59
|
+
readonly sitesConfig: SitesConfig;
|
|
60
|
+
readonly blocks: Blocks;
|
|
61
|
+
readonly data: Data;
|
|
62
|
+
private readonly sites;
|
|
63
|
+
private absoluteMdxPagesRoot?;
|
|
64
|
+
private mdxPagesDefaultLocale;
|
|
65
|
+
private mdxPagesSite;
|
|
66
|
+
private mdxPagesCollection;
|
|
67
|
+
private readonly availableLocales;
|
|
68
|
+
get normalizedContentRoot(): string;
|
|
69
|
+
private constructor();
|
|
70
|
+
static create(options: ContentAPIOptions): Promise<FileSystemContentAPI>;
|
|
71
|
+
/**
|
|
72
|
+
* Clear all caches - useful for testing
|
|
73
|
+
*/
|
|
74
|
+
static clearCaches(): void;
|
|
75
|
+
private indexAllContent;
|
|
76
|
+
private parseFileHeaderWithRepair;
|
|
77
|
+
/**
|
|
78
|
+
* Perform read-repair by writing back the file with missing fields
|
|
79
|
+
* This ensures stable IDs and timestamps across restarts
|
|
80
|
+
*/
|
|
81
|
+
private performReadRepair;
|
|
82
|
+
private scanContentFiles;
|
|
83
|
+
private getFilePath;
|
|
84
|
+
/**
|
|
85
|
+
* Parse a file path back into its components for checking against the path index
|
|
86
|
+
* Returns null if the path doesn't match expected patterns
|
|
87
|
+
*/
|
|
88
|
+
parseFilePath(filePath: string): {
|
|
89
|
+
kind: 'page' | 'block' | 'data';
|
|
90
|
+
site?: string;
|
|
91
|
+
collection: string;
|
|
92
|
+
pathname?: string;
|
|
93
|
+
name?: string;
|
|
94
|
+
locale: string;
|
|
95
|
+
} | null;
|
|
96
|
+
getContent(id: string): Promise<ContentEntry | null>;
|
|
97
|
+
getLocalized(id: string, locale: string): Promise<LocalizedEntry | null>;
|
|
98
|
+
private readLocaleFile;
|
|
99
|
+
createContent(data: CreateContentInput): Promise<CreateResult>;
|
|
100
|
+
updateLocalized(input: UpdateLocaleInput): Promise<UpdateResult>;
|
|
101
|
+
deleteContent(id: string, etag: string): Promise<DeleteResult>;
|
|
102
|
+
deleteLocalized(input: DeleteLocaleInput): Promise<DeleteResult>;
|
|
103
|
+
getSite(siteName: string): Site | null;
|
|
104
|
+
listAllContent(filters?: GlobalFilters): Generator<ContentManifest>;
|
|
105
|
+
findUntranslatedContent(targetLocale: string, options?: FindOptions): Generator<ContentManifest>;
|
|
106
|
+
/**
|
|
107
|
+
* Reindex files that were added or changed after initial creation
|
|
108
|
+
*
|
|
109
|
+
* This method:
|
|
110
|
+
* 1. Either scans for all content files or processes specific paths
|
|
111
|
+
* 2. Uses the path index to check if files are already indexed
|
|
112
|
+
* 3. Indexes new files or force-reindexes specified files
|
|
113
|
+
* 4. Optionally handles file deletions
|
|
114
|
+
*
|
|
115
|
+
* @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
|
|
116
|
+
* @param options - Options for reindexing behavior
|
|
117
|
+
* @returns Statistics about the reindexing operation
|
|
118
|
+
*/
|
|
119
|
+
reindex(paths?: string[], options?: {
|
|
120
|
+
handleDeletions?: boolean;
|
|
121
|
+
}): Promise<ReindexResult>;
|
|
122
|
+
/**
|
|
123
|
+
* Read content directly from cache
|
|
124
|
+
* For testing purposes - returns null if not cached
|
|
125
|
+
*/
|
|
126
|
+
readFromCache(id: string, locale: string): Promise<ContentData | null>;
|
|
127
|
+
getContentAsBuffer(id: string, locale: string): Promise<{
|
|
128
|
+
buffer: Uint8Array;
|
|
129
|
+
etag: string;
|
|
130
|
+
contentType: 'application/json' | 'text/mdx';
|
|
131
|
+
} | null>;
|
|
132
|
+
batchUpdate(operations: UpdateLocaleInput[]): Promise<BatchResult>;
|
|
133
|
+
}
|
|
134
|
+
export {};
|
|
135
|
+
//# sourceMappingURL=filesystem-content-api.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filesystem-content-api.d.ts","sourceRoot":"","sources":["../src/filesystem-content-api.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAgB1D,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAC9B,OAAO,KAAK,EAEV,WA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