@conloca/content-api 0.1.14 → 0.1.15
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/component-registry.types-CBGONnYn.d.mts +71 -0
- package/dist/component-registry.types-CBGONnYn.d.mts.map +1 -0
- package/dist/{content-operations-BZLfJWqT.d.mts → content-operations-Dv67amz3.d.mts} +7 -71
- package/dist/content-operations-Dv67amz3.d.mts.map +1 -0
- package/dist/data-Db1Iv9T0.mjs +60 -0
- package/dist/data-Db1Iv9T0.mjs.map +1 -0
- package/dist/filesystem-content-api-C1TM0GLo.d.mts +119 -0
- package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +1 -0
- package/dist/filesystem-content-api-kxKY5IUw.mjs +2678 -0
- package/dist/filesystem-content-api-kxKY5IUw.mjs.map +1 -0
- package/dist/index.d.mts +3 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/node.d.mts +25 -118
- package/dist/node.d.mts.map +1 -1
- package/dist/node.mjs +175 -2820
- package/dist/node.mjs.map +1 -1
- package/dist/reader.d.mts +18 -0
- package/dist/reader.d.mts.map +1 -0
- package/dist/reader.mjs +22 -0
- package/dist/reader.mjs.map +1 -0
- package/dist/{types-BUG0Cfkg.mjs → site-vNtJ5jCh.mjs} +2 -32
- package/dist/site-vNtJ5jCh.mjs.map +1 -0
- package/dist/types-DWt912tu.mjs +33 -0
- package/dist/types-DWt912tu.mjs.map +1 -0
- package/package.json +14 -5
- package/dist/content-operations-BZLfJWqT.d.mts.map +0 -1
- package/dist/types-BUG0Cfkg.mjs.map +0 -1
|
@@ -0,0 +1,2678 @@
|
|
|
1
|
+
import { E as Blocks, T as serializeMdxWithFrontmatter, a as buildPathnameHistory, b as mapLocales, c as validateAndPrepareMetadata, f as generateContentId, h as isContentPublished, i as buildLocaleVersion, l as validateCreateContent, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, r as analyzeUpdateScope, s as updatePublishDates, t as Site, w as resolvePublishDate, x as mapSiteNames, y as localesOf } from "./site-vNtJ5jCh.mjs";
|
|
2
|
+
import { t as Data } from "./data-Db1Iv9T0.mjs";
|
|
3
|
+
import sortKeys from "sort-keys";
|
|
4
|
+
import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { xxh3 } from "@node-rs/xxhash";
|
|
6
|
+
import matter from "gray-matter";
|
|
7
|
+
import { dirname, join, resolve } from "path";
|
|
8
|
+
import { createHash } from "crypto";
|
|
9
|
+
|
|
10
|
+
//#region \0rolldown/runtime.js
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __exportAll = (all, no_symbols) => {
|
|
13
|
+
let target = {};
|
|
14
|
+
for (var name in all) {
|
|
15
|
+
__defProp(target, name, {
|
|
16
|
+
get: all[name],
|
|
17
|
+
enumerable: true
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
if (!no_symbols) {
|
|
21
|
+
__defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
22
|
+
}
|
|
23
|
+
return target;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/utils/atomic-write.ts
|
|
28
|
+
/**
|
|
29
|
+
* Write file atomically via temp file + rename to prevent corruption on crash.
|
|
30
|
+
* Callers are responsible for ensuring the parent directory exists.
|
|
31
|
+
*/
|
|
32
|
+
async function atomicWriteFile(filePath, content) {
|
|
33
|
+
const hrtime = process.hrtime.bigint();
|
|
34
|
+
const tempFile = `${filePath}.tmp.${process.pid}.${hrtime}`;
|
|
35
|
+
try {
|
|
36
|
+
await writeFile(tempFile, content);
|
|
37
|
+
await rename(tempFile, filePath);
|
|
38
|
+
} catch (error) {
|
|
39
|
+
try {
|
|
40
|
+
await unlink(tempFile);
|
|
41
|
+
} catch {}
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
//#endregion
|
|
47
|
+
//#region src/content-filters.ts
|
|
48
|
+
/**
|
|
49
|
+
* Apply filters to a single content manifest
|
|
50
|
+
* Pure function that checks if a manifest matches all provided filters
|
|
51
|
+
*/
|
|
52
|
+
function applyContentFilters(manifest, filters) {
|
|
53
|
+
if (filters.site && manifest.site !== filters.site) return false;
|
|
54
|
+
if (filters.collection && manifest.collection !== filters.collection) return false;
|
|
55
|
+
if (filters.type && manifest.type !== filters.type) return false;
|
|
56
|
+
if (filters.kind && manifest.kind !== filters.kind) return false;
|
|
57
|
+
if (filters.locales && filters.locales.length > 0) {
|
|
58
|
+
if (!filters.locales.some((locale) => manifest.locales[locale])) return false;
|
|
59
|
+
}
|
|
60
|
+
if (filters.missingLocales && filters.missingLocales.length > 0) {
|
|
61
|
+
if (filters.missingLocales.some((locale) => manifest.locales[locale])) return false;
|
|
62
|
+
}
|
|
63
|
+
if (filters.published !== void 0) {
|
|
64
|
+
let hasPublishedLocale = false;
|
|
65
|
+
for (const localeVersion of localesOf(manifest)) {
|
|
66
|
+
if (!localeVersion.unpublishAt) {
|
|
67
|
+
hasPublishedLocale = true;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
if (new Date(localeVersion.unpublishAt) > /* @__PURE__ */ new Date()) {
|
|
71
|
+
hasPublishedLocale = true;
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (filters.published !== hasPublishedLocale) return false;
|
|
76
|
+
}
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Generator that yields manifests after applying all filters
|
|
81
|
+
* This is the main entry point for filtering content using indexes efficiently
|
|
82
|
+
*/
|
|
83
|
+
function* filterContentWithIndexes(contentIndex, filters, sitesConfig) {
|
|
84
|
+
if (!filters) {
|
|
85
|
+
yield* contentIndex.listAllContent();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
if (filters.kind === "page" && filters.site && filters.collection) {
|
|
89
|
+
if (!contentIndex.getCollectionsForSite(filters.site).has(filters.collection)) return;
|
|
90
|
+
} else if (filters.kind === "block" && filters.collection) {
|
|
91
|
+
if (!contentIndex.getBlockCollections().has(filters.collection)) return;
|
|
92
|
+
}
|
|
93
|
+
let generator;
|
|
94
|
+
if (filters.kind === "page" && filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
|
|
95
|
+
else if (filters.kind === "block" && filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
|
|
96
|
+
else if (filters.kind) generator = contentIndex.getManifestsForKind(filters.kind);
|
|
97
|
+
else if (filters.site && filters.collection) generator = contentIndex.getManifestsForSiteCollection(filters.site, filters.collection);
|
|
98
|
+
else if (filters.site && filters.locales?.length === 1) generator = contentIndex.getManifestsForSiteLocale(filters.site, filters.locales[0]);
|
|
99
|
+
else if (filters.site) generator = contentIndex.getManifestsForSite(filters.site);
|
|
100
|
+
else if (filters.collection) generator = contentIndex.getManifestsForCollection(filters.collection);
|
|
101
|
+
else if (filters.locales?.length === 1) generator = contentIndex.getManifestsForLocale(filters.locales[0]);
|
|
102
|
+
else generator = contentIndex.listAllContent();
|
|
103
|
+
for (const manifest of generator) {
|
|
104
|
+
if (!applyContentFilters(manifest, filters)) continue;
|
|
105
|
+
if (filters.localization) {
|
|
106
|
+
if (filters.localization === "complete" && filters.missingLocales?.length) continue;
|
|
107
|
+
const siteLocales = filters.site && manifest.kind === "page" ? sitesConfig.sites[filters.site]?.locales || sitesConfig.globalLocales : sitesConfig.globalLocales;
|
|
108
|
+
const localeCount = Object.keys(manifest.locales).length;
|
|
109
|
+
const hasLocales = siteLocales.filter((l) => manifest.locales[l]).length;
|
|
110
|
+
const totalLocales = siteLocales.length;
|
|
111
|
+
if (filters.localization === "complete" && hasLocales !== totalLocales) continue;
|
|
112
|
+
if (filters.localization === "partial" && (localeCount <= 1 || hasLocales === totalLocales)) continue;
|
|
113
|
+
if (filters.localization === "one" && localeCount !== 1) continue;
|
|
114
|
+
}
|
|
115
|
+
yield manifest;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/base-content-index.ts
|
|
121
|
+
/**
|
|
122
|
+
* Base class for content indexes (blocks, data)
|
|
123
|
+
* Maintains collection->name->locale lookups with V8-optimized structures
|
|
124
|
+
*/
|
|
125
|
+
var BaseContentIndex = class {
|
|
126
|
+
index = /* @__PURE__ */ new Map();
|
|
127
|
+
contentCache = /* @__PURE__ */ new Map();
|
|
128
|
+
nameIndex = /* @__PURE__ */ new Map();
|
|
129
|
+
collections = /* @__PURE__ */ new Set();
|
|
130
|
+
/**
|
|
131
|
+
* Add or update content in the index
|
|
132
|
+
* Merges manifest locales and updates content cache if provided
|
|
133
|
+
*/
|
|
134
|
+
addContent(identity, localeVersion, content) {
|
|
135
|
+
const existing = this.index.get(identity.id);
|
|
136
|
+
const locale = localeVersion.locale;
|
|
137
|
+
if (existing) {
|
|
138
|
+
const existingLocale = existing.locales[locale];
|
|
139
|
+
if (!existingLocale || existingLocale.etag !== localeVersion.etag) existing.locales[locale] = localeVersion;
|
|
140
|
+
} else {
|
|
141
|
+
const newManifest = {
|
|
142
|
+
id: identity.id,
|
|
143
|
+
type: identity.type,
|
|
144
|
+
kind: identity.kind,
|
|
145
|
+
site: identity.site,
|
|
146
|
+
collection: identity.collection,
|
|
147
|
+
locales: { [locale]: localeVersion }
|
|
148
|
+
};
|
|
149
|
+
this.index.set(identity.id, newManifest);
|
|
150
|
+
this.collections.add(identity.collection);
|
|
151
|
+
}
|
|
152
|
+
if (content !== void 0) {
|
|
153
|
+
const existingCache = this.contentCache.get(identity.id);
|
|
154
|
+
if (existingCache) existingCache[locale] = content;
|
|
155
|
+
else this.contentCache.set(identity.id, { [locale]: content });
|
|
156
|
+
}
|
|
157
|
+
const manifestToIndex = existing || this.index.get(identity.id);
|
|
158
|
+
if (localeVersion.name) {
|
|
159
|
+
if (!this.nameIndex.has(identity.collection)) this.nameIndex.set(identity.collection, /* @__PURE__ */ new Map());
|
|
160
|
+
this.nameIndex.get(identity.collection).set(localeVersion.name, manifestToIndex);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Remove a specific locale from an entry
|
|
165
|
+
*/
|
|
166
|
+
removeLocale(id, locale) {
|
|
167
|
+
const manifest = this.index.get(id);
|
|
168
|
+
if (!manifest || !manifest.locales[locale]) return;
|
|
169
|
+
manifest.locales[locale] = void 0;
|
|
170
|
+
const contentCache = this.contentCache.get(id);
|
|
171
|
+
if (contentCache) delete contentCache[locale];
|
|
172
|
+
if (Object.values(manifest.locales).filter((v) => v !== void 0).length === 0) this.removeEntry(id);
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Remove an entry from the index
|
|
176
|
+
*/
|
|
177
|
+
removeEntry(id) {
|
|
178
|
+
const manifest = this.index.get(id);
|
|
179
|
+
if (!manifest) return;
|
|
180
|
+
for (const localeVersion of localesOf(manifest)) if (localeVersion.name) {
|
|
181
|
+
const collectionMap = this.nameIndex.get(manifest.collection);
|
|
182
|
+
if (collectionMap) collectionMap.delete(localeVersion.name);
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
this.index.delete(id);
|
|
186
|
+
this.contentCache.delete(id);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Get cached content for a specific locale
|
|
190
|
+
*/
|
|
191
|
+
getCachedContent(id, locale) {
|
|
192
|
+
return this.contentCache.get(id)?.[locale] || null;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Get content manifest
|
|
196
|
+
*/
|
|
197
|
+
getManifest(id) {
|
|
198
|
+
return this.index.get(id) || null;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Find entry by name
|
|
202
|
+
*/
|
|
203
|
+
getByName(collection, name, locale) {
|
|
204
|
+
const collectionMap = this.nameIndex.get(collection);
|
|
205
|
+
if (!collectionMap) return null;
|
|
206
|
+
const manifest = collectionMap.get(name);
|
|
207
|
+
if (!manifest) return null;
|
|
208
|
+
if (locale && !manifest.locales[locale]) return null;
|
|
209
|
+
return manifest;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Generator for all manifests
|
|
213
|
+
*/
|
|
214
|
+
*getAllManifests() {
|
|
215
|
+
for (const manifest of this.index.values()) yield manifest;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Generator for manifests by locale
|
|
219
|
+
*/
|
|
220
|
+
*getManifestsByLocale(locale) {
|
|
221
|
+
for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Generator for manifests by collection
|
|
225
|
+
*/
|
|
226
|
+
*getManifestsByCollection(collection) {
|
|
227
|
+
for (const manifest of this.index.values()) if (manifest.collection === collection) yield manifest;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Get the count of indexed content entries (unique IDs)
|
|
231
|
+
*/
|
|
232
|
+
get entryCount() {
|
|
233
|
+
return this.index.size;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Clear all indexes
|
|
237
|
+
*/
|
|
238
|
+
clear() {
|
|
239
|
+
this.index.clear();
|
|
240
|
+
this.contentCache.clear();
|
|
241
|
+
this.nameIndex.clear();
|
|
242
|
+
this.collections.clear();
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
//#endregion
|
|
247
|
+
//#region src/block-index.ts
|
|
248
|
+
/**
|
|
249
|
+
* V8-optimized index for blocks
|
|
250
|
+
* Maintains collection->name->locale lookups
|
|
251
|
+
*/
|
|
252
|
+
var BlockIndex = class extends BaseContentIndex {
|
|
253
|
+
constructor(locales) {
|
|
254
|
+
super();
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/data-index.ts
|
|
260
|
+
/**
|
|
261
|
+
* V8-optimized index for data collections
|
|
262
|
+
* Maintains collection->name->locale lookups
|
|
263
|
+
*/
|
|
264
|
+
var DataIndex = class extends BaseContentIndex {};
|
|
265
|
+
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/site-index.ts
|
|
268
|
+
/**
|
|
269
|
+
* V8-optimized index for a single site
|
|
270
|
+
* Maintains pathname lookups and collections for one site only
|
|
271
|
+
*/
|
|
272
|
+
var SiteIndex = class {
|
|
273
|
+
index = /* @__PURE__ */ new Map();
|
|
274
|
+
contentCache = /* @__PURE__ */ new Map();
|
|
275
|
+
pathnameIndex;
|
|
276
|
+
previousPathnameIndex;
|
|
277
|
+
collections = /* @__PURE__ */ new Set();
|
|
278
|
+
constructor(siteName, locales) {
|
|
279
|
+
this.locales = locales;
|
|
280
|
+
this.pathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
|
|
281
|
+
this.previousPathnameIndex = mapLocales(locales, () => /* @__PURE__ */ new Map());
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Add or update content in the index
|
|
285
|
+
* Merges manifest locales and updates content cache if provided
|
|
286
|
+
*/
|
|
287
|
+
addContent(identity, localeVersion, content) {
|
|
288
|
+
const existing = this.index.get(identity.id);
|
|
289
|
+
const locale = localeVersion.locale;
|
|
290
|
+
if (existing) {
|
|
291
|
+
const existingLocale = existing.locales[locale];
|
|
292
|
+
let oldPathname;
|
|
293
|
+
for (const [pathname, indexedManifest] of this.pathnameIndex[locale].entries()) if (indexedManifest === existing && pathname !== localeVersion.pathname) {
|
|
294
|
+
oldPathname = pathname;
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
if (!oldPathname && existingLocale?.pathname && existingLocale.pathname !== localeVersion.pathname) oldPathname = existingLocale.pathname;
|
|
298
|
+
const hadExistingLocale = !!existingLocale;
|
|
299
|
+
let deletedOldPathname = false;
|
|
300
|
+
let addedNewPathname = false;
|
|
301
|
+
const addedPreviousPathnames = [];
|
|
302
|
+
if (!existingLocale || existingLocale.etag !== localeVersion.etag || existingLocale.modified !== localeVersion.modified || oldPathname && oldPathname !== localeVersion.pathname) try {
|
|
303
|
+
existing.locales[locale] = localeVersion;
|
|
304
|
+
if (localeVersion.pathname) {
|
|
305
|
+
if (oldPathname && oldPathname !== localeVersion.pathname) {
|
|
306
|
+
this.pathnameIndex[locale].delete(oldPathname);
|
|
307
|
+
deletedOldPathname = true;
|
|
308
|
+
if (isContentPublished(localeVersion)) {
|
|
309
|
+
this.previousPathnameIndex[locale].set(oldPathname, existing);
|
|
310
|
+
addedPreviousPathnames.push(oldPathname);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
this.pathnameIndex[locale].set(localeVersion.pathname, existing);
|
|
314
|
+
addedNewPathname = true;
|
|
315
|
+
}
|
|
316
|
+
if (localeVersion.previousPathnames) {
|
|
317
|
+
for (const prevPath of Object.keys(localeVersion.previousPathnames)) if (!this.previousPathnameIndex[locale].has(prevPath)) {
|
|
318
|
+
this.previousPathnameIndex[locale].set(prevPath, existing);
|
|
319
|
+
addedPreviousPathnames.push(prevPath);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if (hadExistingLocale) existing.locales[locale] = existingLocale;
|
|
324
|
+
else existing.locales[locale] = void 0;
|
|
325
|
+
if (deletedOldPathname && oldPathname) this.pathnameIndex[locale].set(oldPathname, existing);
|
|
326
|
+
if (addedNewPathname && localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
|
|
327
|
+
for (const prevPath of addedPreviousPathnames) this.previousPathnameIndex[locale].delete(prevPath);
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
} else {
|
|
331
|
+
const newManifest = {
|
|
332
|
+
id: identity.id,
|
|
333
|
+
type: identity.type,
|
|
334
|
+
kind: identity.kind,
|
|
335
|
+
site: identity.site,
|
|
336
|
+
collection: identity.collection,
|
|
337
|
+
locales: { [locale]: localeVersion }
|
|
338
|
+
};
|
|
339
|
+
this.index.set(identity.id, newManifest);
|
|
340
|
+
this.collections.add(identity.collection);
|
|
341
|
+
if (localeVersion.pathname) this.pathnameIndex[locale].set(localeVersion.pathname, newManifest);
|
|
342
|
+
if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].set(prevPath, newManifest);
|
|
343
|
+
}
|
|
344
|
+
if (content !== void 0) {
|
|
345
|
+
const existingCache = this.contentCache.get(identity.id);
|
|
346
|
+
if (existingCache) existingCache[locale] = content;
|
|
347
|
+
else this.contentCache.set(identity.id, { [locale]: content });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Remove a specific locale from an entry
|
|
352
|
+
*/
|
|
353
|
+
removeLocale(id, locale) {
|
|
354
|
+
const manifest = this.index.get(id);
|
|
355
|
+
if (!manifest || !manifest.locales[locale]) return;
|
|
356
|
+
const localeVersion = manifest.locales[locale];
|
|
357
|
+
if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
|
|
358
|
+
if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
|
|
359
|
+
manifest.locales[locale] = void 0;
|
|
360
|
+
const contentCache = this.contentCache.get(id);
|
|
361
|
+
if (contentCache) delete contentCache[locale];
|
|
362
|
+
if (Object.keys(manifest.locales).length === 0) this.removeEntry(id);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Remove an entry from the index
|
|
366
|
+
*/
|
|
367
|
+
removeEntry(id) {
|
|
368
|
+
const manifest = this.index.get(id);
|
|
369
|
+
if (!manifest) return;
|
|
370
|
+
for (const localeVersion of localesOf(manifest)) {
|
|
371
|
+
const { locale } = localeVersion;
|
|
372
|
+
if (localeVersion.pathname) this.pathnameIndex[locale].delete(localeVersion.pathname);
|
|
373
|
+
if (localeVersion.previousPathnames) for (const prevPath of Object.keys(localeVersion.previousPathnames)) this.previousPathnameIndex[locale].delete(prevPath);
|
|
374
|
+
}
|
|
375
|
+
this.index.delete(id);
|
|
376
|
+
this.contentCache.delete(id);
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Get cached content for a specific locale
|
|
380
|
+
*/
|
|
381
|
+
getCachedContent(id, locale) {
|
|
382
|
+
return this.contentCache.get(id)?.[locale] || null;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Get content manifest
|
|
386
|
+
*/
|
|
387
|
+
getManifest(id) {
|
|
388
|
+
return this.index.get(id) || null;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Find content by pathname
|
|
392
|
+
*/
|
|
393
|
+
getByPathname(pathname, locale) {
|
|
394
|
+
if (locale) return this.pathnameIndex[locale]?.get(pathname) || null;
|
|
395
|
+
for (const locale of this.locales) {
|
|
396
|
+
const manifest = this.pathnameIndex[locale].get(pathname);
|
|
397
|
+
if (manifest) return manifest;
|
|
398
|
+
}
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Find content by previous pathname (for redirects)
|
|
403
|
+
*/
|
|
404
|
+
getByPreviousPathname(pathname, locale) {
|
|
405
|
+
if (locale) return this.previousPathnameIndex[locale]?.get(pathname) || null;
|
|
406
|
+
for (const locale of this.locales) {
|
|
407
|
+
const manifest = this.previousPathnameIndex[locale].get(pathname);
|
|
408
|
+
if (manifest) return manifest;
|
|
409
|
+
}
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Generator for all manifests
|
|
414
|
+
*/
|
|
415
|
+
*getAllManifests() {
|
|
416
|
+
for (const manifest of this.index.values()) yield manifest;
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Generator for manifests by locale
|
|
420
|
+
*/
|
|
421
|
+
*getManifestsByLocale(locale) {
|
|
422
|
+
for (const manifest of this.index.values()) if (manifest.locales[locale]) yield manifest;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Get the count of indexed content entries (unique IDs)
|
|
426
|
+
*/
|
|
427
|
+
get entryCount() {
|
|
428
|
+
return this.index.size;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Clear all indexes
|
|
432
|
+
*/
|
|
433
|
+
clear() {
|
|
434
|
+
this.index.clear();
|
|
435
|
+
this.contentCache.clear();
|
|
436
|
+
for (const locale of this.locales) {
|
|
437
|
+
this.pathnameIndex[locale].clear();
|
|
438
|
+
this.previousPathnameIndex[locale].clear();
|
|
439
|
+
}
|
|
440
|
+
this.collections.clear();
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
//#endregion
|
|
445
|
+
//#region src/content-index.ts
|
|
446
|
+
/**
|
|
447
|
+
* ContentIndex coordinates between per-site indexes and the block index
|
|
448
|
+
* This provides efficient filtering by routing to the appropriate specialized index
|
|
449
|
+
*/
|
|
450
|
+
const globalCache = globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ || {};
|
|
451
|
+
if (!globalThis.__CONLOCA_CONTENT_INDEX_CACHE__) globalThis.__CONLOCA_CONTENT_INDEX_CACHE__ = globalCache;
|
|
452
|
+
var ContentIndex = class ContentIndex {
|
|
453
|
+
static get cache() {
|
|
454
|
+
return globalCache;
|
|
455
|
+
}
|
|
456
|
+
siteIndexes;
|
|
457
|
+
blockIndex;
|
|
458
|
+
dataIndex;
|
|
459
|
+
constructor(sitesConfig) {
|
|
460
|
+
this.sitesConfig = sitesConfig;
|
|
461
|
+
this.blockIndex = new BlockIndex(sitesConfig.globalLocales);
|
|
462
|
+
this.dataIndex = new DataIndex();
|
|
463
|
+
this.siteIndexes = mapSiteNames(sitesConfig, (siteName) => {
|
|
464
|
+
const siteConfig = sitesConfig.sites[siteName];
|
|
465
|
+
return new SiteIndex(siteName, siteConfig.locales);
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Get cached index or create a new one
|
|
470
|
+
*/
|
|
471
|
+
static async getCachedOrCreate(contentRoot, sitesConfig) {
|
|
472
|
+
if (!ContentIndex.cache[contentRoot]) ContentIndex.cache[contentRoot] = new ContentIndex(sitesConfig);
|
|
473
|
+
return ContentIndex.cache[contentRoot];
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Clear all cached indexes
|
|
477
|
+
*/
|
|
478
|
+
static clearCache() {
|
|
479
|
+
Object.keys(globalCache).forEach((key) => delete globalCache[key]);
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Create a new index without caching - for testing
|
|
483
|
+
*/
|
|
484
|
+
static createUncached(sitesConfig) {
|
|
485
|
+
return new ContentIndex(sitesConfig);
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Add or update content in the appropriate index
|
|
489
|
+
* Updates a single locale's manifest and content cache if provided
|
|
490
|
+
*/
|
|
491
|
+
addContent(identity, localeVersion, content) {
|
|
492
|
+
if ((identity.kind === "block" || identity.kind === "data") && identity.site) throw new Error(`${identity.kind} cannot have a site property`);
|
|
493
|
+
if (identity.kind === "page" && !identity.site) throw new Error("Pages must have a site property");
|
|
494
|
+
if (identity.kind === "block") this.blockIndex.addContent(identity, localeVersion, content);
|
|
495
|
+
else if (identity.kind === "data") this.dataIndex.addContent(identity, localeVersion, content);
|
|
496
|
+
else {
|
|
497
|
+
const siteIndex = this.siteIndexes[identity.site];
|
|
498
|
+
if (siteIndex) siteIndex.addContent(identity, localeVersion, content);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Remove a specific locale from content
|
|
503
|
+
*/
|
|
504
|
+
removeLocale(id, locale) {
|
|
505
|
+
const manifest = this.getManifest(id);
|
|
506
|
+
if (!manifest) return;
|
|
507
|
+
if (manifest.kind === "block") this.blockIndex.removeLocale(id, locale);
|
|
508
|
+
else if (manifest.kind === "data") this.dataIndex.removeLocale(id, locale);
|
|
509
|
+
else {
|
|
510
|
+
const siteIndex = this.siteIndexes[manifest.site];
|
|
511
|
+
if (siteIndex) siteIndex.removeLocale(id, locale);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Get cached content
|
|
516
|
+
*/
|
|
517
|
+
getCachedContent(id, locale) {
|
|
518
|
+
const manifest = this.getManifest(id);
|
|
519
|
+
if (!manifest) return null;
|
|
520
|
+
if (manifest.kind === "block") return this.blockIndex.getCachedContent(id, locale);
|
|
521
|
+
if (manifest.kind === "data") return this.dataIndex.getCachedContent(id, locale);
|
|
522
|
+
const siteIndex = this.siteIndexes[manifest.site];
|
|
523
|
+
return siteIndex ? siteIndex.getCachedContent(id, locale) : null;
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Remove an entry from all indexes
|
|
527
|
+
*/
|
|
528
|
+
removeEntry(id) {
|
|
529
|
+
this.blockIndex.removeEntry(id);
|
|
530
|
+
this.dataIndex.removeEntry(id);
|
|
531
|
+
for (const site in this.siteIndexes) {
|
|
532
|
+
const siteIndex = this.siteIndexes[site];
|
|
533
|
+
if (siteIndex) siteIndex.removeEntry(id);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Get content manifest for a content ID
|
|
538
|
+
*/
|
|
539
|
+
getManifest(id) {
|
|
540
|
+
let manifest = this.blockIndex.getManifest(id);
|
|
541
|
+
if (manifest) return manifest;
|
|
542
|
+
manifest = this.dataIndex.getManifest(id);
|
|
543
|
+
if (manifest) return manifest;
|
|
544
|
+
for (const site in this.siteIndexes) {
|
|
545
|
+
const siteIndex = this.siteIndexes[site];
|
|
546
|
+
if (siteIndex) {
|
|
547
|
+
manifest = siteIndex.getManifest(id);
|
|
548
|
+
if (manifest) return manifest;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
return null;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Get a specific locale manifest
|
|
555
|
+
*/
|
|
556
|
+
getLocaleVersion(id, locale) {
|
|
557
|
+
const manifest = this.getManifest(id);
|
|
558
|
+
if (!manifest) return null;
|
|
559
|
+
return manifest.locales[locale] || null;
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Get site index
|
|
563
|
+
*/
|
|
564
|
+
getSiteIndex(site) {
|
|
565
|
+
return this.siteIndexes[site] || null;
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Get block index
|
|
569
|
+
*/
|
|
570
|
+
getBlockIndex() {
|
|
571
|
+
return this.blockIndex;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Find content by pathname (delegates to site indexes)
|
|
575
|
+
*/
|
|
576
|
+
getByPathname(site, pathname, locale) {
|
|
577
|
+
const siteIndex = this.siteIndexes[site];
|
|
578
|
+
return siteIndex ? siteIndex.getByPathname(pathname, locale) : null;
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Find content by previous pathname (for redirects)
|
|
582
|
+
*/
|
|
583
|
+
getByPreviousPathname(site, pathname, locale) {
|
|
584
|
+
const siteIndex = this.siteIndexes[site];
|
|
585
|
+
return siteIndex ? siteIndex.getByPreviousPathname(pathname, locale) : null;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Find block by name
|
|
589
|
+
*/
|
|
590
|
+
getBlockByName(collection, name, locale) {
|
|
591
|
+
return this.blockIndex.getByName(collection, name, locale);
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Get data index
|
|
595
|
+
*/
|
|
596
|
+
getDataIndex() {
|
|
597
|
+
return this.dataIndex;
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Find data entry by name
|
|
601
|
+
*/
|
|
602
|
+
getDataByName(collection, name, locale) {
|
|
603
|
+
return this.dataIndex.getByName(collection, name, locale);
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Get all collections for data
|
|
607
|
+
*/
|
|
608
|
+
getDataCollections() {
|
|
609
|
+
return this.dataIndex.collections;
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* List all content (for iteration)
|
|
613
|
+
*/
|
|
614
|
+
*listAllContent() {
|
|
615
|
+
yield* this.blockIndex.getAllManifests();
|
|
616
|
+
yield* this.dataIndex.getAllManifests();
|
|
617
|
+
for (const site in this.siteIndexes) {
|
|
618
|
+
const siteIndex = this.siteIndexes[site];
|
|
619
|
+
if (siteIndex) yield* siteIndex.getAllManifests();
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* Generator for all sites
|
|
624
|
+
*/
|
|
625
|
+
*allSites() {
|
|
626
|
+
for (const site in this.siteIndexes) if (this.siteIndexes[site]) yield site;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Get all collections for a site
|
|
630
|
+
*/
|
|
631
|
+
getCollectionsForSite(site) {
|
|
632
|
+
const siteIndex = this.siteIndexes[site];
|
|
633
|
+
return siteIndex ? siteIndex.collections : /* @__PURE__ */ new Set();
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Get all collections for blocks
|
|
637
|
+
*/
|
|
638
|
+
getBlockCollections() {
|
|
639
|
+
return this.blockIndex.collections;
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Get default locale for a site
|
|
643
|
+
*/
|
|
644
|
+
getDefaultLocale(site) {
|
|
645
|
+
if (!site) return this.sitesConfig.globalLocales[0];
|
|
646
|
+
return this.sitesConfig.sites[site]?.defaultLocale || this.sitesConfig.globalLocales[0];
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Find content missing a specific locale
|
|
650
|
+
*/
|
|
651
|
+
*findUntranslatedContent(targetLocale, options) {
|
|
652
|
+
for (const manifest of this.blockIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
|
|
653
|
+
if (!options?.includeUnpublished) {
|
|
654
|
+
let hasPublishedLocale = false;
|
|
655
|
+
for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
|
|
656
|
+
hasPublishedLocale = true;
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
if (!hasPublishedLocale) continue;
|
|
660
|
+
}
|
|
661
|
+
yield manifest;
|
|
662
|
+
}
|
|
663
|
+
for (const siteName in this.siteIndexes) {
|
|
664
|
+
const siteIndex = this.siteIndexes[siteName];
|
|
665
|
+
if (!siteIndex || options?.excludeSites?.includes(siteName)) continue;
|
|
666
|
+
for (const manifest of siteIndex.getAllManifests()) if (!manifest.locales[targetLocale]) {
|
|
667
|
+
if (!options?.includeUnpublished) {
|
|
668
|
+
let hasPublishedLocale = false;
|
|
669
|
+
for (const locale of localesOf(manifest)) if (!locale.unpublishAt || new Date(locale.unpublishAt) > /* @__PURE__ */ new Date()) {
|
|
670
|
+
hasPublishedLocale = true;
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
if (!hasPublishedLocale) continue;
|
|
674
|
+
}
|
|
675
|
+
yield manifest;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Generators for efficient filtering
|
|
681
|
+
*/
|
|
682
|
+
*getManifestsForKind(kind) {
|
|
683
|
+
if (kind === "block") yield* this.blockIndex.getAllManifests();
|
|
684
|
+
else if (kind === "data") yield* this.dataIndex.getAllManifests();
|
|
685
|
+
else for (const site in this.siteIndexes) {
|
|
686
|
+
const siteIndex = this.siteIndexes[site];
|
|
687
|
+
if (siteIndex) yield* siteIndex.getAllManifests();
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
*getManifestsForSite(site) {
|
|
691
|
+
const siteIndex = this.siteIndexes[site];
|
|
692
|
+
if (siteIndex) yield* siteIndex.getAllManifests();
|
|
693
|
+
}
|
|
694
|
+
*getManifestsForSiteLocale(site, locale) {
|
|
695
|
+
const siteIndex = this.siteIndexes[site];
|
|
696
|
+
if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
|
|
697
|
+
}
|
|
698
|
+
*getManifestsForSiteCollection(site, collection) {
|
|
699
|
+
const siteIndex = this.siteIndexes[site];
|
|
700
|
+
if (siteIndex) {
|
|
701
|
+
for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
*getManifestsForLocale(locale) {
|
|
705
|
+
yield* this.blockIndex.getManifestsByLocale(locale);
|
|
706
|
+
yield* this.dataIndex.getManifestsByLocale(locale);
|
|
707
|
+
for (const site in this.siteIndexes) {
|
|
708
|
+
const siteIndex = this.siteIndexes[site];
|
|
709
|
+
if (siteIndex) yield* siteIndex.getManifestsByLocale(locale);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
*getManifestsForCollection(collection) {
|
|
713
|
+
yield* this.blockIndex.getManifestsByCollection(collection);
|
|
714
|
+
yield* this.dataIndex.getManifestsByCollection(collection);
|
|
715
|
+
for (const site in this.siteIndexes) {
|
|
716
|
+
const siteIndex = this.siteIndexes[site];
|
|
717
|
+
if (siteIndex) {
|
|
718
|
+
for (const manifest of siteIndex.getAllManifests()) if (manifest.collection === collection) yield manifest;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Get the count of indexed content entries
|
|
724
|
+
*/
|
|
725
|
+
get entryCount() {
|
|
726
|
+
let count = this.blockIndex.entryCount;
|
|
727
|
+
count += this.dataIndex.entryCount;
|
|
728
|
+
for (const site in this.siteIndexes) {
|
|
729
|
+
const siteIndex = this.siteIndexes[site];
|
|
730
|
+
if (siteIndex) count += siteIndex.entryCount;
|
|
731
|
+
}
|
|
732
|
+
return count;
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Clear all indexes
|
|
736
|
+
*/
|
|
737
|
+
clear() {
|
|
738
|
+
this.blockIndex.clear();
|
|
739
|
+
this.dataIndex.clear();
|
|
740
|
+
for (const site in this.siteIndexes) {
|
|
741
|
+
const siteIndex = this.siteIndexes[site];
|
|
742
|
+
if (siteIndex) siteIndex.clear();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
//#endregion
|
|
748
|
+
//#region src/json-whitespace-view.ts
|
|
749
|
+
/**
|
|
750
|
+
* Zero-allocation JSON whitespace-skipping stream transform
|
|
751
|
+
* Skips whitespace outside of JSON strings, preserving whitespace inside strings
|
|
752
|
+
* Optimized to process multiple bytes at once when possible
|
|
753
|
+
*/
|
|
754
|
+
var JsonWhitespaceSkippingView = class {
|
|
755
|
+
inString = false;
|
|
756
|
+
escaped = false;
|
|
757
|
+
singleByte = new Uint8Array(1);
|
|
758
|
+
constructor(downstream) {
|
|
759
|
+
this.downstream = downstream;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Process a single byte from JSON stream
|
|
763
|
+
* @param byte - The byte to process
|
|
764
|
+
*/
|
|
765
|
+
updateByte(byte) {
|
|
766
|
+
let shouldInclude = false;
|
|
767
|
+
if (this.inString) {
|
|
768
|
+
shouldInclude = true;
|
|
769
|
+
if (this.escaped) this.escaped = false;
|
|
770
|
+
else if (byte === 92) this.escaped = true;
|
|
771
|
+
else if (byte === 34) this.inString = false;
|
|
772
|
+
} else if (byte === 34) {
|
|
773
|
+
this.inString = true;
|
|
774
|
+
shouldInclude = true;
|
|
775
|
+
} else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
|
|
776
|
+
if (shouldInclude) {
|
|
777
|
+
this.singleByte[0] = byte;
|
|
778
|
+
this.downstream.update(this.singleByte);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/**
|
|
782
|
+
* Process a buffer range with simple batching
|
|
783
|
+
* Collects consecutive bytes that should be included
|
|
784
|
+
* @param buffer - The buffer to process
|
|
785
|
+
* @param start - Start position (inclusive)
|
|
786
|
+
* @param end - End position (exclusive)
|
|
787
|
+
*/
|
|
788
|
+
updateBuffer(buffer, start = 0, end = buffer.length) {
|
|
789
|
+
let pos = start;
|
|
790
|
+
let runStart = start;
|
|
791
|
+
while (pos < end) {
|
|
792
|
+
const byte = buffer[pos];
|
|
793
|
+
let shouldInclude = false;
|
|
794
|
+
if (this.inString) {
|
|
795
|
+
shouldInclude = true;
|
|
796
|
+
if (this.escaped) this.escaped = false;
|
|
797
|
+
else if (byte === 92) this.escaped = true;
|
|
798
|
+
else if (byte === 34) this.inString = false;
|
|
799
|
+
else {
|
|
800
|
+
pos++;
|
|
801
|
+
let searchPos = pos;
|
|
802
|
+
while (searchPos < end) {
|
|
803
|
+
const quotePos = buffer.indexOf(34, searchPos);
|
|
804
|
+
if (quotePos === -1 || quotePos >= end) {
|
|
805
|
+
pos = end;
|
|
806
|
+
break;
|
|
807
|
+
}
|
|
808
|
+
let backslashCount = 0;
|
|
809
|
+
let checkPos = quotePos - 1;
|
|
810
|
+
while (checkPos >= 0 && buffer[checkPos] === 92) {
|
|
811
|
+
backslashCount++;
|
|
812
|
+
checkPos--;
|
|
813
|
+
}
|
|
814
|
+
if (backslashCount % 2 === 0) {
|
|
815
|
+
pos = quotePos + 1;
|
|
816
|
+
this.inString = false;
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
searchPos = quotePos + 1;
|
|
820
|
+
}
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
} else if (byte === 34) {
|
|
824
|
+
this.inString = true;
|
|
825
|
+
shouldInclude = true;
|
|
826
|
+
} else if (byte !== 9 && byte !== 32 && byte !== 10 && byte !== 13) shouldInclude = true;
|
|
827
|
+
if (shouldInclude) pos++;
|
|
828
|
+
else {
|
|
829
|
+
if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
|
|
830
|
+
pos++;
|
|
831
|
+
runStart = pos;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
if (pos > runStart) this.downstream.update(buffer.subarray(runStart, pos));
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* Reset the parser state
|
|
838
|
+
*/
|
|
839
|
+
reset() {
|
|
840
|
+
this.inString = false;
|
|
841
|
+
this.escaped = false;
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
//#endregion
|
|
846
|
+
//#region src/url-safe-base64.ts
|
|
847
|
+
/**
|
|
848
|
+
* Convert bytes to URL-safe base64
|
|
849
|
+
* Replaces + with -, / with _, and removes = padding
|
|
850
|
+
*/
|
|
851
|
+
function toUrlSafeBase64(bytes) {
|
|
852
|
+
const b64 = Buffer.from(bytes).toString("base64");
|
|
853
|
+
const buf = Buffer.from(b64, "ascii");
|
|
854
|
+
let write = 0;
|
|
855
|
+
for (let read = 0; read < buf.length; read++) {
|
|
856
|
+
const c = buf[read];
|
|
857
|
+
if (c === 43) buf[write++] = 45;
|
|
858
|
+
else if (c === 47) buf[write++] = 95;
|
|
859
|
+
else if (c === 61) {} else buf[write++] = c;
|
|
860
|
+
}
|
|
861
|
+
return buf.subarray(0, write).toString("ascii");
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Convert BigInt to URL-safe base64
|
|
865
|
+
* @param value - The BigInt value to convert
|
|
866
|
+
* @returns URL-safe base64 string representation
|
|
867
|
+
*/
|
|
868
|
+
function bigintToUrlSafeBase64(value) {
|
|
869
|
+
const hashBuffer = new Uint8Array(8);
|
|
870
|
+
new DataView(hashBuffer.buffer).setBigUint64(0, value, false);
|
|
871
|
+
return toUrlSafeBase64(hashBuffer);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
//#endregion
|
|
875
|
+
//#region src/etag-utils.ts
|
|
876
|
+
/**
|
|
877
|
+
* Calculate content ETag using SHA256 from buffer view
|
|
878
|
+
* @param buffer - The file buffer view
|
|
879
|
+
* @param start - Start position (inclusive)
|
|
880
|
+
* @param end - End position (exclusive), or -1 for entire buffer
|
|
881
|
+
*/
|
|
882
|
+
function calculateContentEtagFromBuffer(buffer, start = 0, end = -1) {
|
|
883
|
+
const actualEnd = end === -1 ? buffer.length : end;
|
|
884
|
+
const hasher = createHash("sha256");
|
|
885
|
+
new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
|
|
886
|
+
return toUrlSafeBase64(hasher.digest());
|
|
887
|
+
}
|
|
888
|
+
const dashCode = "-".charCodeAt(0);
|
|
889
|
+
const newlineCode = "\n".charCodeAt(0);
|
|
890
|
+
/**
|
|
891
|
+
* Find the content start position in MDX buffer (after second ---)
|
|
892
|
+
* @param buffer - The MDX content buffer
|
|
893
|
+
* @returns Position where content starts, or -1 if not found
|
|
894
|
+
*/
|
|
895
|
+
function findMdxContentStartPosition(buffer) {
|
|
896
|
+
let dashCount = 0;
|
|
897
|
+
let i = 0;
|
|
898
|
+
while (i < buffer.length - 4) if (buffer[i] === dashCode && buffer[i + 1] === dashCode && buffer[i + 2] === dashCode && buffer[i + 3] === newlineCode) {
|
|
899
|
+
dashCount++;
|
|
900
|
+
if (dashCount === 2) {
|
|
901
|
+
i += 4;
|
|
902
|
+
if (i < buffer.length && buffer[i] === newlineCode) return i + 1;
|
|
903
|
+
return i;
|
|
904
|
+
}
|
|
905
|
+
i += 4;
|
|
906
|
+
} else {
|
|
907
|
+
const nextDashPos = buffer.indexOf(dashCode, i + 1);
|
|
908
|
+
if (nextDashPos === -1) break;
|
|
909
|
+
i = nextDashPos;
|
|
910
|
+
}
|
|
911
|
+
return -1;
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Calculate both ETags from an MDX buffer
|
|
915
|
+
*
|
|
916
|
+
* MDX files use YAML frontmatter which has different characteristics than JSON:
|
|
917
|
+
* - YAML does not require quotes around keys or string values
|
|
918
|
+
* - YAML allows multiple formatting styles (flow vs block style)
|
|
919
|
+
* - YAML field order is not significant for parsing
|
|
920
|
+
*
|
|
921
|
+
* Unlike VXJSON which requires "content" to be the last field and needs special
|
|
922
|
+
* parsing to validate structure, YAML frontmatter can be hashed as-is because:
|
|
923
|
+
* 1. The frontmatter boundaries are clearly delimited by ---
|
|
924
|
+
* 2. Different YAML formatting of the same data SHOULD produce different hashes
|
|
925
|
+
* (e.g., flow style [a,b] vs block style with dashes)
|
|
926
|
+
* 3. There's no requirement to validate field ordering
|
|
927
|
+
*
|
|
928
|
+
* This means we can directly hash the YAML bytes without any whitespace
|
|
929
|
+
* normalization or parsing, which is both simpler and more correct.
|
|
930
|
+
*
|
|
931
|
+
* @param buffer - The complete file buffer
|
|
932
|
+
* @param contentStartPos - Position where content starts (after second ---), or -1 if no content
|
|
933
|
+
*/
|
|
934
|
+
function calculateEtagsFromMdxBuffer(buffer, contentStartPos) {
|
|
935
|
+
if (contentStartPos === -1) {
|
|
936
|
+
const hasher = xxh3.Xxh3.withSeed(0n);
|
|
937
|
+
hasher.update(buffer);
|
|
938
|
+
return {
|
|
939
|
+
metaEtag: bigintToUrlSafeBase64(hasher.digest()),
|
|
940
|
+
contentEtag: calculateContentEtagFromBuffer(new Uint8Array(0))
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
const metaHasher = xxh3.Xxh3.withSeed(0n);
|
|
944
|
+
metaHasher.update(buffer.subarray(0, contentStartPos));
|
|
945
|
+
const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
|
|
946
|
+
const contentHasher = createHash("sha256");
|
|
947
|
+
contentHasher.update(buffer.subarray(contentStartPos));
|
|
948
|
+
return {
|
|
949
|
+
metaEtag,
|
|
950
|
+
contentEtag: toUrlSafeBase64(contentHasher.digest())
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Parse dual ETags from query string: "meta.content"
|
|
955
|
+
*/
|
|
956
|
+
function parseDualEtag(etag) {
|
|
957
|
+
const parts = etag.split(".");
|
|
958
|
+
if (parts.length !== 2) return null;
|
|
959
|
+
return {
|
|
960
|
+
meta: parts[0],
|
|
961
|
+
content: parts[1]
|
|
962
|
+
};
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
//#endregion
|
|
966
|
+
//#region src/vxjson.ts
|
|
967
|
+
const textDecoder$1 = new TextDecoder();
|
|
968
|
+
const CONTENT_MARKER = new TextEncoder().encode("\"content\":");
|
|
969
|
+
/**
|
|
970
|
+
* Calculate metadata ETag using xxHash from buffer view
|
|
971
|
+
* @param buffer - The file buffer view
|
|
972
|
+
* @param start - Start position (inclusive)
|
|
973
|
+
* @param end - End position (exclusive), or -1 for entire buffer
|
|
974
|
+
*/
|
|
975
|
+
function calculateMetaEtagFromBuffer(buffer, start = 0, end = -1) {
|
|
976
|
+
const actualEnd = end === -1 ? buffer.length : end;
|
|
977
|
+
const hasher = xxh3.Xxh3.withSeed(0n);
|
|
978
|
+
new JsonWhitespaceSkippingView(hasher).updateBuffer(buffer, start, actualEnd);
|
|
979
|
+
return bigintToUrlSafeBase64(hasher.digest());
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Calculate both ETags from a VXJSON buffer using views
|
|
983
|
+
* Finds the "content" field position and validates it's the last field
|
|
984
|
+
* @param buffer - The complete file buffer
|
|
985
|
+
* @returns Result with ETags or validation error
|
|
986
|
+
*/
|
|
987
|
+
function calculateEtagsFromVXJSONBuffer(buffer, allowTruncated = false) {
|
|
988
|
+
let pos = 0;
|
|
989
|
+
let depth = 0;
|
|
990
|
+
let inString = false;
|
|
991
|
+
let escaped = false;
|
|
992
|
+
let contentStartPos = -1;
|
|
993
|
+
let foundContentAtRoot = false;
|
|
994
|
+
let expectingKey = false;
|
|
995
|
+
let expectingValue = false;
|
|
996
|
+
let keyStart = -1;
|
|
997
|
+
while (pos < buffer.length && (buffer[pos] === 32 || buffer[pos] === 9 || buffer[pos] === 10 || buffer[pos] === 13)) pos++;
|
|
998
|
+
if (pos >= buffer.length || buffer[pos] !== 123) return {
|
|
999
|
+
success: false,
|
|
1000
|
+
error: "invalid_json"
|
|
1001
|
+
};
|
|
1002
|
+
depth = 1;
|
|
1003
|
+
expectingKey = true;
|
|
1004
|
+
pos++;
|
|
1005
|
+
while (pos < buffer.length && depth > 0) {
|
|
1006
|
+
const byte = buffer[pos];
|
|
1007
|
+
if (inString) {
|
|
1008
|
+
if (escaped) escaped = false;
|
|
1009
|
+
else if (byte === 92) escaped = true;
|
|
1010
|
+
else if (byte === 34) {
|
|
1011
|
+
inString = false;
|
|
1012
|
+
if (depth === 1 && expectingKey && keyStart >= 0) {
|
|
1013
|
+
const keyLength = pos - keyStart + 1;
|
|
1014
|
+
if (foundContentAtRoot) {
|
|
1015
|
+
if (keyLength === 9) {
|
|
1016
|
+
let isContent = true;
|
|
1017
|
+
for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
|
|
1018
|
+
isContent = false;
|
|
1019
|
+
break;
|
|
1020
|
+
}
|
|
1021
|
+
if (isContent) return {
|
|
1022
|
+
success: false,
|
|
1023
|
+
error: "invalid_json"
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
return {
|
|
1027
|
+
success: false,
|
|
1028
|
+
error: "content_not_last"
|
|
1029
|
+
};
|
|
1030
|
+
}
|
|
1031
|
+
if (keyLength === 9) {
|
|
1032
|
+
let isContent = true;
|
|
1033
|
+
for (let i = 0; i < 7; i++) if (buffer[keyStart + 1 + i] !== CONTENT_MARKER[i + 1]) {
|
|
1034
|
+
isContent = false;
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
1037
|
+
if (isContent) {
|
|
1038
|
+
foundContentAtRoot = true;
|
|
1039
|
+
contentStartPos = keyStart;
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
expectingKey = false;
|
|
1043
|
+
expectingValue = true;
|
|
1044
|
+
keyStart = -1;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
} else if (byte === 34) {
|
|
1048
|
+
inString = true;
|
|
1049
|
+
if (depth === 1 && expectingKey) keyStart = pos;
|
|
1050
|
+
} else if (byte === 123 || byte === 91) {
|
|
1051
|
+
depth++;
|
|
1052
|
+
if (depth === 1 && expectingValue) expectingValue = false;
|
|
1053
|
+
} else if (byte === 125 || byte === 93) {
|
|
1054
|
+
depth--;
|
|
1055
|
+
if (depth === 0) break;
|
|
1056
|
+
} else if (byte === 58 && depth === 1) {
|
|
1057
|
+
if (!expectingValue) return {
|
|
1058
|
+
success: false,
|
|
1059
|
+
error: "invalid_json"
|
|
1060
|
+
};
|
|
1061
|
+
} else if (byte === 44 && depth === 1) {
|
|
1062
|
+
expectingKey = true;
|
|
1063
|
+
expectingValue = false;
|
|
1064
|
+
} else if (depth === 1 && expectingValue && byte !== 32 && byte !== 9 && byte !== 10 && byte !== 13) expectingValue = false;
|
|
1065
|
+
pos++;
|
|
1066
|
+
}
|
|
1067
|
+
const isTruncated = depth !== 0;
|
|
1068
|
+
if (isTruncated && !allowTruncated) return {
|
|
1069
|
+
success: false,
|
|
1070
|
+
error: "invalid_json"
|
|
1071
|
+
};
|
|
1072
|
+
if (contentStartPos === -1) return {
|
|
1073
|
+
success: true,
|
|
1074
|
+
metaEtag: calculateMetaEtagFromBuffer(buffer),
|
|
1075
|
+
contentStartPos: -1
|
|
1076
|
+
};
|
|
1077
|
+
if (isTruncated) return {
|
|
1078
|
+
success: true,
|
|
1079
|
+
metaEtag: calculateMetaEtagFromBuffer(buffer, 0, contentStartPos),
|
|
1080
|
+
contentStartPos
|
|
1081
|
+
};
|
|
1082
|
+
let metaEnd = contentStartPos - 1;
|
|
1083
|
+
while (metaEnd > 0) {
|
|
1084
|
+
const byte = buffer[metaEnd];
|
|
1085
|
+
if (byte === 44 || byte === 32 || byte === 9 || byte === 10 || byte === 13) metaEnd--;
|
|
1086
|
+
else break;
|
|
1087
|
+
}
|
|
1088
|
+
const metaHasher = xxh3.Xxh3.withSeed(0n);
|
|
1089
|
+
const metaView = new JsonWhitespaceSkippingView(metaHasher);
|
|
1090
|
+
const openBrace = new Uint8Array([123]);
|
|
1091
|
+
const closeBrace = new Uint8Array([125]);
|
|
1092
|
+
metaHasher.update(openBrace);
|
|
1093
|
+
metaView.updateBuffer(buffer, 1, metaEnd);
|
|
1094
|
+
metaHasher.update(closeBrace);
|
|
1095
|
+
const metaEtag = bigintToUrlSafeBase64(metaHasher.digest());
|
|
1096
|
+
const contentHasher = createHash("sha256");
|
|
1097
|
+
const contentView = new JsonWhitespaceSkippingView(contentHasher);
|
|
1098
|
+
contentHasher.update(openBrace);
|
|
1099
|
+
contentView.updateBuffer(buffer, contentStartPos, buffer.length - 1);
|
|
1100
|
+
contentHasher.update(closeBrace);
|
|
1101
|
+
return {
|
|
1102
|
+
success: true,
|
|
1103
|
+
metaEtag,
|
|
1104
|
+
contentEtag: toUrlSafeBase64(contentHasher.digest()),
|
|
1105
|
+
contentStartPos
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* VXJSON (Variant JSON) module for parsing and serializing VXJSON files
|
|
1110
|
+
*
|
|
1111
|
+
* VXJSON is a specialized JSON format that guarantees:
|
|
1112
|
+
* 1. The root is always an object (never an array or primitive)
|
|
1113
|
+
* 2. The "content" field always comes last in the object
|
|
1114
|
+
* 3. Field order is deterministic for consistent ETag calculation
|
|
1115
|
+
* 4. Metadata fits within 4085 bytes, ensuring "content" field is found within first 4KB
|
|
1116
|
+
* 5. First 4KB must either be complete JSON OR end exactly with '"content":'
|
|
1117
|
+
*
|
|
1118
|
+
* This format enables efficient 4KB parsing where only the first 4KB of a file
|
|
1119
|
+
* needs to be read to extract all metadata and locate the content position.
|
|
1120
|
+
* The constraint that 4KB reads must end with '"content":' ensures reliable parsing.
|
|
1121
|
+
*
|
|
1122
|
+
* This module centralizes all VXJSON-specific logic including:
|
|
1123
|
+
* - Parsing partial buffers (first 4KB for indexing)
|
|
1124
|
+
* - Finding content position for ETag calculation
|
|
1125
|
+
* - Serializing with proper field ordering and size validation
|
|
1126
|
+
* - Calculating ETags from buffers
|
|
1127
|
+
*/
|
|
1128
|
+
/**
|
|
1129
|
+
* VXJSON static utilities for parsing and validating VXJSON files
|
|
1130
|
+
*/
|
|
1131
|
+
var VXJSON = class VXJSON {
|
|
1132
|
+
/**
|
|
1133
|
+
* Parse first 4KB of VXJSON content from buffer
|
|
1134
|
+
* Used during indexing to extract metadata without loading full content
|
|
1135
|
+
*
|
|
1136
|
+
* VXJSON format requirement: first 4KB must either be complete JSON OR end with '"content":'
|
|
1137
|
+
* This ensures reliable parsing and validation.
|
|
1138
|
+
*/
|
|
1139
|
+
static parse4KB(buffer, bytesRead) {
|
|
1140
|
+
if (bytesRead < 4096 || buffer[bytesRead - 1] === 125) {
|
|
1141
|
+
const partialContent = textDecoder$1.decode(buffer.subarray(0, bytesRead));
|
|
1142
|
+
const data = JSON.parse(partialContent);
|
|
1143
|
+
let contentStartPos = -1;
|
|
1144
|
+
if (data.content !== void 0) {
|
|
1145
|
+
const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead));
|
|
1146
|
+
if (etagResult.success) contentStartPos = etagResult.contentStartPos;
|
|
1147
|
+
}
|
|
1148
|
+
return {
|
|
1149
|
+
id: data.id,
|
|
1150
|
+
created: data.created,
|
|
1151
|
+
modified: data.modified,
|
|
1152
|
+
publishAt: data.publishAt,
|
|
1153
|
+
unpublishAt: data.unpublishAt,
|
|
1154
|
+
previousPathnames: data.previousPathnames,
|
|
1155
|
+
pathname: data.pathname,
|
|
1156
|
+
name: data.name,
|
|
1157
|
+
meta: data.meta || {},
|
|
1158
|
+
content: data.content,
|
|
1159
|
+
contentStartPos
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
const etagResult = calculateEtagsFromVXJSONBuffer(buffer.subarray(0, bytesRead), true);
|
|
1163
|
+
if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}. This violates the VXJSON specification.`);
|
|
1164
|
+
const contentStartPos = etagResult.contentStartPos;
|
|
1165
|
+
let metadataEnd = contentStartPos;
|
|
1166
|
+
while (metadataEnd > 0) {
|
|
1167
|
+
const byte = buffer[metadataEnd - 1];
|
|
1168
|
+
if (byte === 44) {
|
|
1169
|
+
metadataEnd--;
|
|
1170
|
+
break;
|
|
1171
|
+
}
|
|
1172
|
+
if (byte === 32 || byte === 9 || byte === 10 || byte === 13) metadataEnd--;
|
|
1173
|
+
else break;
|
|
1174
|
+
}
|
|
1175
|
+
const metadataBuffer = new Uint8Array(metadataEnd + 1);
|
|
1176
|
+
metadataBuffer.set(buffer.subarray(0, metadataEnd));
|
|
1177
|
+
metadataBuffer[metadataEnd] = 125;
|
|
1178
|
+
const partialContent = textDecoder$1.decode(metadataBuffer);
|
|
1179
|
+
const data = JSON.parse(partialContent);
|
|
1180
|
+
return {
|
|
1181
|
+
id: data.id,
|
|
1182
|
+
created: data.created,
|
|
1183
|
+
modified: data.modified,
|
|
1184
|
+
publishAt: data.publishAt,
|
|
1185
|
+
unpublishAt: data.unpublishAt,
|
|
1186
|
+
previousPathnames: data.previousPathnames,
|
|
1187
|
+
pathname: data.pathname,
|
|
1188
|
+
name: data.name,
|
|
1189
|
+
meta: data.meta || {},
|
|
1190
|
+
contentStartPos
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Find the position of the "content" field in a VXJSON buffer
|
|
1195
|
+
* Returns -1 if not found
|
|
1196
|
+
*/
|
|
1197
|
+
static findContentPosition(buffer) {
|
|
1198
|
+
const etagResult = calculateEtagsFromVXJSONBuffer(buffer);
|
|
1199
|
+
if (etagResult.success) return etagResult.contentStartPos;
|
|
1200
|
+
return -1;
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Calculate ETags for a VXJSON buffer
|
|
1204
|
+
* Returns null if the buffer is not valid VXJSON
|
|
1205
|
+
*/
|
|
1206
|
+
static calculateEtagsOnly(buffer) {
|
|
1207
|
+
const result = calculateEtagsFromVXJSONBuffer(buffer);
|
|
1208
|
+
if (!result.success) return null;
|
|
1209
|
+
return {
|
|
1210
|
+
metaEtag: result.metaEtag,
|
|
1211
|
+
contentEtag: result.contentEtag
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Create a dual ETag string from a VXJSON buffer
|
|
1216
|
+
* Returns null if the buffer is not valid VXJSON
|
|
1217
|
+
*/
|
|
1218
|
+
static createEtag(buffer) {
|
|
1219
|
+
const etags = VXJSON.calculateEtagsOnly(buffer);
|
|
1220
|
+
if (!etags) return null;
|
|
1221
|
+
return etags.contentEtag ? `${etags.metaEtag}.${etags.contentEtag}` : etags.metaEtag;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Validate that a VXJSON buffer has the correct structure
|
|
1225
|
+
* (content field must be last)
|
|
1226
|
+
*/
|
|
1227
|
+
static isValid(buffer) {
|
|
1228
|
+
return calculateEtagsFromVXJSONBuffer(buffer).success;
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Parse a complete VXJSON file from string
|
|
1232
|
+
*/
|
|
1233
|
+
static parse(content) {
|
|
1234
|
+
return JSON.parse(content);
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Parse a complete VXJSON file from buffer
|
|
1238
|
+
*/
|
|
1239
|
+
static parseBuffer(buffer) {
|
|
1240
|
+
const content = textDecoder$1.decode(buffer);
|
|
1241
|
+
return VXJSON.parse(content);
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Calculate both ETags from a VXJSON buffer using views
|
|
1245
|
+
* Finds the "content" field position and validates it's the last field
|
|
1246
|
+
* @param buffer - The complete file buffer
|
|
1247
|
+
* @returns Result with ETags or validation error
|
|
1248
|
+
*/
|
|
1249
|
+
static calculateETags = calculateEtagsFromVXJSONBuffer;
|
|
1250
|
+
/**
|
|
1251
|
+
* Calculate a simple single etag from the entire buffer
|
|
1252
|
+
* Used for data files that don't follow the content-last convention
|
|
1253
|
+
*/
|
|
1254
|
+
static calculateSimpleEtag(buffer) {
|
|
1255
|
+
return calculateMetaEtagFromBuffer(buffer);
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Serialize a VXJSONFile to VXJSON format string
|
|
1259
|
+
* Ensures content field is last and enforces 4KB constraint efficiently
|
|
1260
|
+
*/
|
|
1261
|
+
static serialize(data) {
|
|
1262
|
+
const { content, ...metadataFields } = data;
|
|
1263
|
+
if (content === void 0 || content === null) throw new Error("VXJSON format requires a \"content\" field");
|
|
1264
|
+
const sortedMetadata = sortKeys(metadataFields, { deep: true });
|
|
1265
|
+
const metadataJson = JSON.stringify(sortedMetadata, (_key, value) => {
|
|
1266
|
+
if (value === "") return;
|
|
1267
|
+
return value;
|
|
1268
|
+
}, " ");
|
|
1269
|
+
const wrappedContent = JSON.stringify({ c: sortKeys(content, { deep: true }) }, null, " ");
|
|
1270
|
+
const contentJson = wrappedContent.slice(wrappedContent.indexOf(": ") + 2, -2);
|
|
1271
|
+
const metadataWithoutClosing = metadataJson.slice(0, -2);
|
|
1272
|
+
const contentFieldPrefix = ",\n \"content\": ";
|
|
1273
|
+
const contentKeyPosition = metadataWithoutClosing.length + 1 + 2;
|
|
1274
|
+
const maxContentKeyPosition = 4086;
|
|
1275
|
+
if (contentKeyPosition > maxContentKeyPosition) throw new Error(`VXJSON format violation: metadata too large. "content" field would start at position ${contentKeyPosition}, but must start within ${maxContentKeyPosition} bytes. Reduce metadata size by ${contentKeyPosition - maxContentKeyPosition} bytes.`);
|
|
1276
|
+
return `${metadataWithoutClosing}${contentFieldPrefix}${contentJson}\n}`;
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
//#endregion
|
|
1281
|
+
//#region src/filesystem-content-api.ts
|
|
1282
|
+
var filesystem_content_api_exports = /* @__PURE__ */ __exportAll({ FileSystemContentAPI: () => FileSystemContentAPI });
|
|
1283
|
+
function ensureError(error) {
|
|
1284
|
+
if (error instanceof Error) return error;
|
|
1285
|
+
return new Error(String(error));
|
|
1286
|
+
}
|
|
1287
|
+
const textDecoder = new TextDecoder();
|
|
1288
|
+
function parse4KBMDX(buffer, bytesRead) {
|
|
1289
|
+
const { data: frontmatter } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
|
|
1290
|
+
const delimiter = new TextEncoder().encode("---");
|
|
1291
|
+
let delimiterCount = 0;
|
|
1292
|
+
let contentStartPos = -1;
|
|
1293
|
+
for (let i = 0; i <= bytesRead - delimiter.length; i++) {
|
|
1294
|
+
let match = true;
|
|
1295
|
+
for (let j = 0; j < delimiter.length; j++) if (buffer[i + j] !== delimiter[j]) {
|
|
1296
|
+
match = false;
|
|
1297
|
+
break;
|
|
1298
|
+
}
|
|
1299
|
+
if (match) {
|
|
1300
|
+
delimiterCount++;
|
|
1301
|
+
if (delimiterCount === 2) {
|
|
1302
|
+
contentStartPos = i + delimiter.length;
|
|
1303
|
+
while (contentStartPos < bytesRead && (buffer[contentStartPos] === 10 || buffer[contentStartPos] === 13)) contentStartPos++;
|
|
1304
|
+
break;
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
|
|
1309
|
+
return {
|
|
1310
|
+
id,
|
|
1311
|
+
created,
|
|
1312
|
+
modified,
|
|
1313
|
+
publishAt,
|
|
1314
|
+
unpublishAt,
|
|
1315
|
+
meta: metaFields,
|
|
1316
|
+
contentStartPos
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* FileSystem-based Content API Implementation
|
|
1321
|
+
*
|
|
1322
|
+
* Stores content as files on disk in a git-friendly format:
|
|
1323
|
+
* - Pages: /{site}/pages/{filename}.{locale}.vxjson
|
|
1324
|
+
* - Blocks: /blocks/{collection}/{filename}.{locale}.{mdx|vxjson}
|
|
1325
|
+
*
|
|
1326
|
+
* ## Indexing
|
|
1327
|
+
*
|
|
1328
|
+
* Content is indexed at startup for performance. The index is cached per
|
|
1329
|
+
* content root path and cleared when the process restarts.
|
|
1330
|
+
*
|
|
1331
|
+
* ## Read-Repair
|
|
1332
|
+
*
|
|
1333
|
+
* Since files can be modified externally (git, editors), this implementation:
|
|
1334
|
+
*
|
|
1335
|
+
* 1. Repairs invalid VXJSON files (ensures "content" field is last)
|
|
1336
|
+
* 2. Adds missing required fields (id, created, modified)
|
|
1337
|
+
* 3. Handles files added after initial indexing
|
|
1338
|
+
* 4. Updates the index when files are repaired or discovered
|
|
1339
|
+
*
|
|
1340
|
+
* ## Performance
|
|
1341
|
+
*
|
|
1342
|
+
* - Initial indexing reads only first 4KB of each file
|
|
1343
|
+
* - Full content is loaded on demand
|
|
1344
|
+
* - ETags are calculated using streaming for efficiency
|
|
1345
|
+
*/
|
|
1346
|
+
var FileSystemContentAPI = class FileSystemContentAPI {
|
|
1347
|
+
contentRoot;
|
|
1348
|
+
absoluteContentRoot;
|
|
1349
|
+
contentIndex;
|
|
1350
|
+
sitesConfig;
|
|
1351
|
+
blocks;
|
|
1352
|
+
data;
|
|
1353
|
+
sites;
|
|
1354
|
+
get normalizedContentRoot() {
|
|
1355
|
+
return this.contentRoot;
|
|
1356
|
+
}
|
|
1357
|
+
constructor(contentRoot, canvasDir, sitesConfig, contentIndex) {
|
|
1358
|
+
if (contentRoot.startsWith("./")) this.contentRoot = contentRoot.slice(2);
|
|
1359
|
+
else if (contentRoot.startsWith("/")) this.contentRoot = contentRoot;
|
|
1360
|
+
else this.contentRoot = contentRoot;
|
|
1361
|
+
this.absoluteContentRoot = resolve(this.contentRoot);
|
|
1362
|
+
this.sitesConfig = sitesConfig;
|
|
1363
|
+
this.contentIndex = contentIndex;
|
|
1364
|
+
this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
|
|
1365
|
+
this.data = new Data(this, this.contentIndex.getDataIndex());
|
|
1366
|
+
this.sites = mapSiteNames(sitesConfig, (siteName) => {
|
|
1367
|
+
const siteIndex = this.contentIndex.getSiteIndex(siteName);
|
|
1368
|
+
if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
|
|
1369
|
+
return new Site(siteName, this, siteIndex);
|
|
1370
|
+
});
|
|
1371
|
+
}
|
|
1372
|
+
static async create(options) {
|
|
1373
|
+
const { canvasDir } = options;
|
|
1374
|
+
const contentRoot = options.contentRoot;
|
|
1375
|
+
const sitesPath = join(resolve(contentRoot), "sites.json");
|
|
1376
|
+
let sitesConfig;
|
|
1377
|
+
try {
|
|
1378
|
+
const content = await readFile(sitesPath, "utf-8");
|
|
1379
|
+
const parsed = JSON.parse(content);
|
|
1380
|
+
if (!parsed.sites || typeof parsed.sites !== "object") {
|
|
1381
|
+
console.warn(`Warning: sites.json has invalid structure at ${sitesPath}. Expected 'sites' property. Using default configuration.`);
|
|
1382
|
+
sitesConfig = {
|
|
1383
|
+
sites: {},
|
|
1384
|
+
globalLocales: ["en"]
|
|
1385
|
+
};
|
|
1386
|
+
} else if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
|
|
1387
|
+
console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
|
|
1388
|
+
sitesConfig = {
|
|
1389
|
+
sites: parsed.sites,
|
|
1390
|
+
globalLocales: ["en"]
|
|
1391
|
+
};
|
|
1392
|
+
} else sitesConfig = parsed;
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
console.warn(`Warning: sites.json is missing at ${sitesPath}. Using empty configuration.`);
|
|
1395
|
+
sitesConfig = {
|
|
1396
|
+
sites: {},
|
|
1397
|
+
globalLocales: ["en"]
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
const normalizedContentRoot = contentRoot.startsWith("./") ? contentRoot.slice(2) : contentRoot;
|
|
1401
|
+
const contentIndex = await ContentIndex.getCachedOrCreate(normalizedContentRoot, sitesConfig);
|
|
1402
|
+
const api = new FileSystemContentAPI(contentRoot, canvasDir, sitesConfig, contentIndex);
|
|
1403
|
+
if (contentIndex.entryCount === 0) await api.indexAllContent();
|
|
1404
|
+
return api;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Clear all caches - useful for testing
|
|
1408
|
+
*/
|
|
1409
|
+
static clearCaches() {
|
|
1410
|
+
ContentIndex.clearCache();
|
|
1411
|
+
}
|
|
1412
|
+
async indexAllContent() {
|
|
1413
|
+
this.contentIndex.clear();
|
|
1414
|
+
const files = await this.scanContentFiles();
|
|
1415
|
+
const OPTIMAL_BATCH_SIZE = 1e3;
|
|
1416
|
+
console.debug(`Indexing ${files.length} content files...`);
|
|
1417
|
+
const bufferCount = Math.min(files.length, OPTIMAL_BATCH_SIZE);
|
|
1418
|
+
const buffers = Array.from({ length: bufferCount }, () => new Uint8Array(4096));
|
|
1419
|
+
for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
|
|
1420
|
+
const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
|
|
1421
|
+
await Promise.all(batch.map(async (filePath, index) => {
|
|
1422
|
+
try {
|
|
1423
|
+
const result = await this.parseFileHeaderWithRepair(filePath, buffers[index]);
|
|
1424
|
+
if (result) {
|
|
1425
|
+
const { manifest, localeVersion, content } = result;
|
|
1426
|
+
this.contentIndex.addContent(manifest, localeVersion, content);
|
|
1427
|
+
}
|
|
1428
|
+
} catch (error) {
|
|
1429
|
+
console.error(`Failed to index ${filePath}:`, error);
|
|
1430
|
+
}
|
|
1431
|
+
}));
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
async parseFileHeaderWithRepair(originalFilePath, buffer) {
|
|
1435
|
+
let handle;
|
|
1436
|
+
let bytesRead = 0;
|
|
1437
|
+
let filePath = originalFilePath;
|
|
1438
|
+
try {
|
|
1439
|
+
handle = await open(filePath, "r");
|
|
1440
|
+
bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
|
|
1441
|
+
} catch (error) {
|
|
1442
|
+
console.error(`Error reading ${filePath}:`, error);
|
|
1443
|
+
throw error;
|
|
1444
|
+
} finally {
|
|
1445
|
+
await handle?.close();
|
|
1446
|
+
}
|
|
1447
|
+
try {
|
|
1448
|
+
let relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
|
|
1449
|
+
let parts = relativePath.split("/");
|
|
1450
|
+
let site;
|
|
1451
|
+
let collection;
|
|
1452
|
+
let locale = "en";
|
|
1453
|
+
let name;
|
|
1454
|
+
let pathname;
|
|
1455
|
+
let parsedData = {};
|
|
1456
|
+
let kind;
|
|
1457
|
+
if (parts[0] === "blocks") {
|
|
1458
|
+
kind = "block";
|
|
1459
|
+
if (parts.length === 2) {
|
|
1460
|
+
collection = "general";
|
|
1461
|
+
const filename = parts[1];
|
|
1462
|
+
const generalDir = join(this.absoluteContentRoot, "blocks", "general");
|
|
1463
|
+
try {
|
|
1464
|
+
await mkdir(generalDir, { recursive: true });
|
|
1465
|
+
} catch (error) {}
|
|
1466
|
+
const newFilePath = join(generalDir, filename);
|
|
1467
|
+
try {
|
|
1468
|
+
await handle?.close();
|
|
1469
|
+
handle = void 0;
|
|
1470
|
+
try {
|
|
1471
|
+
await (await open(newFilePath, "r")).close();
|
|
1472
|
+
console.warn(`Cannot move ${filename} to blocks/general/: target file already exists`);
|
|
1473
|
+
} catch (error) {
|
|
1474
|
+
await rename(filePath, newFilePath);
|
|
1475
|
+
console.log(`Repaired: Moved ${filename} to blocks/general/ collection`);
|
|
1476
|
+
filePath = newFilePath;
|
|
1477
|
+
relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
|
|
1478
|
+
parts = relativePath.split("/");
|
|
1479
|
+
handle = await open(filePath, "r");
|
|
1480
|
+
bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
|
|
1481
|
+
}
|
|
1482
|
+
} catch (moveError) {
|
|
1483
|
+
console.error(`Failed to move ${filename} to general collection:`, moveError);
|
|
1484
|
+
handle = await open(filePath, "r");
|
|
1485
|
+
bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
|
|
1486
|
+
}
|
|
1487
|
+
} else collection = parts[1];
|
|
1488
|
+
const filename = parts[parts.length - 1];
|
|
1489
|
+
const matchWithLocale = filename.match(/^(.+)\.(\w+)\.(mdx|vxjson)$/);
|
|
1490
|
+
const matchWithoutLocale = filename.match(/^(.+)\.(mdx|vxjson)$/);
|
|
1491
|
+
if (matchWithLocale) {
|
|
1492
|
+
name = matchWithLocale[1];
|
|
1493
|
+
locale = matchWithLocale[2];
|
|
1494
|
+
} else if (matchWithoutLocale) {
|
|
1495
|
+
name = matchWithoutLocale[1];
|
|
1496
|
+
locale = this.contentIndex.getDefaultLocale("");
|
|
1497
|
+
console.log(`Found file without locale suffix: ${filename}`);
|
|
1498
|
+
const extension = matchWithoutLocale[2];
|
|
1499
|
+
const newFilename = `${name}.${locale}.${extension}`;
|
|
1500
|
+
const newFilePath = join(dirname(filePath), newFilename);
|
|
1501
|
+
console.log(`Will rename to: ${newFilename} at ${newFilePath}`);
|
|
1502
|
+
try {
|
|
1503
|
+
await handle?.close();
|
|
1504
|
+
handle = void 0;
|
|
1505
|
+
await (await open(newFilePath, "r")).close();
|
|
1506
|
+
console.warn(`Cannot rename ${filename} to ${newFilename}: target file already exists`);
|
|
1507
|
+
} catch (error) {
|
|
1508
|
+
console.log(`Target file doesn't exist, proceeding with rename`);
|
|
1509
|
+
try {
|
|
1510
|
+
await rename(filePath, newFilePath);
|
|
1511
|
+
console.log(`Successfully renamed ${filename} to ${newFilename}`);
|
|
1512
|
+
filePath = newFilePath;
|
|
1513
|
+
relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
|
|
1514
|
+
parts = relativePath.split("/");
|
|
1515
|
+
handle = await open(filePath, "r");
|
|
1516
|
+
bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
|
|
1517
|
+
} catch (renameError) {
|
|
1518
|
+
console.error(`Failed to rename ${filename}:`, renameError);
|
|
1519
|
+
handle = await open(filePath, "r");
|
|
1520
|
+
bytesRead = (await handle.read(buffer, 0, 4096, 0)).bytesRead;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
if (filePath.endsWith(".mdx")) parsedData = parse4KBMDX(buffer, bytesRead);
|
|
1525
|
+
else parsedData = VXJSON.parse4KB(buffer, bytesRead);
|
|
1526
|
+
} else if (parts[0] === "data") {
|
|
1527
|
+
kind = "data";
|
|
1528
|
+
collection = parts[1];
|
|
1529
|
+
const match = parts[parts.length - 1].match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
|
|
1530
|
+
if (match) {
|
|
1531
|
+
name = match[1];
|
|
1532
|
+
locale = match[2];
|
|
1533
|
+
}
|
|
1534
|
+
const content = textDecoder.decode(buffer.subarray(0, bytesRead));
|
|
1535
|
+
try {
|
|
1536
|
+
const jsonData = JSON.parse(content);
|
|
1537
|
+
parsedData = {
|
|
1538
|
+
id: jsonData.id,
|
|
1539
|
+
type: "json",
|
|
1540
|
+
created: jsonData.created,
|
|
1541
|
+
modified: jsonData.modified,
|
|
1542
|
+
publishAt: jsonData.publishAt,
|
|
1543
|
+
unpublishAt: jsonData.unpublishAt,
|
|
1544
|
+
meta: jsonData.meta || { title: name || "Untitled" },
|
|
1545
|
+
data: jsonData.data,
|
|
1546
|
+
name
|
|
1547
|
+
};
|
|
1548
|
+
} catch (error) {
|
|
1549
|
+
console.error(`Failed to parse JSON data file ${filePath}:`, error);
|
|
1550
|
+
return null;
|
|
1551
|
+
}
|
|
1552
|
+
} else {
|
|
1553
|
+
kind = "page";
|
|
1554
|
+
site = parts[0];
|
|
1555
|
+
collection = parts[1];
|
|
1556
|
+
const pathParts = parts.slice(2);
|
|
1557
|
+
const match = pathParts[pathParts.length - 1].match(/^(.+)\.(\w+)\.vxjson$/);
|
|
1558
|
+
if (match) {
|
|
1559
|
+
locale = match[2];
|
|
1560
|
+
pathParts[pathParts.length - 1] = match[1];
|
|
1561
|
+
pathname = pathParts[pathParts.length - 1] === "index" ? "/" + pathParts.slice(0, -1).join("/") || "/" : "/" + pathParts.join("/");
|
|
1562
|
+
}
|
|
1563
|
+
parsedData = VXJSON.parse4KB(buffer, bytesRead);
|
|
1564
|
+
}
|
|
1565
|
+
const needsRepair = !parsedData.id || !parsedData.created || !parsedData.modified;
|
|
1566
|
+
const id = parsedData.id || generateContentId();
|
|
1567
|
+
const localeVersion = {
|
|
1568
|
+
locale,
|
|
1569
|
+
etag: "",
|
|
1570
|
+
created: parsedData.created || (/* @__PURE__ */ new Date()).toISOString(),
|
|
1571
|
+
modified: parsedData.modified || (/* @__PURE__ */ new Date()).toISOString(),
|
|
1572
|
+
...parsedData.publishAt && { publishAt: parsedData.publishAt },
|
|
1573
|
+
...parsedData.unpublishAt && { unpublishAt: parsedData.unpublishAt },
|
|
1574
|
+
...pathname && { pathname },
|
|
1575
|
+
...parsedData.previousPathnames && { previousPathnames: parsedData.previousPathnames },
|
|
1576
|
+
...name && { name },
|
|
1577
|
+
meta: parsedData.meta || { title: name || "Untitled" }
|
|
1578
|
+
};
|
|
1579
|
+
const manifest = {
|
|
1580
|
+
id,
|
|
1581
|
+
type: parsedData.type || (filePath.endsWith(".mdx") ? "mdx" : filePath.endsWith(".json") ? "json" : "puck"),
|
|
1582
|
+
kind,
|
|
1583
|
+
site,
|
|
1584
|
+
collection,
|
|
1585
|
+
locales: { [locale]: localeVersion }
|
|
1586
|
+
};
|
|
1587
|
+
let content;
|
|
1588
|
+
if (needsRepair) {
|
|
1589
|
+
const repairedData = await this.performReadRepair(filePath, manifest, locale);
|
|
1590
|
+
if (repairedData) {
|
|
1591
|
+
content = repairedData.content;
|
|
1592
|
+
localeVersion.etag = repairedData.etag;
|
|
1593
|
+
localeVersion.modified = repairedData.modified;
|
|
1594
|
+
return {
|
|
1595
|
+
manifest,
|
|
1596
|
+
locale,
|
|
1597
|
+
localeVersion,
|
|
1598
|
+
bytesRead,
|
|
1599
|
+
content
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
console.error(`Failed to repair ${filePath}, skipping`);
|
|
1603
|
+
return null;
|
|
1604
|
+
}
|
|
1605
|
+
if (bytesRead < 4096 || filePath.endsWith(".vxjson") && buffer[bytesRead - 1] === 125 || filePath.endsWith(".json") && buffer[bytesRead - 1] === 125) {
|
|
1606
|
+
if (filePath.endsWith(".mdx")) {
|
|
1607
|
+
const { content: mdx } = matter(textDecoder.decode(buffer.subarray(0, bytesRead)));
|
|
1608
|
+
content = { mdx };
|
|
1609
|
+
} else if (filePath.endsWith(".json")) {
|
|
1610
|
+
const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
|
|
1611
|
+
content = { data: JSON.parse(fullContent).data };
|
|
1612
|
+
} else {
|
|
1613
|
+
const fullContent = textDecoder.decode(buffer.subarray(0, bytesRead));
|
|
1614
|
+
content = JSON.parse(fullContent).content || {};
|
|
1615
|
+
}
|
|
1616
|
+
const validBuffer = buffer.subarray(0, bytesRead);
|
|
1617
|
+
if (filePath.endsWith(".mdx")) {
|
|
1618
|
+
const etags = calculateEtagsFromMdxBuffer(validBuffer, parsedData.contentStartPos || -1);
|
|
1619
|
+
localeVersion.etag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
1620
|
+
} else if (filePath.endsWith(".json")) localeVersion.etag = VXJSON.calculateSimpleEtag(validBuffer);
|
|
1621
|
+
else {
|
|
1622
|
+
const etagResult = VXJSON.calculateETags(validBuffer);
|
|
1623
|
+
if (!etagResult.success) {
|
|
1624
|
+
const repairedData = await this.performReadRepair(filePath, manifest, locale);
|
|
1625
|
+
if (repairedData) {
|
|
1626
|
+
content = repairedData.content;
|
|
1627
|
+
localeVersion.etag = repairedData.etag;
|
|
1628
|
+
localeVersion.modified = repairedData.modified;
|
|
1629
|
+
return {
|
|
1630
|
+
manifest,
|
|
1631
|
+
locale,
|
|
1632
|
+
localeVersion,
|
|
1633
|
+
bytesRead,
|
|
1634
|
+
content
|
|
1635
|
+
};
|
|
1636
|
+
}
|
|
1637
|
+
console.error(`Failed to repair ${filePath}, skipping`);
|
|
1638
|
+
return null;
|
|
1639
|
+
}
|
|
1640
|
+
localeVersion.etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
return {
|
|
1644
|
+
manifest,
|
|
1645
|
+
locale,
|
|
1646
|
+
localeVersion,
|
|
1647
|
+
bytesRead,
|
|
1648
|
+
content
|
|
1649
|
+
};
|
|
1650
|
+
} catch (error) {
|
|
1651
|
+
console.error(`Error indexing ${originalFilePath}:`, error);
|
|
1652
|
+
return null;
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Perform read-repair by writing back the file with missing fields
|
|
1657
|
+
* This ensures stable IDs and timestamps across restarts
|
|
1658
|
+
*/
|
|
1659
|
+
async performReadRepair(filePath, manifest, locale) {
|
|
1660
|
+
try {
|
|
1661
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1662
|
+
let needsWrite = false;
|
|
1663
|
+
if (manifest.type === "mdx") {
|
|
1664
|
+
const parsed = matter(await readFile(filePath, "utf-8"));
|
|
1665
|
+
if (!parsed.data.id) {
|
|
1666
|
+
parsed.data.id = manifest.id;
|
|
1667
|
+
needsWrite = true;
|
|
1668
|
+
}
|
|
1669
|
+
if (!parsed.data.created) {
|
|
1670
|
+
parsed.data.created = now;
|
|
1671
|
+
needsWrite = true;
|
|
1672
|
+
}
|
|
1673
|
+
if (!parsed.data.modified) {
|
|
1674
|
+
parsed.data.modified = now;
|
|
1675
|
+
needsWrite = true;
|
|
1676
|
+
}
|
|
1677
|
+
if (needsWrite) {
|
|
1678
|
+
const updatedContent = matter.stringify(parsed.content, parsed.data);
|
|
1679
|
+
await writeFile(filePath, updatedContent);
|
|
1680
|
+
console.log(`Repaired MDX file: ${filePath} (added missing fields)`);
|
|
1681
|
+
const etags = calculateEtagsFromMdxBuffer(Buffer.from(updatedContent, "utf-8"), updatedContent.indexOf("\n---\n") + 5);
|
|
1682
|
+
const etag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
1683
|
+
return {
|
|
1684
|
+
content: { mdx: parsed.content },
|
|
1685
|
+
etag,
|
|
1686
|
+
modified: parsed.data.modified || now
|
|
1687
|
+
};
|
|
1688
|
+
}
|
|
1689
|
+
} else {
|
|
1690
|
+
const content = await readFile(filePath, "utf-8");
|
|
1691
|
+
const data = JSON.parse(content);
|
|
1692
|
+
if (!data.id) {
|
|
1693
|
+
data.id = manifest.id;
|
|
1694
|
+
needsWrite = true;
|
|
1695
|
+
}
|
|
1696
|
+
if (!data.created) {
|
|
1697
|
+
data.created = now;
|
|
1698
|
+
needsWrite = true;
|
|
1699
|
+
}
|
|
1700
|
+
if (!data.modified) {
|
|
1701
|
+
data.modified = now;
|
|
1702
|
+
needsWrite = true;
|
|
1703
|
+
}
|
|
1704
|
+
needsWrite = true;
|
|
1705
|
+
if (needsWrite) {
|
|
1706
|
+
const vxjsonData = {
|
|
1707
|
+
id: data.id,
|
|
1708
|
+
type: data.type,
|
|
1709
|
+
created: data.created,
|
|
1710
|
+
modified: data.modified,
|
|
1711
|
+
publishAt: data.publishAt,
|
|
1712
|
+
unpublishAt: data.unpublishAt,
|
|
1713
|
+
previousPathnames: data.previousPathnames,
|
|
1714
|
+
meta: data.meta || {},
|
|
1715
|
+
content: data.content || {}
|
|
1716
|
+
};
|
|
1717
|
+
const repairedJson = VXJSON.serialize(vxjsonData);
|
|
1718
|
+
await writeFile(filePath, repairedJson);
|
|
1719
|
+
console.log(`Repaired VXJSON file: ${filePath} (fixed field order or added missing fields)`);
|
|
1720
|
+
const repairedBuffer = Buffer.from(repairedJson, "utf-8");
|
|
1721
|
+
const etagResult = VXJSON.calculateETags(repairedBuffer);
|
|
1722
|
+
if (!etagResult.success) {
|
|
1723
|
+
console.error(`Failed to calculate ETags after repair: ${filePath}`);
|
|
1724
|
+
return null;
|
|
1725
|
+
}
|
|
1726
|
+
const etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
1727
|
+
return {
|
|
1728
|
+
content: vxjsonData.content,
|
|
1729
|
+
etag,
|
|
1730
|
+
modified: vxjsonData.modified
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
return null;
|
|
1735
|
+
} catch (error) {
|
|
1736
|
+
console.error(`Failed to perform read-repair on ${filePath}:`, error);
|
|
1737
|
+
return null;
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
async scanContentFiles() {
|
|
1741
|
+
const files = [];
|
|
1742
|
+
const contentRoot = this.absoluteContentRoot;
|
|
1743
|
+
async function scan(dir, inDataDir = false) {
|
|
1744
|
+
try {
|
|
1745
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
1746
|
+
for (const entry of entries) {
|
|
1747
|
+
const fullPath = join(dir, entry.name);
|
|
1748
|
+
if (entry.isDirectory()) {
|
|
1749
|
+
const isDataDir = dir === contentRoot && entry.name === "data";
|
|
1750
|
+
await scan(fullPath, inDataDir || isDataDir);
|
|
1751
|
+
} else if (entry.isFile()) {
|
|
1752
|
+
if (entry.name.endsWith(".vxjson") || entry.name.endsWith(".mdx")) files.push(fullPath);
|
|
1753
|
+
else if (inDataDir && entry.name.endsWith(".json")) files.push(fullPath);
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
} catch (error) {}
|
|
1757
|
+
}
|
|
1758
|
+
await scan(this.absoluteContentRoot);
|
|
1759
|
+
return files;
|
|
1760
|
+
}
|
|
1761
|
+
getFilePath(manifest, { locale, name, pathname }) {
|
|
1762
|
+
if (manifest.kind === "block") {
|
|
1763
|
+
const ext = manifest.type === "mdx" ? "mdx" : "vxjson";
|
|
1764
|
+
return join(this.absoluteContentRoot, "blocks", manifest.collection, `${name}.${locale}.${ext}`);
|
|
1765
|
+
}
|
|
1766
|
+
if (manifest.kind === "data") return join(this.absoluteContentRoot, "data", manifest.collection, `${name}.${locale}.json`);
|
|
1767
|
+
if (manifest.kind === "page" && pathname && manifest.site) {
|
|
1768
|
+
const basePath = pathname.replace(/^\//, "").replace(/\/$/, "") || "index";
|
|
1769
|
+
return join(this.absoluteContentRoot, manifest.site, manifest.collection, `${basePath}.${locale}.vxjson`);
|
|
1770
|
+
}
|
|
1771
|
+
throw new Error(`Invalid manifest: ${JSON.stringify(manifest, null, 2)}`);
|
|
1772
|
+
}
|
|
1773
|
+
/**
|
|
1774
|
+
* Parse a file path back into its components for checking against the path index
|
|
1775
|
+
* Returns null if the path doesn't match expected patterns
|
|
1776
|
+
*/
|
|
1777
|
+
parseFilePath(filePath) {
|
|
1778
|
+
const parts = filePath.replace(this.absoluteContentRoot + "/", "").split("/");
|
|
1779
|
+
const filename = parts[parts.length - 1];
|
|
1780
|
+
if (parts[0] === "data" && parts.length === 3) {
|
|
1781
|
+
const dataMatch = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.json$/);
|
|
1782
|
+
if (!dataMatch) return null;
|
|
1783
|
+
const [, name, locale] = dataMatch;
|
|
1784
|
+
return {
|
|
1785
|
+
kind: "data",
|
|
1786
|
+
collection: parts[1],
|
|
1787
|
+
name,
|
|
1788
|
+
locale
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
const match = filename.match(/^(.+)\.([a-z]{2}(?:-[A-Z]{2})?)\.(?:vxjson|mdx)$/);
|
|
1792
|
+
if (!match) return null;
|
|
1793
|
+
const [, nameOrPath, locale] = match;
|
|
1794
|
+
if (parts[0] === "blocks" && parts.length === 3) return {
|
|
1795
|
+
kind: "block",
|
|
1796
|
+
collection: parts[1],
|
|
1797
|
+
name: nameOrPath,
|
|
1798
|
+
locale
|
|
1799
|
+
};
|
|
1800
|
+
if (parts.length >= 3 && parts[0] !== "blocks") {
|
|
1801
|
+
const site = parts[0];
|
|
1802
|
+
const collection = parts[1];
|
|
1803
|
+
const pathParts = parts.slice(2, -1);
|
|
1804
|
+
pathParts.push(nameOrPath);
|
|
1805
|
+
return {
|
|
1806
|
+
kind: "page",
|
|
1807
|
+
site,
|
|
1808
|
+
collection,
|
|
1809
|
+
pathname: "/" + pathParts.join("/"),
|
|
1810
|
+
locale
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
return null;
|
|
1814
|
+
}
|
|
1815
|
+
async getContent(id) {
|
|
1816
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
1817
|
+
if (!manifest) return null;
|
|
1818
|
+
const readPromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
|
|
1819
|
+
const filePath = this.getFilePath(manifest, localeVersion);
|
|
1820
|
+
return {
|
|
1821
|
+
localeVersion,
|
|
1822
|
+
content: await this.readLocaleFile(filePath, localeVersion.locale)
|
|
1823
|
+
};
|
|
1824
|
+
});
|
|
1825
|
+
const results = await Promise.all(readPromises);
|
|
1826
|
+
const locales = {};
|
|
1827
|
+
for (const { localeVersion, content } of results) if (content) locales[localeVersion.locale] = {
|
|
1828
|
+
...localeVersion,
|
|
1829
|
+
etag: content.etag,
|
|
1830
|
+
content: content.content
|
|
1831
|
+
};
|
|
1832
|
+
return {
|
|
1833
|
+
id: manifest.id,
|
|
1834
|
+
site: manifest.site,
|
|
1835
|
+
collection: manifest.collection,
|
|
1836
|
+
type: manifest.type,
|
|
1837
|
+
kind: manifest.kind,
|
|
1838
|
+
locales
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
async getLocalized(id, locale) {
|
|
1842
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
1843
|
+
if (!manifest) {
|
|
1844
|
+
await this.reindex();
|
|
1845
|
+
const updatedManifest = this.contentIndex.getManifest(id);
|
|
1846
|
+
if (!updatedManifest || !updatedManifest.locales[locale]) return null;
|
|
1847
|
+
return this.getLocalized(id, locale);
|
|
1848
|
+
}
|
|
1849
|
+
const localeVersion = manifest.locales[locale];
|
|
1850
|
+
if (!localeVersion) return null;
|
|
1851
|
+
const filePath = this.getFilePath(manifest, localeVersion);
|
|
1852
|
+
const localeData = await this.readLocaleFile(filePath, locale);
|
|
1853
|
+
if (!localeData) return null;
|
|
1854
|
+
return {
|
|
1855
|
+
id: manifest.id,
|
|
1856
|
+
site: manifest.site,
|
|
1857
|
+
collection: manifest.collection,
|
|
1858
|
+
type: manifest.type,
|
|
1859
|
+
kind: manifest.kind,
|
|
1860
|
+
localized: {
|
|
1861
|
+
...localeVersion,
|
|
1862
|
+
etag: localeData.etag,
|
|
1863
|
+
content: localeData.content
|
|
1864
|
+
}
|
|
1865
|
+
};
|
|
1866
|
+
}
|
|
1867
|
+
async readLocaleFile(filePath, locale) {
|
|
1868
|
+
try {
|
|
1869
|
+
const buffer = await readFile(filePath);
|
|
1870
|
+
const content = textDecoder.decode(buffer);
|
|
1871
|
+
if (filePath.endsWith(".mdx")) {
|
|
1872
|
+
const { data: frontmatter } = matter(content);
|
|
1873
|
+
const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
|
|
1874
|
+
const etag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
1875
|
+
const { id, created, modified, publishAt, unpublishAt, name, ...metaFields } = frontmatter;
|
|
1876
|
+
const result = {
|
|
1877
|
+
locale,
|
|
1878
|
+
etag,
|
|
1879
|
+
created,
|
|
1880
|
+
modified,
|
|
1881
|
+
meta: metaFields,
|
|
1882
|
+
content: { mdx: content }
|
|
1883
|
+
};
|
|
1884
|
+
if (frontmatter.publishAt !== void 0) result.publishAt = frontmatter.publishAt;
|
|
1885
|
+
if (frontmatter.unpublishAt !== void 0) result.unpublishAt = frontmatter.unpublishAt;
|
|
1886
|
+
return result;
|
|
1887
|
+
}
|
|
1888
|
+
const data = JSON.parse(content);
|
|
1889
|
+
if (data.type === "json") {
|
|
1890
|
+
const result = {
|
|
1891
|
+
locale,
|
|
1892
|
+
etag: VXJSON.calculateSimpleEtag(buffer),
|
|
1893
|
+
created: data.created,
|
|
1894
|
+
modified: data.modified,
|
|
1895
|
+
meta: data.meta || {},
|
|
1896
|
+
content: { data: data.data || {} }
|
|
1897
|
+
};
|
|
1898
|
+
if (data.publishAt !== void 0) result.publishAt = data.publishAt;
|
|
1899
|
+
if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
|
|
1900
|
+
return result;
|
|
1901
|
+
}
|
|
1902
|
+
const etagResult = VXJSON.calculateETags(buffer);
|
|
1903
|
+
if (!etagResult.success) {
|
|
1904
|
+
const repairedData = {
|
|
1905
|
+
id: data.id,
|
|
1906
|
+
type: data.type,
|
|
1907
|
+
created: data.created,
|
|
1908
|
+
modified: data.modified,
|
|
1909
|
+
publishAt: data.publishAt,
|
|
1910
|
+
unpublishAt: data.unpublishAt,
|
|
1911
|
+
previousPathnames: data.previousPathnames,
|
|
1912
|
+
meta: data.meta || {},
|
|
1913
|
+
content: data.content || {}
|
|
1914
|
+
};
|
|
1915
|
+
const repairedJson = VXJSON.serialize(repairedData);
|
|
1916
|
+
await writeFile(filePath, repairedJson);
|
|
1917
|
+
const repairedBuffer = Buffer.from(repairedJson, "utf-8");
|
|
1918
|
+
const repairedEtagResult = VXJSON.calculateETags(repairedBuffer);
|
|
1919
|
+
if (!repairedEtagResult.success) throw new Error(`Failed to repair VXJSON file: ${filePath}`);
|
|
1920
|
+
const etag = repairedEtagResult.contentEtag ? `${repairedEtagResult.metaEtag}.${repairedEtagResult.contentEtag}` : repairedEtagResult.metaEtag;
|
|
1921
|
+
console.log(`Repaired VXJSON file: ${filePath}`);
|
|
1922
|
+
const result = {
|
|
1923
|
+
locale,
|
|
1924
|
+
etag,
|
|
1925
|
+
created: data.created,
|
|
1926
|
+
modified: data.modified,
|
|
1927
|
+
meta: data.meta || {},
|
|
1928
|
+
content: data.content || {}
|
|
1929
|
+
};
|
|
1930
|
+
if (data.publishAt !== void 0) result.publishAt = data.publishAt;
|
|
1931
|
+
if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
|
|
1932
|
+
if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
|
|
1933
|
+
return result;
|
|
1934
|
+
}
|
|
1935
|
+
const result = {
|
|
1936
|
+
locale,
|
|
1937
|
+
etag: etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag,
|
|
1938
|
+
created: data.created,
|
|
1939
|
+
modified: data.modified,
|
|
1940
|
+
meta: data.meta || {},
|
|
1941
|
+
content: data.content || {}
|
|
1942
|
+
};
|
|
1943
|
+
if (data.publishAt !== void 0) result.publishAt = data.publishAt;
|
|
1944
|
+
if (data.unpublishAt !== void 0) result.unpublishAt = data.unpublishAt;
|
|
1945
|
+
if (data.previousPathnames !== void 0) result.previousPathnames = data.previousPathnames;
|
|
1946
|
+
return result;
|
|
1947
|
+
} catch (error) {
|
|
1948
|
+
return null;
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
async createContent(data) {
|
|
1952
|
+
const validation = validateCreateContent(data, this.sites, this.blocks, this.data);
|
|
1953
|
+
if (!validation.valid) return {
|
|
1954
|
+
success: false,
|
|
1955
|
+
reason: validation.reason,
|
|
1956
|
+
error: validation.error ? new Error(validation.error) : void 0,
|
|
1957
|
+
existingId: validation.existingId
|
|
1958
|
+
};
|
|
1959
|
+
const id = generateContentId();
|
|
1960
|
+
const now = data.created || (/* @__PURE__ */ new Date()).toISOString();
|
|
1961
|
+
try {
|
|
1962
|
+
const manifest = {
|
|
1963
|
+
id,
|
|
1964
|
+
type: data.type,
|
|
1965
|
+
kind: data.kind,
|
|
1966
|
+
site: data.site,
|
|
1967
|
+
collection: data.collection,
|
|
1968
|
+
locales: {}
|
|
1969
|
+
};
|
|
1970
|
+
const contentCache = {};
|
|
1971
|
+
for (const [locale, localeData] of Object.entries(data.locales)) {
|
|
1972
|
+
const content = localeData.content;
|
|
1973
|
+
const title = localeData.meta?.title || data.meta?.title;
|
|
1974
|
+
if (!title) return {
|
|
1975
|
+
success: false,
|
|
1976
|
+
reason: "write_error",
|
|
1977
|
+
error: /* @__PURE__ */ new Error("Title is required in metadata")
|
|
1978
|
+
};
|
|
1979
|
+
const meta = {
|
|
1980
|
+
title,
|
|
1981
|
+
...data.meta,
|
|
1982
|
+
...localeData.meta
|
|
1983
|
+
};
|
|
1984
|
+
const fileData = {
|
|
1985
|
+
id,
|
|
1986
|
+
type: data.type,
|
|
1987
|
+
created: now,
|
|
1988
|
+
modified: now,
|
|
1989
|
+
publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
|
|
1990
|
+
unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
|
|
1991
|
+
meta,
|
|
1992
|
+
content
|
|
1993
|
+
};
|
|
1994
|
+
const filePath = this.getFilePath(manifest, {
|
|
1995
|
+
locale,
|
|
1996
|
+
name: data.name,
|
|
1997
|
+
pathname: localeData.pathname
|
|
1998
|
+
});
|
|
1999
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
2000
|
+
let etag;
|
|
2001
|
+
if (data.type === "mdx") {
|
|
2002
|
+
const mdxContent = serializeMdxWithFrontmatter({
|
|
2003
|
+
id,
|
|
2004
|
+
created: now,
|
|
2005
|
+
modified: now,
|
|
2006
|
+
...localeData.publishAt && { publishAt: localeData.publishAt },
|
|
2007
|
+
...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
|
|
2008
|
+
...meta
|
|
2009
|
+
}, content.mdx || "");
|
|
2010
|
+
await writeFile(filePath, mdxContent);
|
|
2011
|
+
const mdxBuffer = new TextEncoder().encode(mdxContent);
|
|
2012
|
+
const contentStartMarker = new TextEncoder().encode("---\n\n");
|
|
2013
|
+
let contentPos = -1;
|
|
2014
|
+
for (let i = 0; i <= mdxBuffer.length - contentStartMarker.length; i++) {
|
|
2015
|
+
let match = true;
|
|
2016
|
+
for (let j = 0; j < contentStartMarker.length; j++) if (mdxBuffer[i + j] !== contentStartMarker[j]) {
|
|
2017
|
+
match = false;
|
|
2018
|
+
break;
|
|
2019
|
+
}
|
|
2020
|
+
if (match) {
|
|
2021
|
+
contentPos = i + contentStartMarker.length;
|
|
2022
|
+
break;
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
const etags = calculateEtagsFromMdxBuffer(mdxBuffer, contentPos);
|
|
2026
|
+
etag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
2027
|
+
} else if (data.type === "json") {
|
|
2028
|
+
const dataFileContent = {
|
|
2029
|
+
id,
|
|
2030
|
+
type: "json",
|
|
2031
|
+
created: now,
|
|
2032
|
+
modified: now,
|
|
2033
|
+
...localeData.publishAt && typeof localeData.publishAt === "string" && { publishAt: localeData.publishAt },
|
|
2034
|
+
...localeData.unpublishAt && typeof localeData.unpublishAt === "string" && { unpublishAt: localeData.unpublishAt },
|
|
2035
|
+
meta,
|
|
2036
|
+
data: content.data || {}
|
|
2037
|
+
};
|
|
2038
|
+
const jsonContent = JSON.stringify(sortKeys(dataFileContent, { deep: true }), null, " ");
|
|
2039
|
+
await writeFile(filePath, jsonContent);
|
|
2040
|
+
const jsonBuffer = new TextEncoder().encode(jsonContent);
|
|
2041
|
+
etag = VXJSON.calculateSimpleEtag(jsonBuffer);
|
|
2042
|
+
} else {
|
|
2043
|
+
const jsonContent = VXJSON.serialize(fileData);
|
|
2044
|
+
const jsonBuffer = new TextEncoder().encode(jsonContent);
|
|
2045
|
+
const etagResult = VXJSON.calculateETags(jsonBuffer);
|
|
2046
|
+
if (!etagResult.success) throw new Error(`Invalid VXJSON format when creating content: ${etagResult.error}`);
|
|
2047
|
+
etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
2048
|
+
await writeFile(filePath, jsonContent);
|
|
2049
|
+
}
|
|
2050
|
+
const localeVersion = buildLocaleVersion({
|
|
2051
|
+
locale,
|
|
2052
|
+
etag,
|
|
2053
|
+
created: now,
|
|
2054
|
+
modified: now,
|
|
2055
|
+
meta,
|
|
2056
|
+
kind: data.kind,
|
|
2057
|
+
pathname: data.kind === "page" ? localeData.pathname : void 0,
|
|
2058
|
+
name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
|
|
2059
|
+
publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
|
|
2060
|
+
unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
|
|
2061
|
+
});
|
|
2062
|
+
manifest.locales[locale] = localeVersion;
|
|
2063
|
+
contentCache[locale] = content;
|
|
2064
|
+
}
|
|
2065
|
+
for (const localeVersion of localesOf(manifest)) {
|
|
2066
|
+
const { locale } = localeVersion;
|
|
2067
|
+
this.contentIndex.addContent(manifest, localeVersion, contentCache[locale]);
|
|
2068
|
+
}
|
|
2069
|
+
return {
|
|
2070
|
+
success: true,
|
|
2071
|
+
id
|
|
2072
|
+
};
|
|
2073
|
+
} catch (error) {
|
|
2074
|
+
return {
|
|
2075
|
+
success: false,
|
|
2076
|
+
reason: "write_error",
|
|
2077
|
+
error: ensureError(error)
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
async updateLocalized(input) {
|
|
2082
|
+
const { id, locale, data, etag } = input;
|
|
2083
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
2084
|
+
if (!manifest) return {
|
|
2085
|
+
success: false,
|
|
2086
|
+
reason: "not_found"
|
|
2087
|
+
};
|
|
2088
|
+
const localeVersion = manifest.locales[locale];
|
|
2089
|
+
if (!localeVersion) return {
|
|
2090
|
+
success: false,
|
|
2091
|
+
reason: "not_found"
|
|
2092
|
+
};
|
|
2093
|
+
const filePath = this.getFilePath(manifest, localeVersion);
|
|
2094
|
+
const current = await this.readLocaleFile(filePath, locale);
|
|
2095
|
+
if (!current) return {
|
|
2096
|
+
success: false,
|
|
2097
|
+
reason: "not_found"
|
|
2098
|
+
};
|
|
2099
|
+
const currentEtag = current.etag;
|
|
2100
|
+
if (manifest.kind === "data") {
|
|
2101
|
+
if (etag !== currentEtag) return {
|
|
2102
|
+
success: false,
|
|
2103
|
+
reason: "stale_write",
|
|
2104
|
+
currentEtag
|
|
2105
|
+
};
|
|
2106
|
+
} else {
|
|
2107
|
+
const etagParts = parseDualEtag(etag);
|
|
2108
|
+
const currentParts = parseDualEtag(currentEtag);
|
|
2109
|
+
if (!etagParts || !currentParts) return {
|
|
2110
|
+
success: false,
|
|
2111
|
+
reason: "stale_write",
|
|
2112
|
+
currentEtag
|
|
2113
|
+
};
|
|
2114
|
+
const updateScope = analyzeUpdateScope(data);
|
|
2115
|
+
const updatingMeta = (updateScope & UPDATE_SCOPE.META) !== 0;
|
|
2116
|
+
const updatingContent = (updateScope & UPDATE_SCOPE.CONTENT) !== 0;
|
|
2117
|
+
if (updatingMeta && etagParts.meta !== currentParts.meta) return {
|
|
2118
|
+
success: false,
|
|
2119
|
+
reason: "stale_write",
|
|
2120
|
+
currentEtag
|
|
2121
|
+
};
|
|
2122
|
+
if (updatingContent && etagParts.content !== currentParts.content) return {
|
|
2123
|
+
success: false,
|
|
2124
|
+
reason: "stale_write",
|
|
2125
|
+
currentEtag
|
|
2126
|
+
};
|
|
2127
|
+
}
|
|
2128
|
+
let modified;
|
|
2129
|
+
if (shouldUpdateModifiedTimestamp(data)) modified = data.modified || (/* @__PURE__ */ new Date()).toISOString();
|
|
2130
|
+
else if (data.modified) modified = data.modified;
|
|
2131
|
+
else modified = current.modified;
|
|
2132
|
+
const { sortedMeta: newMeta, valid: metaValid, error: metaError } = validateAndPrepareMetadata({
|
|
2133
|
+
...current.meta,
|
|
2134
|
+
...data.meta ? data.meta : {}
|
|
2135
|
+
});
|
|
2136
|
+
if (!newMeta || !metaValid) return {
|
|
2137
|
+
success: false,
|
|
2138
|
+
reason: "write_error",
|
|
2139
|
+
error: new Error(metaError)
|
|
2140
|
+
};
|
|
2141
|
+
const newContent = data.content ? {
|
|
2142
|
+
...current.content,
|
|
2143
|
+
...data.content
|
|
2144
|
+
} : current.content;
|
|
2145
|
+
if (data.pathname && manifest.kind === "page" && manifest.site) {
|
|
2146
|
+
const site = this.sites[manifest.site];
|
|
2147
|
+
if (site) {
|
|
2148
|
+
const existingId = site.getPathnameConflict(data.pathname, locale, id);
|
|
2149
|
+
if (existingId) return {
|
|
2150
|
+
success: false,
|
|
2151
|
+
reason: "write_error",
|
|
2152
|
+
error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
|
|
2153
|
+
};
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
if (data.name && (manifest.kind === "block" || manifest.kind === "data")) {
|
|
2157
|
+
const existing = (manifest.kind === "block" ? this.contentIndex.getBlockIndex() : this.contentIndex.getDataIndex()).getByName(manifest.collection, data.name);
|
|
2158
|
+
if (existing && existing.id !== id) {
|
|
2159
|
+
const existingTitle = Object.values(existing.locales).find((lv) => lv !== void 0)?.meta?.title;
|
|
2160
|
+
const kindLabel = manifest.kind === "block" ? "Block" : "Data";
|
|
2161
|
+
return {
|
|
2162
|
+
success: false,
|
|
2163
|
+
reason: "write_error",
|
|
2164
|
+
error: /* @__PURE__ */ new Error(`${kindLabel} name "${data.name}" is already in use${existingTitle ? ` by "${existingTitle}"` : ""}`)
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
const pathnameHistory = buildPathnameHistory(localeVersion.pathname, data.pathname, isContentPublished({
|
|
2169
|
+
publishAt: resolvePublishDate(data.publishAt, current.publishAt),
|
|
2170
|
+
unpublishAt: resolvePublishDate(data.unpublishAt, current.unpublishAt)
|
|
2171
|
+
}), (/* @__PURE__ */ new Date()).toISOString());
|
|
2172
|
+
try {
|
|
2173
|
+
let targetFilePath = filePath;
|
|
2174
|
+
if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname && manifest.site) {
|
|
2175
|
+
const newLocaleVersion = {
|
|
2176
|
+
...localeVersion,
|
|
2177
|
+
pathname: data.pathname
|
|
2178
|
+
};
|
|
2179
|
+
targetFilePath = this.getFilePath(manifest, newLocaleVersion);
|
|
2180
|
+
await mkdir(dirname(targetFilePath), { recursive: true });
|
|
2181
|
+
} else if (data.name && localeVersion.name && data.name !== localeVersion.name && manifest.kind === "block") {
|
|
2182
|
+
const newLocaleVersion = {
|
|
2183
|
+
...localeVersion,
|
|
2184
|
+
name: data.name
|
|
2185
|
+
};
|
|
2186
|
+
targetFilePath = this.getFilePath(manifest, newLocaleVersion);
|
|
2187
|
+
await mkdir(dirname(targetFilePath), { recursive: true });
|
|
2188
|
+
}
|
|
2189
|
+
if (targetFilePath.endsWith(".mdx")) {
|
|
2190
|
+
const publishAt = resolvePublishDate(data.publishAt, current.publishAt);
|
|
2191
|
+
const unpublishAt = resolvePublishDate(data.unpublishAt, current.unpublishAt);
|
|
2192
|
+
const frontmatterData = {
|
|
2193
|
+
id: manifest.id,
|
|
2194
|
+
created: current.created,
|
|
2195
|
+
modified,
|
|
2196
|
+
...publishAt && { publishAt },
|
|
2197
|
+
...unpublishAt && { unpublishAt },
|
|
2198
|
+
...newMeta
|
|
2199
|
+
};
|
|
2200
|
+
let mdxContentPart = newContent.mdx || "";
|
|
2201
|
+
if (mdxContentPart.startsWith("---")) {
|
|
2202
|
+
const { content: contentOnly } = matter(mdxContentPart);
|
|
2203
|
+
mdxContentPart = contentOnly;
|
|
2204
|
+
}
|
|
2205
|
+
const mdxContent = serializeMdxWithFrontmatter(frontmatterData, mdxContentPart);
|
|
2206
|
+
await atomicWriteFile(targetFilePath, mdxContent);
|
|
2207
|
+
} else if (targetFilePath.endsWith(".json")) {
|
|
2208
|
+
const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
|
|
2209
|
+
const updatedFile = {
|
|
2210
|
+
id: fileContent.id,
|
|
2211
|
+
type: "json",
|
|
2212
|
+
created: fileContent.created,
|
|
2213
|
+
modified,
|
|
2214
|
+
...fileContent.publishAt && { publishAt: fileContent.publishAt },
|
|
2215
|
+
...fileContent.unpublishAt && { unpublishAt: fileContent.unpublishAt },
|
|
2216
|
+
meta: newMeta,
|
|
2217
|
+
data: sortKeys(newContent.data || {}, { deep: true })
|
|
2218
|
+
};
|
|
2219
|
+
if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
|
|
2220
|
+
else delete updatedFile.publishAt;
|
|
2221
|
+
if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
|
|
2222
|
+
else delete updatedFile.unpublishAt;
|
|
2223
|
+
const serializedContent = JSON.stringify(sortKeys(updatedFile, { deep: true }), null, " ");
|
|
2224
|
+
await atomicWriteFile(targetFilePath, serializedContent);
|
|
2225
|
+
} else {
|
|
2226
|
+
const fileContent = JSON.parse(await readFile(filePath, "utf-8"));
|
|
2227
|
+
const updatedFile = {
|
|
2228
|
+
id: fileContent.id,
|
|
2229
|
+
type: fileContent.type,
|
|
2230
|
+
created: fileContent.created,
|
|
2231
|
+
modified,
|
|
2232
|
+
publishAt: fileContent.publishAt,
|
|
2233
|
+
unpublishAt: fileContent.unpublishAt,
|
|
2234
|
+
previousPathnames: fileContent.previousPathnames,
|
|
2235
|
+
meta: newMeta,
|
|
2236
|
+
content: sortKeys(newContent, { deep: true })
|
|
2237
|
+
};
|
|
2238
|
+
if (data.pathname && localeVersion.pathname && data.pathname !== localeVersion.pathname) {
|
|
2239
|
+
if (isContentPublished(current)) {
|
|
2240
|
+
if (!updatedFile.previousPathnames) updatedFile.previousPathnames = {};
|
|
2241
|
+
updatedFile.previousPathnames[localeVersion.pathname] = modified;
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
if ("publishAt" in data) if (data.publishAt) updatedFile.publishAt = data.publishAt;
|
|
2245
|
+
else delete updatedFile.publishAt;
|
|
2246
|
+
if ("unpublishAt" in data) if (data.unpublishAt) updatedFile.unpublishAt = data.unpublishAt;
|
|
2247
|
+
else delete updatedFile.unpublishAt;
|
|
2248
|
+
const serializedContent = VXJSON.serialize(updatedFile);
|
|
2249
|
+
await atomicWriteFile(targetFilePath, serializedContent);
|
|
2250
|
+
}
|
|
2251
|
+
const writtenBuffer = await readFile(targetFilePath);
|
|
2252
|
+
let newEtag;
|
|
2253
|
+
if (targetFilePath.endsWith(".mdx")) {
|
|
2254
|
+
const contentStartMarker = new TextEncoder().encode("---\n\n");
|
|
2255
|
+
let contentPos = -1;
|
|
2256
|
+
for (let i = 0; i <= writtenBuffer.length - contentStartMarker.length; i++) {
|
|
2257
|
+
let match = true;
|
|
2258
|
+
for (let j = 0; j < contentStartMarker.length; j++) if (writtenBuffer[i + j] !== contentStartMarker[j]) {
|
|
2259
|
+
match = false;
|
|
2260
|
+
break;
|
|
2261
|
+
}
|
|
2262
|
+
if (match) {
|
|
2263
|
+
contentPos = i + contentStartMarker.length;
|
|
2264
|
+
break;
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
const etags = calculateEtagsFromMdxBuffer(writtenBuffer, contentPos);
|
|
2268
|
+
newEtag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
2269
|
+
} else if (targetFilePath.endsWith(".json")) newEtag = VXJSON.calculateSimpleEtag(writtenBuffer);
|
|
2270
|
+
else {
|
|
2271
|
+
const etagResult = VXJSON.calculateETags(writtenBuffer);
|
|
2272
|
+
if (!etagResult.success) throw new Error(`Invalid VXJSON format when updating content: ${etagResult.error}`);
|
|
2273
|
+
newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
2274
|
+
}
|
|
2275
|
+
const updatedLocaleVersion = {
|
|
2276
|
+
...localeVersion,
|
|
2277
|
+
etag: newEtag,
|
|
2278
|
+
modified,
|
|
2279
|
+
meta: newMeta,
|
|
2280
|
+
...data.pathname && { pathname: data.pathname },
|
|
2281
|
+
...data.name && { name: data.name }
|
|
2282
|
+
};
|
|
2283
|
+
if (current.publishAt && !("publishAt" in data)) updatedLocaleVersion.publishAt = current.publishAt;
|
|
2284
|
+
if (current.unpublishAt && !("unpublishAt" in data)) updatedLocaleVersion.unpublishAt = current.unpublishAt;
|
|
2285
|
+
updatePublishDates(updatedLocaleVersion, data);
|
|
2286
|
+
if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
|
|
2287
|
+
...localeVersion.previousPathnames,
|
|
2288
|
+
...pathnameHistory
|
|
2289
|
+
};
|
|
2290
|
+
else {
|
|
2291
|
+
const existingPreviousPathnames = localeVersion.previousPathnames;
|
|
2292
|
+
if (existingPreviousPathnames && Object.keys(existingPreviousPathnames).length > 0) updatedLocaleVersion.previousPathnames = existingPreviousPathnames;
|
|
2293
|
+
else delete updatedLocaleVersion.previousPathnames;
|
|
2294
|
+
}
|
|
2295
|
+
const oldLocaleVersion = manifest.locales[locale];
|
|
2296
|
+
try {
|
|
2297
|
+
manifest.locales[locale] = updatedLocaleVersion;
|
|
2298
|
+
this.contentIndex.addContent(manifest, updatedLocaleVersion, newContent);
|
|
2299
|
+
if (targetFilePath !== filePath) try {
|
|
2300
|
+
await unlink(filePath);
|
|
2301
|
+
} catch (error) {
|
|
2302
|
+
console.warn(`Failed to delete old file ${filePath}:`, error);
|
|
2303
|
+
}
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
manifest.locales[locale] = oldLocaleVersion;
|
|
2306
|
+
if (targetFilePath !== filePath) try {
|
|
2307
|
+
await unlink(targetFilePath);
|
|
2308
|
+
} catch {}
|
|
2309
|
+
throw error;
|
|
2310
|
+
}
|
|
2311
|
+
return {
|
|
2312
|
+
success: true,
|
|
2313
|
+
etag: newEtag,
|
|
2314
|
+
modified: /* @__PURE__ */ new Date()
|
|
2315
|
+
};
|
|
2316
|
+
} catch (error) {
|
|
2317
|
+
return {
|
|
2318
|
+
success: false,
|
|
2319
|
+
reason: "write_error",
|
|
2320
|
+
error: ensureError(error)
|
|
2321
|
+
};
|
|
2322
|
+
}
|
|
2323
|
+
}
|
|
2324
|
+
async deleteContent(id, etag) {
|
|
2325
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
2326
|
+
if (!manifest) return {
|
|
2327
|
+
success: false,
|
|
2328
|
+
reason: "not_found",
|
|
2329
|
+
error: /* @__PURE__ */ new Error("Content not found")
|
|
2330
|
+
};
|
|
2331
|
+
let matchingLocale;
|
|
2332
|
+
for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
|
|
2333
|
+
matchingLocale = localeVersion;
|
|
2334
|
+
break;
|
|
2335
|
+
}
|
|
2336
|
+
if (!matchingLocale) return {
|
|
2337
|
+
success: false,
|
|
2338
|
+
reason: "stale_write",
|
|
2339
|
+
currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
|
|
2340
|
+
error: /* @__PURE__ */ new Error("Invalid etag - must match at least one locale")
|
|
2341
|
+
};
|
|
2342
|
+
try {
|
|
2343
|
+
const deletePromises = Array.from(localesOf(manifest)).map(async (localeVersion) => {
|
|
2344
|
+
await unlink(this.getFilePath(manifest, localeVersion));
|
|
2345
|
+
});
|
|
2346
|
+
await Promise.all(deletePromises);
|
|
2347
|
+
this.contentIndex.removeEntry(id);
|
|
2348
|
+
return { success: true };
|
|
2349
|
+
} catch (error) {
|
|
2350
|
+
return {
|
|
2351
|
+
success: false,
|
|
2352
|
+
error: ensureError(error)
|
|
2353
|
+
};
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
async deleteLocalized(input) {
|
|
2357
|
+
const { id, locale, etag } = input;
|
|
2358
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
2359
|
+
if (!manifest) return {
|
|
2360
|
+
success: false,
|
|
2361
|
+
reason: "not_found",
|
|
2362
|
+
error: /* @__PURE__ */ new Error("Content not found")
|
|
2363
|
+
};
|
|
2364
|
+
const localeVersion = manifest.locales[locale];
|
|
2365
|
+
if (!localeVersion) return {
|
|
2366
|
+
success: false,
|
|
2367
|
+
reason: "not_found",
|
|
2368
|
+
error: /* @__PURE__ */ new Error("Locale not found")
|
|
2369
|
+
};
|
|
2370
|
+
if (localeVersion.etag !== etag) return {
|
|
2371
|
+
success: false,
|
|
2372
|
+
reason: "stale_write",
|
|
2373
|
+
currentEtag: localeVersion.etag,
|
|
2374
|
+
error: /* @__PURE__ */ new Error("Invalid etag for locale")
|
|
2375
|
+
};
|
|
2376
|
+
if (Object.keys(manifest.locales).length === 1) return {
|
|
2377
|
+
success: false,
|
|
2378
|
+
error: /* @__PURE__ */ new Error("Cannot delete the last locale. Use deleteContent to delete all content.")
|
|
2379
|
+
};
|
|
2380
|
+
try {
|
|
2381
|
+
await unlink(this.getFilePath(manifest, localeVersion));
|
|
2382
|
+
manifest.locales[locale] = void 0;
|
|
2383
|
+
this.contentIndex.removeLocale(manifest.id, locale);
|
|
2384
|
+
return { success: true };
|
|
2385
|
+
} catch (error) {
|
|
2386
|
+
return {
|
|
2387
|
+
success: false,
|
|
2388
|
+
error: ensureError(error)
|
|
2389
|
+
};
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
getSite(siteName) {
|
|
2393
|
+
if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
|
|
2394
|
+
return this.sites[siteName] || null;
|
|
2395
|
+
}
|
|
2396
|
+
*listAllContent(filters) {
|
|
2397
|
+
yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
|
|
2398
|
+
}
|
|
2399
|
+
*findUntranslatedContent(targetLocale, options) {
|
|
2400
|
+
yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Reindex files that were added or changed after initial creation
|
|
2404
|
+
*
|
|
2405
|
+
* This method:
|
|
2406
|
+
* 1. Either scans for all content files or processes specific paths
|
|
2407
|
+
* 2. Uses the path index to check if files are already indexed
|
|
2408
|
+
* 3. Indexes new files or force-reindexes specified files
|
|
2409
|
+
* 4. Optionally handles file deletions
|
|
2410
|
+
*
|
|
2411
|
+
* @param paths - Optional array of specific file paths to reindex. If not provided, scans all content files.
|
|
2412
|
+
* @param options - Options for reindexing behavior
|
|
2413
|
+
* @returns Statistics about the reindexing operation
|
|
2414
|
+
*/
|
|
2415
|
+
async reindex(paths, options) {
|
|
2416
|
+
const filesToProcess = paths || await this.scanContentFiles();
|
|
2417
|
+
let filesSkipped = 0;
|
|
2418
|
+
let filesProcessed = 0;
|
|
2419
|
+
let filesDeleted = 0;
|
|
2420
|
+
let errors = 0;
|
|
2421
|
+
const filesToIndex = [];
|
|
2422
|
+
const updated = [];
|
|
2423
|
+
const deleted = [];
|
|
2424
|
+
for (const filePath of filesToProcess) {
|
|
2425
|
+
if (options?.handleDeletions && paths) try {
|
|
2426
|
+
await readFile(filePath);
|
|
2427
|
+
} catch (error) {
|
|
2428
|
+
const parsed = this.parseFilePath(filePath);
|
|
2429
|
+
if (parsed) {
|
|
2430
|
+
let manifest = null;
|
|
2431
|
+
if (parsed.kind === "block" && parsed.name) manifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
|
|
2432
|
+
else if (parsed.kind === "data" && parsed.name) manifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
|
|
2433
|
+
else if (parsed.kind === "page" && parsed.site && parsed.pathname) manifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
|
|
2434
|
+
if (manifest) {
|
|
2435
|
+
deleted.push({
|
|
2436
|
+
id: manifest.id,
|
|
2437
|
+
locale: parsed.locale,
|
|
2438
|
+
kind: parsed.kind
|
|
2439
|
+
});
|
|
2440
|
+
if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(manifest.id);
|
|
2441
|
+
else {
|
|
2442
|
+
manifest.locales[parsed.locale] = void 0;
|
|
2443
|
+
this.contentIndex.removeLocale(manifest.id, parsed.locale);
|
|
2444
|
+
}
|
|
2445
|
+
filesDeleted++;
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
continue;
|
|
2449
|
+
}
|
|
2450
|
+
const parsed = this.parseFilePath(filePath);
|
|
2451
|
+
if (!parsed) {
|
|
2452
|
+
console.warn(`Skipping unrecognized file pattern: ${filePath}`);
|
|
2453
|
+
errors++;
|
|
2454
|
+
continue;
|
|
2455
|
+
}
|
|
2456
|
+
let isIndexed = false;
|
|
2457
|
+
if (parsed.kind === "block" && parsed.name) isIndexed = !!this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
|
|
2458
|
+
else if (parsed.kind === "page" && parsed.site && parsed.pathname) isIndexed = !!this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
|
|
2459
|
+
else if (parsed.kind === "data" && parsed.name) isIndexed = !!this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
|
|
2460
|
+
if (isIndexed) if (!paths) filesSkipped++;
|
|
2461
|
+
else {
|
|
2462
|
+
const fileStats = await readFile(filePath);
|
|
2463
|
+
let currentManifest = null;
|
|
2464
|
+
if (parsed.kind === "block" && parsed.name) currentManifest = this.contentIndex.getBlockByName(parsed.collection, parsed.name, parsed.locale);
|
|
2465
|
+
else if (parsed.kind === "data" && parsed.name) currentManifest = this.contentIndex.getDataByName(parsed.collection, parsed.name, parsed.locale);
|
|
2466
|
+
else if (parsed.kind === "page" && parsed.site && parsed.pathname) currentManifest = this.contentIndex.getByPathname(parsed.site, parsed.pathname, parsed.locale);
|
|
2467
|
+
if (currentManifest) {
|
|
2468
|
+
const buffer = fileStats;
|
|
2469
|
+
let currentEtag;
|
|
2470
|
+
if (filePath.endsWith(".mdx")) {
|
|
2471
|
+
const etags = calculateEtagsFromMdxBuffer(buffer, findMdxContentStartPosition(buffer));
|
|
2472
|
+
currentEtag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
2473
|
+
} else if (filePath.endsWith(".vxjson")) {
|
|
2474
|
+
const etagResult = VXJSON.calculateETags(buffer);
|
|
2475
|
+
if (!etagResult.success) {
|
|
2476
|
+
filesToIndex.push(filePath);
|
|
2477
|
+
continue;
|
|
2478
|
+
}
|
|
2479
|
+
currentEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
2480
|
+
} else if (filePath.endsWith(".json")) currentEtag = xxh3.xxh64(buffer).toString(16);
|
|
2481
|
+
else {
|
|
2482
|
+
filesSkipped++;
|
|
2483
|
+
continue;
|
|
2484
|
+
}
|
|
2485
|
+
if (currentManifest.locales[parsed.locale]?.etag === currentEtag) {
|
|
2486
|
+
const relativePath = filePath.replace(this.absoluteContentRoot + "/", "");
|
|
2487
|
+
console.log(`[Content] skip ${relativePath} (unchanged)`);
|
|
2488
|
+
filesSkipped++;
|
|
2489
|
+
} else filesToIndex.push(filePath);
|
|
2490
|
+
} else filesToIndex.push(filePath);
|
|
2491
|
+
}
|
|
2492
|
+
else filesToIndex.push(filePath);
|
|
2493
|
+
}
|
|
2494
|
+
const buffers = Array.from({ length: Math.min(filesToIndex.length, 100) }, () => new Uint8Array(4096));
|
|
2495
|
+
for (let i = 0; i < filesToIndex.length; i++) {
|
|
2496
|
+
const filePath = filesToIndex[i];
|
|
2497
|
+
const bufferIndex = i % buffers.length;
|
|
2498
|
+
try {
|
|
2499
|
+
const result = await this.parseFileHeaderWithRepair(filePath, buffers[bufferIndex]);
|
|
2500
|
+
if (result) {
|
|
2501
|
+
const { manifest, localeVersion, content } = result;
|
|
2502
|
+
this.contentIndex.addContent(manifest, localeVersion, content);
|
|
2503
|
+
filesProcessed++;
|
|
2504
|
+
const localizedManifest = {
|
|
2505
|
+
id: manifest.id,
|
|
2506
|
+
type: manifest.type,
|
|
2507
|
+
kind: manifest.kind,
|
|
2508
|
+
site: manifest.site,
|
|
2509
|
+
collection: manifest.collection,
|
|
2510
|
+
localized: localeVersion
|
|
2511
|
+
};
|
|
2512
|
+
updated.push(localizedManifest);
|
|
2513
|
+
}
|
|
2514
|
+
} catch (error) {
|
|
2515
|
+
console.error(`Failed to reindex ${filePath}:`, error);
|
|
2516
|
+
errors++;
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
const result = {
|
|
2520
|
+
filesProcessed,
|
|
2521
|
+
filesSkipped,
|
|
2522
|
+
updated
|
|
2523
|
+
};
|
|
2524
|
+
if (options?.handleDeletions && deleted.length > 0) {
|
|
2525
|
+
result.filesDeleted = filesDeleted;
|
|
2526
|
+
result.deleted = deleted;
|
|
2527
|
+
}
|
|
2528
|
+
if (errors > 0) result.errors = errors;
|
|
2529
|
+
return result;
|
|
2530
|
+
}
|
|
2531
|
+
/**
|
|
2532
|
+
* Read content directly from cache
|
|
2533
|
+
* For testing purposes - returns null if not cached
|
|
2534
|
+
*/
|
|
2535
|
+
async readFromCache(id, locale) {
|
|
2536
|
+
return this.contentIndex.getCachedContent(id, locale);
|
|
2537
|
+
}
|
|
2538
|
+
async getContentAsBuffer(id, locale) {
|
|
2539
|
+
const manifest = this.contentIndex.getManifest(id);
|
|
2540
|
+
if (!manifest || !manifest.locales[locale]) return null;
|
|
2541
|
+
const localeVersion = manifest.locales[locale];
|
|
2542
|
+
const filePath = this.getFilePath(manifest, localeVersion);
|
|
2543
|
+
const buffer = await readFile(filePath);
|
|
2544
|
+
const contentType = filePath.endsWith(".mdx") ? "text/mdx" : "application/json";
|
|
2545
|
+
let etag;
|
|
2546
|
+
if (contentType === "text/mdx") {
|
|
2547
|
+
const contentStartMarker = new TextEncoder().encode("---\n\n");
|
|
2548
|
+
let contentPos = -1;
|
|
2549
|
+
for (let i = 0; i <= buffer.length - contentStartMarker.length; i++) {
|
|
2550
|
+
let match = true;
|
|
2551
|
+
for (let j = 0; j < contentStartMarker.length; j++) if (buffer[i + j] !== contentStartMarker[j]) {
|
|
2552
|
+
match = false;
|
|
2553
|
+
break;
|
|
2554
|
+
}
|
|
2555
|
+
if (match) {
|
|
2556
|
+
contentPos = i + contentStartMarker.length;
|
|
2557
|
+
break;
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
const etags = calculateEtagsFromMdxBuffer(buffer, contentPos);
|
|
2561
|
+
etag = `${etags.metaEtag}.${etags.contentEtag}`;
|
|
2562
|
+
} else {
|
|
2563
|
+
const etagResult = VXJSON.calculateETags(buffer);
|
|
2564
|
+
if (!etagResult.success) throw new Error(`Invalid VXJSON format in getContentAsBuffer: ${etagResult.error}`);
|
|
2565
|
+
etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
2566
|
+
}
|
|
2567
|
+
return {
|
|
2568
|
+
buffer,
|
|
2569
|
+
etag,
|
|
2570
|
+
contentType
|
|
2571
|
+
};
|
|
2572
|
+
}
|
|
2573
|
+
async batchUpdate(operations) {
|
|
2574
|
+
const validationResults = [];
|
|
2575
|
+
for (const op of operations) {
|
|
2576
|
+
const manifest = this.contentIndex.getManifest(op.id);
|
|
2577
|
+
if (!manifest) return {
|
|
2578
|
+
operations: operations.map((o) => ({
|
|
2579
|
+
id: o.id,
|
|
2580
|
+
locale: o.locale,
|
|
2581
|
+
updated: false,
|
|
2582
|
+
error: /* @__PURE__ */ new Error("Content not found")
|
|
2583
|
+
})),
|
|
2584
|
+
success: false,
|
|
2585
|
+
updated: 0,
|
|
2586
|
+
failed: operations.length
|
|
2587
|
+
};
|
|
2588
|
+
const localeVersion = manifest.locales[op.locale];
|
|
2589
|
+
if (!localeVersion) return {
|
|
2590
|
+
operations: operations.map((o) => ({
|
|
2591
|
+
id: o.id,
|
|
2592
|
+
locale: o.locale,
|
|
2593
|
+
updated: false,
|
|
2594
|
+
error: /* @__PURE__ */ new Error("Locale not found")
|
|
2595
|
+
})),
|
|
2596
|
+
success: false,
|
|
2597
|
+
updated: 0,
|
|
2598
|
+
failed: operations.length
|
|
2599
|
+
};
|
|
2600
|
+
if (localeVersion.etag !== op.etag) return {
|
|
2601
|
+
operations: operations.map((o) => ({
|
|
2602
|
+
id: o.id,
|
|
2603
|
+
locale: o.locale,
|
|
2604
|
+
updated: false,
|
|
2605
|
+
error: /* @__PURE__ */ new Error("Stale write")
|
|
2606
|
+
})),
|
|
2607
|
+
success: false,
|
|
2608
|
+
updated: 0,
|
|
2609
|
+
failed: operations.length
|
|
2610
|
+
};
|
|
2611
|
+
const filePath = this.getFilePath(manifest, localeVersion);
|
|
2612
|
+
const current = await this.readLocaleFile(filePath, op.locale);
|
|
2613
|
+
if (!current) return {
|
|
2614
|
+
operations: operations.map((o) => ({
|
|
2615
|
+
id: o.id,
|
|
2616
|
+
locale: o.locale,
|
|
2617
|
+
updated: false,
|
|
2618
|
+
error: /* @__PURE__ */ new Error("Failed to read content")
|
|
2619
|
+
})),
|
|
2620
|
+
success: false,
|
|
2621
|
+
updated: 0,
|
|
2622
|
+
failed: operations.length
|
|
2623
|
+
};
|
|
2624
|
+
if (op.data.meta) {
|
|
2625
|
+
const validation = validateAndPrepareMetadata({
|
|
2626
|
+
...current.meta,
|
|
2627
|
+
...op.data.meta
|
|
2628
|
+
});
|
|
2629
|
+
if (!validation.valid) return {
|
|
2630
|
+
operations: operations.map((o) => ({
|
|
2631
|
+
id: o.id,
|
|
2632
|
+
locale: o.locale,
|
|
2633
|
+
updated: false,
|
|
2634
|
+
error: new Error(validation.error)
|
|
2635
|
+
})),
|
|
2636
|
+
success: false,
|
|
2637
|
+
updated: 0,
|
|
2638
|
+
failed: operations.length
|
|
2639
|
+
};
|
|
2640
|
+
}
|
|
2641
|
+
validationResults.push({
|
|
2642
|
+
op,
|
|
2643
|
+
manifest,
|
|
2644
|
+
localeVersion,
|
|
2645
|
+
current
|
|
2646
|
+
});
|
|
2647
|
+
}
|
|
2648
|
+
const results = [];
|
|
2649
|
+
let updated = 0;
|
|
2650
|
+
for (const { op } of validationResults) {
|
|
2651
|
+
const result = await this.updateLocalized(op);
|
|
2652
|
+
if (result.success) {
|
|
2653
|
+
updated++;
|
|
2654
|
+
results.push({
|
|
2655
|
+
id: op.id,
|
|
2656
|
+
locale: op.locale,
|
|
2657
|
+
updated: true,
|
|
2658
|
+
etag: result.etag
|
|
2659
|
+
});
|
|
2660
|
+
} else results.push({
|
|
2661
|
+
id: op.id,
|
|
2662
|
+
locale: op.locale,
|
|
2663
|
+
updated: false,
|
|
2664
|
+
error: result.error
|
|
2665
|
+
});
|
|
2666
|
+
}
|
|
2667
|
+
return {
|
|
2668
|
+
operations: results,
|
|
2669
|
+
success: updated === operations.length,
|
|
2670
|
+
updated,
|
|
2671
|
+
failed: operations.length - updated
|
|
2672
|
+
};
|
|
2673
|
+
}
|
|
2674
|
+
};
|
|
2675
|
+
|
|
2676
|
+
//#endregion
|
|
2677
|
+
export { findMdxContentStartPosition as a, atomicWriteFile as c, calculateEtagsFromMdxBuffer as i, filesystem_content_api_exports as n, ContentIndex as o, VXJSON as r, filterContentWithIndexes as s, FileSystemContentAPI as t };
|
|
2678
|
+
//# sourceMappingURL=filesystem-content-api-kxKY5IUw.mjs.map
|