@conloca/content-api 0.2.1 → 0.2.3
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/.build-inputs.json +71 -0
- package/dist/address-site.d.ts +6 -0
- package/dist/address-site.d.ts.map +1 -0
- package/dist/address-site.js +15 -0
- package/dist/address-site.js.map +1 -0
- package/dist/asset-operations.d.ts +15 -2
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +216 -78
- package/dist/asset-operations.js.map +1 -1
- package/dist/cf-access.d.ts +4 -2
- package/dist/cf-access.d.ts.map +1 -1
- package/dist/cf-access.js +29 -13
- package/dist/cf-access.js.map +1 -1
- package/dist/content-file-id.d.ts +9 -0
- package/dist/content-file-id.d.ts.map +1 -0
- package/dist/content-file-id.js +33 -0
- package/dist/content-file-id.js.map +1 -0
- package/dist/content-utils.d.ts +4 -1
- package/dist/content-utils.d.ts.map +1 -1
- package/dist/content-utils.js +14 -1
- package/dist/content-utils.js.map +1 -1
- package/dist/editor-host.d.ts +121 -0
- package/dist/editor-host.d.ts.map +1 -0
- package/dist/editor-host.js +212 -0
- package/dist/editor-host.js.map +1 -0
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +3 -2
- package/dist/filesystem-content-api.js.map +1 -1
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +162 -34
- package/dist/git-operations.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +5 -0
- package/dist/middleware.js.map +1 -1
- package/dist/schemas/index.d.ts +9 -97
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +8 -83
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/normalize.d.ts +101 -0
- package/dist/schemas/normalize.d.ts.map +1 -0
- package/dist/schemas/normalize.js +168 -0
- package/dist/schemas/normalize.js.map +1 -0
- package/dist/schemas/types.d.ts +135 -0
- package/dist/schemas/types.d.ts.map +1 -0
- package/dist/schemas/types.js +17 -0
- package/dist/schemas/types.js.map +1 -0
- package/dist/schemas/validators.d.ts +46 -0
- package/dist/schemas/validators.d.ts.map +1 -0
- package/dist/schemas/validators.js +938 -0
- package/dist/schemas/validators.js.map +1 -0
- package/dist/site.d.ts.map +1 -1
- package/dist/site.js +3 -1
- package/dist/site.js.map +1 -1
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +17 -5
- package/src/address-site.ts +19 -0
- package/src/asset-operations.ts +256 -83
- package/src/cf-access.ts +30 -14
- package/src/content-file-id.ts +31 -0
- package/src/content-utils.ts +18 -2
- package/src/editor-host.ts +268 -0
- package/src/filesystem-content-api.ts +3 -2
- package/src/git-operations.ts +188 -41
- package/src/index.ts +19 -1
- package/src/middleware.ts +5 -0
- package/src/schemas/index.ts +34 -108
- package/src/schemas/normalize.ts +194 -0
- package/src/schemas/types.ts +154 -0
- package/src/schemas/validators.ts +176 -0
- package/src/site.ts +3 -1
- package/src/types.ts +9 -0
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { isRecord } from './component-vocabulary.js';
|
|
2
|
+
|
|
3
|
+
/** The wire protocol an editor page built by this release speaks; the editor UI path is /host/v<this>/. */
|
|
4
|
+
export const EDITOR_HOST_PROTOCOL = 1;
|
|
5
|
+
/** Protocols the current editor UI accepts. */
|
|
6
|
+
export const EDITOR_HOST_PROTOCOLS = { min: 1, max: 1 } as const;
|
|
7
|
+
export const DEFAULT_EDITOR_ENDPOINT = 'https://app.conloca.com';
|
|
8
|
+
/** Where the editor page is served, below the site's base. */
|
|
9
|
+
export const EDITOR_PAGE_PATH = '/_conloca/editor/';
|
|
10
|
+
/** The deployable-site id grammar (moved here from cloud-astro's site-id.ts; the census imports it too). */
|
|
11
|
+
export const SITE_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
12
|
+
|
|
13
|
+
/** The parsed http(s) URL when its host is `app.` plus at least two non-empty labels, else null. */
|
|
14
|
+
function appUrl(url: string): URL | null {
|
|
15
|
+
let parsed: URL;
|
|
16
|
+
try {
|
|
17
|
+
parsed = new URL(url);
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
|
|
22
|
+
const labels = parsed.hostname.split('.');
|
|
23
|
+
return labels.length >= 3 && labels[0] === 'app' && labels.every((label) => label !== '') ? parsed : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The editor UI origin for an endpoint, or null unless its host is `app.` plus at least two labels. */
|
|
27
|
+
export function editorUiOrigin(endpoint: string | undefined): string | null {
|
|
28
|
+
return appUrl(endpoint ?? DEFAULT_EDITOR_ENDPOINT)?.origin ?? null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The parent root for a URL on the editor UI origin (`app.conloca.com` → `conloca.com`), or null under the same rule. */
|
|
32
|
+
export function parentRoot(url: string): string | null {
|
|
33
|
+
return appUrl(url)?.hostname.slice('app.'.length) ?? null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Editor UI file per bare specifier the page's bundle keeps external, under `<origin>/host/v<protocol>/`. */
|
|
37
|
+
export const EDITOR_UI_MODULE_FILES = {
|
|
38
|
+
react: 'react.js',
|
|
39
|
+
'react-dom': 'react-dom.js',
|
|
40
|
+
'react-dom/client': 'react-dom-client.js',
|
|
41
|
+
'react/jsx-runtime': 'jsx-runtime.js',
|
|
42
|
+
'react/jsx-dev-runtime': 'jsx-dev-runtime.js',
|
|
43
|
+
'@puckeditor/core': 'puck.js',
|
|
44
|
+
} as const;
|
|
45
|
+
|
|
46
|
+
export type EditorHostStatus =
|
|
47
|
+
| 'ready'
|
|
48
|
+
| 'no-address'
|
|
49
|
+
| 'blocked-address'
|
|
50
|
+
| 'unreachable'
|
|
51
|
+
| 'protected'
|
|
52
|
+
| 'not-found'
|
|
53
|
+
| 'invalid'
|
|
54
|
+
| 'wrong-repo'
|
|
55
|
+
| 'wrong-site'
|
|
56
|
+
| 'unsupported-protocol'
|
|
57
|
+
| 'frame-blocked';
|
|
58
|
+
|
|
59
|
+
export type EditorFrameFailure = 'handshake-timeout' | 'origin-rejected' | 'unsupported-protocol' | 'site-load-failed';
|
|
60
|
+
|
|
61
|
+
/** The page's inline JSON block, `<script type="application/json" id="conloca-editor-host">`. URLs are base-absolute. */
|
|
62
|
+
export interface EditorHostPageData {
|
|
63
|
+
protocol: number;
|
|
64
|
+
repo: string | null;
|
|
65
|
+
siteId: string;
|
|
66
|
+
site: string;
|
|
67
|
+
css: string[];
|
|
68
|
+
editorCss: string | null;
|
|
69
|
+
sandboxFrame: string;
|
|
70
|
+
info: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** conloca.json: public facts about one deploy of the editor page. Grants nothing. */
|
|
74
|
+
export interface EditorPageInfo {
|
|
75
|
+
protocol: number;
|
|
76
|
+
repo: string | null;
|
|
77
|
+
siteId: string;
|
|
78
|
+
commit: string | null;
|
|
79
|
+
branch: string | null;
|
|
80
|
+
builtWith: string;
|
|
81
|
+
/** `path` is relative to the editor folder. */
|
|
82
|
+
componentManifest: { path: string; sha256: string } | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const EDITOR_PAGE_INFO_FORMATS = {
|
|
86
|
+
commit: /^[0-9a-f]{40}$/,
|
|
87
|
+
builtWith: /^@conloca\/cloud-astro@\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,
|
|
88
|
+
repo: /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/,
|
|
89
|
+
siteId: SITE_ID_RE,
|
|
90
|
+
sha256: /^[0-9a-f]{64}$/,
|
|
91
|
+
manifestPath: /^component-manifest\.[0-9a-f]{16}\.json$/,
|
|
92
|
+
} as const;
|
|
93
|
+
|
|
94
|
+
/** Where the host serves a build of every other branch, recorded by the production build. */
|
|
95
|
+
export type BranchDeploys = { host: 'cloudflare-pages'; project: string };
|
|
96
|
+
|
|
97
|
+
// One DNS label: the Pages project names the first label of its `pages.dev` address.
|
|
98
|
+
const PAGES_PROJECT_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
99
|
+
|
|
100
|
+
/** A parsed conloca.json object, whether or not it passed `isEditorPageInfo`, as the optional-field readers take it. */
|
|
101
|
+
export type ConlocaJson = EditorPageInfo | { branchDeploys?: unknown; contentPaths?: unknown };
|
|
102
|
+
|
|
103
|
+
/** conloca.json `branchDeploys`; `undefined` when absent or malformed, so a bad optional field never makes the page invalid. */
|
|
104
|
+
export function branchDeploysOf(info: ConlocaJson): BranchDeploys | undefined {
|
|
105
|
+
const value: unknown = Reflect.get(info, 'branchDeploys');
|
|
106
|
+
if (!isRecord(value) || value.host !== 'cloudflare-pages') return undefined;
|
|
107
|
+
const { project } = value;
|
|
108
|
+
return typeof project === 'string' && PAGES_PROJECT_RE.test(project)
|
|
109
|
+
? { host: 'cloudflare-pages', project }
|
|
110
|
+
: undefined;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const CONTENT_PATHS_MAX = 16;
|
|
114
|
+
|
|
115
|
+
/** '' (the repository root) or a relative path of plain segments, at most 255 characters. */
|
|
116
|
+
function isContentPath(path: unknown): path is string {
|
|
117
|
+
if (path === '') return true;
|
|
118
|
+
if (typeof path !== 'string' || path.length > 255 || path.includes('\\')) return false;
|
|
119
|
+
return path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* conloca.json `contentPaths`: repository paths the site's content lives under, duplicates removed;
|
|
124
|
+
* `undefined` when absent or malformed, so a bad optional field never makes the page invalid.
|
|
125
|
+
*/
|
|
126
|
+
export function contentPathsOf(info: ConlocaJson): string[] | undefined {
|
|
127
|
+
const value: unknown = Reflect.get(info, 'contentPaths');
|
|
128
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > CONTENT_PATHS_MAX) return undefined;
|
|
129
|
+
if (!value.every(isContentPath)) return undefined;
|
|
130
|
+
return [...new Set<string>(value)];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// `~^:?*[\`, `..`, `@{` and `//` anywhere (`git check-ref-format`); space and control characters are checked apart.
|
|
134
|
+
const BRANCH_FORBIDDEN_RE = /[~^:?*[\\]|\.\.|@\{|\/\//;
|
|
135
|
+
|
|
136
|
+
/** Git's ref-name rules for one branch name, at most 255 characters. */
|
|
137
|
+
export function isValidBranchName(name: string): boolean {
|
|
138
|
+
if (name === '' || name.length > 255 || name === '@' || BRANCH_FORBIDDEN_RE.test(name)) return false;
|
|
139
|
+
for (let index = 0; index < name.length; index++) {
|
|
140
|
+
const code = name.charCodeAt(index);
|
|
141
|
+
if (code <= 0x20 || code === 0x7f) return false;
|
|
142
|
+
}
|
|
143
|
+
if (name.startsWith('-') || name.startsWith('/') || name.endsWith('/') || name.endsWith('.')) return false;
|
|
144
|
+
return name.split('/').every((segment) => !segment.startsWith('.') && !segment.endsWith('.lock'));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Shape and field formats of a parsed conloca.json; null allowed where the type allows it. */
|
|
148
|
+
export function isEditorPageInfo(value: unknown): value is EditorPageInfo {
|
|
149
|
+
if (!isRecord(value)) return false;
|
|
150
|
+
const { protocol, repo, siteId, commit, branch, builtWith, componentManifest } = value;
|
|
151
|
+
const formats = EDITOR_PAGE_INFO_FORMATS;
|
|
152
|
+
return (
|
|
153
|
+
typeof protocol === 'number' &&
|
|
154
|
+
Number.isSafeInteger(protocol) &&
|
|
155
|
+
(repo === null || (typeof repo === 'string' && formats.repo.test(repo))) &&
|
|
156
|
+
typeof siteId === 'string' &&
|
|
157
|
+
formats.siteId.test(siteId) &&
|
|
158
|
+
(commit === null || (typeof commit === 'string' && formats.commit.test(commit))) &&
|
|
159
|
+
(branch === null || (typeof branch === 'string' && isValidBranchName(branch))) &&
|
|
160
|
+
typeof builtWith === 'string' &&
|
|
161
|
+
formats.builtWith.test(builtWith) &&
|
|
162
|
+
(componentManifest === null ||
|
|
163
|
+
(isRecord(componentManifest) &&
|
|
164
|
+
typeof componentManifest.path === 'string' &&
|
|
165
|
+
formats.manifestPath.test(componentManifest.path) &&
|
|
166
|
+
typeof componentManifest.sha256 === 'string' &&
|
|
167
|
+
formats.sha256.test(componentManifest.sha256)))
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** True when `location` is an absolute URL on vercel.com or a subdomain (Vercel's sign-in redirect). */
|
|
172
|
+
export function isVercelSignIn(location: string | null): boolean {
|
|
173
|
+
if (location === null) return false;
|
|
174
|
+
let host: string;
|
|
175
|
+
try {
|
|
176
|
+
host = new URL(location).hostname;
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
return host === 'vercel.com' || host.endsWith('.vercel.com');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Any Vercel signal on an answer: an `x-vercel-*` header or a sign-in redirect. Feeds the classifier's `vercel`. */
|
|
184
|
+
export function isFromVercel(headers: Headers): boolean {
|
|
185
|
+
for (const [name] of headers) if (name.startsWith('x-vercel-')) return true;
|
|
186
|
+
return isVercelSignIn(headers.get('location'));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** What one conloca.json answer means; `info` is the parsed file once it passed the format checks. */
|
|
190
|
+
export interface EditorHostVerdict {
|
|
191
|
+
status: EditorHostStatus;
|
|
192
|
+
reason?: 'repo-missing';
|
|
193
|
+
info?: EditorPageInfo;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* One conloca.json answer → status; body is null when not read (non-200 or over the cap).
|
|
198
|
+
* `vercel` (any Vercel signal) only picks the caller's message: an ordinary redirect on Vercel stays `invalid`.
|
|
199
|
+
*/
|
|
200
|
+
export function classifyEditorHostResponse(
|
|
201
|
+
response: {
|
|
202
|
+
status: number;
|
|
203
|
+
contentType: string | null;
|
|
204
|
+
location: string | null;
|
|
205
|
+
vercel: boolean;
|
|
206
|
+
body: string | null;
|
|
207
|
+
},
|
|
208
|
+
expected: { repoUri: string; siteId: string; protocols: { min: number; max: number } },
|
|
209
|
+
): EditorHostVerdict {
|
|
210
|
+
const { status, contentType, body } = response;
|
|
211
|
+
if (status >= 500 || status === 429) return { status: 'unreachable' };
|
|
212
|
+
if (status === 401 || status === 403) return { status: 'protected' };
|
|
213
|
+
if (status === 404) return { status: 'not-found' };
|
|
214
|
+
if (status >= 300 && status < 400) return { status: isVercelSignIn(response.location) ? 'protected' : 'invalid' };
|
|
215
|
+
if (status !== 200) return { status: 'invalid' };
|
|
216
|
+
// A host serving its HTML fallback for unknown paths.
|
|
217
|
+
if (contentType?.split(';')[0]?.trim().toLowerCase() === 'text/html') return { status: 'not-found' };
|
|
218
|
+
if (body === null) return { status: 'invalid' };
|
|
219
|
+
if (body.trimStart().startsWith('<')) return { status: 'not-found' };
|
|
220
|
+
let parsed: unknown;
|
|
221
|
+
try {
|
|
222
|
+
parsed = JSON.parse(body);
|
|
223
|
+
} catch {
|
|
224
|
+
return { status: 'invalid' };
|
|
225
|
+
}
|
|
226
|
+
if (!isEditorPageInfo(parsed)) return { status: 'invalid' };
|
|
227
|
+
const info = parsed;
|
|
228
|
+
if (info.protocol < expected.protocols.min || info.protocol > expected.protocols.max) {
|
|
229
|
+
return { status: 'unsupported-protocol', info };
|
|
230
|
+
}
|
|
231
|
+
if (info.repo === null) return { status: 'wrong-repo', reason: 'repo-missing', info };
|
|
232
|
+
if (info.repo.toLowerCase() !== expected.repoUri.toLowerCase()) return { status: 'wrong-repo', info };
|
|
233
|
+
if (info.siteId !== expected.siteId) return { status: 'wrong-site', info };
|
|
234
|
+
return { status: 'ready', info };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** A CSP source expression compared as a token: case-insensitive, without a trailing `/`. */
|
|
238
|
+
function sourceToken(source: string): string {
|
|
239
|
+
return source.toLowerCase().replace(/\/$/, '');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Frame headers of the page → whether a workspace parent may frame it. `allowedAncestors` are the source expressions
|
|
244
|
+
* that admit the workspace; `*` and `https:` always do. A `frame-ancestors` directive overrides X-Frame-Options.
|
|
245
|
+
* shortcut: sources match as exact tokens, so a broader host wildcard (`https://*.com`) reads as blocked; parse
|
|
246
|
+
* host patterns if a real site needs one.
|
|
247
|
+
*/
|
|
248
|
+
export function classifyFrameHeaders(
|
|
249
|
+
headers: { xFrameOptions: string | null; csp: string | null },
|
|
250
|
+
allowedAncestors: readonly string[],
|
|
251
|
+
): 'ok' | 'frame-blocked' {
|
|
252
|
+
const admitting = new Set(['*', 'https:', ...allowedAncestors.map(sourceToken)]);
|
|
253
|
+
// A combined header joins policies with commas; every policy is enforced on its own, by its first frame-ancestors.
|
|
254
|
+
const ancestorLists = (headers.csp ?? '').split(',').flatMap((policy) => {
|
|
255
|
+
const directive = policy
|
|
256
|
+
.split(';')
|
|
257
|
+
.map((part) => part.trim().split(/\s+/))
|
|
258
|
+
.find(([name]) => name?.toLowerCase() === 'frame-ancestors');
|
|
259
|
+
return directive ? [directive.slice(1)] : [];
|
|
260
|
+
});
|
|
261
|
+
if (ancestorLists.length > 0) {
|
|
262
|
+
return ancestorLists.every((sources) => sources.some((source) => admitting.has(sourceToken(source))))
|
|
263
|
+
? 'ok'
|
|
264
|
+
: 'frame-blocked';
|
|
265
|
+
}
|
|
266
|
+
const xfo = new Set((headers.xFrameOptions ?? '').split(',').map((value) => value.trim().toLowerCase()));
|
|
267
|
+
return xfo.has('deny') || xfo.has('sameorigin') ? 'frame-blocked' : 'ok';
|
|
268
|
+
}
|
|
@@ -431,8 +431,8 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
431
431
|
// site's locales array) both have slots for every option-declared
|
|
432
432
|
// locale. Without this, the parser would correctly identify a file's
|
|
433
433
|
// locale but `addContent` would crash on a missing index bucket.
|
|
434
|
-
// We preserve the resolved site's existing `mdxPages
|
|
435
|
-
// through the rewrite so the locale-override doesn't clobber the
|
|
434
|
+
// We preserve the resolved site's existing `mdxPages`, `domains` and
|
|
435
|
+
// `base` through the rewrite so the locale-override doesn't clobber the
|
|
436
436
|
// per-site content config.
|
|
437
437
|
if (options.availableLocales && options.availableLocales.length > 0) {
|
|
438
438
|
const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
|
|
@@ -445,6 +445,7 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
445
445
|
locales: options.availableLocales,
|
|
446
446
|
defaultLocale: optionDefaultLocale,
|
|
447
447
|
...(existingSite?.domains && { domains: existingSite.domains }),
|
|
448
|
+
...(existingSite?.base && { base: existingSite.base }),
|
|
448
449
|
...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),
|
|
449
450
|
},
|
|
450
451
|
},
|
package/src/git-operations.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import { access, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { access, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
3
4
|
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
6
|
+
|
|
7
|
+
/** Tries at lining the shared index up after a commit; ~1.5s total covers a briefly held index.lock. */
|
|
8
|
+
const INDEX_SYNC_ATTEMPTS = 6;
|
|
4
9
|
|
|
5
10
|
export interface GitStatus {
|
|
6
11
|
isRepo: boolean;
|
|
@@ -53,9 +58,15 @@ interface GitCommandResult {
|
|
|
53
58
|
stderr: string;
|
|
54
59
|
}
|
|
55
60
|
|
|
56
|
-
function runGitCommand(
|
|
61
|
+
function runGitCommand(
|
|
62
|
+
cwd: string,
|
|
63
|
+
args: string[],
|
|
64
|
+
env?: NodeJS.ProcessEnv,
|
|
65
|
+
input?: string,
|
|
66
|
+
): Promise<GitCommandResult> {
|
|
57
67
|
return new Promise((resolveCommand, reject) => {
|
|
58
|
-
const process = spawn('git', args, { cwd, stdio:
|
|
68
|
+
const process = spawn('git', args, { cwd, env, stdio: 'pipe' });
|
|
69
|
+
process.stdin.end(input);
|
|
59
70
|
let stdout = '';
|
|
60
71
|
let stderr = '';
|
|
61
72
|
|
|
@@ -79,6 +90,66 @@ function runGitCommand(cwd: string, args: string[]): Promise<GitCommandResult> {
|
|
|
79
90
|
});
|
|
80
91
|
}
|
|
81
92
|
|
|
93
|
+
/** One path a commit changed, from `git diff-tree -r -z` raw output. */
|
|
94
|
+
interface TreeChange {
|
|
95
|
+
path: string;
|
|
96
|
+
oldBlob: string;
|
|
97
|
+
newMode: string;
|
|
98
|
+
newBlob: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function parseRawDiff(raw: string): TreeChange[] {
|
|
102
|
+
const fields = raw.split('\0');
|
|
103
|
+
const changes: TreeChange[] = [];
|
|
104
|
+
for (let i = 0; i + 1 < fields.length; i += 2) {
|
|
105
|
+
// ":oldmode newmode oldblob newblob status" then the path
|
|
106
|
+
const [, newMode, oldBlob, newBlob] = fields[i].replace(/^:/, '').split(' ');
|
|
107
|
+
if (!newBlob) continue;
|
|
108
|
+
changes.push({ path: fields[i + 1], oldBlob, newMode, newBlob });
|
|
109
|
+
}
|
|
110
|
+
return changes;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Point the shared index at the committed blobs, so committed files do not show as staged
|
|
115
|
+
* reversals — but only for entries that still hold what the parent commit had. An entry
|
|
116
|
+
* someone staged differently in the meantime is theirs and is left alone, as is everything
|
|
117
|
+
* outside the commit. Retries while another Git process briefly holds index.lock, re-reading
|
|
118
|
+
* the index each time so a `git add` made during the wait is not overwritten.
|
|
119
|
+
*/
|
|
120
|
+
async function syncSharedIndex(
|
|
121
|
+
repoRoot: string,
|
|
122
|
+
contentPath: string,
|
|
123
|
+
changes: TreeChange[],
|
|
124
|
+
): Promise<{ ok: true } | { ok: false; error: string }> {
|
|
125
|
+
if (changes.length === 0) return { ok: true };
|
|
126
|
+
let error = 'git update-index failed';
|
|
127
|
+
for (let attempt = 0; attempt < INDEX_SYNC_ATTEMPTS; attempt += 1) {
|
|
128
|
+
// oxlint-disable-next-line no-await-in-loop -- each retry waits for the lock holder to finish.
|
|
129
|
+
if (attempt > 0) await sleep(attempt * 100);
|
|
130
|
+
// A commit only ever changes paths under contentPath, so one pathspec covers them all
|
|
131
|
+
// without passing each path on the command line.
|
|
132
|
+
// oxlint-disable-next-line no-await-in-loop -- each attempt must see the index as it is now.
|
|
133
|
+
const staged = await runGitCommand(repoRoot, ['ls-files', '-s', '-z', '--', contentPath]);
|
|
134
|
+
const stagedBlob = new Map<string, string>();
|
|
135
|
+
for (const entry of staged.stdout.split('\0')) {
|
|
136
|
+
const tab = entry.indexOf('\t');
|
|
137
|
+
if (tab < 0) continue;
|
|
138
|
+
const [, blob, stage] = entry.slice(0, tab).split(' ');
|
|
139
|
+
if (stage === '0') stagedBlob.set(entry.slice(tab + 1), blob);
|
|
140
|
+
}
|
|
141
|
+
const lines = changes
|
|
142
|
+
.filter((c) => (stagedBlob.get(c.path) ?? '0'.repeat(c.oldBlob.length)) === c.oldBlob)
|
|
143
|
+
.map((c) => (/^0+$/.test(c.newBlob) ? `0 ${c.newBlob}\t${c.path}\0` : `${c.newMode} ${c.newBlob}\t${c.path}\0`));
|
|
144
|
+
if (lines.length === 0) return { ok: true };
|
|
145
|
+
// oxlint-disable-next-line no-await-in-loop -- retries are sequential by design.
|
|
146
|
+
const result = await runGitCommand(repoRoot, ['update-index', '-z', '--index-info'], undefined, lines.join(''));
|
|
147
|
+
if (result.exitCode === 0) return { ok: true };
|
|
148
|
+
error = result.stderr || error;
|
|
149
|
+
}
|
|
150
|
+
return { ok: false, error };
|
|
151
|
+
}
|
|
152
|
+
|
|
82
153
|
/**
|
|
83
154
|
* Resolve the git repository root from a content path.
|
|
84
155
|
* Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.
|
|
@@ -93,6 +164,22 @@ async function resolveRepoRoot(contentPath: string): Promise<string | null> {
|
|
|
93
164
|
return result.stdout;
|
|
94
165
|
}
|
|
95
166
|
|
|
167
|
+
/**
|
|
168
|
+
* Commits and pulls both move HEAD; queueing them per repository keeps one request's commit
|
|
169
|
+
* from landing inside another's. Module-wide and keyed by repo root because the router builds
|
|
170
|
+
* a fresh GitOperations for every request.
|
|
171
|
+
*/
|
|
172
|
+
const headQueues = new Map<string, Promise<unknown>>();
|
|
173
|
+
function serializedOnRepo<T>(repoRoot: string, operation: () => Promise<T>): Promise<T> {
|
|
174
|
+
const run = (headQueues.get(repoRoot) ?? Promise.resolve()).then(operation, operation);
|
|
175
|
+
const settled = run.catch(() => undefined);
|
|
176
|
+
headQueues.set(repoRoot, settled);
|
|
177
|
+
void settled.then(() => {
|
|
178
|
+
if (headQueues.get(repoRoot) === settled) headQueues.delete(repoRoot);
|
|
179
|
+
});
|
|
180
|
+
return run;
|
|
181
|
+
}
|
|
182
|
+
|
|
96
183
|
/**
|
|
97
184
|
* Create git operations using local git CLI commands.
|
|
98
185
|
* Requires git binary available on PATH and CONTENT_PATH inside a git repository.
|
|
@@ -112,6 +199,100 @@ export function createGitOperations(config: GitConfig): GitOperations {
|
|
|
112
199
|
return cachedRepoRoot;
|
|
113
200
|
}
|
|
114
201
|
|
|
202
|
+
async function commitContent(repoRoot: string, message: string, author?: GitAuthor): Promise<GitCommitResult> {
|
|
203
|
+
// Build the commit in a private index seeded from HEAD. The shared index may hold work
|
|
204
|
+
// someone staged outside contentPath; it must neither ride along nor lose its staging.
|
|
205
|
+
// Writing the tree from the private index (not a pathspec commit, which re-reads the
|
|
206
|
+
// working tree) also pins the snapshot `git add` took against content writes meanwhile.
|
|
207
|
+
const indexDir = await mkdtemp(join(tmpdir(), 'conloca-git-index-'));
|
|
208
|
+
const privateIndex = { ...process.env, GIT_INDEX_FILE: join(indexDir, 'index') };
|
|
209
|
+
try {
|
|
210
|
+
const headResult = await runGitCommand(repoRoot, ['rev-parse', '--verify', '--quiet', 'HEAD']);
|
|
211
|
+
const parent = headResult.exitCode === 0 ? headResult.stdout : null;
|
|
212
|
+
const seed = await runGitCommand(
|
|
213
|
+
repoRoot,
|
|
214
|
+
parent ? ['read-tree', parent] : ['read-tree', '--empty'],
|
|
215
|
+
privateIndex,
|
|
216
|
+
);
|
|
217
|
+
if (seed.exitCode !== 0) {
|
|
218
|
+
return { success: false, error: seed.stderr || 'Failed to prepare commit' };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const addResult = await runGitCommand(repoRoot, ['add', '-A', '--', contentPath], privateIndex);
|
|
222
|
+
if (addResult.exitCode !== 0) {
|
|
223
|
+
return { success: false, error: addResult.stderr || 'Failed to stage changes' };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const treeResult = await runGitCommand(repoRoot, ['write-tree'], privateIndex);
|
|
227
|
+
if (treeResult.exitCode !== 0) {
|
|
228
|
+
return { success: false, error: treeResult.stderr || 'Failed to write tree' };
|
|
229
|
+
}
|
|
230
|
+
const tree = treeResult.stdout;
|
|
231
|
+
if (parent && (await runGitCommand(repoRoot, ['rev-parse', `${parent}^{tree}`])).stdout === tree) {
|
|
232
|
+
return { success: false, error: 'No changes to commit' };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// author.name/author.email set only the author; the committer stays the server's identity,
|
|
236
|
+
// as `git commit --author` left it.
|
|
237
|
+
const authorConfig = author ? ['-c', `author.name=${author.name}`, '-c', `author.email=${author.email}`] : [];
|
|
238
|
+
const commitResult = await runGitCommand(repoRoot, [
|
|
239
|
+
...authorConfig,
|
|
240
|
+
'commit-tree',
|
|
241
|
+
tree,
|
|
242
|
+
...(parent ? ['-p', parent] : []),
|
|
243
|
+
'-m',
|
|
244
|
+
message,
|
|
245
|
+
]);
|
|
246
|
+
if (commitResult.exitCode !== 0) {
|
|
247
|
+
return { success: false, error: commitResult.stderr || 'Commit failed' };
|
|
248
|
+
}
|
|
249
|
+
const commitSha = commitResult.stdout;
|
|
250
|
+
|
|
251
|
+
// Move HEAD only if it still points where the tree was built from. A commit another
|
|
252
|
+
// process made meanwhile would otherwise be silently reverted by this stale tree.
|
|
253
|
+
const expected = parent ?? '0'.repeat(commitSha.length);
|
|
254
|
+
const moveHead = await runGitCommand(repoRoot, [
|
|
255
|
+
'update-ref',
|
|
256
|
+
'-m',
|
|
257
|
+
`commit: ${message}`,
|
|
258
|
+
'HEAD',
|
|
259
|
+
commitSha,
|
|
260
|
+
expected,
|
|
261
|
+
]);
|
|
262
|
+
if (moveHead.exitCode !== 0) {
|
|
263
|
+
return { success: false, error: 'The branch moved while committing; nothing was committed. Try again.' };
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Count and sync from the commit just made, never from HEAD, which others may move again.
|
|
267
|
+
const changesResult = await runGitCommand(repoRoot, [
|
|
268
|
+
'diff-tree',
|
|
269
|
+
'-r',
|
|
270
|
+
'-z',
|
|
271
|
+
'--no-renames',
|
|
272
|
+
'--no-commit-id',
|
|
273
|
+
...(parent ? [parent, commitSha] : ['--root', commitSha]),
|
|
274
|
+
]);
|
|
275
|
+
const changes = parseRawDiff(changesResult.stdout);
|
|
276
|
+
|
|
277
|
+
const synced = await syncSharedIndex(repoRoot, contentPath, changes);
|
|
278
|
+
if (!synced.ok) {
|
|
279
|
+
return {
|
|
280
|
+
success: false,
|
|
281
|
+
commit: commitSha,
|
|
282
|
+
error: `Committed ${commitSha}, but the Git index could not be updated for the content folder (${synced.error}). Run \`git reset -- ${contentPath}\` before committing outside the CMS.`,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
return {
|
|
287
|
+
success: true,
|
|
288
|
+
commit: commitSha,
|
|
289
|
+
summary: `${changes.length} files committed`,
|
|
290
|
+
};
|
|
291
|
+
} finally {
|
|
292
|
+
await rm(indexDir, { recursive: true, force: true });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
115
296
|
return {
|
|
116
297
|
async getStatus(): Promise<GitStatus> {
|
|
117
298
|
try {
|
|
@@ -164,43 +345,7 @@ export function createGitOperations(config: GitConfig): GitOperations {
|
|
|
164
345
|
if (!repoRoot) {
|
|
165
346
|
return { success: false, error: 'Not a git repository' };
|
|
166
347
|
}
|
|
167
|
-
|
|
168
|
-
// Stage all changes
|
|
169
|
-
const addResult = await runGitCommand(repoRoot, ['add', '-A', '--', contentPath]);
|
|
170
|
-
if (addResult.exitCode !== 0) {
|
|
171
|
-
return { success: false, error: addResult.stderr || 'Failed to stage changes' };
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// Check if there's anything to commit after staging
|
|
175
|
-
const diffResult = await runGitCommand(repoRoot, ['diff', '--cached', '--quiet', '--', contentPath]);
|
|
176
|
-
if (diffResult.exitCode === 0) {
|
|
177
|
-
return { success: false, error: 'No changes to commit' };
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// Count staged files for summary
|
|
181
|
-
const diffStatResult = await runGitCommand(repoRoot, ['diff', '--cached', '--numstat', '--', contentPath]);
|
|
182
|
-
const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split('\n').filter((l) => l.trim()).length : 0;
|
|
183
|
-
|
|
184
|
-
// Build commit command
|
|
185
|
-
const commitArgs = ['commit', '-m', message];
|
|
186
|
-
if (author) {
|
|
187
|
-
commitArgs.push('--author', `${author.name} <${author.email}>`);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
const commitResult = await runGitCommand(repoRoot, commitArgs);
|
|
191
|
-
if (commitResult.exitCode !== 0) {
|
|
192
|
-
return { success: false, error: commitResult.stderr || 'Commit failed' };
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// Get the commit SHA
|
|
196
|
-
const shaResult = await runGitCommand(repoRoot, ['rev-parse', 'HEAD']);
|
|
197
|
-
const commitSha = shaResult.stdout || undefined;
|
|
198
|
-
|
|
199
|
-
return {
|
|
200
|
-
success: true,
|
|
201
|
-
commit: commitSha,
|
|
202
|
-
summary: `${fileCount} files committed`,
|
|
203
|
-
};
|
|
348
|
+
return await serializedOnRepo(repoRoot, () => commitContent(repoRoot, message, author));
|
|
204
349
|
} catch (error) {
|
|
205
350
|
return {
|
|
206
351
|
success: false,
|
|
@@ -279,7 +424,9 @@ export function createGitOperations(config: GitConfig): GitOperations {
|
|
|
279
424
|
targetBranch = branchResult.stdout;
|
|
280
425
|
}
|
|
281
426
|
|
|
282
|
-
const pullResult = await
|
|
427
|
+
const pullResult = await serializedOnRepo(repoRoot, () =>
|
|
428
|
+
runGitCommand(repoRoot, ['pull', '--autostash', '--rebase', 'origin', targetBranch]),
|
|
429
|
+
);
|
|
283
430
|
|
|
284
431
|
if (pullResult.exitCode !== 0) {
|
|
285
432
|
return {
|
package/src/index.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* For Node.js-specific APIs (filesystem, in-memory, middleware, etc.), import from '@conloca/content-api/node'
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
// The address site and its base path, shared by every host that reads a sites.json.
|
|
9
|
+
export { addressSiteName, isValidSiteBase } from './address-site.js';
|
|
8
10
|
// Upload ceiling + image allowlist. Pure data, no node deps — the source of
|
|
9
11
|
// truth other asset backends read through this entry.
|
|
10
12
|
// DEFAULT_ACCEPTED_FORMATS deliberately stays off the barrel — it is just the map's keys.
|
|
@@ -37,7 +39,23 @@ export type { GitCommitResult, GitPullResult, GitPushResult, GitStatus } from '.
|
|
|
37
39
|
export { pageReferenceOf, pageTimestampsOf, selectPagesByPrefix } from './page-references.js';
|
|
38
40
|
// Reader backend interface types (browser-safe; type-only re-export).
|
|
39
41
|
export type { BackendReadResult, ContentReaderBackend } from './reader-backend.js';
|
|
40
|
-
|
|
42
|
+
// Content metadata shapes. Types only: the generated validators live on the
|
|
43
|
+
// `./schemas` subpath so this browser barrel stays free of the Typia
|
|
44
|
+
// transform's output (and of anything a consumer would tree-shake to avoid it).
|
|
45
|
+
export type {
|
|
46
|
+
DataEditable,
|
|
47
|
+
DataMeta,
|
|
48
|
+
FragmentEditable,
|
|
49
|
+
FragmentMeta,
|
|
50
|
+
LooseDataMeta,
|
|
51
|
+
LooseFragmentMeta,
|
|
52
|
+
LoosePageMeta,
|
|
53
|
+
MdxPageFrontmatter,
|
|
54
|
+
PageEditable,
|
|
55
|
+
PageMeta,
|
|
56
|
+
SchemaIssue,
|
|
57
|
+
SchemaParseResult,
|
|
58
|
+
} from './schemas/types.js';
|
|
41
59
|
export { Site } from './site.js';
|
|
42
60
|
export * from './types.js';
|
|
43
61
|
// SSRF host predicate — pure string/number logic, so any host's import guards can share it.
|
package/src/middleware.ts
CHANGED
|
@@ -560,6 +560,11 @@ export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRout
|
|
|
560
560
|
|
|
561
561
|
const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
|
|
562
562
|
|
|
563
|
+
// A partly finished move answers with the result itself, so the editor learns which
|
|
564
|
+
// assets stayed and can keep exactly those selected for a retry.
|
|
565
|
+
if (!result.success && result.moved) {
|
|
566
|
+
return c.json(result);
|
|
567
|
+
}
|
|
563
568
|
if (!result.success) {
|
|
564
569
|
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
|
|
565
570
|
}
|