@conloca/content-api 0.1.16 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/asset-constraints.d.ts +16 -0
- package/dist/asset-constraints.d.ts.map +1 -0
- package/dist/asset-constraints.js +29 -0
- package/dist/asset-constraints.js.map +1 -0
- package/dist/asset-metadata-store.d.ts +60 -0
- package/dist/asset-metadata-store.d.ts.map +1 -0
- package/dist/asset-metadata-store.js +335 -0
- package/dist/asset-metadata-store.js.map +1 -0
- package/dist/asset-operations.d.ts +18 -13
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +302 -254
- package/dist/asset-operations.js.map +1 -0
- package/dist/asset-types.d.ts +23 -7
- package/dist/asset-types.d.ts.map +1 -1
- package/dist/asset-types.js +8 -2
- package/dist/asset-types.js.map +1 -0
- package/dist/asset-usage.d.ts +10 -0
- package/dist/asset-usage.d.ts.map +1 -0
- package/dist/asset-usage.js +49 -0
- package/dist/asset-usage.js.map +1 -0
- package/dist/base-content-index.d.ts +8 -2
- package/dist/base-content-index.d.ts.map +1 -1
- package/dist/base-content-index.js +24 -3
- package/dist/base-content-index.js.map +1 -0
- package/dist/cf-access.js +1 -0
- package/dist/cf-access.js.map +1 -0
- package/dist/component-registry.d.ts +1 -1
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/component-registry.js +2 -1
- package/dist/component-registry.js.map +1 -0
- package/dist/component-registry.types.js +1 -0
- package/dist/component-registry.types.js.map +1 -0
- package/dist/component-vocabulary.d.ts +33 -0
- package/dist/component-vocabulary.d.ts.map +1 -0
- package/dist/component-vocabulary.js +105 -0
- package/dist/component-vocabulary.js.map +1 -0
- package/dist/content-api.interface.d.ts +5 -5
- package/dist/content-api.interface.d.ts.map +1 -1
- package/dist/content-api.interface.js +1 -0
- package/dist/content-api.interface.js.map +1 -0
- package/dist/content-filters.d.ts +2 -2
- package/dist/content-filters.d.ts.map +1 -1
- package/dist/content-filters.js +9 -8
- package/dist/content-filters.js.map +1 -0
- package/dist/content-index.d.ts +74 -16
- package/dist/content-index.d.ts.map +1 -1
- package/dist/content-index.js +183 -55
- package/dist/content-index.js.map +1 -0
- package/dist/content-operations.d.ts +71 -7
- package/dist/content-operations.d.ts.map +1 -1
- package/dist/content-operations.js +166 -82
- package/dist/content-operations.js.map +1 -0
- package/dist/content-path.d.ts +59 -0
- package/dist/content-path.d.ts.map +1 -0
- package/dist/content-path.js +88 -0
- package/dist/content-path.js.map +1 -0
- package/dist/content-reader.d.ts +2 -2
- package/dist/content-reader.d.ts.map +1 -1
- package/dist/content-reader.js +2 -1
- package/dist/content-reader.js.map +1 -0
- package/dist/content-utils.d.ts +53 -10
- package/dist/content-utils.d.ts.map +1 -1
- package/dist/content-utils.js +103 -34
- package/dist/content-utils.js.map +1 -0
- package/dist/content-watcher.d.ts +3 -3
- package/dist/content-watcher.d.ts.map +1 -1
- package/dist/content-watcher.js +13 -10
- package/dist/content-watcher.js.map +1 -0
- package/dist/data-index.d.ts +1 -1
- package/dist/data-index.d.ts.map +1 -1
- package/dist/data-index.js +2 -1
- package/dist/data-index.js.map +1 -0
- package/dist/data.d.ts +5 -13
- package/dist/data.d.ts.map +1 -1
- package/dist/data.js +7 -6
- package/dist/data.js.map +1 -0
- package/dist/editor-data-bindings.d.ts +10 -0
- package/dist/editor-data-bindings.d.ts.map +1 -0
- package/dist/editor-data-bindings.js +67 -0
- package/dist/editor-data-bindings.js.map +1 -0
- package/dist/etag-utils.d.ts.map +1 -1
- package/dist/etag-utils.js +5 -4
- package/dist/etag-utils.js.map +1 -0
- package/dist/filesystem-content-api.d.ts +45 -18
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +407 -281
- package/dist/filesystem-content-api.js.map +1 -0
- package/dist/filesystem-reader-backend.d.ts +46 -0
- package/dist/filesystem-reader-backend.d.ts.map +1 -0
- package/dist/filesystem-reader-backend.js +119 -0
- package/dist/filesystem-reader-backend.js.map +1 -0
- package/dist/fragment-index.d.ts +8 -0
- package/dist/fragment-index.d.ts.map +1 -0
- package/dist/fragment-index.js +8 -0
- package/dist/fragment-index.js.map +1 -0
- package/dist/fragments.d.ts +16 -0
- package/dist/fragments.d.ts.map +1 -0
- package/dist/fragments.js +104 -0
- package/dist/fragments.js.map +1 -0
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +5 -1
- package/dist/git-operations.js.map +1 -0
- package/dist/header-parser.d.ts +4 -4
- package/dist/header-parser.d.ts.map +1 -1
- package/dist/header-parser.js +8 -61
- package/dist/header-parser.js.map +1 -0
- package/dist/in-memory-content-api.d.ts +7 -7
- package/dist/in-memory-content-api.d.ts.map +1 -1
- package/dist/in-memory-content-api.js +74 -56
- package/dist/in-memory-content-api.js.map +1 -0
- package/dist/index.d.ts +19 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -9
- package/dist/index.js.map +1 -0
- package/dist/indexing.d.ts +4 -4
- package/dist/indexing.d.ts.map +1 -1
- package/dist/indexing.js +6 -5
- package/dist/indexing.js.map +1 -0
- package/dist/json-whitespace-view.js +1 -0
- package/dist/json-whitespace-view.js.map +1 -0
- package/dist/middleware.d.ts +6 -6
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +170 -119
- package/dist/middleware.js.map +1 -0
- package/dist/node.d.ts +24 -17
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +17 -14
- package/dist/node.js.map +1 -0
- package/dist/page-references.d.ts +21 -0
- package/dist/page-references.d.ts.map +1 -0
- package/dist/page-references.js +50 -0
- package/dist/page-references.js.map +1 -0
- package/dist/read-date.d.ts +3 -0
- package/dist/read-date.d.ts.map +1 -0
- package/dist/read-date.js +9 -0
- package/dist/read-date.js.map +1 -0
- package/dist/reader-backend.d.ts +54 -0
- package/dist/reader-backend.d.ts.map +1 -0
- package/dist/reader-backend.js +2 -0
- package/dist/reader-backend.js.map +1 -0
- package/dist/reader.d.ts +8 -8
- package/dist/reader.d.ts.map +1 -1
- package/dist/reader.js +8 -7
- package/dist/reader.js.map +1 -0
- package/dist/schemas/index.d.ts +6 -6
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +9 -8
- package/dist/schemas/index.js.map +1 -0
- package/dist/site-index.d.ts +3 -3
- package/dist/site-index.d.ts.map +1 -1
- package/dist/site-index.js +9 -5
- package/dist/site-index.js.map +1 -0
- package/dist/site.d.ts +5 -3
- package/dist/site.d.ts.map +1 -1
- package/dist/site.js +14 -2
- package/dist/site.js.map +1 -0
- package/dist/types.d.ts +203 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -0
- package/dist/url-safe-base64.js +1 -0
- package/dist/url-safe-base64.js.map +1 -0
- package/dist/url-validation.d.ts +14 -0
- package/dist/url-validation.d.ts.map +1 -1
- package/dist/url-validation.js +56 -14
- package/dist/url-validation.js.map +1 -0
- package/dist/utils/atomic-write.js +1 -0
- package/dist/utils/atomic-write.js.map +1 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +2 -1
- package/dist/utils.js.map +1 -0
- package/dist/vite-plugin.d.ts +2 -2
- package/dist/vite-plugin.js +5 -4
- package/dist/vite-plugin.js.map +1 -0
- package/dist/vxjson-serialize.d.ts +5 -6
- package/dist/vxjson-serialize.d.ts.map +1 -1
- package/dist/vxjson-serialize.js +13 -10
- package/dist/vxjson-serialize.js.map +1 -0
- package/dist/vxjson.d.ts +4 -3
- package/dist/vxjson.d.ts.map +1 -1
- package/dist/vxjson.js +10 -20
- package/dist/vxjson.js.map +1 -0
- package/dist/xxhash.d.ts.map +1 -1
- package/dist/xxhash.js +6 -2
- package/dist/xxhash.js.map +1 -0
- package/package.json +92 -56
- package/src/asset-constraints.ts +33 -0
- package/src/asset-metadata-store.ts +401 -0
- package/src/asset-operations.ts +914 -0
- package/src/asset-types.ts +74 -0
- package/src/asset-usage.ts +47 -0
- package/src/base-content-index.ts +227 -0
- package/src/cf-access.ts +85 -0
- package/src/component-registry.ts +145 -0
- package/src/component-registry.types.ts +12 -0
- package/src/component-vocabulary.ts +87 -0
- package/src/content-api.interface.ts +94 -0
- package/src/content-filters.ts +278 -0
- package/src/content-index.ts +642 -0
- package/src/content-operations.ts +497 -0
- package/src/content-path.ts +113 -0
- package/src/content-reader.ts +18 -0
- package/src/content-utils.ts +474 -0
- package/src/content-watcher.ts +122 -0
- package/src/data-index.ts +7 -0
- package/src/data.ts +134 -0
- package/src/editor-data-bindings.ts +66 -0
- package/src/etag-utils.ts +204 -0
- package/src/filesystem-content-api.ts +2685 -0
- package/src/filesystem-reader-backend.ts +135 -0
- package/src/fragment-index.ts +7 -0
- package/src/fragments.ts +113 -0
- package/src/git-operations.ts +340 -0
- package/src/header-parser.ts +272 -0
- package/src/in-memory-content-api.ts +760 -0
- package/src/index.ts +45 -0
- package/src/indexing.ts +8 -0
- package/src/json-whitespace-view.ts +155 -0
- package/src/middleware.ts +1341 -0
- package/src/node.ts +40 -0
- package/src/page-references.ts +76 -0
- package/src/read-date.ts +7 -0
- package/src/reader-backend.ts +54 -0
- package/src/reader.ts +15 -0
- package/src/schemas/index.ts +113 -0
- package/src/site-index.ts +330 -0
- package/src/site.ts +198 -0
- package/src/types.ts +759 -0
- package/src/url-safe-base64.ts +38 -0
- package/src/url-validation.ts +121 -0
- package/src/utils/atomic-write.ts +20 -0
- package/src/utils.ts +84 -0
- package/src/vite-plugin.ts +45 -0
- package/src/vxjson-serialize.ts +66 -0
- package/src/vxjson.ts +442 -0
- package/src/xxhash.ts +43 -0
- package/dist/asset-manifest.d.ts +0 -23
- package/dist/asset-manifest.d.ts.map +0 -1
- package/dist/asset-manifest.js +0 -73
- package/dist/block-index.d.ts +0 -9
- package/dist/block-index.d.ts.map +0 -1
- package/dist/block-index.js +0 -11
- package/dist/blocks.d.ts +0 -16
- package/dist/blocks.d.ts.map +0 -1
- package/dist/blocks.js +0 -103
- package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
- package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
- package/dist/content-index-D092_vk1.mjs +0 -629
- package/dist/content-index-D092_vk1.mjs.map +0 -1
- package/dist/content-index-D6IVMmAB.d.mts +0 -127
- package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
- package/dist/content-operations-DIbsxG5A.d.mts +0 -354
- package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
- package/dist/content-utils-fWNHTrPy.mjs +0 -280
- package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
- package/dist/data-DquNIEnQ.mjs +0 -62
- package/dist/data-DquNIEnQ.mjs.map +0 -1
- package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
- package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
- package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
- package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
- package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
- package/dist/index-DxVTFK66.d.mts +0 -105
- package/dist/index-DxVTFK66.d.mts.map +0 -1
- package/dist/index.d.mts +0 -80
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -78
- package/dist/index.mjs.map +0 -1
- package/dist/indexing.d.mts +0 -152
- package/dist/indexing.d.mts.map +0 -1
- package/dist/indexing.mjs +0 -255
- package/dist/indexing.mjs.map +0 -1
- package/dist/node.d.mts +0 -373
- package/dist/node.d.mts.map +0 -1
- package/dist/node.mjs +0 -2572
- package/dist/node.mjs.map +0 -1
- package/dist/reader.d.mts +0 -15
- package/dist/reader.d.mts.map +0 -1
- package/dist/reader.mjs +0 -22
- package/dist/reader.mjs.map +0 -1
- package/dist/schemas/index.d.mts +0 -2
- package/dist/schemas/index.mjs +0 -2
- package/dist/schemas-CFRD0FIQ.mjs +0 -84
- package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
- package/dist/site-8oaj1Q60.mjs +0 -366
- package/dist/site-8oaj1Q60.mjs.map +0 -1
- package/dist/site-index-B_254bCc.d.mts +0 -136
- package/dist/site-index-B_254bCc.d.mts.map +0 -1
- package/dist/types-DOdldbfD.mjs +0 -34
- package/dist/types-DOdldbfD.mjs.map +0 -1
- package/dist/types-DjfhS272.d.mts +0 -456
- package/dist/types-DjfhS272.d.mts.map +0 -1
- package/dist/vxjson-qHrgLGip.mjs +0 -555
- package/dist/vxjson-qHrgLGip.mjs.map +0 -1
- package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
- package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
- package/dist/vxjson-serialize.d.mts +0 -17
- package/dist/vxjson-serialize.d.mts.map +0 -1
- package/dist/vxjson-serialize.mjs +0 -2
package/dist/node.mjs
DELETED
|
@@ -1,2572 +0,0 @@
|
|
|
1
|
-
import { a as buildPathnameHistory, c as validateAndPrepareMetadata, i as buildLocaleVersion, l as validateCreateContent, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, r as analyzeUpdateScope, s as updatePublishDates, t as Site, u as Blocks } from "./site-8oaj1Q60.mjs";
|
|
2
|
-
import { _ as serializeMdxWithFrontmatter, a as getMetadataSize, c as isValidBlockName, d as mapLocales, f as mapSiteNames, g as resolvePublishDate, h as parseDate, i as getCurrentISODate, l as isValidPathname, m as normalizePathname, n as formatFileSize, o as isContentPublished, p as normalizeAndValidatePathname, r as generateContentId, s as isMetadataTooLarge, t as extractBlockName, u as localesOf } from "./content-utils-fWNHTrPy.mjs";
|
|
3
|
-
import { t as ContentIndex } from "./content-index-D092_vk1.mjs";
|
|
4
|
-
import { t as ErrorCodes } from "./types-DOdldbfD.mjs";
|
|
5
|
-
import { n as calculateEtagsFromMdxBuffer, r as findMdxContentStartPosition, t as VXJSON } from "./vxjson-qHrgLGip.mjs";
|
|
6
|
-
import { i as atomicWriteFile, n as readSitesConfig, r as filterContentWithIndexes, t as FileSystemContentAPI } from "./filesystem-content-api-C0HIhqZi.mjs";
|
|
7
|
-
import { t as Data } from "./data-DquNIEnQ.mjs";
|
|
8
|
-
import sortKeys from "sort-keys";
|
|
9
|
-
import { access, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
10
|
-
import { dirname, extname, join, normalize, parse, resolve } from "node:path";
|
|
11
|
-
import { imageSize } from "image-size";
|
|
12
|
-
import { spawn } from "node:child_process";
|
|
13
|
-
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
14
|
-
import { Hono } from "hono";
|
|
15
|
-
import { cors } from "hono/cors";
|
|
16
|
-
import { getRequestListener } from "@hono/node-server";
|
|
17
|
-
//#region src/asset-manifest.ts
|
|
18
|
-
const MANIFEST_FILENAME = ".asset-manifest.json";
|
|
19
|
-
var AssetManifest = class {
|
|
20
|
-
manifestPath;
|
|
21
|
-
_lock = Promise.resolve();
|
|
22
|
-
constructor(assetsPath) {
|
|
23
|
-
this.manifestPath = join(assetsPath, MANIFEST_FILENAME);
|
|
24
|
-
}
|
|
25
|
-
async read() {
|
|
26
|
-
try {
|
|
27
|
-
const raw = await readFile(this.manifestPath, "utf-8");
|
|
28
|
-
return JSON.parse(raw);
|
|
29
|
-
} catch {
|
|
30
|
-
return {};
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
async write(data) {
|
|
34
|
-
await atomicWriteFile(this.manifestPath, JSON.stringify(data, null, 2));
|
|
35
|
-
}
|
|
36
|
-
/** Atomic read-modify-write with promise-based mutex to prevent concurrent corruption */
|
|
37
|
-
async withManifest(fn) {
|
|
38
|
-
const prev = this._lock;
|
|
39
|
-
let release;
|
|
40
|
-
this._lock = new Promise((r) => {
|
|
41
|
-
release = r;
|
|
42
|
-
});
|
|
43
|
-
await prev;
|
|
44
|
-
try {
|
|
45
|
-
const updated = fn(await this.read());
|
|
46
|
-
await this.write(updated);
|
|
47
|
-
} finally {
|
|
48
|
-
release();
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
async add(relativePath, data) {
|
|
52
|
-
await this.withManifest((manifest) => {
|
|
53
|
-
manifest[relativePath] = data;
|
|
54
|
-
return manifest;
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
async remove(relativePath) {
|
|
58
|
-
let existed = false;
|
|
59
|
-
await this.withManifest((manifest) => {
|
|
60
|
-
existed = relativePath in manifest;
|
|
61
|
-
if (existed) delete manifest[relativePath];
|
|
62
|
-
return manifest;
|
|
63
|
-
});
|
|
64
|
-
return existed;
|
|
65
|
-
}
|
|
66
|
-
async get(relativePath) {
|
|
67
|
-
return (await this.read())[relativePath];
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Backward compat helper: search manifest keys for entry ending with /filename or equal to filename
|
|
71
|
-
* Useful during transition when only filename is known (not full relative path)
|
|
72
|
-
*/
|
|
73
|
-
async getByFilename(filename) {
|
|
74
|
-
const manifest = await this.read();
|
|
75
|
-
for (const [key, value] of Object.entries(manifest)) if (key === filename || key.endsWith(`/${filename}`)) return {
|
|
76
|
-
relativePath: key,
|
|
77
|
-
data: value
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/git-operations.ts
|
|
83
|
-
function runGitCommand(cwd, args) {
|
|
84
|
-
return new Promise((resolveCommand, reject) => {
|
|
85
|
-
const process = spawn("git", args, {
|
|
86
|
-
cwd,
|
|
87
|
-
stdio: [
|
|
88
|
-
"ignore",
|
|
89
|
-
"pipe",
|
|
90
|
-
"pipe"
|
|
91
|
-
]
|
|
92
|
-
});
|
|
93
|
-
let stdout = "";
|
|
94
|
-
let stderr = "";
|
|
95
|
-
process.stdout.on("data", (data) => {
|
|
96
|
-
stdout += data.toString();
|
|
97
|
-
});
|
|
98
|
-
process.stderr.on("data", (data) => {
|
|
99
|
-
stderr += data.toString();
|
|
100
|
-
});
|
|
101
|
-
process.on("error", reject);
|
|
102
|
-
process.on("close", (exitCode) => {
|
|
103
|
-
resolveCommand({
|
|
104
|
-
exitCode: exitCode ?? 1,
|
|
105
|
-
stdout: stdout.trim(),
|
|
106
|
-
stderr: stderr.trim()
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
});
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Resolve the git repository root from a content path.
|
|
113
|
-
* Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.
|
|
114
|
-
*/
|
|
115
|
-
async function resolveRepoRoot(contentPath) {
|
|
116
|
-
const result = await runGitCommand(dirname(resolve(contentPath)), ["rev-parse", "--show-toplevel"]);
|
|
117
|
-
if (result.exitCode !== 0) return null;
|
|
118
|
-
return result.stdout;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Create git operations using local git CLI commands.
|
|
122
|
-
* Requires git binary available on PATH and CONTENT_PATH inside a git repository.
|
|
123
|
-
*/
|
|
124
|
-
function createGitOperations(config) {
|
|
125
|
-
const { contentPath, branch } = config;
|
|
126
|
-
let cachedRepoRoot;
|
|
127
|
-
async function getCachedRepoRoot() {
|
|
128
|
-
if (cachedRepoRoot === void 0) cachedRepoRoot = await resolveRepoRoot(contentPath);
|
|
129
|
-
return cachedRepoRoot;
|
|
130
|
-
}
|
|
131
|
-
return {
|
|
132
|
-
async getStatus() {
|
|
133
|
-
try {
|
|
134
|
-
const repoRoot = await getCachedRepoRoot();
|
|
135
|
-
if (!repoRoot) return {
|
|
136
|
-
isRepo: false,
|
|
137
|
-
hasChanges: false,
|
|
138
|
-
changedFiles: 0,
|
|
139
|
-
ahead: 0,
|
|
140
|
-
behind: 0,
|
|
141
|
-
branch: "unknown"
|
|
142
|
-
};
|
|
143
|
-
const branchResult = await runGitCommand(repoRoot, [
|
|
144
|
-
"rev-parse",
|
|
145
|
-
"--abbrev-ref",
|
|
146
|
-
"HEAD"
|
|
147
|
-
]);
|
|
148
|
-
const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : "unknown";
|
|
149
|
-
const statusResult = await runGitCommand(repoRoot, [
|
|
150
|
-
"status",
|
|
151
|
-
"--porcelain",
|
|
152
|
-
"--",
|
|
153
|
-
contentPath
|
|
154
|
-
]);
|
|
155
|
-
const changedFiles = (statusResult.stdout ? statusResult.stdout.split("\n").filter((l) => l.trim()) : []).length;
|
|
156
|
-
const hasChanges = changedFiles > 0;
|
|
157
|
-
const remoteConfigured = (await runGitCommand(repoRoot, [
|
|
158
|
-
"remote",
|
|
159
|
-
"get-url",
|
|
160
|
-
"origin"
|
|
161
|
-
])).exitCode === 0;
|
|
162
|
-
let ahead = 0;
|
|
163
|
-
let behind = 0;
|
|
164
|
-
if (remoteConfigured) {
|
|
165
|
-
const revListResult = await runGitCommand(repoRoot, [
|
|
166
|
-
"rev-list",
|
|
167
|
-
"--left-right",
|
|
168
|
-
"--count",
|
|
169
|
-
`HEAD...origin/${branch || currentBranch}`
|
|
170
|
-
]);
|
|
171
|
-
if (revListResult.exitCode === 0 && revListResult.stdout) {
|
|
172
|
-
const [a, b] = revListResult.stdout.split(" ").map(Number);
|
|
173
|
-
ahead = a || 0;
|
|
174
|
-
behind = b || 0;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
return {
|
|
178
|
-
isRepo: true,
|
|
179
|
-
hasChanges,
|
|
180
|
-
changedFiles,
|
|
181
|
-
ahead,
|
|
182
|
-
behind,
|
|
183
|
-
branch: currentBranch,
|
|
184
|
-
remoteConfigured
|
|
185
|
-
};
|
|
186
|
-
} catch {
|
|
187
|
-
return {
|
|
188
|
-
isRepo: false,
|
|
189
|
-
hasChanges: false,
|
|
190
|
-
changedFiles: 0,
|
|
191
|
-
ahead: 0,
|
|
192
|
-
behind: 0,
|
|
193
|
-
branch: "unknown"
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
},
|
|
197
|
-
async commitAll(message, author) {
|
|
198
|
-
try {
|
|
199
|
-
const repoRoot = await getCachedRepoRoot();
|
|
200
|
-
if (!repoRoot) return {
|
|
201
|
-
success: false,
|
|
202
|
-
error: "Not a git repository"
|
|
203
|
-
};
|
|
204
|
-
const addResult = await runGitCommand(repoRoot, [
|
|
205
|
-
"add",
|
|
206
|
-
"-A",
|
|
207
|
-
"--",
|
|
208
|
-
contentPath
|
|
209
|
-
]);
|
|
210
|
-
if (addResult.exitCode !== 0) return {
|
|
211
|
-
success: false,
|
|
212
|
-
error: addResult.stderr || "Failed to stage changes"
|
|
213
|
-
};
|
|
214
|
-
if ((await runGitCommand(repoRoot, [
|
|
215
|
-
"diff",
|
|
216
|
-
"--cached",
|
|
217
|
-
"--quiet",
|
|
218
|
-
"--",
|
|
219
|
-
contentPath
|
|
220
|
-
])).exitCode === 0) return {
|
|
221
|
-
success: false,
|
|
222
|
-
error: "No changes to commit"
|
|
223
|
-
};
|
|
224
|
-
const diffStatResult = await runGitCommand(repoRoot, [
|
|
225
|
-
"diff",
|
|
226
|
-
"--cached",
|
|
227
|
-
"--numstat",
|
|
228
|
-
"--",
|
|
229
|
-
contentPath
|
|
230
|
-
]);
|
|
231
|
-
const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split("\n").filter((l) => l.trim()).length : 0;
|
|
232
|
-
const commitArgs = [
|
|
233
|
-
"commit",
|
|
234
|
-
"-m",
|
|
235
|
-
message
|
|
236
|
-
];
|
|
237
|
-
if (author) commitArgs.push("--author", `${author.name} <${author.email}>`);
|
|
238
|
-
const commitResult = await runGitCommand(repoRoot, commitArgs);
|
|
239
|
-
if (commitResult.exitCode !== 0) return {
|
|
240
|
-
success: false,
|
|
241
|
-
error: commitResult.stderr || "Commit failed"
|
|
242
|
-
};
|
|
243
|
-
return {
|
|
244
|
-
success: true,
|
|
245
|
-
commit: (await runGitCommand(repoRoot, ["rev-parse", "HEAD"])).stdout || void 0,
|
|
246
|
-
summary: `${fileCount} files committed`
|
|
247
|
-
};
|
|
248
|
-
} catch (error) {
|
|
249
|
-
return {
|
|
250
|
-
success: false,
|
|
251
|
-
error: error instanceof Error ? error.message : "Commit failed"
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
},
|
|
255
|
-
async pushOrigin() {
|
|
256
|
-
try {
|
|
257
|
-
const repoRoot = await getCachedRepoRoot();
|
|
258
|
-
if (!repoRoot) return {
|
|
259
|
-
success: false,
|
|
260
|
-
error: "Not a git repository"
|
|
261
|
-
};
|
|
262
|
-
if ((await runGitCommand(repoRoot, [
|
|
263
|
-
"remote",
|
|
264
|
-
"get-url",
|
|
265
|
-
"origin"
|
|
266
|
-
])).exitCode !== 0) return {
|
|
267
|
-
success: false,
|
|
268
|
-
error: "No git remote \"origin\" configured. Please configure a remote to enable push."
|
|
269
|
-
};
|
|
270
|
-
let targetBranch = branch;
|
|
271
|
-
if (!targetBranch) targetBranch = (await runGitCommand(repoRoot, [
|
|
272
|
-
"rev-parse",
|
|
273
|
-
"--abbrev-ref",
|
|
274
|
-
"HEAD"
|
|
275
|
-
])).stdout;
|
|
276
|
-
const pushResult = await runGitCommand(repoRoot, [
|
|
277
|
-
"push",
|
|
278
|
-
"origin",
|
|
279
|
-
targetBranch
|
|
280
|
-
]);
|
|
281
|
-
if (pushResult.exitCode !== 0) {
|
|
282
|
-
const stderr = pushResult.stderr || "";
|
|
283
|
-
if (stderr.includes("non-fast-forward") || stderr.includes("rejected")) return {
|
|
284
|
-
success: false,
|
|
285
|
-
error: "Push rejected: remote has changes. Pull first, then try pushing again."
|
|
286
|
-
};
|
|
287
|
-
if (stderr.includes("Could not resolve host")) return {
|
|
288
|
-
success: false,
|
|
289
|
-
error: "Cannot reach git remote. Check your network connection."
|
|
290
|
-
};
|
|
291
|
-
if (stderr.includes("Permission denied") || stderr.includes("Authentication failed")) return {
|
|
292
|
-
success: false,
|
|
293
|
-
error: "Git remote authentication failed. Check server SSH key or credential configuration."
|
|
294
|
-
};
|
|
295
|
-
return {
|
|
296
|
-
success: false,
|
|
297
|
-
error: stderr || "Push failed"
|
|
298
|
-
};
|
|
299
|
-
}
|
|
300
|
-
return { success: true };
|
|
301
|
-
} catch (error) {
|
|
302
|
-
return {
|
|
303
|
-
success: false,
|
|
304
|
-
error: error instanceof Error ? error.message : "Push failed"
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
},
|
|
308
|
-
async pull() {
|
|
309
|
-
try {
|
|
310
|
-
const repoRoot = await getCachedRepoRoot();
|
|
311
|
-
if (!repoRoot) return {
|
|
312
|
-
success: false,
|
|
313
|
-
error: "Not a git repository"
|
|
314
|
-
};
|
|
315
|
-
let targetBranch = branch;
|
|
316
|
-
if (!targetBranch) targetBranch = (await runGitCommand(repoRoot, [
|
|
317
|
-
"rev-parse",
|
|
318
|
-
"--abbrev-ref",
|
|
319
|
-
"HEAD"
|
|
320
|
-
])).stdout;
|
|
321
|
-
const pullResult = await runGitCommand(repoRoot, [
|
|
322
|
-
"pull",
|
|
323
|
-
"--autostash",
|
|
324
|
-
"--rebase",
|
|
325
|
-
"origin",
|
|
326
|
-
targetBranch
|
|
327
|
-
]);
|
|
328
|
-
if (pullResult.exitCode !== 0) return {
|
|
329
|
-
success: false,
|
|
330
|
-
error: pullResult.stderr || pullResult.stdout || "Pull failed"
|
|
331
|
-
};
|
|
332
|
-
return {
|
|
333
|
-
success: true,
|
|
334
|
-
summary: pullResult.stdout || `Pulled latest changes from origin/${targetBranch}`
|
|
335
|
-
};
|
|
336
|
-
} catch (error) {
|
|
337
|
-
return {
|
|
338
|
-
success: false,
|
|
339
|
-
error: error instanceof Error ? error.message : "Pull failed"
|
|
340
|
-
};
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
const LFS_PATTERNS = [
|
|
346
|
-
"*.jpg filter=lfs diff=lfs merge=lfs -text",
|
|
347
|
-
"*.jpeg filter=lfs diff=lfs merge=lfs -text",
|
|
348
|
-
"*.png filter=lfs diff=lfs merge=lfs -text",
|
|
349
|
-
"*.gif filter=lfs diff=lfs merge=lfs -text",
|
|
350
|
-
"*.svg filter=lfs diff=lfs merge=lfs -text",
|
|
351
|
-
"*.webp filter=lfs diff=lfs merge=lfs -text",
|
|
352
|
-
"*.avif filter=lfs diff=lfs merge=lfs -text",
|
|
353
|
-
"*.ico filter=lfs diff=lfs merge=lfs -text"
|
|
354
|
-
];
|
|
355
|
-
/**
|
|
356
|
-
* Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.
|
|
357
|
-
* Creates the file if missing, or appends missing patterns if file exists.
|
|
358
|
-
*/
|
|
359
|
-
async function setupGitLfsAttributes(contentRoot) {
|
|
360
|
-
const gitattributesPath = join(contentRoot, ".gitattributes");
|
|
361
|
-
let existing = "";
|
|
362
|
-
try {
|
|
363
|
-
await access(gitattributesPath);
|
|
364
|
-
existing = await readFile(gitattributesPath, "utf-8");
|
|
365
|
-
} catch {}
|
|
366
|
-
const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));
|
|
367
|
-
if (missingPatterns.length === 0) return;
|
|
368
|
-
await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
|
|
369
|
-
}
|
|
370
|
-
//#endregion
|
|
371
|
-
//#region src/url-validation.ts
|
|
372
|
-
/**
|
|
373
|
-
* URL validation for SSRF prevention in server-side fetch operations.
|
|
374
|
-
* Blocks private/reserved IP addresses and non-http(s) schemes.
|
|
375
|
-
*/
|
|
376
|
-
const BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set(["localhost"]);
|
|
377
|
-
/** Check if an IPv4 address string points to a private/reserved range */
|
|
378
|
-
function isPrivateIPv4(hostname) {
|
|
379
|
-
const parts = hostname.split(".");
|
|
380
|
-
if (parts.length !== 4) return false;
|
|
381
|
-
const octets = parts.map((p) => Number.parseInt(p, 10));
|
|
382
|
-
if (octets.some((o) => Number.isNaN(o) || o < 0 || o > 255)) return false;
|
|
383
|
-
const [first, second] = octets;
|
|
384
|
-
if (first === 0) return true;
|
|
385
|
-
if (first === 10) return true;
|
|
386
|
-
if (first === 127) return true;
|
|
387
|
-
if (first === 169 && second === 254) return true;
|
|
388
|
-
if (first === 172 && second >= 16 && second <= 31) return true;
|
|
389
|
-
if (first === 192 && second === 168) return true;
|
|
390
|
-
return false;
|
|
391
|
-
}
|
|
392
|
-
/** Check if an IPv6 address string points to a private/reserved range */
|
|
393
|
-
function isPrivateIPv6(hostname) {
|
|
394
|
-
const lower = hostname.toLowerCase();
|
|
395
|
-
if (lower === "::1") return true;
|
|
396
|
-
if (lower === "::") return true;
|
|
397
|
-
if (lower.startsWith("fe80:") || lower.startsWith("fe80%")) return true;
|
|
398
|
-
if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
|
|
399
|
-
return false;
|
|
400
|
-
}
|
|
401
|
-
/**
|
|
402
|
-
* Validate that a URL is safe to fetch server-side.
|
|
403
|
-
* Blocks private/reserved IP addresses and non-http(s) schemes.
|
|
404
|
-
*
|
|
405
|
-
* @param url The URL string to validate
|
|
406
|
-
* @returns The parsed URL object if valid
|
|
407
|
-
* @throws Error if the URL is invalid, uses a blocked scheme, or points to a private IP
|
|
408
|
-
*/
|
|
409
|
-
function validateFetchUrl(url) {
|
|
410
|
-
const parsed = new URL(url);
|
|
411
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("URL scheme must be http or https");
|
|
412
|
-
const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
|
|
413
|
-
if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) throw new Error("URL points to a private/reserved IP address");
|
|
414
|
-
if (isPrivateIPv4(hostname)) throw new Error("URL points to a private/reserved IP address");
|
|
415
|
-
if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
|
|
416
|
-
return parsed;
|
|
417
|
-
}
|
|
418
|
-
//#endregion
|
|
419
|
-
//#region src/asset-operations.ts
|
|
420
|
-
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
421
|
-
const DEFAULT_ACCEPTED_FORMATS = [
|
|
422
|
-
"jpg",
|
|
423
|
-
"jpeg",
|
|
424
|
-
"png",
|
|
425
|
-
"gif",
|
|
426
|
-
"webp",
|
|
427
|
-
"avif",
|
|
428
|
-
"svg",
|
|
429
|
-
"ico"
|
|
430
|
-
];
|
|
431
|
-
const MIME_MAP = {
|
|
432
|
-
jpg: "image/jpeg",
|
|
433
|
-
jpeg: "image/jpeg",
|
|
434
|
-
png: "image/png",
|
|
435
|
-
gif: "image/gif",
|
|
436
|
-
webp: "image/webp",
|
|
437
|
-
avif: "image/avif",
|
|
438
|
-
svg: "image/svg+xml",
|
|
439
|
-
ico: "image/x-icon"
|
|
440
|
-
};
|
|
441
|
-
/** Recognized web image extensions for filesystem scanning */
|
|
442
|
-
const RECOGNIZED_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
443
|
-
"jpg",
|
|
444
|
-
"jpeg",
|
|
445
|
-
"png",
|
|
446
|
-
"gif",
|
|
447
|
-
"webp",
|
|
448
|
-
"svg",
|
|
449
|
-
"avif",
|
|
450
|
-
"ico"
|
|
451
|
-
]);
|
|
452
|
-
/** System files to skip during filesystem scanning */
|
|
453
|
-
const SYSTEM_FILES = /* @__PURE__ */ new Set([
|
|
454
|
-
".ds_store",
|
|
455
|
-
"thumbs.db",
|
|
456
|
-
".gitkeep",
|
|
457
|
-
"desktop.ini",
|
|
458
|
-
".asset-manifest.json"
|
|
459
|
-
]);
|
|
460
|
-
/** Check if filename has a recognized web image extension */
|
|
461
|
-
function isRecognizedImageExtension(filename) {
|
|
462
|
-
const ext = extname(filename).slice(1).toLowerCase();
|
|
463
|
-
return RECOGNIZED_IMAGE_EXTENSIONS.has(ext);
|
|
464
|
-
}
|
|
465
|
-
/** Check if file is a system/hidden file that should be skipped */
|
|
466
|
-
function isSystemFile(filename) {
|
|
467
|
-
return filename.startsWith(".") || SYSTEM_FILES.has(filename.toLowerCase());
|
|
468
|
-
}
|
|
469
|
-
var AssetOperations = class {
|
|
470
|
-
config;
|
|
471
|
-
manifest;
|
|
472
|
-
dirEnsured = false;
|
|
473
|
-
lfsSetup = false;
|
|
474
|
-
constructor(config) {
|
|
475
|
-
this.config = {
|
|
476
|
-
assetsPath: config.assetsPath,
|
|
477
|
-
maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
|
|
478
|
-
acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,
|
|
479
|
-
contentRoot: config.contentRoot
|
|
480
|
-
};
|
|
481
|
-
this.manifest = new AssetManifest(config.assetsPath);
|
|
482
|
-
}
|
|
483
|
-
/** Resolve folder from manifest when only filename is known */
|
|
484
|
-
async resolveFolder(filename) {
|
|
485
|
-
const entry = await this.manifest.getByFilename(filename);
|
|
486
|
-
if (!entry) return "/";
|
|
487
|
-
const lastSlash = entry.relativePath.lastIndexOf("/");
|
|
488
|
-
return lastSlash > 0 ? `/${entry.relativePath.slice(0, lastSlash)}` : "/";
|
|
489
|
-
}
|
|
490
|
-
async ensureDir(subpath) {
|
|
491
|
-
const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
|
|
492
|
-
if (!subpath && this.dirEnsured) return;
|
|
493
|
-
await mkdir(targetPath, { recursive: true });
|
|
494
|
-
if (!subpath) this.dirEnsured = true;
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* Validate that a subpath is safe (no path traversal attacks)
|
|
498
|
-
* Returns the resolved full path if valid, throws if invalid
|
|
499
|
-
*/
|
|
500
|
-
validateSubpath(subpath) {
|
|
501
|
-
const normalizedSubpath = subpath.replace(/^\/+|\/+$/g, "") || ".";
|
|
502
|
-
const assetsAbsolute = resolve(this.config.assetsPath);
|
|
503
|
-
const fullPath = resolve(assetsAbsolute, normalizedSubpath);
|
|
504
|
-
if (!fullPath.startsWith(assetsAbsolute)) throw new Error("Path traversal detected");
|
|
505
|
-
return fullPath;
|
|
506
|
-
}
|
|
507
|
-
/**
|
|
508
|
-
* Resolve a unique filename by appending -1, -2, etc. if collision exists
|
|
509
|
-
* @param originalName Original filename
|
|
510
|
-
* @param folder Optional folder path (relative to assets root)
|
|
511
|
-
*/
|
|
512
|
-
async resolveFilename(originalName, folder) {
|
|
513
|
-
const { name, ext } = parse(originalName);
|
|
514
|
-
const sanitized = name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
|
|
515
|
-
const safeExt = ext.toLowerCase();
|
|
516
|
-
const baseDir = folder && folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, "")) : this.config.assetsPath;
|
|
517
|
-
let candidate = `${sanitized}${safeExt}`;
|
|
518
|
-
let counter = 0;
|
|
519
|
-
while (true) try {
|
|
520
|
-
await access(join(baseDir, candidate));
|
|
521
|
-
counter++;
|
|
522
|
-
candidate = `${sanitized}-${counter}${safeExt}`;
|
|
523
|
-
} catch {
|
|
524
|
-
break;
|
|
525
|
-
}
|
|
526
|
-
return candidate;
|
|
527
|
-
}
|
|
528
|
-
validateFormat(filename) {
|
|
529
|
-
const ext = extname(filename).slice(1).toLowerCase();
|
|
530
|
-
return this.config.acceptedFormats.includes(ext);
|
|
531
|
-
}
|
|
532
|
-
validateSize(size) {
|
|
533
|
-
return size <= this.config.maxFileSize;
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* Get image dimensions from manifest cache or by reading file headers
|
|
537
|
-
*/
|
|
538
|
-
async getDimensions(filePath, manifestEntry) {
|
|
539
|
-
if (manifestEntry?.width && manifestEntry?.height) return {
|
|
540
|
-
width: manifestEntry.width,
|
|
541
|
-
height: manifestEntry.height,
|
|
542
|
-
fromCache: true
|
|
543
|
-
};
|
|
544
|
-
try {
|
|
545
|
-
const buffer = await readFile(filePath);
|
|
546
|
-
const result = imageSize(new Uint8Array(buffer));
|
|
547
|
-
return {
|
|
548
|
-
width: result.width,
|
|
549
|
-
height: result.height,
|
|
550
|
-
fromCache: false
|
|
551
|
-
};
|
|
552
|
-
} catch {
|
|
553
|
-
return {
|
|
554
|
-
width: void 0,
|
|
555
|
-
height: void 0,
|
|
556
|
-
fromCache: false
|
|
557
|
-
};
|
|
558
|
-
}
|
|
559
|
-
}
|
|
560
|
-
/**
|
|
561
|
-
* Build an AssetEntry from a directory entry, enriching with manifest metadata
|
|
562
|
-
*/
|
|
563
|
-
async buildAssetEntry(dirent, folder, manifestData) {
|
|
564
|
-
const relativePath = folder === "/" ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
|
|
565
|
-
const manifestEntry = manifestData[relativePath];
|
|
566
|
-
const fullPath = this.getAssetPath(dirent.name, folder);
|
|
567
|
-
const stats = await stat(fullPath);
|
|
568
|
-
const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
|
|
569
|
-
if (!fromCache && width && height) this.manifest.add(relativePath, {
|
|
570
|
-
...manifestEntry,
|
|
571
|
-
width,
|
|
572
|
-
height
|
|
573
|
-
}).catch(() => {});
|
|
574
|
-
const ext = extname(dirent.name).slice(1).toLowerCase();
|
|
575
|
-
const mimeType = MIME_MAP[ext] || `image/${ext}`;
|
|
576
|
-
return {
|
|
577
|
-
filename: dirent.name,
|
|
578
|
-
originalName: manifestEntry?.originalName || dirent.name,
|
|
579
|
-
mimeType,
|
|
580
|
-
size: stats.size,
|
|
581
|
-
width,
|
|
582
|
-
height,
|
|
583
|
-
alt: manifestEntry?.alt,
|
|
584
|
-
uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
|
|
585
|
-
uploadedBy: manifestEntry?.uploadedBy,
|
|
586
|
-
folder,
|
|
587
|
-
tags: manifestEntry?.tags
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
async upload(file, metadata) {
|
|
591
|
-
if (!this.validateFormat(file.name)) return {
|
|
592
|
-
success: false,
|
|
593
|
-
error: `Invalid format. Accepted: ${this.config.acceptedFormats.join(", ")}`
|
|
594
|
-
};
|
|
595
|
-
if (!this.validateSize(file.size)) return {
|
|
596
|
-
success: false,
|
|
597
|
-
error: `File too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
|
|
598
|
-
};
|
|
599
|
-
const folder = metadata?.folder && metadata.folder !== "/" ? "/" + metadata.folder.replace(/^\/+|\/+$/g, "") : "/";
|
|
600
|
-
if (folder !== "/") try {
|
|
601
|
-
this.validateSubpath(folder);
|
|
602
|
-
} catch {
|
|
603
|
-
return {
|
|
604
|
-
success: false,
|
|
605
|
-
error: "Invalid folder path"
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
await this.ensureDir();
|
|
609
|
-
if (folder !== "/") await this.ensureDir(folder.replace(/^\//, ""));
|
|
610
|
-
if (!this.lfsSetup) {
|
|
611
|
-
await setupGitLfsAttributes(this.config.assetsPath);
|
|
612
|
-
this.lfsSetup = true;
|
|
613
|
-
}
|
|
614
|
-
const filename = await this.resolveFilename(file.name, folder);
|
|
615
|
-
const filePath = folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\//, ""), filename) : join(this.config.assetsPath, filename);
|
|
616
|
-
const arrayBuffer = await file.arrayBuffer();
|
|
617
|
-
await writeFile(filePath, new Uint8Array(arrayBuffer));
|
|
618
|
-
const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
|
|
619
|
-
const manifestEntry = {
|
|
620
|
-
alt: metadata?.alt,
|
|
621
|
-
width: metadata?.width,
|
|
622
|
-
height: metadata?.height,
|
|
623
|
-
uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
624
|
-
uploadedBy: metadata?.uploadedBy,
|
|
625
|
-
originalName: file.name
|
|
626
|
-
};
|
|
627
|
-
await this.manifest.add(relativePath, manifestEntry);
|
|
628
|
-
const ext = extname(filename).slice(1).toLowerCase();
|
|
629
|
-
return {
|
|
630
|
-
success: true,
|
|
631
|
-
asset: {
|
|
632
|
-
filename,
|
|
633
|
-
originalName: file.name,
|
|
634
|
-
mimeType: MIME_MAP[ext] || `image/${ext}`,
|
|
635
|
-
size: file.size,
|
|
636
|
-
width: metadata?.width,
|
|
637
|
-
height: metadata?.height,
|
|
638
|
-
alt: metadata?.alt,
|
|
639
|
-
uploadedAt: manifestEntry.uploadedAt,
|
|
640
|
-
uploadedBy: metadata?.uploadedBy,
|
|
641
|
-
folder
|
|
642
|
-
}
|
|
643
|
-
};
|
|
644
|
-
}
|
|
645
|
-
/**
|
|
646
|
-
* List all assets recursively from filesystem
|
|
647
|
-
*/
|
|
648
|
-
async list() {
|
|
649
|
-
const manifestData = await this.manifest.read();
|
|
650
|
-
const assets = [];
|
|
651
|
-
const scanFolder = async (folderPath, folder) => {
|
|
652
|
-
let entries;
|
|
653
|
-
try {
|
|
654
|
-
entries = await readdir(folderPath, { withFileTypes: true });
|
|
655
|
-
} catch {
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
for (const entry of entries) {
|
|
659
|
-
if (isSystemFile(entry.name) || entry.isSymbolicLink()) continue;
|
|
660
|
-
const entryPath = join(folderPath, entry.name);
|
|
661
|
-
if (entry.isDirectory()) {
|
|
662
|
-
const subFolder = folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`;
|
|
663
|
-
await scanFolder(entryPath, subFolder);
|
|
664
|
-
} else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
|
|
665
|
-
const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);
|
|
666
|
-
assets.push(assetEntry);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
};
|
|
670
|
-
await scanFolder(this.config.assetsPath, "/");
|
|
671
|
-
return assets;
|
|
672
|
-
}
|
|
673
|
-
/**
|
|
674
|
-
* Get asset by filename and optional folder
|
|
675
|
-
*/
|
|
676
|
-
async getAsset(filename, folder = "/") {
|
|
677
|
-
const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
|
|
678
|
-
const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
|
|
679
|
-
const fullPath = this.getAssetPath(filename, resolvedFolder);
|
|
680
|
-
let stats;
|
|
681
|
-
try {
|
|
682
|
-
stats = await stat(fullPath);
|
|
683
|
-
} catch {
|
|
684
|
-
return;
|
|
685
|
-
}
|
|
686
|
-
if (!stats.isFile()) return;
|
|
687
|
-
const manifestEntry = (await this.manifest.read())[relativePath];
|
|
688
|
-
const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
|
|
689
|
-
if (!fromCache && width && height) this.manifest.add(relativePath, {
|
|
690
|
-
...manifestEntry,
|
|
691
|
-
width,
|
|
692
|
-
height
|
|
693
|
-
}).catch(() => {});
|
|
694
|
-
const ext = extname(filename).slice(1).toLowerCase();
|
|
695
|
-
const mimeType = MIME_MAP[ext] || `image/${ext}`;
|
|
696
|
-
return {
|
|
697
|
-
filename,
|
|
698
|
-
originalName: manifestEntry?.originalName || filename,
|
|
699
|
-
mimeType,
|
|
700
|
-
size: stats.size,
|
|
701
|
-
width,
|
|
702
|
-
height,
|
|
703
|
-
alt: manifestEntry?.alt,
|
|
704
|
-
uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
|
|
705
|
-
uploadedBy: manifestEntry?.uploadedBy,
|
|
706
|
-
folder: resolvedFolder,
|
|
707
|
-
tags: manifestEntry?.tags
|
|
708
|
-
};
|
|
709
|
-
}
|
|
710
|
-
/**
|
|
711
|
-
* Delete asset file and manifest entry
|
|
712
|
-
*/
|
|
713
|
-
async delete(filename, folder = "/") {
|
|
714
|
-
const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
|
|
715
|
-
const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
|
|
716
|
-
const filePath = this.getAssetPath(filename, resolvedFolder);
|
|
717
|
-
try {
|
|
718
|
-
await unlink(filePath);
|
|
719
|
-
} catch {}
|
|
720
|
-
await this.manifest.remove(relativePath);
|
|
721
|
-
return { success: true };
|
|
722
|
-
}
|
|
723
|
-
/**
|
|
724
|
-
* Import an image from a URL (server-side fetch, no CORS issues)
|
|
725
|
-
* Validates URL against SSRF, enforces 30s timeout, and checks response size.
|
|
726
|
-
*/
|
|
727
|
-
async importFromUrl(url, metadata) {
|
|
728
|
-
try {
|
|
729
|
-
validateFetchUrl(url);
|
|
730
|
-
} catch (err) {
|
|
731
|
-
return {
|
|
732
|
-
success: false,
|
|
733
|
-
error: err instanceof Error ? err.message : "Invalid URL"
|
|
734
|
-
};
|
|
735
|
-
}
|
|
736
|
-
const controller = new AbortController();
|
|
737
|
-
const timeout = setTimeout(() => controller.abort(), 3e4);
|
|
738
|
-
let response;
|
|
739
|
-
try {
|
|
740
|
-
response = await fetch(url, { signal: controller.signal });
|
|
741
|
-
} catch {
|
|
742
|
-
return {
|
|
743
|
-
success: false,
|
|
744
|
-
error: "Failed to fetch URL"
|
|
745
|
-
};
|
|
746
|
-
} finally {
|
|
747
|
-
clearTimeout(timeout);
|
|
748
|
-
}
|
|
749
|
-
if (!response.ok) return {
|
|
750
|
-
success: false,
|
|
751
|
-
error: `Fetch failed with status ${response.status}`
|
|
752
|
-
};
|
|
753
|
-
const contentLength = response.headers.get("content-length");
|
|
754
|
-
if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) return {
|
|
755
|
-
success: false,
|
|
756
|
-
error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
|
|
757
|
-
};
|
|
758
|
-
const contentType = response.headers.get("content-type") || "";
|
|
759
|
-
const urlFilename = new URL(url).pathname.split("/").pop() || "imported-image.jpg";
|
|
760
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
761
|
-
if (arrayBuffer.byteLength > this.config.maxFileSize) return {
|
|
762
|
-
success: false,
|
|
763
|
-
error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
|
|
764
|
-
};
|
|
765
|
-
const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
|
|
766
|
-
return this.upload(file, metadata);
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* List assets and subfolders within a folder (filesystem-first)
|
|
770
|
-
* @param subpath Folder path relative to assets root (default '/')
|
|
771
|
-
*/
|
|
772
|
-
async listFolder(subpath = "/") {
|
|
773
|
-
const normalizedSubpath = subpath === "/" ? "/" : "/" + subpath.replace(/^\/+|\/+$/g, "");
|
|
774
|
-
let fullPath;
|
|
775
|
-
if (normalizedSubpath === "/") fullPath = this.config.assetsPath;
|
|
776
|
-
else fullPath = this.validateSubpath(normalizedSubpath);
|
|
777
|
-
let entries;
|
|
778
|
-
try {
|
|
779
|
-
entries = await readdir(fullPath, { withFileTypes: true });
|
|
780
|
-
} catch {
|
|
781
|
-
return {
|
|
782
|
-
assets: [],
|
|
783
|
-
folders: []
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
const folders = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && !e.isSymbolicLink()).map((e) => ({
|
|
787
|
-
name: e.name,
|
|
788
|
-
path: normalizedSubpath === "/" ? `/${e.name}` : `${normalizedSubpath}/${e.name}`
|
|
789
|
-
}));
|
|
790
|
-
const imageFiles = entries.filter((e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name));
|
|
791
|
-
const manifestData = await this.manifest.read();
|
|
792
|
-
return {
|
|
793
|
-
assets: await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData))),
|
|
794
|
-
folders
|
|
795
|
-
};
|
|
796
|
-
}
|
|
797
|
-
/**
|
|
798
|
-
* Create a folder on disk
|
|
799
|
-
* @param subpath Folder path relative to assets root
|
|
800
|
-
*/
|
|
801
|
-
async createFolder(subpath) {
|
|
802
|
-
if (!subpath || subpath === "/") return {
|
|
803
|
-
success: false,
|
|
804
|
-
error: "Cannot create root folder"
|
|
805
|
-
};
|
|
806
|
-
let fullPath;
|
|
807
|
-
try {
|
|
808
|
-
fullPath = this.validateSubpath(subpath);
|
|
809
|
-
} catch {
|
|
810
|
-
return {
|
|
811
|
-
success: false,
|
|
812
|
-
error: "Invalid folder path"
|
|
813
|
-
};
|
|
814
|
-
}
|
|
815
|
-
try {
|
|
816
|
-
await mkdir(fullPath, { recursive: true });
|
|
817
|
-
return { success: true };
|
|
818
|
-
} catch (err) {
|
|
819
|
-
return {
|
|
820
|
-
success: false,
|
|
821
|
-
error: `Failed to create folder: ${err instanceof Error ? err.message : "Unknown error"}`
|
|
822
|
-
};
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
/**
|
|
826
|
-
* Update asset metadata (alt text, tags)
|
|
827
|
-
* @param filename Asset filename
|
|
828
|
-
* @param updates Metadata updates (alt, tags)
|
|
829
|
-
* @param folder Optional folder path (default '/')
|
|
830
|
-
*/
|
|
831
|
-
async updateMetadata(filename, updates, folder = "/") {
|
|
832
|
-
const resolvedFolder = folder === "/" ? await this.resolveFolder(filename) : folder;
|
|
833
|
-
const relativePath = resolvedFolder === "/" ? filename : `${resolvedFolder.slice(1)}/${filename}`;
|
|
834
|
-
const fullPath = this.getAssetPath(filename, resolvedFolder);
|
|
835
|
-
try {
|
|
836
|
-
await stat(fullPath);
|
|
837
|
-
} catch {
|
|
838
|
-
return {
|
|
839
|
-
success: false,
|
|
840
|
-
error: "Asset not found"
|
|
841
|
-
};
|
|
842
|
-
}
|
|
843
|
-
const merged = {
|
|
844
|
-
...(await this.manifest.read())[relativePath] || {},
|
|
845
|
-
...updates
|
|
846
|
-
};
|
|
847
|
-
await this.manifest.add(relativePath, merged);
|
|
848
|
-
const asset = await this.getAsset(filename, resolvedFolder);
|
|
849
|
-
if (!asset) return {
|
|
850
|
-
success: false,
|
|
851
|
-
error: "Failed to retrieve updated asset"
|
|
852
|
-
};
|
|
853
|
-
return {
|
|
854
|
-
success: true,
|
|
855
|
-
asset
|
|
856
|
-
};
|
|
857
|
-
}
|
|
858
|
-
/**
|
|
859
|
-
* Get usage information for an asset (which pages reference it)
|
|
860
|
-
* @param filename Asset filename
|
|
861
|
-
*/
|
|
862
|
-
async getUsage(filename) {
|
|
863
|
-
if (!this.config.contentRoot) return [];
|
|
864
|
-
const usages = [];
|
|
865
|
-
const searchPatterns = [
|
|
866
|
-
filename,
|
|
867
|
-
`/assets/uploads/${filename}`,
|
|
868
|
-
`assets/uploads/${filename}`
|
|
869
|
-
];
|
|
870
|
-
const walkDir = async (dir) => {
|
|
871
|
-
const files = [];
|
|
872
|
-
let entries;
|
|
873
|
-
try {
|
|
874
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
875
|
-
} catch {
|
|
876
|
-
return files;
|
|
877
|
-
}
|
|
878
|
-
for (const entry of entries) {
|
|
879
|
-
const fullPath = join(dir, entry.name);
|
|
880
|
-
if (entry.isDirectory() && !entry.name.startsWith(".")) files.push(...await walkDir(fullPath));
|
|
881
|
-
else if (entry.isFile() && entry.name.endsWith(".vxjson")) files.push(fullPath);
|
|
882
|
-
}
|
|
883
|
-
return files;
|
|
884
|
-
};
|
|
885
|
-
const vxjsonFiles = await walkDir(this.config.contentRoot);
|
|
886
|
-
for (const filePath of vxjsonFiles) try {
|
|
887
|
-
const content = await readFile(filePath, "utf-8");
|
|
888
|
-
if (searchPatterns.some((pattern) => content.includes(pattern))) {
|
|
889
|
-
const pageName = filePath.replace(this.config.contentRoot, "").replace(/^[/\\]/, "").replace(/\.vxjson$/, "");
|
|
890
|
-
let field = "unknown";
|
|
891
|
-
try {
|
|
892
|
-
const json = JSON.parse(content);
|
|
893
|
-
field = this.findFieldWithAsset(json, searchPatterns) || "content";
|
|
894
|
-
} catch {
|
|
895
|
-
field = "content";
|
|
896
|
-
}
|
|
897
|
-
usages.push({
|
|
898
|
-
page: pageName,
|
|
899
|
-
field
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
} catch {}
|
|
903
|
-
return usages;
|
|
904
|
-
}
|
|
905
|
-
/**
|
|
906
|
-
* Get the file path for an asset
|
|
907
|
-
* @param filename Asset filename
|
|
908
|
-
* @param folder Optional folder path (defaults to asset's stored folder)
|
|
909
|
-
*/
|
|
910
|
-
getAssetPath(filename, folder) {
|
|
911
|
-
const subpath = folder && folder !== "/" ? folder.replace(/^\/+|\/+$/g, "") : "";
|
|
912
|
-
const combined = subpath ? `${subpath}/${filename}` : filename;
|
|
913
|
-
return this.validateSubpath(combined);
|
|
914
|
-
}
|
|
915
|
-
/**
|
|
916
|
-
* Read asset file contents for serving (filesystem-first)
|
|
917
|
-
* @param filename Asset filename
|
|
918
|
-
* @param folder Optional folder path (default '/')
|
|
919
|
-
*/
|
|
920
|
-
async readAssetFile(filename, folder = "/") {
|
|
921
|
-
const filePath = this.getAssetPath(filename, folder);
|
|
922
|
-
const ext = extname(filename).slice(1).toLowerCase();
|
|
923
|
-
const mimeType = MIME_MAP[ext] || `image/${ext}`;
|
|
924
|
-
try {
|
|
925
|
-
return {
|
|
926
|
-
success: true,
|
|
927
|
-
buffer: await readFile(filePath),
|
|
928
|
-
mimeType
|
|
929
|
-
};
|
|
930
|
-
} catch {
|
|
931
|
-
return {
|
|
932
|
-
success: false,
|
|
933
|
-
error: "Asset not found"
|
|
934
|
-
};
|
|
935
|
-
}
|
|
936
|
-
}
|
|
937
|
-
/**
|
|
938
|
-
* Helper to find which field contains an asset reference
|
|
939
|
-
*/
|
|
940
|
-
findFieldWithAsset(obj, patterns, path = "") {
|
|
941
|
-
if (typeof obj === "string") {
|
|
942
|
-
if (patterns.some((p) => obj.includes(p))) return path || "root";
|
|
943
|
-
return null;
|
|
944
|
-
}
|
|
945
|
-
if (Array.isArray(obj)) {
|
|
946
|
-
for (let i = 0; i < obj.length; i++) {
|
|
947
|
-
const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);
|
|
948
|
-
if (result) return result;
|
|
949
|
-
}
|
|
950
|
-
return null;
|
|
951
|
-
}
|
|
952
|
-
if (obj && typeof obj === "object") for (const [key, value] of Object.entries(obj)) {
|
|
953
|
-
const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);
|
|
954
|
-
if (result) return result;
|
|
955
|
-
}
|
|
956
|
-
return null;
|
|
957
|
-
}
|
|
958
|
-
/**
|
|
959
|
-
* Move assets from one folder to another
|
|
960
|
-
* @param filenames List of filenames to move
|
|
961
|
-
* @param sourceFolder Source folder path (relative to assets root)
|
|
962
|
-
* @param targetFolder Target folder path (relative to assets root)
|
|
963
|
-
*/
|
|
964
|
-
async moveAssets(filenames, sourceFolder, targetFolder) {
|
|
965
|
-
const normalizedSource = sourceFolder === "/" ? "/" : "/" + sourceFolder.replace(/^\/+|\/+$/g, "");
|
|
966
|
-
const normalizedTarget = targetFolder === "/" ? "/" : "/" + targetFolder.replace(/^\/+|\/+$/g, "");
|
|
967
|
-
let sourcePath;
|
|
968
|
-
let targetPath;
|
|
969
|
-
try {
|
|
970
|
-
sourcePath = normalizedSource === "/" ? this.config.assetsPath : this.validateSubpath(normalizedSource);
|
|
971
|
-
targetPath = normalizedTarget === "/" ? this.config.assetsPath : this.validateSubpath(normalizedTarget);
|
|
972
|
-
} catch {
|
|
973
|
-
return {
|
|
974
|
-
success: false,
|
|
975
|
-
error: "Invalid folder path"
|
|
976
|
-
};
|
|
977
|
-
}
|
|
978
|
-
try {
|
|
979
|
-
if (!(await stat(sourcePath)).isDirectory()) return {
|
|
980
|
-
success: false,
|
|
981
|
-
error: "Source folder does not exist"
|
|
982
|
-
};
|
|
983
|
-
} catch {
|
|
984
|
-
return {
|
|
985
|
-
success: false,
|
|
986
|
-
error: "Source folder does not exist"
|
|
987
|
-
};
|
|
988
|
-
}
|
|
989
|
-
try {
|
|
990
|
-
if (!(await stat(targetPath)).isDirectory()) return {
|
|
991
|
-
success: false,
|
|
992
|
-
error: "Target folder does not exist"
|
|
993
|
-
};
|
|
994
|
-
} catch {
|
|
995
|
-
return {
|
|
996
|
-
success: false,
|
|
997
|
-
error: "Target folder does not exist"
|
|
998
|
-
};
|
|
999
|
-
}
|
|
1000
|
-
const moves = [];
|
|
1001
|
-
for (const filename of filenames) {
|
|
1002
|
-
const sourceFile = join(sourcePath, filename);
|
|
1003
|
-
const targetFile = join(targetPath, filename);
|
|
1004
|
-
const oldRelativePath = normalizedSource === "/" ? filename : `${normalizedSource.slice(1)}/${filename}`;
|
|
1005
|
-
const newRelativePath = normalizedTarget === "/" ? filename : `${normalizedTarget.slice(1)}/${filename}`;
|
|
1006
|
-
try {
|
|
1007
|
-
await rename(sourceFile, targetFile);
|
|
1008
|
-
moves.push({
|
|
1009
|
-
oldPath: oldRelativePath,
|
|
1010
|
-
newPath: newRelativePath
|
|
1011
|
-
});
|
|
1012
|
-
} catch (err) {
|
|
1013
|
-
console.error(`[AssetOperations] Failed to move ${filename}:`, err);
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
if (moves.length > 0) await this.manifest.withManifest((data) => {
|
|
1017
|
-
for (const { oldPath, newPath } of moves) {
|
|
1018
|
-
const entry = data[oldPath];
|
|
1019
|
-
if (entry) {
|
|
1020
|
-
delete data[oldPath];
|
|
1021
|
-
data[newPath] = entry;
|
|
1022
|
-
}
|
|
1023
|
-
}
|
|
1024
|
-
return data;
|
|
1025
|
-
});
|
|
1026
|
-
return {
|
|
1027
|
-
success: true,
|
|
1028
|
-
moved: moves.length
|
|
1029
|
-
};
|
|
1030
|
-
}
|
|
1031
|
-
/**
|
|
1032
|
-
* Get the complete folder tree with asset counts
|
|
1033
|
-
* @returns Array of folder tree nodes representing the folder hierarchy
|
|
1034
|
-
*/
|
|
1035
|
-
async getFolderTree() {
|
|
1036
|
-
const buildTree = async (folderPath, folder) => {
|
|
1037
|
-
let entries;
|
|
1038
|
-
try {
|
|
1039
|
-
entries = await readdir(folderPath, { withFileTypes: true });
|
|
1040
|
-
} catch {
|
|
1041
|
-
return [];
|
|
1042
|
-
}
|
|
1043
|
-
const result = [];
|
|
1044
|
-
for (const entry of entries) {
|
|
1045
|
-
if (isSystemFile(entry.name) || entry.isSymbolicLink()) continue;
|
|
1046
|
-
if (entry.isDirectory()) {
|
|
1047
|
-
const entryPath = join(folderPath, entry.name);
|
|
1048
|
-
const subFolder = folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`;
|
|
1049
|
-
let assetCount = 0;
|
|
1050
|
-
try {
|
|
1051
|
-
assetCount = (await readdir(entryPath, { withFileTypes: true })).filter((e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name)).length;
|
|
1052
|
-
} catch {}
|
|
1053
|
-
const children = await buildTree(entryPath, subFolder);
|
|
1054
|
-
result.push({
|
|
1055
|
-
name: entry.name,
|
|
1056
|
-
path: subFolder,
|
|
1057
|
-
assetCount,
|
|
1058
|
-
children
|
|
1059
|
-
});
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
return result;
|
|
1063
|
-
};
|
|
1064
|
-
let rootAssetCount = 0;
|
|
1065
|
-
try {
|
|
1066
|
-
rootAssetCount = (await readdir(this.config.assetsPath, { withFileTypes: true })).filter((e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name)).length;
|
|
1067
|
-
} catch {}
|
|
1068
|
-
const children = await buildTree(this.config.assetsPath, "/");
|
|
1069
|
-
return [{
|
|
1070
|
-
name: "Root",
|
|
1071
|
-
path: "/",
|
|
1072
|
-
assetCount: rootAssetCount,
|
|
1073
|
-
children
|
|
1074
|
-
}];
|
|
1075
|
-
}
|
|
1076
|
-
};
|
|
1077
|
-
//#endregion
|
|
1078
|
-
//#region src/cf-access.ts
|
|
1079
|
-
/**
|
|
1080
|
-
* Cloudflare Access JWT validation utility
|
|
1081
|
-
*
|
|
1082
|
-
* Validates JWT tokens from CF Access for API authorization and git commit attribution.
|
|
1083
|
-
* When CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD env vars are set, requests must have valid tokens.
|
|
1084
|
-
* When env vars are not set (local dev), validation is skipped.
|
|
1085
|
-
*/
|
|
1086
|
-
const CF_ACCESS_TEAM_NAME = process.env.CF_ACCESS_TEAM_NAME;
|
|
1087
|
-
const CF_ACCESS_AUD = process.env.CF_ACCESS_AUD;
|
|
1088
|
-
const JWKS = CF_ACCESS_TEAM_NAME ? createRemoteJWKSet(new URL(`https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs`)) : null;
|
|
1089
|
-
/**
|
|
1090
|
-
* Extract CF Access JWT token from request.
|
|
1091
|
-
* Checks Cf-Access-Jwt-Assertion header first, falls back to CF_Authorization cookie.
|
|
1092
|
-
*/
|
|
1093
|
-
function extractCFAccessToken(request) {
|
|
1094
|
-
const headerToken = request.headers.get("Cf-Access-Jwt-Assertion");
|
|
1095
|
-
if (headerToken) return headerToken;
|
|
1096
|
-
const match = (request.headers.get("Cookie") || "").match(/CF_Authorization=([^;]+)/);
|
|
1097
|
-
return match ? match[1] : null;
|
|
1098
|
-
}
|
|
1099
|
-
/**
|
|
1100
|
-
* Validate CF Access JWT from request.
|
|
1101
|
-
*
|
|
1102
|
-
* Returns { valid: true, required: false } when env vars not set (local dev mode).
|
|
1103
|
-
* Returns { valid: true, required: true, user } when token is valid.
|
|
1104
|
-
* Returns { valid: false, required: true, error } when token is invalid or missing.
|
|
1105
|
-
*/
|
|
1106
|
-
async function validateCFAccessRequest(request) {
|
|
1107
|
-
if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) return {
|
|
1108
|
-
valid: true,
|
|
1109
|
-
required: false
|
|
1110
|
-
};
|
|
1111
|
-
const token = extractCFAccessToken(request);
|
|
1112
|
-
if (!token) return {
|
|
1113
|
-
valid: false,
|
|
1114
|
-
required: true,
|
|
1115
|
-
error: "No token provided"
|
|
1116
|
-
};
|
|
1117
|
-
try {
|
|
1118
|
-
const { payload } = await jwtVerify(token, JWKS, {
|
|
1119
|
-
issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,
|
|
1120
|
-
audience: CF_ACCESS_AUD
|
|
1121
|
-
});
|
|
1122
|
-
return {
|
|
1123
|
-
valid: true,
|
|
1124
|
-
required: true,
|
|
1125
|
-
user: {
|
|
1126
|
-
email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
|
|
1127
|
-
sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
|
|
1128
|
-
}
|
|
1129
|
-
};
|
|
1130
|
-
} catch (error) {
|
|
1131
|
-
return {
|
|
1132
|
-
valid: false,
|
|
1133
|
-
required: true,
|
|
1134
|
-
error: error instanceof Error ? error.message : "Validation failed"
|
|
1135
|
-
};
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
//#endregion
|
|
1139
|
-
//#region src/component-registry.ts
|
|
1140
|
-
/**
|
|
1141
|
-
* Component Registry for managing linked and unlinked components
|
|
1142
|
-
*
|
|
1143
|
-
* Registry is stored at {canvasDir}/components/registry.json
|
|
1144
|
-
* Component IDs must follow the format: vx-{uuid}
|
|
1145
|
-
*/
|
|
1146
|
-
var ComponentRegistry = class {
|
|
1147
|
-
registryPath;
|
|
1148
|
-
registry = {};
|
|
1149
|
-
initialized = false;
|
|
1150
|
-
constructor(canvasDir) {
|
|
1151
|
-
this.registryPath = join(canvasDir, "components", "registry.json");
|
|
1152
|
-
}
|
|
1153
|
-
/**
|
|
1154
|
-
* Initialize the registry by loading from disk or creating new
|
|
1155
|
-
*/
|
|
1156
|
-
async initialize() {
|
|
1157
|
-
if (this.initialized) return;
|
|
1158
|
-
try {
|
|
1159
|
-
const content = await readFile(this.registryPath, "utf-8");
|
|
1160
|
-
this.registry = JSON.parse(content);
|
|
1161
|
-
} catch (error) {
|
|
1162
|
-
if (error.code === "ENOENT") await this.save();
|
|
1163
|
-
else throw error;
|
|
1164
|
-
}
|
|
1165
|
-
this.initialized = true;
|
|
1166
|
-
}
|
|
1167
|
-
/**
|
|
1168
|
-
* Validate component ID format (vx-{uuid})
|
|
1169
|
-
*/
|
|
1170
|
-
validateComponentId(id) {
|
|
1171
|
-
if (!/^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid component ID format. Expected: vx-{uuid}");
|
|
1172
|
-
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Save registry to disk atomically
|
|
1175
|
-
*/
|
|
1176
|
-
async save() {
|
|
1177
|
-
await mkdir(dirname(this.registryPath), { recursive: true });
|
|
1178
|
-
const sorted = sortKeys(this.registry, { deep: true });
|
|
1179
|
-
const content = JSON.stringify(sorted, null, 2);
|
|
1180
|
-
await atomicWriteFile(this.registryPath, content);
|
|
1181
|
-
}
|
|
1182
|
-
/**
|
|
1183
|
-
* Register a new component or update existing
|
|
1184
|
-
*/
|
|
1185
|
-
async register(id, entry) {
|
|
1186
|
-
await this.initialize();
|
|
1187
|
-
this.validateComponentId(id);
|
|
1188
|
-
this.registry[id] = {
|
|
1189
|
-
displayName: entry.displayName,
|
|
1190
|
-
path: entry.path
|
|
1191
|
-
};
|
|
1192
|
-
await this.save();
|
|
1193
|
-
}
|
|
1194
|
-
/**
|
|
1195
|
-
* Get a component entry by ID
|
|
1196
|
-
*/
|
|
1197
|
-
async get(id) {
|
|
1198
|
-
await this.initialize();
|
|
1199
|
-
return this.registry[id] || null;
|
|
1200
|
-
}
|
|
1201
|
-
/**
|
|
1202
|
-
* Link a component to a path
|
|
1203
|
-
*/
|
|
1204
|
-
async link(id, path) {
|
|
1205
|
-
await this.initialize();
|
|
1206
|
-
const entry = this.registry[id];
|
|
1207
|
-
if (!entry) throw new Error(`Component ${id} not found in registry`);
|
|
1208
|
-
entry.path = path;
|
|
1209
|
-
await this.save();
|
|
1210
|
-
}
|
|
1211
|
-
/**
|
|
1212
|
-
* Unlink a component (set path to null)
|
|
1213
|
-
*/
|
|
1214
|
-
async unlink(id) {
|
|
1215
|
-
await this.initialize();
|
|
1216
|
-
const entry = this.registry[id];
|
|
1217
|
-
if (!entry) throw new Error(`Component ${id} not found in registry`);
|
|
1218
|
-
entry.path = null;
|
|
1219
|
-
await this.save();
|
|
1220
|
-
}
|
|
1221
|
-
/**
|
|
1222
|
-
* List all components
|
|
1223
|
-
*/
|
|
1224
|
-
async list() {
|
|
1225
|
-
await this.initialize();
|
|
1226
|
-
return Object.entries(this.registry).map(([id, entry]) => ({
|
|
1227
|
-
id,
|
|
1228
|
-
...entry
|
|
1229
|
-
}));
|
|
1230
|
-
}
|
|
1231
|
-
/**
|
|
1232
|
-
* Delete a component from registry
|
|
1233
|
-
*/
|
|
1234
|
-
async delete(id) {
|
|
1235
|
-
await this.initialize();
|
|
1236
|
-
delete this.registry[id];
|
|
1237
|
-
await this.save();
|
|
1238
|
-
}
|
|
1239
|
-
};
|
|
1240
|
-
//#endregion
|
|
1241
|
-
//#region src/content-watcher.ts
|
|
1242
|
-
/**
|
|
1243
|
-
* Creates a content API instance for the given options
|
|
1244
|
-
*/
|
|
1245
|
-
async function createContentAPI(options) {
|
|
1246
|
-
return await FileSystemContentAPI.create({
|
|
1247
|
-
...options,
|
|
1248
|
-
canvasDir: options.canvasDir || "./canvas"
|
|
1249
|
-
});
|
|
1250
|
-
}
|
|
1251
|
-
/**
|
|
1252
|
-
* Creates file change handlers for content watching
|
|
1253
|
-
*/
|
|
1254
|
-
function createContentWatchHandlers(contentApi, options, ws, onReindexed) {
|
|
1255
|
-
const handleFileChange = async (file, action) => {
|
|
1256
|
-
const isContentFile = file.endsWith(".mdx") || file.endsWith(".vxjson");
|
|
1257
|
-
const isDataFile = file.endsWith(".json") && file.includes("/data/");
|
|
1258
|
-
if (!isContentFile && !isDataFile) return;
|
|
1259
|
-
const normalizedFile = normalize(resolve(file));
|
|
1260
|
-
const normalizedRoot = normalize(resolve(options.contentRoot));
|
|
1261
|
-
const normalizedMdxRoot = options.mdxPagesRoot ? normalize(resolve(options.mdxPagesRoot)) : null;
|
|
1262
|
-
const inContentRoot = normalizedFile === normalizedRoot || normalizedFile.startsWith(normalizedRoot + "/");
|
|
1263
|
-
const inMdxRoot = !!normalizedMdxRoot && (normalizedFile === normalizedMdxRoot || normalizedFile.startsWith(normalizedMdxRoot + "/"));
|
|
1264
|
-
if (inContentRoot || inMdxRoot) {
|
|
1265
|
-
const matchedRoot = inContentRoot ? normalizedRoot : normalizedMdxRoot;
|
|
1266
|
-
const relativePath = normalizedFile.replace(matchedRoot + "/", "");
|
|
1267
|
-
console.log(`[Content] ${action}: ${relativePath}`);
|
|
1268
|
-
try {
|
|
1269
|
-
const reindexOptions = action === "delete" ? { handleDeletions: true } : void 0;
|
|
1270
|
-
const result = await contentApi.reindex([normalizedFile], reindexOptions);
|
|
1271
|
-
for (const manifest of result.updated) {
|
|
1272
|
-
const message = {
|
|
1273
|
-
type: "custom",
|
|
1274
|
-
event: "conloca:content-update",
|
|
1275
|
-
data: {
|
|
1276
|
-
action,
|
|
1277
|
-
manifest
|
|
1278
|
-
}
|
|
1279
|
-
};
|
|
1280
|
-
ws.send(message);
|
|
1281
|
-
}
|
|
1282
|
-
if (action === "delete" && result.deleted) for (const deletion of result.deleted) ws.send({
|
|
1283
|
-
type: "custom",
|
|
1284
|
-
event: "conloca:content-update",
|
|
1285
|
-
data: {
|
|
1286
|
-
action: "delete",
|
|
1287
|
-
...deletion
|
|
1288
|
-
}
|
|
1289
|
-
});
|
|
1290
|
-
} catch (error) {
|
|
1291
|
-
console.error("[Content Watcher] Reindex failed:", error);
|
|
1292
|
-
return;
|
|
1293
|
-
}
|
|
1294
|
-
try {
|
|
1295
|
-
await onReindexed?.({
|
|
1296
|
-
file: normalizedFile,
|
|
1297
|
-
action,
|
|
1298
|
-
inMdxRoot,
|
|
1299
|
-
inContentRoot
|
|
1300
|
-
});
|
|
1301
|
-
} catch (error) {
|
|
1302
|
-
console.error("[Content Watcher] onReindexed callback failed:", error);
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
};
|
|
1306
|
-
return {
|
|
1307
|
-
onChange: (file) => handleFileChange(file, "update"),
|
|
1308
|
-
onAdd: (file) => handleFileChange(file, "create"),
|
|
1309
|
-
onUnlink: (file) => handleFileChange(file, "delete")
|
|
1310
|
-
};
|
|
1311
|
-
}
|
|
1312
|
-
//#endregion
|
|
1313
|
-
//#region src/in-memory-content-api.ts
|
|
1314
|
-
/**
|
|
1315
|
-
* In-memory implementation of ContentAPI for testing
|
|
1316
|
-
* Provides a clean, mock-free way to test the API without filesystem dependencies
|
|
1317
|
-
*/
|
|
1318
|
-
var InMemoryContentAPI = class {
|
|
1319
|
-
contentIndex;
|
|
1320
|
-
sitesConfig;
|
|
1321
|
-
blocks;
|
|
1322
|
-
data;
|
|
1323
|
-
sites;
|
|
1324
|
-
constructor(sitesConfig) {
|
|
1325
|
-
this.sitesConfig = sitesConfig || {
|
|
1326
|
-
sites: {},
|
|
1327
|
-
globalLocales: ["en"]
|
|
1328
|
-
};
|
|
1329
|
-
this.contentIndex = ContentIndex.createUncached(this.sitesConfig);
|
|
1330
|
-
this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
|
|
1331
|
-
this.data = new Data(this, this.contentIndex.getDataIndex());
|
|
1332
|
-
this.sites = mapSiteNames(this.sitesConfig, (siteName) => {
|
|
1333
|
-
const siteIndex = this.contentIndex.getSiteIndex(siteName);
|
|
1334
|
-
if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
|
|
1335
|
-
return new Site(siteName, this, siteIndex);
|
|
1336
|
-
});
|
|
1337
|
-
}
|
|
1338
|
-
async getContent(id) {
|
|
1339
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1340
|
-
if (!manifest) return null;
|
|
1341
|
-
const contentEntry = {
|
|
1342
|
-
id: manifest.id,
|
|
1343
|
-
kind: manifest.kind,
|
|
1344
|
-
site: manifest.site,
|
|
1345
|
-
collection: manifest.collection,
|
|
1346
|
-
type: manifest.type,
|
|
1347
|
-
locales: {}
|
|
1348
|
-
};
|
|
1349
|
-
for (const localeVersion of localesOf(manifest)) {
|
|
1350
|
-
const { locale } = localeVersion;
|
|
1351
|
-
const cachedContent = this.contentIndex.getCachedContent(id, locale);
|
|
1352
|
-
if (cachedContent) contentEntry.locales[locale] = {
|
|
1353
|
-
...localeVersion,
|
|
1354
|
-
content: cachedContent
|
|
1355
|
-
};
|
|
1356
|
-
}
|
|
1357
|
-
return contentEntry;
|
|
1358
|
-
}
|
|
1359
|
-
async getLocalized(id, locale) {
|
|
1360
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1361
|
-
if (!manifest || !manifest.locales[locale]) return null;
|
|
1362
|
-
const localeVersion = manifest.locales[locale];
|
|
1363
|
-
const cachedContent = this.contentIndex.getCachedContent(id, locale);
|
|
1364
|
-
if (!cachedContent) return null;
|
|
1365
|
-
const contentToReturn = { ...cachedContent };
|
|
1366
|
-
return {
|
|
1367
|
-
id,
|
|
1368
|
-
site: manifest.site,
|
|
1369
|
-
collection: manifest.collection,
|
|
1370
|
-
type: manifest.type,
|
|
1371
|
-
kind: manifest.kind,
|
|
1372
|
-
localized: {
|
|
1373
|
-
...localeVersion,
|
|
1374
|
-
meta: { ...localeVersion.meta },
|
|
1375
|
-
content: contentToReturn,
|
|
1376
|
-
previousPathnames: localeVersion.previousPathnames ? { ...localeVersion.previousPathnames } : void 0
|
|
1377
|
-
}
|
|
1378
|
-
};
|
|
1379
|
-
}
|
|
1380
|
-
async createContent(data) {
|
|
1381
|
-
const validation = validateCreateContent(data, this.sites, this.blocks);
|
|
1382
|
-
if (!validation.valid) return {
|
|
1383
|
-
success: false,
|
|
1384
|
-
reason: validation.reason,
|
|
1385
|
-
error: validation.error ? new Error(validation.error) : void 0,
|
|
1386
|
-
existingId: validation.existingId
|
|
1387
|
-
};
|
|
1388
|
-
const id = generateContentId();
|
|
1389
|
-
const now = getCurrentISODate();
|
|
1390
|
-
const contentCache = {};
|
|
1391
|
-
const locales = mapLocales(data.site ? this.sitesConfig.sites[data.site].locales : this.sitesConfig.globalLocales, (locale) => {
|
|
1392
|
-
const localeData = data.locales[locale];
|
|
1393
|
-
if (!localeData) return void 0;
|
|
1394
|
-
const meta = {
|
|
1395
|
-
...data.meta,
|
|
1396
|
-
...localeData.meta
|
|
1397
|
-
};
|
|
1398
|
-
const fileData = {
|
|
1399
|
-
id,
|
|
1400
|
-
type: data.type,
|
|
1401
|
-
created: now,
|
|
1402
|
-
modified: now,
|
|
1403
|
-
publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
|
|
1404
|
-
unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
|
|
1405
|
-
meta,
|
|
1406
|
-
content: localeData.content
|
|
1407
|
-
};
|
|
1408
|
-
let buffer;
|
|
1409
|
-
let etag;
|
|
1410
|
-
if (data.type === "mdx") {
|
|
1411
|
-
const mdxContent = serializeMdxWithFrontmatter({
|
|
1412
|
-
id,
|
|
1413
|
-
created: now,
|
|
1414
|
-
modified: now,
|
|
1415
|
-
...localeData.publishAt && { publishAt: localeData.publishAt },
|
|
1416
|
-
...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
|
|
1417
|
-
...meta
|
|
1418
|
-
}, localeData.content.mdx || "");
|
|
1419
|
-
buffer = new TextEncoder().encode(mdxContent);
|
|
1420
|
-
const contentPos = findMdxContentStartPosition(buffer);
|
|
1421
|
-
const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
|
|
1422
|
-
etag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
|
|
1423
|
-
} else {
|
|
1424
|
-
const jsonStr = VXJSON.serialize(fileData);
|
|
1425
|
-
buffer = Buffer.from(jsonStr, "utf-8");
|
|
1426
|
-
const etagResult = VXJSON.calculateETags(buffer);
|
|
1427
|
-
if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
|
|
1428
|
-
etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
1429
|
-
}
|
|
1430
|
-
const localeVersion = buildLocaleVersion({
|
|
1431
|
-
locale,
|
|
1432
|
-
etag,
|
|
1433
|
-
created: now,
|
|
1434
|
-
modified: now,
|
|
1435
|
-
meta,
|
|
1436
|
-
kind: data.kind,
|
|
1437
|
-
pathname: data.kind === "page" ? localeData.pathname : void 0,
|
|
1438
|
-
name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
|
|
1439
|
-
publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
|
|
1440
|
-
unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
|
|
1441
|
-
});
|
|
1442
|
-
contentCache[locale] = localeData.content;
|
|
1443
|
-
return localeVersion;
|
|
1444
|
-
});
|
|
1445
|
-
const manifest = {
|
|
1446
|
-
id,
|
|
1447
|
-
type: data.type,
|
|
1448
|
-
kind: data.kind,
|
|
1449
|
-
site: data.site,
|
|
1450
|
-
collection: data.collection,
|
|
1451
|
-
locales
|
|
1452
|
-
};
|
|
1453
|
-
for (const localeVersion of localesOf(manifest)) this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);
|
|
1454
|
-
return {
|
|
1455
|
-
success: true,
|
|
1456
|
-
id,
|
|
1457
|
-
etag: Object.values(manifest.locales)[0]?.etag || "",
|
|
1458
|
-
created: new Date(now)
|
|
1459
|
-
};
|
|
1460
|
-
}
|
|
1461
|
-
async updateLocalized(input) {
|
|
1462
|
-
const { id, locale, data, etag } = input;
|
|
1463
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1464
|
-
if (!manifest) return {
|
|
1465
|
-
success: false,
|
|
1466
|
-
reason: "not_found"
|
|
1467
|
-
};
|
|
1468
|
-
const localeVersion = manifest.locales[locale];
|
|
1469
|
-
if (!localeVersion) return {
|
|
1470
|
-
success: false,
|
|
1471
|
-
reason: "not_found"
|
|
1472
|
-
};
|
|
1473
|
-
if (localeVersion.etag !== etag) return {
|
|
1474
|
-
success: false,
|
|
1475
|
-
reason: "stale_write",
|
|
1476
|
-
currentEtag: localeVersion.etag
|
|
1477
|
-
};
|
|
1478
|
-
const currentContent = this.contentIndex.getCachedContent(id, locale);
|
|
1479
|
-
if (!currentContent) return {
|
|
1480
|
-
success: false,
|
|
1481
|
-
reason: "not_found"
|
|
1482
|
-
};
|
|
1483
|
-
if (data.meta) {
|
|
1484
|
-
const validation = validateAndPrepareMetadata({
|
|
1485
|
-
...localeVersion.meta,
|
|
1486
|
-
...data.meta
|
|
1487
|
-
});
|
|
1488
|
-
if (!validation.valid) return {
|
|
1489
|
-
success: false,
|
|
1490
|
-
reason: "write_error",
|
|
1491
|
-
error: new Error(validation.error)
|
|
1492
|
-
};
|
|
1493
|
-
}
|
|
1494
|
-
if (data.pathname && manifest.kind === "page" && manifest.site) {
|
|
1495
|
-
const site = this.sites[manifest.site];
|
|
1496
|
-
if (site) {
|
|
1497
|
-
const existingId = site.getPathnameConflict(data.pathname, locale, id);
|
|
1498
|
-
if (existingId) return {
|
|
1499
|
-
success: false,
|
|
1500
|
-
reason: "write_error",
|
|
1501
|
-
error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
|
|
1502
|
-
};
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
const now = /* @__PURE__ */ new Date();
|
|
1506
|
-
const nowStr = now.toISOString();
|
|
1507
|
-
const oldPathname = localeVersion.pathname;
|
|
1508
|
-
const updatedLocaleVersion = { ...localeVersion };
|
|
1509
|
-
if (shouldUpdateModifiedTimestamp(data)) updatedLocaleVersion.modified = data.modified || nowStr;
|
|
1510
|
-
else if (data.modified) updatedLocaleVersion.modified = data.modified;
|
|
1511
|
-
if (data.meta) updatedLocaleVersion.meta = {
|
|
1512
|
-
...localeVersion.meta,
|
|
1513
|
-
...data.meta
|
|
1514
|
-
};
|
|
1515
|
-
if (data.pathname !== void 0 && manifest.kind === "page") {
|
|
1516
|
-
const pathnameHistory = buildPathnameHistory(oldPathname, data.pathname, isContentPublished(localeVersion), nowStr);
|
|
1517
|
-
if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
|
|
1518
|
-
...localeVersion.previousPathnames,
|
|
1519
|
-
...pathnameHistory
|
|
1520
|
-
};
|
|
1521
|
-
updatedLocaleVersion.pathname = data.pathname;
|
|
1522
|
-
}
|
|
1523
|
-
updatePublishDates(updatedLocaleVersion, data);
|
|
1524
|
-
const updatedContent = data.content ? {
|
|
1525
|
-
...currentContent,
|
|
1526
|
-
...data.content
|
|
1527
|
-
} : currentContent;
|
|
1528
|
-
const fileData = {
|
|
1529
|
-
id: manifest.id,
|
|
1530
|
-
type: manifest.type,
|
|
1531
|
-
created: updatedLocaleVersion.created,
|
|
1532
|
-
modified: updatedLocaleVersion.modified,
|
|
1533
|
-
publishAt: updatedLocaleVersion.publishAt,
|
|
1534
|
-
unpublishAt: updatedLocaleVersion.unpublishAt,
|
|
1535
|
-
meta: updatedLocaleVersion.meta,
|
|
1536
|
-
previousPathnames: updatedLocaleVersion.previousPathnames,
|
|
1537
|
-
content: updatedContent
|
|
1538
|
-
};
|
|
1539
|
-
let buffer;
|
|
1540
|
-
let newEtag;
|
|
1541
|
-
if (manifest.type === "mdx") {
|
|
1542
|
-
const mdxContent = serializeMdxWithFrontmatter({
|
|
1543
|
-
id: manifest.id,
|
|
1544
|
-
created: updatedLocaleVersion.created,
|
|
1545
|
-
modified: updatedLocaleVersion.modified,
|
|
1546
|
-
...updatedLocaleVersion.publishAt && { publishAt: updatedLocaleVersion.publishAt },
|
|
1547
|
-
...updatedLocaleVersion.unpublishAt && { unpublishAt: updatedLocaleVersion.unpublishAt },
|
|
1548
|
-
...updatedLocaleVersion.meta
|
|
1549
|
-
}, updatedContent.mdx || "");
|
|
1550
|
-
buffer = new TextEncoder().encode(mdxContent);
|
|
1551
|
-
const contentPos = findMdxContentStartPosition(buffer);
|
|
1552
|
-
const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
|
|
1553
|
-
newEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
|
|
1554
|
-
} else {
|
|
1555
|
-
const jsonStr = VXJSON.serialize(fileData);
|
|
1556
|
-
buffer = Buffer.from(jsonStr, "utf-8");
|
|
1557
|
-
const etagResult = VXJSON.calculateETags(buffer);
|
|
1558
|
-
if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
|
|
1559
|
-
newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
1560
|
-
}
|
|
1561
|
-
updatedLocaleVersion.etag = newEtag;
|
|
1562
|
-
const updatedManifest = {
|
|
1563
|
-
...manifest,
|
|
1564
|
-
locales: {
|
|
1565
|
-
...manifest.locales,
|
|
1566
|
-
[locale]: updatedLocaleVersion
|
|
1567
|
-
}
|
|
1568
|
-
};
|
|
1569
|
-
this.contentIndex.addContent(updatedManifest, updatedLocaleVersion, updatedContent);
|
|
1570
|
-
return {
|
|
1571
|
-
success: true,
|
|
1572
|
-
etag: updatedLocaleVersion.etag,
|
|
1573
|
-
modified: now
|
|
1574
|
-
};
|
|
1575
|
-
}
|
|
1576
|
-
async deleteContent(id, etag) {
|
|
1577
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1578
|
-
if (!manifest) return {
|
|
1579
|
-
success: false,
|
|
1580
|
-
reason: "not_found",
|
|
1581
|
-
error: /* @__PURE__ */ new Error("Content not found")
|
|
1582
|
-
};
|
|
1583
|
-
let hasMatchingEtag = false;
|
|
1584
|
-
for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
|
|
1585
|
-
hasMatchingEtag = true;
|
|
1586
|
-
break;
|
|
1587
|
-
}
|
|
1588
|
-
if (!hasMatchingEtag && etag) return {
|
|
1589
|
-
success: false,
|
|
1590
|
-
reason: "stale_write",
|
|
1591
|
-
currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
|
|
1592
|
-
error: /* @__PURE__ */ new Error("ETag mismatch")
|
|
1593
|
-
};
|
|
1594
|
-
this.contentIndex.removeEntry(id);
|
|
1595
|
-
return { success: true };
|
|
1596
|
-
}
|
|
1597
|
-
getSite(siteName) {
|
|
1598
|
-
if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
|
|
1599
|
-
return this.sites[siteName] || null;
|
|
1600
|
-
}
|
|
1601
|
-
*listAllContent(filters) {
|
|
1602
|
-
yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
|
|
1603
|
-
}
|
|
1604
|
-
*findUntranslatedContent(targetLocale, options) {
|
|
1605
|
-
yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
|
|
1606
|
-
}
|
|
1607
|
-
async deleteLocalized(input) {
|
|
1608
|
-
const { id, locale, etag } = input;
|
|
1609
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1610
|
-
if (!manifest) return {
|
|
1611
|
-
success: false,
|
|
1612
|
-
reason: "not_found",
|
|
1613
|
-
error: /* @__PURE__ */ new Error("Content not found")
|
|
1614
|
-
};
|
|
1615
|
-
const localeVersion = manifest.locales[locale];
|
|
1616
|
-
if (!localeVersion) return {
|
|
1617
|
-
success: false,
|
|
1618
|
-
reason: "not_found",
|
|
1619
|
-
error: /* @__PURE__ */ new Error("Locale not found")
|
|
1620
|
-
};
|
|
1621
|
-
if (localeVersion.etag !== etag) return {
|
|
1622
|
-
success: false,
|
|
1623
|
-
reason: "stale_write",
|
|
1624
|
-
currentEtag: localeVersion.etag,
|
|
1625
|
-
error: /* @__PURE__ */ new Error("Stale write - etag mismatch")
|
|
1626
|
-
};
|
|
1627
|
-
if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(id);
|
|
1628
|
-
else {
|
|
1629
|
-
const updatedManifest = {
|
|
1630
|
-
...manifest,
|
|
1631
|
-
locales: { ...manifest.locales }
|
|
1632
|
-
};
|
|
1633
|
-
updatedManifest.locales[locale] = void 0;
|
|
1634
|
-
this.contentIndex.removeLocale(manifest.id, locale);
|
|
1635
|
-
}
|
|
1636
|
-
return { success: true };
|
|
1637
|
-
}
|
|
1638
|
-
async batchUpdate(operations) {
|
|
1639
|
-
const results = {
|
|
1640
|
-
operations: [],
|
|
1641
|
-
success: true,
|
|
1642
|
-
failed: 0,
|
|
1643
|
-
updated: 0
|
|
1644
|
-
};
|
|
1645
|
-
for (const op of operations) {
|
|
1646
|
-
const result = await this.updateLocalized(op);
|
|
1647
|
-
if (result.success) {
|
|
1648
|
-
results.updated++;
|
|
1649
|
-
results.operations.push({
|
|
1650
|
-
id: op.id,
|
|
1651
|
-
locale: op.locale,
|
|
1652
|
-
updated: true,
|
|
1653
|
-
etag: result.etag
|
|
1654
|
-
});
|
|
1655
|
-
} else {
|
|
1656
|
-
results.failed++;
|
|
1657
|
-
results.success = false;
|
|
1658
|
-
results.operations.push({
|
|
1659
|
-
id: op.id,
|
|
1660
|
-
locale: op.locale,
|
|
1661
|
-
updated: false,
|
|
1662
|
-
error: result.error || new Error(result.reason || "Update failed")
|
|
1663
|
-
});
|
|
1664
|
-
}
|
|
1665
|
-
}
|
|
1666
|
-
return results;
|
|
1667
|
-
}
|
|
1668
|
-
setContent(id, content) {
|
|
1669
|
-
const manifest = {
|
|
1670
|
-
id: content.id,
|
|
1671
|
-
type: content.type,
|
|
1672
|
-
kind: content.kind,
|
|
1673
|
-
site: content.site,
|
|
1674
|
-
collection: content.collection,
|
|
1675
|
-
locales: {}
|
|
1676
|
-
};
|
|
1677
|
-
const contentCache = {};
|
|
1678
|
-
for (const [locale, localeData] of Object.entries(content.locales)) {
|
|
1679
|
-
const manifestLocale = {
|
|
1680
|
-
locale,
|
|
1681
|
-
etag: localeData.etag,
|
|
1682
|
-
created: localeData.created,
|
|
1683
|
-
modified: localeData.modified,
|
|
1684
|
-
meta: localeData.meta
|
|
1685
|
-
};
|
|
1686
|
-
if (localeData.publishAt !== void 0) manifestLocale.publishAt = localeData.publishAt;
|
|
1687
|
-
if (localeData.unpublishAt !== void 0) manifestLocale.unpublishAt = localeData.unpublishAt;
|
|
1688
|
-
if (localeData.name) manifestLocale.name = localeData.name;
|
|
1689
|
-
if (localeData.pathname) manifestLocale.pathname = localeData.pathname;
|
|
1690
|
-
if (localeData.previousPathnames) manifestLocale.previousPathnames = localeData.previousPathnames;
|
|
1691
|
-
manifest.locales[locale] = manifestLocale;
|
|
1692
|
-
contentCache[locale] = localeData.content;
|
|
1693
|
-
}
|
|
1694
|
-
for (const localeVersion of localesOf(manifest)) this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);
|
|
1695
|
-
}
|
|
1696
|
-
clear() {
|
|
1697
|
-
this.contentIndex.clear();
|
|
1698
|
-
}
|
|
1699
|
-
async getContentAsBuffer(id, locale) {
|
|
1700
|
-
const manifest = this.contentIndex.getManifest(id);
|
|
1701
|
-
if (!manifest || !manifest.locales[locale]) return null;
|
|
1702
|
-
const localeVersion = manifest.locales[locale];
|
|
1703
|
-
const cachedContent = this.contentIndex.getCachedContent(id, locale);
|
|
1704
|
-
if (!cachedContent) return null;
|
|
1705
|
-
let buffer;
|
|
1706
|
-
let calculatedEtag;
|
|
1707
|
-
let contentType;
|
|
1708
|
-
if (manifest.type === "mdx") {
|
|
1709
|
-
const mdxContent = serializeMdxWithFrontmatter({
|
|
1710
|
-
id: manifest.id,
|
|
1711
|
-
created: localeVersion.created,
|
|
1712
|
-
modified: localeVersion.modified,
|
|
1713
|
-
...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
|
|
1714
|
-
...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
|
|
1715
|
-
...localeVersion.meta
|
|
1716
|
-
}, cachedContent.mdx || "");
|
|
1717
|
-
buffer = new TextEncoder().encode(mdxContent);
|
|
1718
|
-
const contentPos = findMdxContentStartPosition(buffer);
|
|
1719
|
-
const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
|
|
1720
|
-
calculatedEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
|
|
1721
|
-
contentType = "text/mdx";
|
|
1722
|
-
} else {
|
|
1723
|
-
const fileData = {
|
|
1724
|
-
id: manifest.id,
|
|
1725
|
-
type: manifest.type,
|
|
1726
|
-
created: localeVersion.created,
|
|
1727
|
-
modified: localeVersion.modified,
|
|
1728
|
-
publishAt: localeVersion.publishAt,
|
|
1729
|
-
unpublishAt: localeVersion.unpublishAt,
|
|
1730
|
-
meta: localeVersion.meta,
|
|
1731
|
-
previousPathnames: localeVersion.previousPathnames,
|
|
1732
|
-
content: cachedContent
|
|
1733
|
-
};
|
|
1734
|
-
const jsonStr = VXJSON.serialize(fileData);
|
|
1735
|
-
buffer = Buffer.from(jsonStr, "utf-8");
|
|
1736
|
-
const etagResult = VXJSON.calculateETags(buffer);
|
|
1737
|
-
if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
|
|
1738
|
-
calculatedEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
|
|
1739
|
-
contentType = "application/json";
|
|
1740
|
-
}
|
|
1741
|
-
return {
|
|
1742
|
-
buffer,
|
|
1743
|
-
etag: calculatedEtag,
|
|
1744
|
-
contentType
|
|
1745
|
-
};
|
|
1746
|
-
}
|
|
1747
|
-
};
|
|
1748
|
-
//#endregion
|
|
1749
|
-
//#region src/middleware.ts
|
|
1750
|
-
/**
|
|
1751
|
-
* Helper to create standardized error responses
|
|
1752
|
-
*/
|
|
1753
|
-
function errorResponse(code, message, details) {
|
|
1754
|
-
return { error: {
|
|
1755
|
-
code,
|
|
1756
|
-
message,
|
|
1757
|
-
...details && { details }
|
|
1758
|
-
} };
|
|
1759
|
-
}
|
|
1760
|
-
/**
|
|
1761
|
-
* Helper to log and create error responses for unexpected errors
|
|
1762
|
-
*/
|
|
1763
|
-
function logAndCreateErrorResponse(error, code, message, details) {
|
|
1764
|
-
console.error(`[Content API] ${message}:`, error);
|
|
1765
|
-
return errorResponse(code, message, details);
|
|
1766
|
-
}
|
|
1767
|
-
function errorMessage(error, fallback) {
|
|
1768
|
-
return error instanceof Error ? error.message : fallback;
|
|
1769
|
-
}
|
|
1770
|
-
function createContentAPIRouter(api, options) {
|
|
1771
|
-
const app = new Hono();
|
|
1772
|
-
app.use("/*", cors());
|
|
1773
|
-
app.get("/auth/user", async (c) => {
|
|
1774
|
-
const email = c.req.header("X-CF-User-Email");
|
|
1775
|
-
const sub = c.req.header("X-CF-User-Sub");
|
|
1776
|
-
if (!email) return c.json({ authenticated: false });
|
|
1777
|
-
return c.json({
|
|
1778
|
-
authenticated: true,
|
|
1779
|
-
user: {
|
|
1780
|
-
email,
|
|
1781
|
-
sub
|
|
1782
|
-
}
|
|
1783
|
-
});
|
|
1784
|
-
});
|
|
1785
|
-
app.get("/content/collections", async (c) => {
|
|
1786
|
-
try {
|
|
1787
|
-
const allCollections = /* @__PURE__ */ new Set();
|
|
1788
|
-
const blockCollections = api.blocks.collections;
|
|
1789
|
-
for (const collection of blockCollections) allCollections.add(collection);
|
|
1790
|
-
for (const siteName of Object.keys(api.sitesConfig.sites)) {
|
|
1791
|
-
const site = api.getSite(siteName);
|
|
1792
|
-
if (site) {
|
|
1793
|
-
const siteCollections = site.collections;
|
|
1794
|
-
for (const collection of siteCollections) allCollections.add(collection);
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
return c.json({ collections: Array.from(allCollections).sort() });
|
|
1798
|
-
} catch (error) {
|
|
1799
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list collections"), 500);
|
|
1800
|
-
}
|
|
1801
|
-
});
|
|
1802
|
-
app.get("/content", async (c) => {
|
|
1803
|
-
const kind = c.req.query("kind");
|
|
1804
|
-
const site = c.req.query("site");
|
|
1805
|
-
const collection = c.req.query("collection");
|
|
1806
|
-
const locales = c.req.query("locales");
|
|
1807
|
-
const type = c.req.query("type");
|
|
1808
|
-
const published = c.req.query("published");
|
|
1809
|
-
const localization = c.req.query("localization");
|
|
1810
|
-
const missingLocales = c.req.query("missingLocales");
|
|
1811
|
-
try {
|
|
1812
|
-
const filters = {};
|
|
1813
|
-
if (kind) filters.kind = kind;
|
|
1814
|
-
if (site) filters.site = site;
|
|
1815
|
-
if (collection) filters.collection = collection;
|
|
1816
|
-
if (locales) filters.locales = locales.split(",").map((l) => l.trim());
|
|
1817
|
-
if (type) filters.type = type;
|
|
1818
|
-
if (published !== void 0) filters.published = published === "true";
|
|
1819
|
-
if (localization) filters.localization = localization;
|
|
1820
|
-
if (missingLocales) filters.missingLocales = missingLocales.split(",").map((l) => l.trim());
|
|
1821
|
-
const items = Array.from(api.listAllContent(filters));
|
|
1822
|
-
return c.json({
|
|
1823
|
-
items,
|
|
1824
|
-
total: items.length
|
|
1825
|
-
});
|
|
1826
|
-
} catch (error) {
|
|
1827
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list content"), 500);
|
|
1828
|
-
}
|
|
1829
|
-
});
|
|
1830
|
-
app.get("/content/:id", async (c) => {
|
|
1831
|
-
const id = c.req.param("id");
|
|
1832
|
-
try {
|
|
1833
|
-
const content = await api.getContent(id);
|
|
1834
|
-
if (!content) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
|
|
1835
|
-
return c.json(content);
|
|
1836
|
-
} catch (error) {
|
|
1837
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch content"), 500);
|
|
1838
|
-
}
|
|
1839
|
-
});
|
|
1840
|
-
app.get("/content/:id/:locale", async (c) => {
|
|
1841
|
-
const id = c.req.param("id");
|
|
1842
|
-
const locale = c.req.param("locale");
|
|
1843
|
-
try {
|
|
1844
|
-
const content = await api.getLocalized(id, locale);
|
|
1845
|
-
if (!content) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
|
|
1846
|
-
c.header("ETag", content.localized.etag);
|
|
1847
|
-
return c.json(content);
|
|
1848
|
-
} catch (error) {
|
|
1849
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch localized content"), 500);
|
|
1850
|
-
}
|
|
1851
|
-
});
|
|
1852
|
-
app.post("/content", async (c) => {
|
|
1853
|
-
try {
|
|
1854
|
-
const data = await c.req.json();
|
|
1855
|
-
const result = await api.createContent(data);
|
|
1856
|
-
if (!result.success) {
|
|
1857
|
-
const errMessage = (result.error instanceof Error ? result.error.message : void 0) ?? "";
|
|
1858
|
-
if (result.reason === "already_exists") return c.json({
|
|
1859
|
-
...result,
|
|
1860
|
-
...errorResponse(ErrorCodes.ALREADY_EXISTS, errMessage || "Content already exists")
|
|
1861
|
-
}, 409);
|
|
1862
|
-
if (result.reason === "name_taken") return c.json({
|
|
1863
|
-
...result,
|
|
1864
|
-
...errorResponse(ErrorCodes.NAME_TAKEN, errMessage || "A block with that name already exists")
|
|
1865
|
-
}, 409);
|
|
1866
|
-
if (result.reason === "pathname_taken") return c.json({
|
|
1867
|
-
...result,
|
|
1868
|
-
...errorResponse(ErrorCodes.PATHNAME_TAKEN, errMessage || "Pathname already taken")
|
|
1869
|
-
}, 409);
|
|
1870
|
-
if (result.reason === "invalid_name") return c.json({
|
|
1871
|
-
...result,
|
|
1872
|
-
...errorResponse(ErrorCodes.INVALID_REQUEST, errMessage || "Invalid name")
|
|
1873
|
-
}, 400);
|
|
1874
|
-
if (result.reason === "invalid_pathname") return c.json({
|
|
1875
|
-
...result,
|
|
1876
|
-
...errorResponse(ErrorCodes.INVALID_PATHNAME, errMessage || "Invalid pathname")
|
|
1877
|
-
}, 400);
|
|
1878
|
-
if (result.reason === "metadata_too_large") return c.json({
|
|
1879
|
-
...result,
|
|
1880
|
-
...errorResponse(ErrorCodes.METADATA_TOO_LARGE, errMessage || "Metadata too large")
|
|
1881
|
-
}, 400);
|
|
1882
|
-
return c.json({
|
|
1883
|
-
...result,
|
|
1884
|
-
...errorResponse(ErrorCodes.WRITE_ERROR, errMessage || "Failed to create content")
|
|
1885
|
-
}, 500);
|
|
1886
|
-
}
|
|
1887
|
-
return c.json(result, 201);
|
|
1888
|
-
} catch (error) {
|
|
1889
|
-
console.error("[Content API] Failed to create content:", error);
|
|
1890
|
-
return c.json({
|
|
1891
|
-
success: false,
|
|
1892
|
-
reason: "write_error",
|
|
1893
|
-
...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, "Failed to create content"))
|
|
1894
|
-
}, 500);
|
|
1895
|
-
}
|
|
1896
|
-
});
|
|
1897
|
-
app.put("/content/:id", async (c) => {
|
|
1898
|
-
const id = c.req.param("id");
|
|
1899
|
-
const locale = c.req.query("locale");
|
|
1900
|
-
const etag = c.req.query("etag") || "";
|
|
1901
|
-
if (!locale) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "locale query parameter is required", { field: "locale" }), 400);
|
|
1902
|
-
try {
|
|
1903
|
-
const data = await c.req.json();
|
|
1904
|
-
const result = await api.updateLocalized({
|
|
1905
|
-
id,
|
|
1906
|
-
locale,
|
|
1907
|
-
data,
|
|
1908
|
-
etag
|
|
1909
|
-
});
|
|
1910
|
-
if (!result.success) {
|
|
1911
|
-
if (result.reason === "stale_write") return c.json(errorResponse(ErrorCodes.STALE_WRITE, "Content has been modified since you last loaded it", { currentEtag: result.currentEtag }), 412);
|
|
1912
|
-
if (result.reason === "not_found") return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
|
|
1913
|
-
return c.json(result, 500);
|
|
1914
|
-
}
|
|
1915
|
-
c.header("ETag", result.etag);
|
|
1916
|
-
return c.json(result);
|
|
1917
|
-
} catch (error) {
|
|
1918
|
-
console.error("[Content API] Failed to update content:", error);
|
|
1919
|
-
return c.json({
|
|
1920
|
-
success: false,
|
|
1921
|
-
reason: "write_error",
|
|
1922
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
1923
|
-
}, 500);
|
|
1924
|
-
}
|
|
1925
|
-
});
|
|
1926
|
-
app.patch("/content/:id", async (c) => {
|
|
1927
|
-
const id = c.req.param("id");
|
|
1928
|
-
const locale = c.req.query("locale");
|
|
1929
|
-
const etag = c.req.query("etag") || "";
|
|
1930
|
-
if (!locale) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "locale query parameter is required", { field: "locale" }), 400);
|
|
1931
|
-
try {
|
|
1932
|
-
const data = await c.req.json();
|
|
1933
|
-
const result = await api.updateLocalized({
|
|
1934
|
-
id,
|
|
1935
|
-
locale,
|
|
1936
|
-
data,
|
|
1937
|
-
etag
|
|
1938
|
-
});
|
|
1939
|
-
if (!result.success) {
|
|
1940
|
-
if (result.reason === "stale_write") return c.json(errorResponse(ErrorCodes.STALE_WRITE, "Content has been modified since you last loaded it", { currentEtag: result.currentEtag }), 412);
|
|
1941
|
-
if (result.reason === "not_found") return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
|
|
1942
|
-
return c.json(result, 500);
|
|
1943
|
-
}
|
|
1944
|
-
c.header("ETag", result.etag);
|
|
1945
|
-
return c.json(result);
|
|
1946
|
-
} catch (error) {
|
|
1947
|
-
console.error("[Content API] Failed to patch content:", error);
|
|
1948
|
-
return c.json({
|
|
1949
|
-
success: false,
|
|
1950
|
-
reason: "write_error",
|
|
1951
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
1952
|
-
}, 500);
|
|
1953
|
-
}
|
|
1954
|
-
});
|
|
1955
|
-
app.delete("/content/:id", async (c) => {
|
|
1956
|
-
const id = c.req.param("id");
|
|
1957
|
-
const locale = c.req.query("locale");
|
|
1958
|
-
const ifMatch = c.req.header("If-Match") || "";
|
|
1959
|
-
try {
|
|
1960
|
-
let result;
|
|
1961
|
-
if (locale) result = await api.deleteLocalized({
|
|
1962
|
-
id,
|
|
1963
|
-
locale,
|
|
1964
|
-
etag: ifMatch
|
|
1965
|
-
});
|
|
1966
|
-
else result = await api.deleteContent(id, ifMatch);
|
|
1967
|
-
if (!result.success) {
|
|
1968
|
-
if (result.reason === "not_found") return c.json({
|
|
1969
|
-
success: false,
|
|
1970
|
-
error: "Content not found"
|
|
1971
|
-
}, 404);
|
|
1972
|
-
if (result.reason === "stale_write") return c.json({
|
|
1973
|
-
success: false,
|
|
1974
|
-
reason: result.reason,
|
|
1975
|
-
currentEtag: result.currentEtag,
|
|
1976
|
-
message: "Content has been modified"
|
|
1977
|
-
}, 412);
|
|
1978
|
-
return c.json(result, 500);
|
|
1979
|
-
}
|
|
1980
|
-
return c.json({ success: true });
|
|
1981
|
-
} catch (error) {
|
|
1982
|
-
console.error("[Content API] Failed to delete content:", error);
|
|
1983
|
-
return c.json({
|
|
1984
|
-
success: false,
|
|
1985
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
1986
|
-
}, 500);
|
|
1987
|
-
}
|
|
1988
|
-
});
|
|
1989
|
-
app.get("/data/collections", async (c) => {
|
|
1990
|
-
try {
|
|
1991
|
-
const collections = api.data.collections;
|
|
1992
|
-
return c.json({ collections: Array.from(collections).sort() });
|
|
1993
|
-
} catch (error) {
|
|
1994
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list data collections"), 500);
|
|
1995
|
-
}
|
|
1996
|
-
});
|
|
1997
|
-
app.get("/data/name-available", async (c) => {
|
|
1998
|
-
const name = c.req.query("name");
|
|
1999
|
-
const collection = c.req.query("collection");
|
|
2000
|
-
const excludeId = c.req.query("excludeId");
|
|
2001
|
-
if (!name) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "name query parameter is required", { field: "name" }), 400);
|
|
2002
|
-
if (!collection) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "collection query parameter is required", { field: "collection" }), 400);
|
|
2003
|
-
try {
|
|
2004
|
-
if (api.data.isNameAvailable(collection, name, excludeId)) return c.json({ available: true });
|
|
2005
|
-
const existing = api.data.getByName(collection, name);
|
|
2006
|
-
return c.json({
|
|
2007
|
-
available: false,
|
|
2008
|
-
existingId: existing?.id
|
|
2009
|
-
});
|
|
2010
|
-
} catch (error) {
|
|
2011
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check data name availability"), 500);
|
|
2012
|
-
}
|
|
2013
|
-
});
|
|
2014
|
-
app.get("/data", async (c) => {
|
|
2015
|
-
const collection = c.req.query("collection");
|
|
2016
|
-
const locale = c.req.query("locale");
|
|
2017
|
-
try {
|
|
2018
|
-
const filters = { kind: "data" };
|
|
2019
|
-
if (collection) filters.collection = collection;
|
|
2020
|
-
if (locale) filters.locales = [locale];
|
|
2021
|
-
const items = Array.from(api.listAllContent(filters));
|
|
2022
|
-
return c.json({
|
|
2023
|
-
items,
|
|
2024
|
-
total: items.length
|
|
2025
|
-
});
|
|
2026
|
-
} catch (error) {
|
|
2027
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list data entries"), 500);
|
|
2028
|
-
}
|
|
2029
|
-
});
|
|
2030
|
-
app.get("/data/:name", async (c) => {
|
|
2031
|
-
const name = c.req.param("name");
|
|
2032
|
-
const collection = c.req.query("collection");
|
|
2033
|
-
const locale = c.req.query("locale");
|
|
2034
|
-
if (!collection) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "collection query parameter is required", { field: "collection" }), 400);
|
|
2035
|
-
try {
|
|
2036
|
-
const dataEntry = api.data.getByName(collection, name, locale);
|
|
2037
|
-
if (!dataEntry) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Data entry not found", {
|
|
2038
|
-
name,
|
|
2039
|
-
collection
|
|
2040
|
-
}), 404);
|
|
2041
|
-
if (locale && dataEntry.locales[locale]) return c.json({
|
|
2042
|
-
...dataEntry,
|
|
2043
|
-
locales: { [locale]: dataEntry.locales[locale] }
|
|
2044
|
-
});
|
|
2045
|
-
return c.json(dataEntry);
|
|
2046
|
-
} catch (error) {
|
|
2047
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch data entry"), 500);
|
|
2048
|
-
}
|
|
2049
|
-
});
|
|
2050
|
-
if (options?.assetsPath) {
|
|
2051
|
-
const assetOps = new AssetOperations({
|
|
2052
|
-
assetsPath: options.assetsPath,
|
|
2053
|
-
contentRoot: options.contentRoot,
|
|
2054
|
-
...options.assetConfig
|
|
2055
|
-
});
|
|
2056
|
-
function splitAssetPath(relativePath) {
|
|
2057
|
-
const lastSlash = relativePath.lastIndexOf("/");
|
|
2058
|
-
if (lastSlash > 0) return {
|
|
2059
|
-
folder: `/${relativePath.slice(0, lastSlash)}`,
|
|
2060
|
-
filename: relativePath.slice(lastSlash + 1)
|
|
2061
|
-
};
|
|
2062
|
-
return {
|
|
2063
|
-
folder: "/",
|
|
2064
|
-
filename: relativePath
|
|
2065
|
-
};
|
|
2066
|
-
}
|
|
2067
|
-
app.post("/assets/move", async (c) => {
|
|
2068
|
-
try {
|
|
2069
|
-
const { filenames, sourceFolder, targetFolder } = await c.req.json();
|
|
2070
|
-
if (!Array.isArray(filenames)) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "filenames must be an array"), 400);
|
|
2071
|
-
if (typeof sourceFolder !== "string") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "sourceFolder is required"), 400);
|
|
2072
|
-
if (typeof targetFolder !== "string") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "targetFolder is required"), 400);
|
|
2073
|
-
const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
|
|
2074
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
|
|
2075
|
-
return c.json(result);
|
|
2076
|
-
} catch (error) {
|
|
2077
|
-
if (error instanceof Error && error.message === "Path traversal detected") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid folder path"), 400);
|
|
2078
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to move assets"), 500);
|
|
2079
|
-
}
|
|
2080
|
-
});
|
|
2081
|
-
app.post("/assets/upload", async (c) => {
|
|
2082
|
-
try {
|
|
2083
|
-
const body = await c.req.parseBody();
|
|
2084
|
-
const file = body.file;
|
|
2085
|
-
if (!(file instanceof File)) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "No file provided in \"file\" field"), 400);
|
|
2086
|
-
const alt = typeof body.alt === "string" ? body.alt : void 0;
|
|
2087
|
-
const uploadedBy = typeof body.uploadedBy === "string" ? body.uploadedBy : void 0;
|
|
2088
|
-
const width = typeof body.width === "string" ? Number.parseInt(body.width, 10) : void 0;
|
|
2089
|
-
const height = typeof body.height === "string" ? Number.parseInt(body.height, 10) : void 0;
|
|
2090
|
-
const folder = typeof body.folder === "string" ? body.folder : void 0;
|
|
2091
|
-
const result = await assetOps.upload(file, {
|
|
2092
|
-
alt,
|
|
2093
|
-
uploadedBy,
|
|
2094
|
-
width,
|
|
2095
|
-
height,
|
|
2096
|
-
folder
|
|
2097
|
-
});
|
|
2098
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
|
|
2099
|
-
return c.json(result.asset, 201);
|
|
2100
|
-
} catch (error) {
|
|
2101
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, "Upload failed"), 500);
|
|
2102
|
-
}
|
|
2103
|
-
});
|
|
2104
|
-
app.post("/assets/import-url", async (c) => {
|
|
2105
|
-
try {
|
|
2106
|
-
const { url, alt, uploadedBy, folder } = await c.req.json();
|
|
2107
|
-
if (!url) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "url is required"), 400);
|
|
2108
|
-
const result = await assetOps.importFromUrl(url, {
|
|
2109
|
-
alt,
|
|
2110
|
-
uploadedBy,
|
|
2111
|
-
folder
|
|
2112
|
-
});
|
|
2113
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
|
|
2114
|
-
return c.json(result.asset, 201);
|
|
2115
|
-
} catch (error) {
|
|
2116
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, "URL import failed"), 500);
|
|
2117
|
-
}
|
|
2118
|
-
});
|
|
2119
|
-
app.get("/assets", async (c) => {
|
|
2120
|
-
try {
|
|
2121
|
-
const assets = await assetOps.list();
|
|
2122
|
-
return c.json({ assets });
|
|
2123
|
-
} catch (error) {
|
|
2124
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list assets"), 500);
|
|
2125
|
-
}
|
|
2126
|
-
});
|
|
2127
|
-
app.get("/assets/folders", async (c) => {
|
|
2128
|
-
try {
|
|
2129
|
-
const path = c.req.query("path") || "/";
|
|
2130
|
-
const result = await assetOps.listFolder(path);
|
|
2131
|
-
return c.json(result);
|
|
2132
|
-
} catch (error) {
|
|
2133
|
-
if (error instanceof Error && error.message === "Path traversal detected") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid folder path"), 400);
|
|
2134
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list folder"), 500);
|
|
2135
|
-
}
|
|
2136
|
-
});
|
|
2137
|
-
app.post("/assets/folders", async (c) => {
|
|
2138
|
-
try {
|
|
2139
|
-
const { path } = await c.req.json();
|
|
2140
|
-
if (!path) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "path is required"), 400);
|
|
2141
|
-
const result = await assetOps.createFolder(path);
|
|
2142
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
|
|
2143
|
-
return c.json({ success: true }, 201);
|
|
2144
|
-
} catch (error) {
|
|
2145
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to create folder"), 500);
|
|
2146
|
-
}
|
|
2147
|
-
});
|
|
2148
|
-
app.get("/assets/folder-tree", async (c) => {
|
|
2149
|
-
try {
|
|
2150
|
-
const tree = await assetOps.getFolderTree();
|
|
2151
|
-
return c.json({ tree });
|
|
2152
|
-
} catch (error) {
|
|
2153
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get folder tree"), 500);
|
|
2154
|
-
}
|
|
2155
|
-
});
|
|
2156
|
-
app.get("/assets/usage/:path{.+}", async (c) => {
|
|
2157
|
-
try {
|
|
2158
|
-
const { filename } = splitAssetPath(c.req.param("path"));
|
|
2159
|
-
const usage = await assetOps.getUsage(filename);
|
|
2160
|
-
return c.json({ usage });
|
|
2161
|
-
} catch (error) {
|
|
2162
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get asset usage"), 500);
|
|
2163
|
-
}
|
|
2164
|
-
});
|
|
2165
|
-
app.get("/assets/serve/:path{.+}", async (c) => {
|
|
2166
|
-
try {
|
|
2167
|
-
const { folder, filename } = splitAssetPath(c.req.param("path"));
|
|
2168
|
-
const result = await assetOps.readAssetFile(filename, folder);
|
|
2169
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
|
|
2170
|
-
return new Response(new Uint8Array(result.buffer), { headers: {
|
|
2171
|
-
"Content-Type": result.mimeType,
|
|
2172
|
-
"Cache-Control": "public, max-age=31536000, immutable"
|
|
2173
|
-
} });
|
|
2174
|
-
} catch (error) {
|
|
2175
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to serve asset"), 500);
|
|
2176
|
-
}
|
|
2177
|
-
});
|
|
2178
|
-
app.get("/assets/meta/:path{.+}", async (c) => {
|
|
2179
|
-
try {
|
|
2180
|
-
const { folder, filename } = splitAssetPath(c.req.param("path"));
|
|
2181
|
-
const asset = await assetOps.getAsset(filename, folder);
|
|
2182
|
-
if (!asset) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, "Asset not found"), 404);
|
|
2183
|
-
return c.json(asset);
|
|
2184
|
-
} catch (error) {
|
|
2185
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get asset"), 500);
|
|
2186
|
-
}
|
|
2187
|
-
});
|
|
2188
|
-
app.patch("/assets/meta/:path{.+}", async (c) => {
|
|
2189
|
-
try {
|
|
2190
|
-
const { folder, filename } = splitAssetPath(c.req.param("path"));
|
|
2191
|
-
const { alt, tags } = await c.req.json();
|
|
2192
|
-
const result = await assetOps.updateMetadata(filename, {
|
|
2193
|
-
alt,
|
|
2194
|
-
tags
|
|
2195
|
-
}, folder);
|
|
2196
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
|
|
2197
|
-
return c.json(result.asset);
|
|
2198
|
-
} catch (error) {
|
|
2199
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to update asset"), 500);
|
|
2200
|
-
}
|
|
2201
|
-
});
|
|
2202
|
-
app.delete("/assets/meta/:path{.+}", async (c) => {
|
|
2203
|
-
try {
|
|
2204
|
-
const { folder, filename } = splitAssetPath(c.req.param("path"));
|
|
2205
|
-
const result = await assetOps.delete(filename, folder);
|
|
2206
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
|
|
2207
|
-
return c.json({ success: true });
|
|
2208
|
-
} catch (error) {
|
|
2209
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to delete asset"), 500);
|
|
2210
|
-
}
|
|
2211
|
-
});
|
|
2212
|
-
}
|
|
2213
|
-
app.get("/:site/collections", async (c) => {
|
|
2214
|
-
const site = c.req.param("site");
|
|
2215
|
-
try {
|
|
2216
|
-
if (site === "blocks") {
|
|
2217
|
-
const collections = Array.from(api.blocks.collections).sort();
|
|
2218
|
-
return c.json({ collections });
|
|
2219
|
-
}
|
|
2220
|
-
const siteObj = api.getSite(site);
|
|
2221
|
-
if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
2222
|
-
const collections = Array.from(siteObj.collections).sort();
|
|
2223
|
-
return c.json({ collections });
|
|
2224
|
-
} catch (error) {
|
|
2225
|
-
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
2226
|
-
}
|
|
2227
|
-
});
|
|
2228
|
-
app.get("/:site/pages", async (c) => {
|
|
2229
|
-
const site = c.req.param("site");
|
|
2230
|
-
const locale = c.req.query("locale");
|
|
2231
|
-
try {
|
|
2232
|
-
if (site === "blocks") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Blocks do not have pages. Use /content?kind=block to list blocks."), 400);
|
|
2233
|
-
const siteObj = api.getSite(site);
|
|
2234
|
-
if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
2235
|
-
const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));
|
|
2236
|
-
const result = {
|
|
2237
|
-
items,
|
|
2238
|
-
total: items.length
|
|
2239
|
-
};
|
|
2240
|
-
return c.json(result);
|
|
2241
|
-
} catch (error) {
|
|
2242
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, { site }), 500);
|
|
2243
|
-
}
|
|
2244
|
-
});
|
|
2245
|
-
app.get("/:site/pathname-available", async (c) => {
|
|
2246
|
-
const site = c.req.param("site");
|
|
2247
|
-
const pathname = c.req.query("pathname");
|
|
2248
|
-
const locale = c.req.query("locale") || "en";
|
|
2249
|
-
const excludeId = c.req.query("excludeId");
|
|
2250
|
-
if (!pathname) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "pathname query parameter is required", { field: "pathname" }), 400);
|
|
2251
|
-
try {
|
|
2252
|
-
if (site === "blocks") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Blocks do not have pathnames. This endpoint is only for page content."), 400);
|
|
2253
|
-
const validation = normalizeAndValidatePathname(pathname);
|
|
2254
|
-
if (!validation.valid) return c.json({
|
|
2255
|
-
available: false,
|
|
2256
|
-
reason: "invalid_pathname",
|
|
2257
|
-
message: validation.message
|
|
2258
|
-
});
|
|
2259
|
-
const normalized = validation.value;
|
|
2260
|
-
const siteObj = api.getSite(site);
|
|
2261
|
-
if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
2262
|
-
if (siteObj.isPathnameAvailable(normalized, locale, excludeId)) return c.json({ available: true });
|
|
2263
|
-
const existingId = siteObj.getPathnameConflict(normalized, locale, excludeId);
|
|
2264
|
-
return c.json({
|
|
2265
|
-
available: false,
|
|
2266
|
-
existingId
|
|
2267
|
-
});
|
|
2268
|
-
} catch (error) {
|
|
2269
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check pathname availability"), 500);
|
|
2270
|
-
}
|
|
2271
|
-
});
|
|
2272
|
-
app.get("/blocks", async (c) => {
|
|
2273
|
-
const collection = c.req.query("collection");
|
|
2274
|
-
const locale = c.req.query("locale");
|
|
2275
|
-
try {
|
|
2276
|
-
const filters = { kind: "block" };
|
|
2277
|
-
if (collection) filters.collection = collection;
|
|
2278
|
-
if (locale) filters.locales = [locale];
|
|
2279
|
-
const items = Array.from(api.listAllContent(filters));
|
|
2280
|
-
return c.json({
|
|
2281
|
-
items,
|
|
2282
|
-
total: items.length
|
|
2283
|
-
});
|
|
2284
|
-
} catch (error) {
|
|
2285
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list blocks"), 500);
|
|
2286
|
-
}
|
|
2287
|
-
});
|
|
2288
|
-
app.get("/blocks/name-available", async (c) => {
|
|
2289
|
-
const name = c.req.query("name");
|
|
2290
|
-
const collection = c.req.query("collection") || "components";
|
|
2291
|
-
const locale = c.req.query("locale") || "en";
|
|
2292
|
-
const excludeId = c.req.query("excludeId");
|
|
2293
|
-
if (!name) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "name query parameter is required", { field: "name" }), 400);
|
|
2294
|
-
try {
|
|
2295
|
-
const existing = Array.from(api.listAllContent({
|
|
2296
|
-
kind: "block",
|
|
2297
|
-
collection,
|
|
2298
|
-
locales: [locale]
|
|
2299
|
-
}));
|
|
2300
|
-
let taken;
|
|
2301
|
-
for (const item of existing) for (const localeVersion of localesOf(item)) if (localeVersion.name === name) {
|
|
2302
|
-
taken = item;
|
|
2303
|
-
break;
|
|
2304
|
-
}
|
|
2305
|
-
if (!taken) return c.json({ available: true });
|
|
2306
|
-
if (excludeId && taken.id === excludeId) return c.json({ available: true });
|
|
2307
|
-
return c.json({
|
|
2308
|
-
available: false,
|
|
2309
|
-
existingId: taken.id
|
|
2310
|
-
});
|
|
2311
|
-
} catch (error) {
|
|
2312
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check block name availability"), 500);
|
|
2313
|
-
}
|
|
2314
|
-
});
|
|
2315
|
-
app.get("/blocks/:name", async (c) => {
|
|
2316
|
-
const name = c.req.param("name");
|
|
2317
|
-
const collection = c.req.query("collection") || "components";
|
|
2318
|
-
const locale = c.req.query("locale");
|
|
2319
|
-
try {
|
|
2320
|
-
const block = api.blocks.getByName(collection, name, locale);
|
|
2321
|
-
if (!block) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Block not found", {
|
|
2322
|
-
name,
|
|
2323
|
-
collection
|
|
2324
|
-
}), 404);
|
|
2325
|
-
if (locale && block.locales[locale]) return c.json({
|
|
2326
|
-
...block,
|
|
2327
|
-
locales: { [locale]: block.locales[locale] }
|
|
2328
|
-
});
|
|
2329
|
-
return c.json(block);
|
|
2330
|
-
} catch (error) {
|
|
2331
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch block"), 500);
|
|
2332
|
-
}
|
|
2333
|
-
});
|
|
2334
|
-
app.post("/:site/move", async (c) => {
|
|
2335
|
-
const site = c.req.param("site");
|
|
2336
|
-
try {
|
|
2337
|
-
const { id, pathname, locale, etag } = await c.req.json();
|
|
2338
|
-
if (!id || !pathname || !locale || !etag) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "id, pathname, locale, and etag are required"), 400);
|
|
2339
|
-
const siteObj = api.getSite(site);
|
|
2340
|
-
if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
2341
|
-
const existing = siteObj.getByPathname(pathname, locale);
|
|
2342
|
-
if (existing && existing.id !== id) return c.json({
|
|
2343
|
-
moved: false,
|
|
2344
|
-
reason: "already_exists",
|
|
2345
|
-
...errorResponse(ErrorCodes.PATHNAME_TAKEN, "Pathname already taken", { existingId: existing.id })
|
|
2346
|
-
}, 409);
|
|
2347
|
-
const current = await api.getLocalized(id, locale);
|
|
2348
|
-
if (!current) return c.json({
|
|
2349
|
-
moved: false,
|
|
2350
|
-
...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id })
|
|
2351
|
-
}, 404);
|
|
2352
|
-
const previousPathname = current.localized.pathname;
|
|
2353
|
-
const updateResult = await api.updateLocalized({
|
|
2354
|
-
id,
|
|
2355
|
-
locale,
|
|
2356
|
-
data: {
|
|
2357
|
-
pathname,
|
|
2358
|
-
meta: current.localized.meta
|
|
2359
|
-
},
|
|
2360
|
-
etag
|
|
2361
|
-
});
|
|
2362
|
-
if (!updateResult.success) {
|
|
2363
|
-
if (updateResult.reason === "stale_write") return c.json({
|
|
2364
|
-
moved: false,
|
|
2365
|
-
reason: "stale_write",
|
|
2366
|
-
currentEtag: updateResult.currentEtag,
|
|
2367
|
-
message: "Content has been modified"
|
|
2368
|
-
}, 412);
|
|
2369
|
-
if (updateResult.reason === "not_found") return c.json({
|
|
2370
|
-
moved: false,
|
|
2371
|
-
...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id })
|
|
2372
|
-
}, 404);
|
|
2373
|
-
return c.json({
|
|
2374
|
-
moved: false,
|
|
2375
|
-
...errorResponse(ErrorCodes.WRITE_ERROR, "Update failed")
|
|
2376
|
-
}, 500);
|
|
2377
|
-
}
|
|
2378
|
-
return c.json({
|
|
2379
|
-
moved: true,
|
|
2380
|
-
previousPathname,
|
|
2381
|
-
etag: updateResult.etag
|
|
2382
|
-
});
|
|
2383
|
-
} catch (error) {
|
|
2384
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to move page"), 500);
|
|
2385
|
-
}
|
|
2386
|
-
});
|
|
2387
|
-
app.get("/untranslated/:targetLocale", async (c) => {
|
|
2388
|
-
const targetLocale = c.req.param("targetLocale");
|
|
2389
|
-
const excludeSites = c.req.query("excludeSites")?.split(",").map((s) => s.trim()).filter((s) => s);
|
|
2390
|
-
const includeUnpublished = c.req.query("includeUnpublished") === "true";
|
|
2391
|
-
try {
|
|
2392
|
-
const options = {
|
|
2393
|
-
...excludeSites?.length && { excludeSites },
|
|
2394
|
-
...includeUnpublished && { includeUnpublished }
|
|
2395
|
-
};
|
|
2396
|
-
const items = Array.from(api.findUntranslatedContent(targetLocale, options));
|
|
2397
|
-
return c.json({
|
|
2398
|
-
items,
|
|
2399
|
-
total: items.length
|
|
2400
|
-
});
|
|
2401
|
-
} catch (error) {
|
|
2402
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to find untranslated content"), 500);
|
|
2403
|
-
}
|
|
2404
|
-
});
|
|
2405
|
-
app.get("/sites", async (c) => {
|
|
2406
|
-
try {
|
|
2407
|
-
const config = api.sitesConfig;
|
|
2408
|
-
return c.json(config);
|
|
2409
|
-
} catch (error) {
|
|
2410
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch sites configuration"), 500);
|
|
2411
|
-
}
|
|
2412
|
-
});
|
|
2413
|
-
app.post("/content/batch", async (c) => {
|
|
2414
|
-
try {
|
|
2415
|
-
const { operations } = await c.req.json();
|
|
2416
|
-
const result = await api.batchUpdate(operations);
|
|
2417
|
-
if (!result.success) return c.json(result, 207);
|
|
2418
|
-
return c.json(result);
|
|
2419
|
-
} catch (error) {
|
|
2420
|
-
console.error("[Content API] Failed to batch update:", error);
|
|
2421
|
-
return c.json({
|
|
2422
|
-
success: false,
|
|
2423
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
2424
|
-
}, 500);
|
|
2425
|
-
}
|
|
2426
|
-
});
|
|
2427
|
-
/**
|
|
2428
|
-
* Get git config from router options or environment variables.
|
|
2429
|
-
* contentRoot from router options takes priority over CONTENT_PATH env var.
|
|
2430
|
-
* Optional: GIT_BRANCH (defaults to current checked-out branch)
|
|
2431
|
-
*/
|
|
2432
|
-
function getGitConfig() {
|
|
2433
|
-
const contentPath = options?.contentRoot || process.env.CONTENT_PATH;
|
|
2434
|
-
if (!contentPath) throw new Error("contentRoot option or CONTENT_PATH environment variable is required for git operations");
|
|
2435
|
-
return {
|
|
2436
|
-
contentPath,
|
|
2437
|
-
branch: process.env.GIT_BRANCH
|
|
2438
|
-
};
|
|
2439
|
-
}
|
|
2440
|
-
app.get("/git/status", async (c) => {
|
|
2441
|
-
try {
|
|
2442
|
-
const status = await createGitOperations(getGitConfig()).getStatus();
|
|
2443
|
-
if (!status.isRepo) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, "Repository not accessible"), 400);
|
|
2444
|
-
return c.json(status);
|
|
2445
|
-
} catch (error) {
|
|
2446
|
-
if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
2447
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, "Failed to get git status"), 500);
|
|
2448
|
-
}
|
|
2449
|
-
});
|
|
2450
|
-
app.post("/git/commit", async (c) => {
|
|
2451
|
-
try {
|
|
2452
|
-
const body = await c.req.json().catch(() => ({}));
|
|
2453
|
-
const date = /* @__PURE__ */ new Date();
|
|
2454
|
-
const defaultMessage = `CMS changes - ${[
|
|
2455
|
-
"Jan",
|
|
2456
|
-
"Feb",
|
|
2457
|
-
"Mar",
|
|
2458
|
-
"Apr",
|
|
2459
|
-
"May",
|
|
2460
|
-
"Jun",
|
|
2461
|
-
"Jul",
|
|
2462
|
-
"Aug",
|
|
2463
|
-
"Sep",
|
|
2464
|
-
"Oct",
|
|
2465
|
-
"Nov",
|
|
2466
|
-
"Dec"
|
|
2467
|
-
][date.getMonth()]} ${date.getDate()}`;
|
|
2468
|
-
const message = body.message || defaultMessage;
|
|
2469
|
-
const userEmail = c.req.header("X-CF-User-Email");
|
|
2470
|
-
const author = userEmail ? {
|
|
2471
|
-
name: userEmail.split("@")[0],
|
|
2472
|
-
email: userEmail
|
|
2473
|
-
} : void 0;
|
|
2474
|
-
const result = await createGitOperations(getGitConfig()).commitAll(message, author);
|
|
2475
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || "Commit failed"), 500);
|
|
2476
|
-
return c.json(result);
|
|
2477
|
-
} catch (error) {
|
|
2478
|
-
if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
2479
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, "Failed to commit changes"), 500);
|
|
2480
|
-
}
|
|
2481
|
-
});
|
|
2482
|
-
app.post("/git/push", async (c) => {
|
|
2483
|
-
try {
|
|
2484
|
-
const result = await createGitOperations(getGitConfig()).pushOrigin();
|
|
2485
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || "Push failed"), 500);
|
|
2486
|
-
return c.json(result);
|
|
2487
|
-
} catch (error) {
|
|
2488
|
-
if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
2489
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, "Failed to push to origin"), 500);
|
|
2490
|
-
}
|
|
2491
|
-
});
|
|
2492
|
-
app.post("/git/pull", async (c) => {
|
|
2493
|
-
try {
|
|
2494
|
-
const result = await createGitOperations(getGitConfig()).pull();
|
|
2495
|
-
if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || "Pull failed"), 500);
|
|
2496
|
-
return c.json(result);
|
|
2497
|
-
} catch (error) {
|
|
2498
|
-
if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
2499
|
-
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, "Failed to pull from origin"), 500);
|
|
2500
|
-
}
|
|
2501
|
-
});
|
|
2502
|
-
return app;
|
|
2503
|
-
}
|
|
2504
|
-
/**
|
|
2505
|
-
* Create middleware for backwards compatibility with existing code
|
|
2506
|
-
* This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse
|
|
2507
|
-
*/
|
|
2508
|
-
function createContentMiddleware(contentApi, options) {
|
|
2509
|
-
const app = createContentAPIRouter(contentApi, options);
|
|
2510
|
-
return async (req, res, next) => {
|
|
2511
|
-
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
2512
|
-
const basePath = url.pathname.startsWith("/__cms/api") ? "/__cms/api" : "/__conloca/api";
|
|
2513
|
-
if (!url.pathname.startsWith(basePath)) return next();
|
|
2514
|
-
const path = url.pathname.replace(basePath, "");
|
|
2515
|
-
const request = new Request(`http://localhost${path}${url.search}`, {
|
|
2516
|
-
method: req.method,
|
|
2517
|
-
headers: req.headers,
|
|
2518
|
-
body: ["GET", "HEAD"].includes(req.method) ? void 0 : await readBody(req)
|
|
2519
|
-
});
|
|
2520
|
-
const response = await app.fetch(request);
|
|
2521
|
-
response.headers.forEach((value, key) => {
|
|
2522
|
-
res.setHeader(key, value);
|
|
2523
|
-
});
|
|
2524
|
-
res.statusCode = response.status;
|
|
2525
|
-
const body = await response.text();
|
|
2526
|
-
res.end(body);
|
|
2527
|
-
};
|
|
2528
|
-
}
|
|
2529
|
-
function readBody(req) {
|
|
2530
|
-
return new Promise((resolve, reject) => {
|
|
2531
|
-
const chunks = [];
|
|
2532
|
-
req.on("data", (chunk) => chunks.push(new Uint8Array(chunk)));
|
|
2533
|
-
req.on("end", () => {
|
|
2534
|
-
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
|
|
2535
|
-
const combined = new Uint8Array(totalLength);
|
|
2536
|
-
let offset = 0;
|
|
2537
|
-
for (const chunk of chunks) {
|
|
2538
|
-
combined.set(chunk, offset);
|
|
2539
|
-
offset += chunk.length;
|
|
2540
|
-
}
|
|
2541
|
-
resolve(Buffer.from(combined).toString());
|
|
2542
|
-
});
|
|
2543
|
-
req.on("error", reject);
|
|
2544
|
-
});
|
|
2545
|
-
}
|
|
2546
|
-
//#endregion
|
|
2547
|
-
//#region src/vite-plugin.ts
|
|
2548
|
-
/**
|
|
2549
|
-
* Vite plugin wrapper for content middleware
|
|
2550
|
-
* This follows the spec in 04-cms-api.md and 09-conloca-content-editing.md
|
|
2551
|
-
*/
|
|
2552
|
-
function conlocaContent(options) {
|
|
2553
|
-
let contentApi;
|
|
2554
|
-
const basePath = options.basePath || "/__conloca/api/content";
|
|
2555
|
-
return {
|
|
2556
|
-
name: "vite-plugin-conloca-content",
|
|
2557
|
-
async configureServer(server) {
|
|
2558
|
-
contentApi = await createContentAPI(options);
|
|
2559
|
-
server.watcher.add(options.contentRoot);
|
|
2560
|
-
const app = createContentAPIRouter(contentApi);
|
|
2561
|
-
server.middlewares.use(basePath, getRequestListener(app.fetch));
|
|
2562
|
-
const handlers = createContentWatchHandlers(contentApi, options, server.ws);
|
|
2563
|
-
server.watcher.on("change", handlers.onChange);
|
|
2564
|
-
server.watcher.on("add", handlers.onAdd);
|
|
2565
|
-
server.watcher.on("unlink", handlers.onUnlink);
|
|
2566
|
-
}
|
|
2567
|
-
};
|
|
2568
|
-
}
|
|
2569
|
-
//#endregion
|
|
2570
|
-
export { AssetManifest, AssetOperations, Blocks, ComponentRegistry, ErrorCodes, FileSystemContentAPI, InMemoryContentAPI, Site, UPDATE_SCOPE, analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, conlocaContent, createContentAPI, createContentAPIRouter, createContentMiddleware, createContentWatchHandlers, extractBlockName, extractCFAccessToken, formatFileSize, generateContentId, getCurrentISODate, getMetadataSize, isContentPublished, isMetadataTooLarge, isValidBlockName, isValidPathname, localesOf, mapLocales, mapSiteNames, normalizeAndValidatePathname, normalizePathname, parseDate, readSitesConfig, resolvePublishDate, serializeMdxWithFrontmatter, shouldUpdateModifiedTimestamp, updatePublishDates, validateAndPrepareMetadata, validateCFAccessRequest, validateCreateContent };
|
|
2571
|
-
|
|
2572
|
-
//# sourceMappingURL=node.mjs.map
|