@conloca/content-api 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-operations.d.ts +5 -17
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +3 -88
- package/dist/asset-operations.js.map +1 -1
- package/dist/asset-usage.d.ts +5 -4
- package/dist/asset-usage.d.ts.map +1 -1
- package/dist/asset-usage.js +6 -5
- package/dist/asset-usage.js.map +1 -1
- package/dist/content-operations.js +2 -2
- package/dist/content-operations.js.map +1 -1
- package/dist/content-path.d.ts +5 -0
- package/dist/content-path.d.ts.map +1 -1
- package/dist/content-path.js +7 -0
- package/dist/content-path.js.map +1 -1
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +60 -17
- package/dist/filesystem-content-api.js.map +1 -1
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +16 -31
- package/dist/middleware.js.map +1 -1
- package/package.json +1 -1
- package/src/asset-operations.ts +5 -105
- package/src/asset-usage.ts +6 -5
- package/src/content-operations.ts +2 -2
- package/src/content-path.ts +8 -0
- package/src/filesystem-content-api.ts +72 -17
- package/src/middleware.ts +18 -37
|
@@ -21,7 +21,13 @@ import {
|
|
|
21
21
|
validateAndPrepareMetadata,
|
|
22
22
|
validateCreateContent,
|
|
23
23
|
} from './content-operations.js';
|
|
24
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
type ContentPathLayout,
|
|
26
|
+
invalidLocaleMessage,
|
|
27
|
+
isContentLocale,
|
|
28
|
+
parseContentPathLayout,
|
|
29
|
+
parseLocaleFilename,
|
|
30
|
+
} from './content-path.js';
|
|
25
31
|
import {
|
|
26
32
|
applyMetaPatch,
|
|
27
33
|
localesOf,
|
|
@@ -86,6 +92,13 @@ function ensureError(error: unknown): Error {
|
|
|
86
92
|
// Reusable TextDecoder instance - safe to reuse as it's stateless
|
|
87
93
|
const textDecoder = new TextDecoder();
|
|
88
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Where the read repair moves a fragment saved straight into fragments/: the
|
|
97
|
+
* folder the editor saves new fragments to, which every conlocaFragments(...)
|
|
98
|
+
* call in a site's content config declares, so the moved fragment still builds.
|
|
99
|
+
*/
|
|
100
|
+
const REPAIRED_FRAGMENT_COLLECTION = 'fragments';
|
|
101
|
+
|
|
89
102
|
async function readFilePrefix(filePath: string, buffer: Uint8Array): Promise<number> {
|
|
90
103
|
const handle = await open(filePath, 'r');
|
|
91
104
|
try {
|
|
@@ -229,14 +242,52 @@ export async function readSitesConfig(contentRoot: string): Promise<SitesConfig>
|
|
|
229
242
|
}
|
|
230
243
|
if (!parsed.globalLocales || !Array.isArray(parsed.globalLocales)) {
|
|
231
244
|
console.warn(`Warning: sites.json is missing 'globalLocales' array at ${sitesPath}. Using default global locales.`);
|
|
245
|
+
warnUnreadableLocales(sitesPath, parsed.sites, []);
|
|
232
246
|
return {
|
|
233
247
|
sites: parsed.sites,
|
|
234
248
|
globalLocales: ['en'],
|
|
235
249
|
};
|
|
236
250
|
}
|
|
251
|
+
warnUnreadableLocales(sitesPath, parsed.sites, parsed.globalLocales);
|
|
237
252
|
return parsed;
|
|
238
253
|
}
|
|
239
254
|
|
|
255
|
+
/**
|
|
256
|
+
* Why a page file's name gives no locale the content grammar reads: either it
|
|
257
|
+
* names one the grammar refuses ('about.pt-br.vxjson') or it names none.
|
|
258
|
+
*/
|
|
259
|
+
function unreadablePageLocaleMessage(filename: string): string {
|
|
260
|
+
const written = /^.+\.([^.]+)\.(?:mdx|vxjson)$/.exec(filename)?.[1];
|
|
261
|
+
return written === undefined
|
|
262
|
+
? `Page file ${filename} has no locale in its name (<name>.<locale>.vxjson), so it is not indexed.`
|
|
263
|
+
: `Page file ${filename} is not indexed. ${invalidLocaleMessage(written)}`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// One warning per sites.json and locale for the whole process: the file is
|
|
267
|
+
// read again by every content API created and every config reload.
|
|
268
|
+
const warnedLocales = new Set<string>();
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Warn about each locale sites.json declares that content file names cannot
|
|
272
|
+
* carry: its pages can be neither created nor read, and nothing else says so
|
|
273
|
+
* until a save is refused.
|
|
274
|
+
*/
|
|
275
|
+
function warnUnreadableLocales(sitesPath: string, sites: SitesConfig['sites'], globalLocales: unknown[]): void {
|
|
276
|
+
const declared = [...globalLocales];
|
|
277
|
+
for (const site of Object.values(sites)) {
|
|
278
|
+
if (Array.isArray(site?.locales)) declared.push(...site.locales);
|
|
279
|
+
declared.push(site?.defaultLocale);
|
|
280
|
+
}
|
|
281
|
+
for (const locale of declared) {
|
|
282
|
+
const key = `${sitesPath}\0${locale}`;
|
|
283
|
+
if (typeof locale !== 'string' || isContentLocale(locale) || warnedLocales.has(key)) continue;
|
|
284
|
+
warnedLocales.add(key);
|
|
285
|
+
console.warn(
|
|
286
|
+
`Warning: sites.json at ${sitesPath} declares a locale no content file can carry, so its pages can be neither created nor read. ${invalidLocaleMessage(locale)}`,
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
240
291
|
export type { IndexProblem } from './content-index.js';
|
|
241
292
|
|
|
242
293
|
function messageOf(error: unknown): string {
|
|
@@ -463,18 +514,18 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
463
514
|
// is the one every local dev server and Astro build hydrates through.
|
|
464
515
|
const claimedBy = new Map<string, string>();
|
|
465
516
|
|
|
466
|
-
//
|
|
467
|
-
//
|
|
468
|
-
// contract (reads up to 4096
|
|
469
|
-
|
|
517
|
+
// One 4KB buffer per file in a batch: the batch is read in parallel, so
|
|
518
|
+
// two files sharing a buffer overwrite each other's bytes mid-parse.
|
|
519
|
+
// parseFileHeaderWithRepair owns the buffer contract (reads up to 4096
|
|
520
|
+
// bytes from offset 0).
|
|
521
|
+
const buffers = Array.from({ length: Math.min(files.length, OPTIMAL_BATCH_SIZE) }, () => new Uint8Array(4096));
|
|
470
522
|
|
|
471
523
|
for (let i = 0; i < files.length; i += OPTIMAL_BATCH_SIZE) {
|
|
472
524
|
const batch = files.slice(i, i + OPTIMAL_BATCH_SIZE);
|
|
473
525
|
await Promise.all(
|
|
474
526
|
batch.map(async (filePath, batchIndex) => {
|
|
475
|
-
const buffer = buffers[(i + batchIndex) % buffers.length];
|
|
476
527
|
try {
|
|
477
|
-
const result = await this.parseFileHeaderWithRepair(filePath,
|
|
528
|
+
const result = await this.parseFileHeaderWithRepair(filePath, buffers[batchIndex]);
|
|
478
529
|
if (result) {
|
|
479
530
|
// Same reason as the shared indexAll loop: a page under a site
|
|
480
531
|
// sites.json does not declare would be filed nowhere and
|
|
@@ -634,29 +685,31 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
634
685
|
collection = '';
|
|
635
686
|
const filename = parts[1];
|
|
636
687
|
|
|
637
|
-
// Create the
|
|
638
|
-
const
|
|
688
|
+
// Create the repair folder if it doesn't exist
|
|
689
|
+
const repairDir = join(this.absoluteContentRoot, 'fragments', REPAIRED_FRAGMENT_COLLECTION);
|
|
639
690
|
try {
|
|
640
|
-
await mkdir(
|
|
691
|
+
await mkdir(repairDir, { recursive: true });
|
|
641
692
|
} catch {
|
|
642
693
|
// Directory might already exist, that's fine
|
|
643
694
|
}
|
|
644
695
|
|
|
645
|
-
// Move the file to the
|
|
646
|
-
const newFilePath = join(
|
|
696
|
+
// Move the file to the repair folder
|
|
697
|
+
const newFilePath = join(repairDir, filename);
|
|
647
698
|
|
|
648
699
|
try {
|
|
649
700
|
// Check if target file already exists
|
|
650
701
|
try {
|
|
651
702
|
await access(newFilePath);
|
|
652
|
-
console.warn(
|
|
703
|
+
console.warn(
|
|
704
|
+
`Cannot move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/: target file already exists`,
|
|
705
|
+
);
|
|
653
706
|
} catch {
|
|
654
707
|
// Target doesn't exist, safe to move
|
|
655
708
|
await rename(filePath, newFilePath);
|
|
656
|
-
console.log(`Repaired: Moved ${filename} to fragments/
|
|
709
|
+
console.log(`Repaired: Moved ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/ collection`);
|
|
657
710
|
|
|
658
711
|
// The file now uses the repaired collection layout.
|
|
659
|
-
collection =
|
|
712
|
+
collection = REPAIRED_FRAGMENT_COLLECTION;
|
|
660
713
|
filePath = newFilePath;
|
|
661
714
|
|
|
662
715
|
// Update relativePath and parts for the new file path
|
|
@@ -666,7 +719,7 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
666
719
|
bytesRead = await readFilePrefix(filePath, buffer);
|
|
667
720
|
}
|
|
668
721
|
} catch (moveError) {
|
|
669
|
-
console.error(`Failed to move ${filename} to
|
|
722
|
+
console.error(`Failed to move ${filename} to fragments/${REPAIRED_FRAGMENT_COLLECTION}/:`, moveError);
|
|
670
723
|
// Continue processing with original file
|
|
671
724
|
bytesRead = await readFilePrefix(filePath, buffer);
|
|
672
725
|
}
|
|
@@ -789,7 +842,9 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
789
842
|
// (the reindex path) has always refused these — now both halves agree.
|
|
790
843
|
const localeSuffix = filename ? parseLocaleFilename(filename) : null;
|
|
791
844
|
if (!localeSuffix || localeSuffix.extension === 'json') {
|
|
792
|
-
|
|
845
|
+
const message = unreadablePageLocaleMessage(filename ?? relativePath);
|
|
846
|
+
console.warn(`Skipping ${filePath}: ${message}`);
|
|
847
|
+
this.recordIndexProblem(filePath, 'unsupported-locale-path', message);
|
|
793
848
|
return null;
|
|
794
849
|
}
|
|
795
850
|
locale = localeSuffix.locale;
|
package/src/middleware.ts
CHANGED
|
@@ -2,11 +2,10 @@ import { type Context, Hono } from 'hono';
|
|
|
2
2
|
import { type AssetConfig, AssetOperations } from './asset-operations.js';
|
|
3
3
|
import { findAssetUsage } from './asset-usage.js';
|
|
4
4
|
import type { ContentAPI } from './content-api.interface.js';
|
|
5
|
-
import {
|
|
5
|
+
import { normalizeAndValidatePathname } from './content-utils.js';
|
|
6
6
|
import { createGitOperations, type GitAuthor, type GitConfig } from './git-operations.js';
|
|
7
7
|
import type {
|
|
8
8
|
APIError,
|
|
9
|
-
ContentManifest,
|
|
10
9
|
CreateResult,
|
|
11
10
|
DeleteResult,
|
|
12
11
|
ErrorCode,
|
|
@@ -101,6 +100,8 @@ function isCrossSiteWrite(c: Context): boolean {
|
|
|
101
100
|
*/
|
|
102
101
|
export interface ContentAPIRouterOptions {
|
|
103
102
|
assetsPath?: string;
|
|
103
|
+
/** Where the site serves `assetsPath`, which begins every image link the editor stores; `/assets` when unset */
|
|
104
|
+
assetRefBase?: string;
|
|
104
105
|
assetConfig?: Omit<AssetConfig, 'assetsPath' | 'contentRoot'>;
|
|
105
106
|
/** Content root directory: holds asset metadata records, is scanned for asset usage, and is where git runs */
|
|
106
107
|
contentRoot?: string;
|
|
@@ -365,12 +366,16 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
365
366
|
);
|
|
366
367
|
}
|
|
367
368
|
if (result.reason === 'stale_write') {
|
|
369
|
+
// The error envelope is what a client reads to tell an outdated etag from any other failure.
|
|
368
370
|
return c.json(
|
|
369
371
|
{
|
|
370
372
|
success: false,
|
|
371
373
|
reason: result.reason,
|
|
372
374
|
currentEtag: result.currentEtag,
|
|
373
375
|
message: 'Content has been modified',
|
|
376
|
+
...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
|
|
377
|
+
currentEtag: result.currentEtag,
|
|
378
|
+
}),
|
|
374
379
|
},
|
|
375
380
|
412,
|
|
376
381
|
);
|
|
@@ -679,7 +684,7 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
679
684
|
// GET /assets/usage/:path{.+} — content that links to the asset at this path from the assets root
|
|
680
685
|
app.get('/assets/usage/:path{.+}', async (c) => {
|
|
681
686
|
try {
|
|
682
|
-
const usage = await findAssetUsage(api, c.req.param('path'));
|
|
687
|
+
const usage = await findAssetUsage(api, c.req.param('path'), options.assetRefBase);
|
|
683
688
|
return c.json({ usage });
|
|
684
689
|
} catch (error) {
|
|
685
690
|
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);
|
|
@@ -921,11 +926,12 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
921
926
|
}
|
|
922
927
|
});
|
|
923
928
|
|
|
924
|
-
// GET /fragments/name-available - Check if fragment name is available
|
|
929
|
+
// GET /fragments/name-available - Check if fragment name is available, the way a create checks it: in
|
|
930
|
+
// any letter case and in any language. `locale` is still accepted but narrows nothing, since a fragment
|
|
931
|
+
// has one name for all its languages.
|
|
925
932
|
app.get('/fragments/name-available', async (c) => {
|
|
926
933
|
const name = c.req.query('name');
|
|
927
934
|
const collection = c.req.query('collection') || 'components';
|
|
928
|
-
const locale = c.req.query('locale') || 'en';
|
|
929
935
|
const excludeId = c.req.query('excludeId');
|
|
930
936
|
|
|
931
937
|
if (!name) {
|
|
@@ -936,41 +942,12 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
936
942
|
}
|
|
937
943
|
|
|
938
944
|
try {
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
api.listAllContent({
|
|
942
|
-
kind: 'fragment',
|
|
943
|
-
collection: collection,
|
|
944
|
-
locales: [locale],
|
|
945
|
-
}),
|
|
946
|
-
);
|
|
947
|
-
|
|
948
|
-
let taken: ContentManifest | undefined;
|
|
949
|
-
for (const item of existing) {
|
|
950
|
-
for (const localeVersion of localesOf(item)) {
|
|
951
|
-
if (localeVersion.name === name) {
|
|
952
|
-
taken = item;
|
|
953
|
-
break;
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
// If no existing fragment, name is available
|
|
959
|
-
if (!taken) {
|
|
960
|
-
return c.json({ available: true });
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
// If existing fragment has same ID as excludeId, name is available
|
|
964
|
-
// (useful when editing existing fragment)
|
|
965
|
-
if (excludeId && taken.id === excludeId) {
|
|
945
|
+
const existingId = api.fragments.getNameConflict(collection, name, excludeId);
|
|
946
|
+
if (existingId === null) {
|
|
966
947
|
return c.json({ available: true });
|
|
967
948
|
}
|
|
968
949
|
|
|
969
|
-
|
|
970
|
-
return c.json({
|
|
971
|
-
available: false,
|
|
972
|
-
existingId: taken.id,
|
|
973
|
-
});
|
|
950
|
+
return c.json({ available: false, existingId });
|
|
974
951
|
} catch (error) {
|
|
975
952
|
return c.json(
|
|
976
953
|
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check fragment name availability'),
|
|
@@ -1062,12 +1039,16 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
1062
1039
|
|
|
1063
1040
|
if (!updateResult.success) {
|
|
1064
1041
|
if (updateResult.reason === 'stale_write') {
|
|
1042
|
+
// The error envelope is what a client reads to tell an outdated etag from any other failure.
|
|
1065
1043
|
return c.json(
|
|
1066
1044
|
{
|
|
1067
1045
|
moved: false,
|
|
1068
1046
|
reason: 'stale_write',
|
|
1069
1047
|
currentEtag: updateResult.currentEtag,
|
|
1070
1048
|
message: 'Content has been modified',
|
|
1049
|
+
...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
|
|
1050
|
+
currentEtag: updateResult.currentEtag,
|
|
1051
|
+
}),
|
|
1071
1052
|
},
|
|
1072
1053
|
412,
|
|
1073
1054
|
);
|