@sandboxsonny/ace-kit 0.5.0 → 0.6.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/CHANGELOG.md +6 -0
- package/dist/astro-integration.js +1 -1
- package/dist/chunk-7M26C36M.js +35 -0
- package/dist/cli.js +14 -1179
- package/dist/environment-T5K5ZJ2M.js +222 -0
- package/dist/main-YRQQWLHX.js +1454 -0
- package/dist/vite.js +1 -1
- package/docs/command-line.md +30 -1
- package/docs/getting-started.md +8 -0
- package/package.json +5 -2
- package/templates/astro/.dockerignore +7 -0
- package/templates/astro/.github/dependabot.yml +19 -0
- package/templates/astro/.github/workflows/ci.yml +23 -0
- package/templates/astro/.prettierignore +6 -0
- package/templates/astro/.prettierrc.json +20 -0
- package/templates/astro/.vscode/extensions.json +4 -0
- package/templates/astro/.vscode/launch.json +11 -0
- package/templates/astro/AGENTS.md +22 -0
- package/templates/astro/Dockerfile +17 -0
- package/templates/astro/_gitignore +26 -0
- package/templates/astro/astro.config.mjs +18 -0
- package/templates/astro/eslint.config.js +56 -0
- package/templates/astro/package.json +41 -0
- package/templates/astro/public/favicon.ico +0 -0
- package/templates/astro/public/favicon.svg +9 -0
- package/templates/astro/src/ace-kit.generated.d.ts +24 -0
- package/templates/astro/src/components/PageContent.astro +113 -0
- package/templates/astro/src/components/SiteFooter.astro +19 -0
- package/templates/astro/src/components/SiteHeader.astro +121 -0
- package/templates/astro/src/components/sections/Faq.astro +54 -0
- package/templates/astro/src/components/sections/Faq.schema.ts +17 -0
- package/templates/astro/src/components/sections/Gallery.astro +74 -0
- package/templates/astro/src/components/sections/Gallery.schema.ts +20 -0
- package/templates/astro/src/components/sections/Hero.astro +58 -0
- package/templates/astro/src/components/sections/Hero.schema.ts +14 -0
- package/templates/astro/src/layouts/BaseLayout.astro +36 -0
- package/templates/astro/src/pages/[...slug].astro +31 -0
- package/templates/astro/src/styles/global.css +56 -0
- package/templates/astro/src/types/page.d.ts +4 -0
- package/templates/astro/tsconfig.json +11 -0
- package/templates/astro/vitest.config.ts +4 -0
- package/templates/astro.section-types.json +109 -0
- package/templates/react-router/.prettierignore +5 -0
- package/templates/react-router/.prettierrc.json +11 -0
- package/templates/react-router/_gitignore +7 -0
- package/templates/react-router/app/ace-kit.generated.d.ts +18 -0
- package/templates/react-router/app/app.css +172 -0
- package/templates/react-router/app/components/page-content.tsx +32 -0
- package/templates/react-router/app/components/site-footer.tsx +9 -0
- package/templates/react-router/app/components/site-header.tsx +49 -0
- package/templates/react-router/app/entry.server.tsx +1 -0
- package/templates/react-router/app/root.tsx +75 -0
- package/templates/react-router/app/routes/page.test.tsx +64 -0
- package/templates/react-router/app/routes/page.tsx +22 -0
- package/templates/react-router/app/routes.ts +4 -0
- package/templates/react-router/app/types/page.d.ts +4 -0
- package/templates/react-router/eslint.config.js +76 -0
- package/templates/react-router/package.json +51 -0
- package/templates/react-router/public/favicon.svg +9 -0
- package/templates/react-router/react-router.config.ts +6 -0
- package/templates/react-router/tsconfig.json +22 -0
- package/templates/react-router/vite.config.ts +10 -0
- package/templates/react-router/vitest.config.ts +15 -0
- /package/dist/{chunk-WM5NOQE3.js → chunk-G5FGBOFT.js} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,1184 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
// src/cli/
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
// src/auth/file-store.ts
|
|
9
|
-
import { mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
10
|
-
import { homedir } from "os";
|
|
11
|
-
import { dirname, join } from "path";
|
|
12
|
-
|
|
13
|
-
// src/auth/login-store.ts
|
|
14
|
-
function normaliseApiUrl(address) {
|
|
15
|
-
let parsed;
|
|
16
|
-
try {
|
|
17
|
-
parsed = new URL(address.trim());
|
|
18
|
-
} catch {
|
|
19
|
-
throw new Error(`"${address}" is not a web address. Write the API address like http://localhost:8080.`);
|
|
20
|
-
}
|
|
21
|
-
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
22
|
-
throw new Error(`The API address must start with http:// or https:// (it was "${address}").`);
|
|
23
|
-
}
|
|
24
|
-
if (parsed.username || parsed.password) {
|
|
25
|
-
throw new Error("The API address must not contain a username or password.");
|
|
26
|
-
}
|
|
27
|
-
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
|
|
28
|
-
}
|
|
29
|
-
function hasExpired(login, now) {
|
|
30
|
-
const endsAt = Date.parse(login.expiresAt);
|
|
31
|
-
return Number.isNaN(endsAt) || endsAt <= now;
|
|
32
|
-
}
|
|
33
|
-
function parseStoredLogin(value) {
|
|
34
|
-
if (typeof value !== "object" || value === null) return null;
|
|
35
|
-
const { token, expiresAt, email } = value;
|
|
36
|
-
if (typeof token !== "string" || token === "" || typeof expiresAt !== "string" || typeof email !== "string")
|
|
37
|
-
return null;
|
|
38
|
-
return { token, expiresAt, email };
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// src/auth/file-store.ts
|
|
42
|
-
function defaultLoginFile(variables, platform) {
|
|
43
|
-
if (platform === "win32" && variables.APPDATA) return join(variables.APPDATA, "ace-kit", "credentials.json");
|
|
44
|
-
const configFolder = variables.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
45
|
-
return join(configFolder, "ace-kit", "credentials.json");
|
|
46
|
-
}
|
|
47
|
-
function createFileStore(path) {
|
|
48
|
-
async function readAll() {
|
|
49
|
-
let text;
|
|
50
|
-
try {
|
|
51
|
-
text = await readFile(path, "utf8");
|
|
52
|
-
} catch {
|
|
53
|
-
return {};
|
|
54
|
-
}
|
|
55
|
-
let parsed;
|
|
56
|
-
try {
|
|
57
|
-
parsed = JSON.parse(text);
|
|
58
|
-
} catch {
|
|
59
|
-
return {};
|
|
60
|
-
}
|
|
61
|
-
const found = {};
|
|
62
|
-
if (typeof parsed === "object" && parsed !== null) {
|
|
63
|
-
for (const [address, value] of Object.entries(parsed)) {
|
|
64
|
-
const login = parseStoredLogin(value);
|
|
65
|
-
if (login) found[address] = login;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return found;
|
|
69
|
-
}
|
|
70
|
-
async function writeAll(logins) {
|
|
71
|
-
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
72
|
-
const temporary = `${path}.${process.pid}.tmp`;
|
|
73
|
-
await writeFile(temporary, `${JSON.stringify(logins, null, 2)}
|
|
74
|
-
`, { mode: 384 });
|
|
75
|
-
await rename(temporary, path);
|
|
76
|
-
}
|
|
77
|
-
return {
|
|
78
|
-
description: path,
|
|
79
|
-
async read(apiUrl) {
|
|
80
|
-
return (await readAll())[normaliseApiUrl(apiUrl)] ?? null;
|
|
81
|
-
},
|
|
82
|
-
async write(apiUrl, login) {
|
|
83
|
-
const logins = await readAll();
|
|
84
|
-
logins[normaliseApiUrl(apiUrl)] = login;
|
|
85
|
-
await writeAll(logins);
|
|
86
|
-
},
|
|
87
|
-
async remove(apiUrl) {
|
|
88
|
-
const logins = await readAll();
|
|
89
|
-
delete logins[normaliseApiUrl(apiUrl)];
|
|
90
|
-
await writeAll(logins);
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// src/auth/keychain-store.ts
|
|
96
|
-
var keychainService = "ace-kit";
|
|
97
|
-
function createKeychainStore(run) {
|
|
98
|
-
async function read(apiUrl) {
|
|
99
|
-
const found = await run("security", [
|
|
100
|
-
"find-generic-password",
|
|
101
|
-
"-s",
|
|
102
|
-
keychainService,
|
|
103
|
-
"-a",
|
|
104
|
-
normaliseApiUrl(apiUrl),
|
|
105
|
-
"-w"
|
|
106
|
-
]);
|
|
107
|
-
if (found.exitCode !== 0) return null;
|
|
108
|
-
try {
|
|
109
|
-
return parseStoredLogin(JSON.parse(Buffer.from(found.stdout.trim(), "base64").toString("utf8")));
|
|
110
|
-
} catch {
|
|
111
|
-
return null;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
return {
|
|
115
|
-
description: "the macOS Keychain",
|
|
116
|
-
read,
|
|
117
|
-
async write(apiUrl, login) {
|
|
118
|
-
const account = normaliseApiUrl(apiUrl);
|
|
119
|
-
if (/["\\\s]/.test(account)) throw new Error("That API address can't be kept in the Keychain.");
|
|
120
|
-
const secret = Buffer.from(JSON.stringify(login), "utf8").toString("base64");
|
|
121
|
-
await run(
|
|
122
|
-
"security",
|
|
123
|
-
["-i"],
|
|
124
|
-
`add-generic-password -s "${keychainService}" -a "${account}" -l "Ace Kit login" -w "${secret}" -U
|
|
125
|
-
`
|
|
126
|
-
);
|
|
127
|
-
const kept = await read(apiUrl);
|
|
128
|
-
if (kept?.token !== login.token) throw new Error("The login could not be saved in the macOS Keychain.");
|
|
129
|
-
},
|
|
130
|
-
async remove(apiUrl) {
|
|
131
|
-
await run("security", ["delete-generic-password", "-s", keychainService, "-a", normaliseApiUrl(apiUrl)]);
|
|
132
|
-
}
|
|
133
|
-
};
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
// src/auth/choose-store.ts
|
|
137
|
-
async function chooseLoginStore(options) {
|
|
138
|
-
const file = createFileStore(defaultLoginFile(options.variables, options.platform));
|
|
139
|
-
if (options.platform !== "darwin" || options.variables.ACE_KIT_CREDENTIALS === "file") return file;
|
|
140
|
-
try {
|
|
141
|
-
await options.run("security", ["help"]);
|
|
142
|
-
return createKeychainStore(options.run);
|
|
143
|
-
} catch {
|
|
144
|
-
return file;
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// src/auth/last-api-url.ts
|
|
149
|
-
import { mkdir as mkdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "fs/promises";
|
|
150
|
-
import { dirname as dirname2, join as join2 } from "path";
|
|
151
|
-
function defaultLastApiUrlFile(variables, platform) {
|
|
152
|
-
return join2(dirname2(defaultLoginFile(variables, platform)), "last-api-url");
|
|
153
|
-
}
|
|
154
|
-
function createLastApiUrl(path) {
|
|
155
|
-
return {
|
|
156
|
-
async read() {
|
|
157
|
-
try {
|
|
158
|
-
return normaliseApiUrl((await readFile2(path, "utf8")).trim());
|
|
159
|
-
} catch {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
},
|
|
163
|
-
async write(apiUrl) {
|
|
164
|
-
await mkdir2(dirname2(path), { recursive: true, mode: 448 });
|
|
165
|
-
const temporary = `${path}.${process.pid}.tmp`;
|
|
166
|
-
await writeFile2(temporary, `${normaliseApiUrl(apiUrl)}
|
|
167
|
-
`, { mode: 384 });
|
|
168
|
-
await rename2(temporary, path);
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// src/cli/version.ts
|
|
174
|
-
var aceKitVersion = true ? "0.5.0" : "development";
|
|
175
|
-
|
|
176
|
-
// src/cli/environment.ts
|
|
177
|
-
var runCommand = (command, commandArguments, input) => new Promise((resolve2, reject) => {
|
|
178
|
-
const child = spawn(command, commandArguments, { stdio: ["pipe", "pipe", "ignore"] });
|
|
179
|
-
let stdout = "";
|
|
180
|
-
child.stdout.on("data", (chunk) => {
|
|
181
|
-
stdout += chunk.toString("utf8");
|
|
182
|
-
});
|
|
183
|
-
child.on("error", reject);
|
|
184
|
-
child.on("close", (exitCode) => resolve2({ exitCode: exitCode ?? 1, stdout }));
|
|
185
|
-
child.stdin.on("error", () => {
|
|
186
|
-
});
|
|
187
|
-
child.stdin.end(input ?? "");
|
|
188
|
-
});
|
|
189
|
-
function browserCommand(platform, address) {
|
|
190
|
-
if (platform === "darwin") return { command: "open", commandArguments: [address] };
|
|
191
|
-
if (platform === "win32") return { command: "rundll32", commandArguments: ["url.dll,FileProtocolHandler", address] };
|
|
192
|
-
return { command: "xdg-open", commandArguments: [address] };
|
|
193
|
-
}
|
|
194
|
-
async function openBrowser(platform, address) {
|
|
195
|
-
const { command, commandArguments } = browserCommand(platform, address);
|
|
196
|
-
await new Promise((resolve2) => {
|
|
197
|
-
const child = spawn(command, commandArguments, { stdio: "ignore", detached: true });
|
|
198
|
-
child.on("error", () => resolve2());
|
|
199
|
-
child.on("spawn", () => {
|
|
200
|
-
child.unref();
|
|
201
|
-
resolve2();
|
|
202
|
-
});
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
async function importModule(path) {
|
|
206
|
-
try {
|
|
207
|
-
return await import(pathToFileURL(path).href);
|
|
208
|
-
} catch (error) {
|
|
209
|
-
if (error.code === "ERR_UNKNOWN_FILE_EXTENSION") {
|
|
210
|
-
throw new Error(
|
|
211
|
-
"this version of Node can't run TypeScript files. Use Node 22.18 or newer, or write the schema in .js.",
|
|
212
|
-
{ cause: error }
|
|
213
|
-
);
|
|
214
|
-
}
|
|
215
|
-
throw error;
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
async function createRealEnvironment() {
|
|
219
|
-
try {
|
|
220
|
-
process.loadEnvFile(".env");
|
|
221
|
-
} catch {
|
|
222
|
-
}
|
|
223
|
-
const variables = { ...process.env };
|
|
224
|
-
const platform = process.platform;
|
|
225
|
-
return {
|
|
226
|
-
variables,
|
|
227
|
-
platform,
|
|
228
|
-
hostname: hostname(),
|
|
229
|
-
version: aceKitVersion,
|
|
230
|
-
out: (text) => process.stdout.write(`${text}
|
|
231
|
-
`),
|
|
232
|
-
error: (text) => console.error(text),
|
|
233
|
-
fetchImplementation: (input, init) => fetch(input, init),
|
|
234
|
-
sleep: (milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)),
|
|
235
|
-
now: Date.now,
|
|
236
|
-
workingDirectory: process.cwd(),
|
|
237
|
-
importModule,
|
|
238
|
-
openBrowser: (address) => openBrowser(platform, address),
|
|
239
|
-
store: await chooseLoginStore({ platform, variables, run: runCommand }),
|
|
240
|
-
lastApiUrl: createLastApiUrl(defaultLastApiUrlFile(variables, platform))
|
|
241
|
-
};
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
// src/cli/generate-command.ts
|
|
245
|
-
import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
|
|
246
|
-
import { dirname as dirname3, resolve } from "path";
|
|
247
|
-
import { parseArgs } from "util";
|
|
248
|
-
|
|
249
|
-
// src/client/errors.ts
|
|
250
|
-
var AcePreviewExpiredError = class extends Error {
|
|
251
|
-
constructor() {
|
|
252
|
-
super("The preview link has expired.");
|
|
253
|
-
this.name = "AcePreviewExpiredError";
|
|
254
|
-
}
|
|
255
|
-
};
|
|
256
|
-
var AceUnavailableError = class extends Error {
|
|
257
|
-
constructor(message) {
|
|
258
|
-
super(message);
|
|
259
|
-
this.name = "AceUnavailableError";
|
|
260
|
-
}
|
|
261
|
-
};
|
|
262
|
-
|
|
263
|
-
// src/client/create-client.ts
|
|
264
|
-
var requestTimeoutMilliseconds = 5e3;
|
|
265
|
-
var maximumCachedAnswers = 500;
|
|
266
|
-
function createAceClient({
|
|
267
|
-
apiUrl,
|
|
268
|
-
siteDomain,
|
|
269
|
-
cacheSeconds = 5,
|
|
270
|
-
fetchImplementation = (input, init) => fetch(input, init),
|
|
271
|
-
now = Date.now
|
|
272
|
-
}) {
|
|
273
|
-
const cache = /* @__PURE__ */ new Map();
|
|
274
|
-
function forgetSomeAnswers() {
|
|
275
|
-
for (const [path, answer] of cache) if (answer.expiresAt <= now()) cache.delete(path);
|
|
276
|
-
for (const path of cache.keys()) {
|
|
277
|
-
if (cache.size < maximumCachedAnswers) break;
|
|
278
|
-
cache.delete(path);
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
async function get(path, options = { cached: true }) {
|
|
282
|
-
const cached = options.cached ? cache.get(path) : void 0;
|
|
283
|
-
if (cached && cached.expiresAt > now()) return cached.value;
|
|
284
|
-
let response;
|
|
285
|
-
try {
|
|
286
|
-
response = await fetchImplementation(`${apiUrl.replace(/\/+$/, "")}${path}`, {
|
|
287
|
-
headers: { Accept: "application/json", "X-Ace-Site-Domain": siteDomain, "X-Forwarded-Host": siteDomain },
|
|
288
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds)
|
|
289
|
-
});
|
|
290
|
-
} catch {
|
|
291
|
-
throw new AceUnavailableError("Could not reach the CMS.");
|
|
292
|
-
}
|
|
293
|
-
let value = null;
|
|
294
|
-
if (response.status === 404) {
|
|
295
|
-
const reply = await response.json().catch(() => ({}));
|
|
296
|
-
if (reply.error === "no site for this domain") {
|
|
297
|
-
throw new AceUnavailableError(`The CMS has no site with the domain "${siteDomain}".`);
|
|
298
|
-
}
|
|
299
|
-
} else if (response.status === 403 && !options.cached) {
|
|
300
|
-
throw new AcePreviewExpiredError();
|
|
301
|
-
} else if (response.ok) {
|
|
302
|
-
value = await response.json().catch(() => {
|
|
303
|
-
throw new AceUnavailableError("The CMS sent a reply that could not be read.");
|
|
304
|
-
});
|
|
305
|
-
} else {
|
|
306
|
-
throw new AceUnavailableError(`The CMS answered with an error (${response.status}).`);
|
|
307
|
-
}
|
|
308
|
-
if (options.cached && cacheSeconds > 0) {
|
|
309
|
-
if (cache.size >= maximumCachedAnswers) forgetSomeAnswers();
|
|
310
|
-
cache.set(path, { expiresAt: now() + cacheSeconds * 1e3, value });
|
|
311
|
-
}
|
|
312
|
-
return value;
|
|
313
|
-
}
|
|
314
|
-
return {
|
|
315
|
-
/**
|
|
316
|
-
* One live entry of a content type, by its handle; null if the site has no such entry. With a preview token the
|
|
317
|
-
* entry the token was made for comes back with its draft applied (never cached); a token that has run out throws
|
|
318
|
-
* AcePreviewExpiredError.
|
|
319
|
-
*/
|
|
320
|
-
async getEntry(contentTypeHandle, handle, options = {}) {
|
|
321
|
-
const path = `/public/entries/${encodeURIComponent(handle)}`;
|
|
322
|
-
const entry = options.previewToken ? await get(`${path}?preview=${encodeURIComponent(options.previewToken)}`, {
|
|
323
|
-
cached: false
|
|
324
|
-
}) : await get(path);
|
|
325
|
-
return entry && entry.content_type_handle === contentTypeHandle ? entry : null;
|
|
326
|
-
},
|
|
327
|
-
/** The live entries of a content type, newest first. */
|
|
328
|
-
async getEntries(contentTypeHandle, options = {}) {
|
|
329
|
-
const query = new URLSearchParams({ content_type: contentTypeHandle });
|
|
330
|
-
if (options.limit) query.set("limit", String(options.limit));
|
|
331
|
-
return await get(`/public/entries?${query}`) ?? [];
|
|
332
|
-
},
|
|
333
|
-
/** One of the site's navigation menus by its handle, with every link worked out; null if the site has none. */
|
|
334
|
-
getMenu(handle) {
|
|
335
|
-
return get(`/public/menus/${encodeURIComponent(handle)}`);
|
|
336
|
-
},
|
|
337
|
-
/** What the site's content types and fields are, which is what type generation reads. */
|
|
338
|
-
async getContentTypes() {
|
|
339
|
-
return await get("/public/content-types") ?? [];
|
|
340
|
-
}
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
// src/helpers/generate-types.ts
|
|
345
|
-
var quote = (text) => JSON.stringify(text);
|
|
346
|
-
function typeOfField(field) {
|
|
347
|
-
switch (field.component_key) {
|
|
348
|
-
case "text":
|
|
349
|
-
case "textarea":
|
|
350
|
-
return { type: "string" };
|
|
351
|
-
case "number":
|
|
352
|
-
return { type: "number" };
|
|
353
|
-
case "checkbox":
|
|
354
|
-
return { type: "boolean" };
|
|
355
|
-
case "select": {
|
|
356
|
-
const options = field.config?.options ?? [];
|
|
357
|
-
return { type: options.length > 0 ? options.map(quote).join(" | ") : "string" };
|
|
358
|
-
}
|
|
359
|
-
case "image":
|
|
360
|
-
return { type: "AceImageData", uses: "AceImageData" };
|
|
361
|
-
case "richtext":
|
|
362
|
-
return { type: "AceRichTextDocument", uses: "AceRichTextDocument" };
|
|
363
|
-
case "date":
|
|
364
|
-
return { type: "string" };
|
|
365
|
-
case "link":
|
|
366
|
-
return { type: "AceLinkData", uses: "AceLinkData" };
|
|
367
|
-
case "sections":
|
|
368
|
-
return { type: "AceSection[]", uses: "AceSection" };
|
|
369
|
-
default:
|
|
370
|
-
return { type: "unknown" };
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
function generateTypes(contentTypes, packageName2, source) {
|
|
374
|
-
const used = /* @__PURE__ */ new Set();
|
|
375
|
-
const blocks = contentTypes.map((contentType) => {
|
|
376
|
-
const lines = contentType.fields.map((field) => {
|
|
377
|
-
const { type, uses } = typeOfField(field);
|
|
378
|
-
if (uses) used.add(uses);
|
|
379
|
-
const optional = field.config?.required === true ? "" : "?";
|
|
380
|
-
return ` /** ${field.label.replace(/\*\//g, "* /")} */
|
|
381
|
-
${quote(field.handle)}${optional}: ${type};`;
|
|
382
|
-
});
|
|
383
|
-
const body = lines.length > 0 ? `{
|
|
384
|
-
${lines.join("\n")}
|
|
385
|
-
}` : "Record<string, never>";
|
|
386
|
-
return ` /** ${contentType.name.replace(/\*\//g, "* /")} */
|
|
387
|
-
${quote(contentType.handle)}: ${body};`;
|
|
388
|
-
});
|
|
389
|
-
const imports = used.size > 0 ? `import type { ${[...used].sort().join(", ")} } from ${quote(packageName2)};
|
|
390
|
-
|
|
391
|
-
` : "";
|
|
392
|
-
return `// Generated by ace-kit from ${source}. Do not edit: run \`ace-kit generate\` to update it.
|
|
393
|
-
${imports}declare module ${quote(packageName2)} {
|
|
394
|
-
interface AceContentTypes {
|
|
395
|
-
${blocks.join("\n")}
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
export {};
|
|
400
|
-
`;
|
|
401
|
-
}
|
|
402
|
-
|
|
403
|
-
// src/helpers/package-name.ts
|
|
404
|
-
var packageName = "@sandboxsonny/ace-kit";
|
|
405
|
-
|
|
406
|
-
// src/helpers/platform.ts
|
|
407
|
-
var hostedApiUrl = "https://api.ace-cms.co.uk";
|
|
408
|
-
function domainFromSite(site) {
|
|
409
|
-
const trimmed = site.trim();
|
|
410
|
-
if (trimmed.includes("://")) {
|
|
411
|
-
try {
|
|
412
|
-
return new URL(trimmed).hostname.toLowerCase();
|
|
413
|
-
} catch {
|
|
414
|
-
return trimmed.toLowerCase();
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return trimmed.replace(/\/.*$/, "").replace(/:\d+$/, "").toLowerCase();
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// src/cli/generate-command.ts
|
|
421
|
-
var generateUsage = `ace-kit generate: write TypeScript types for your CMS Ace content types.
|
|
422
|
-
|
|
423
|
-
Usage:
|
|
424
|
-
ace-kit generate [--site <domain>] [--api-url <address>] [--out <file>]
|
|
425
|
-
|
|
426
|
-
Options:
|
|
427
|
-
--site The domain your site has in the CMS, e.g. example.com (or set ACE_SITE_DOMAIN). --domain means the same.
|
|
428
|
-
--api-url Where the CMS Ace API lives (or set ACE_API_URL). Only for a CMS on your own machine.
|
|
429
|
-
--out Where to write the types (default: src/ace-kit.generated.d.ts).
|
|
430
|
-
--help Show this message.
|
|
431
|
-
`;
|
|
432
|
-
async function generateCommand(commandArguments, environment) {
|
|
433
|
-
const { values } = parseArgs({
|
|
434
|
-
// eslint-disable-next-line id-denylist -- "args" is the name node's parseArgs gives this option.
|
|
435
|
-
args: commandArguments,
|
|
436
|
-
options: {
|
|
437
|
-
"api-url": { type: "string" },
|
|
438
|
-
site: { type: "string" },
|
|
439
|
-
domain: { type: "string" },
|
|
440
|
-
out: { type: "string" },
|
|
441
|
-
help: { type: "boolean" }
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
if (values.help) {
|
|
445
|
-
environment.out(generateUsage);
|
|
446
|
-
return 0;
|
|
447
|
-
}
|
|
448
|
-
const apiUrl = values["api-url"] ?? environment.variables.ACE_API_URL ?? hostedApiUrl;
|
|
449
|
-
const given = values.site ?? values.domain ?? environment.variables.ACE_SITE_DOMAIN;
|
|
450
|
-
if (!given) {
|
|
451
|
-
environment.error("Give the site's domain: --site, or ACE_SITE_DOMAIN.");
|
|
452
|
-
return 1;
|
|
453
|
-
}
|
|
454
|
-
const siteDomain = domainFromSite(given);
|
|
455
|
-
const client = createAceClient({
|
|
456
|
-
apiUrl,
|
|
457
|
-
siteDomain,
|
|
458
|
-
cacheSeconds: 0,
|
|
459
|
-
fetchImplementation: environment.fetchImplementation
|
|
460
|
-
});
|
|
461
|
-
const contentTypes = await client.getContentTypes();
|
|
462
|
-
const file = resolve(values.out ?? "src/ace-kit.generated.d.ts");
|
|
463
|
-
await mkdir3(dirname3(file), { recursive: true });
|
|
464
|
-
await writeFile3(file, generateTypes(contentTypes, packageName, siteDomain));
|
|
465
|
-
environment.out(
|
|
466
|
-
`Wrote types for ${contentTypes.length} content type${contentTypes.length === 1 ? "" : "s"} to ${file}.`
|
|
467
|
-
);
|
|
468
|
-
return 0;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// src/cli/login-commands.ts
|
|
472
|
-
import { parseArgs as parseArgs2 } from "util";
|
|
473
|
-
|
|
474
|
-
// src/auth/device-login.ts
|
|
475
|
-
var DeviceLoginError = class extends Error {
|
|
476
|
-
reason;
|
|
477
|
-
constructor(reason, message) {
|
|
478
|
-
super(message);
|
|
479
|
-
this.name = "DeviceLoginError";
|
|
480
|
-
this.reason = reason;
|
|
481
|
-
}
|
|
482
|
-
};
|
|
483
|
-
var requestTimeoutMilliseconds2 = 15e3;
|
|
484
|
-
var maximumFailures = 5;
|
|
485
|
-
async function post(dependencies, apiUrl, path, body) {
|
|
486
|
-
return dependencies.fetchImplementation(`${apiUrl}${path}`, {
|
|
487
|
-
method: "POST",
|
|
488
|
-
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
|
489
|
-
body: JSON.stringify(body),
|
|
490
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds2)
|
|
491
|
-
});
|
|
492
|
-
}
|
|
493
|
-
async function readMessage(response) {
|
|
494
|
-
try {
|
|
495
|
-
const body = await response.json();
|
|
496
|
-
if (typeof body.error === "string") return body.error;
|
|
497
|
-
} catch {
|
|
498
|
-
}
|
|
499
|
-
return `The CMS answered with an error (${response.status}).`;
|
|
500
|
-
}
|
|
501
|
-
async function startDeviceLogin(dependencies) {
|
|
502
|
-
let response;
|
|
503
|
-
try {
|
|
504
|
-
response = await post(dependencies, dependencies.apiUrl, "/auth/device", { client_name: dependencies.clientName });
|
|
505
|
-
} catch {
|
|
506
|
-
throw new DeviceLoginError("unavailable", `Could not reach the CMS at ${dependencies.apiUrl}.`);
|
|
507
|
-
}
|
|
508
|
-
if (response.status === 503) throw new DeviceLoginError("unsupported", await readMessage(response));
|
|
509
|
-
if (response.status === 429)
|
|
510
|
-
throw new DeviceLoginError("unavailable", "Too many attempts. Wait a minute and try again.");
|
|
511
|
-
if (response.status === 404) {
|
|
512
|
-
throw new DeviceLoginError(
|
|
513
|
-
"unsupported",
|
|
514
|
-
`${dependencies.apiUrl} does not offer command-line sign-in. Is it a CMS Ace API, and is it up to date?`
|
|
515
|
-
);
|
|
516
|
-
}
|
|
517
|
-
if (!response.ok) throw new DeviceLoginError("unavailable", await readMessage(response));
|
|
518
|
-
const body = await response.json().catch(() => null);
|
|
519
|
-
const { device_code, user_code, verification_uri, expires_in, interval } = body ?? {};
|
|
520
|
-
if (typeof device_code !== "string" || typeof user_code !== "string" || typeof verification_uri !== "string" || typeof expires_in !== "number" || typeof interval !== "number") {
|
|
521
|
-
throw new DeviceLoginError(
|
|
522
|
-
"unavailable",
|
|
523
|
-
"The CMS sent a reply this version of ace-kit can't read. Update ace-kit."
|
|
524
|
-
);
|
|
525
|
-
}
|
|
526
|
-
return {
|
|
527
|
-
deviceCode: device_code,
|
|
528
|
-
userCode: user_code,
|
|
529
|
-
verificationUri: verification_uri,
|
|
530
|
-
expiresInSeconds: expires_in,
|
|
531
|
-
intervalSeconds: Math.max(1, interval)
|
|
532
|
-
};
|
|
533
|
-
}
|
|
534
|
-
async function waitForApproval(dependencies) {
|
|
535
|
-
const { apiUrl, request, sleep, now } = dependencies;
|
|
536
|
-
const deadline = now() + request.expiresInSeconds * 1e3;
|
|
537
|
-
let intervalSeconds = request.intervalSeconds;
|
|
538
|
-
let failures = 0;
|
|
539
|
-
for (; ; ) {
|
|
540
|
-
await sleep(intervalSeconds * 1e3);
|
|
541
|
-
if (now() > deadline)
|
|
542
|
-
throw new DeviceLoginError("expired", "The code ran out before it was approved. Run ace-kit login again.");
|
|
543
|
-
let response;
|
|
544
|
-
try {
|
|
545
|
-
response = await post(dependencies, apiUrl, "/auth/device/token", { device_code: request.deviceCode });
|
|
546
|
-
} catch {
|
|
547
|
-
failures += 1;
|
|
548
|
-
if (failures >= maximumFailures)
|
|
549
|
-
throw new DeviceLoginError("unavailable", `Lost contact with the CMS at ${apiUrl}.`);
|
|
550
|
-
continue;
|
|
551
|
-
}
|
|
552
|
-
if (response.status === 404) {
|
|
553
|
-
throw new DeviceLoginError("expired", "The CMS no longer knows this login. Run ace-kit login again.");
|
|
554
|
-
}
|
|
555
|
-
if (response.status === 429) {
|
|
556
|
-
intervalSeconds += 5;
|
|
557
|
-
continue;
|
|
558
|
-
}
|
|
559
|
-
if (!response.ok) {
|
|
560
|
-
failures += 1;
|
|
561
|
-
if (failures >= maximumFailures) throw new DeviceLoginError("unavailable", await readMessage(response));
|
|
562
|
-
continue;
|
|
563
|
-
}
|
|
564
|
-
failures = 0;
|
|
565
|
-
const body = await response.json().catch(() => null);
|
|
566
|
-
switch (body?.status) {
|
|
567
|
-
case "pending":
|
|
568
|
-
continue;
|
|
569
|
-
case "slow_down":
|
|
570
|
-
intervalSeconds += 5;
|
|
571
|
-
continue;
|
|
572
|
-
case "denied":
|
|
573
|
-
throw new DeviceLoginError("denied", "The login was turned down in the admin app.");
|
|
574
|
-
case "expired":
|
|
575
|
-
throw new DeviceLoginError("expired", "The code ran out before it was approved. Run ace-kit login again.");
|
|
576
|
-
case "approved": {
|
|
577
|
-
const user = body.user;
|
|
578
|
-
if (typeof body.token !== "string" || typeof body.expires_at !== "string" || typeof user?.email !== "string") {
|
|
579
|
-
throw new DeviceLoginError("unavailable", "The CMS approved the login but sent a reply that can't be read.");
|
|
580
|
-
}
|
|
581
|
-
return { token: body.token, expiresAt: body.expires_at, email: user.email };
|
|
582
|
-
}
|
|
583
|
-
default:
|
|
584
|
-
throw new DeviceLoginError(
|
|
585
|
-
"unavailable",
|
|
586
|
-
"The CMS sent a reply this version of ace-kit can't read. Update ace-kit."
|
|
587
|
-
);
|
|
588
|
-
}
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
// src/auth/resolve-login.ts
|
|
593
|
-
async function resolveLogin(options) {
|
|
594
|
-
const fromEnvironment = options.variables.ACE_TOKEN?.trim();
|
|
595
|
-
if (fromEnvironment) return { token: fromEnvironment, source: "the ACE_TOKEN setting" };
|
|
596
|
-
const stored = await options.store.read(options.apiUrl);
|
|
597
|
-
if (!stored || hasExpired(stored, options.now())) return null;
|
|
598
|
-
return { token: stored.token, email: stored.email, source: options.store.description };
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// src/cli/api-url.ts
|
|
602
|
-
async function resolveApiUrl(fromOption, environment) {
|
|
603
|
-
const address = fromOption ?? environment.variables.ACE_API_URL ?? await environment.lastApiUrl.read() ?? hostedApiUrl;
|
|
604
|
-
try {
|
|
605
|
-
return normaliseApiUrl(address);
|
|
606
|
-
} catch (error) {
|
|
607
|
-
environment.error(error instanceof Error ? error.message : String(error));
|
|
608
|
-
return null;
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
function isLocalApiUrl(apiUrl) {
|
|
612
|
-
return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(apiUrl).hostname);
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
// src/cli/login-commands.ts
|
|
616
|
-
var loginUsage = `ace-kit login: sign in to CMS Ace from the command line.
|
|
617
|
-
|
|
618
|
-
Usage:
|
|
619
|
-
ace-kit login [--api-url <address>] Sign in. Opens the admin app, where you type the code shown here.
|
|
620
|
-
ace-kit logout [--api-url <address>] Sign out, and forget the login kept on this machine.
|
|
621
|
-
ace-kit whoami [--api-url <address>] Say who you are signed in as.
|
|
622
|
-
|
|
623
|
-
Options:
|
|
624
|
-
--api-url Where the CMS Ace API lives (or set ACE_API_URL, in the environment or a .env file).
|
|
625
|
-
--help Show this message.
|
|
626
|
-
|
|
627
|
-
The login is kept in the macOS Keychain, or in a file only you can read on other systems. On a build server,
|
|
628
|
-
where nobody can approve a login in a browser, set ACE_TOKEN instead.
|
|
629
|
-
`;
|
|
630
|
-
var requestTimeoutMilliseconds3 = 15e3;
|
|
631
|
-
async function readApiUrl(commandArguments, environment) {
|
|
632
|
-
const { values } = parseArgs2({
|
|
633
|
-
// eslint-disable-next-line id-denylist -- "args" is the name node's parseArgs gives this option.
|
|
634
|
-
args: commandArguments,
|
|
635
|
-
options: { "api-url": { type: "string" }, help: { type: "boolean" } }
|
|
636
|
-
});
|
|
637
|
-
if (values.help) return { help: true };
|
|
638
|
-
const apiUrl = await resolveApiUrl(values["api-url"], environment);
|
|
639
|
-
return apiUrl === null ? null : { apiUrl };
|
|
640
|
-
}
|
|
641
|
-
function webAddress(address) {
|
|
642
|
-
try {
|
|
643
|
-
const parsed = new URL(address);
|
|
644
|
-
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.href : null;
|
|
645
|
-
} catch {
|
|
646
|
-
return null;
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
async function loginCommand(commandArguments, environment) {
|
|
650
|
-
const read = await readApiUrl(commandArguments, environment);
|
|
651
|
-
if (!read) return 1;
|
|
652
|
-
if ("help" in read) {
|
|
653
|
-
environment.out(loginUsage);
|
|
654
|
-
return 0;
|
|
655
|
-
}
|
|
656
|
-
const { apiUrl } = read;
|
|
657
|
-
if (apiUrl.startsWith("http://") && !isLocalApiUrl(apiUrl)) {
|
|
658
|
-
environment.error(
|
|
659
|
-
`Warning: ${apiUrl} is not encrypted (http://), so the login could be read on the way. Use https:// if you can.`
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
|
-
try {
|
|
663
|
-
const request = await startDeviceLogin({
|
|
664
|
-
fetchImplementation: environment.fetchImplementation,
|
|
665
|
-
apiUrl,
|
|
666
|
-
clientName: `ace-kit ${environment.version} on ${environment.hostname}`
|
|
667
|
-
});
|
|
668
|
-
const page = webAddress(request.verificationUri);
|
|
669
|
-
if (!page)
|
|
670
|
-
throw new DeviceLoginError(
|
|
671
|
-
"unsupported",
|
|
672
|
-
"The CMS sent an approval address that isn't a web address, so it was not opened."
|
|
673
|
-
);
|
|
674
|
-
environment.out(`Signing in to ${apiUrl}
|
|
675
|
-
`);
|
|
676
|
-
environment.out(` 1. Go to ${page}`);
|
|
677
|
-
environment.out(` 2. Type ${request.userCode}
|
|
678
|
-
`);
|
|
679
|
-
environment.out("Check the code on that page matches. Waiting for you to approve it (Ctrl-C to cancel)...");
|
|
680
|
-
await environment.openBrowser(page).catch(() => void 0);
|
|
681
|
-
const login = await waitForApproval({
|
|
682
|
-
fetchImplementation: environment.fetchImplementation,
|
|
683
|
-
apiUrl,
|
|
684
|
-
request,
|
|
685
|
-
sleep: environment.sleep,
|
|
686
|
-
now: environment.now
|
|
687
|
-
});
|
|
688
|
-
await environment.store.write(apiUrl, login);
|
|
689
|
-
await environment.lastApiUrl.write(apiUrl).catch(() => void 0);
|
|
690
|
-
environment.out(`
|
|
691
|
-
Signed in as ${login.email}. The login is kept in ${environment.store.description}.`);
|
|
692
|
-
return 0;
|
|
693
|
-
} catch (error) {
|
|
694
|
-
environment.error(`
|
|
695
|
-
${error instanceof Error ? error.message : String(error)}`);
|
|
696
|
-
return 1;
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
async function logoutCommand(commandArguments, environment) {
|
|
700
|
-
const read = await readApiUrl(commandArguments, environment);
|
|
701
|
-
if (!read) return 1;
|
|
702
|
-
if ("help" in read) {
|
|
703
|
-
environment.out(loginUsage);
|
|
704
|
-
return 0;
|
|
705
|
-
}
|
|
706
|
-
const { apiUrl } = read;
|
|
707
|
-
const stored = await environment.store.read(apiUrl);
|
|
708
|
-
if (!stored) {
|
|
709
|
-
environment.out(`Not signed in to ${apiUrl}.`);
|
|
710
|
-
return 0;
|
|
711
|
-
}
|
|
712
|
-
const ended = await environment.fetchImplementation(`${apiUrl}/auth/logout`, {
|
|
713
|
-
method: "POST",
|
|
714
|
-
headers: { Authorization: `Bearer ${stored.token}` },
|
|
715
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds3)
|
|
716
|
-
}).then(
|
|
717
|
-
(response) => response.ok || response.status === 401,
|
|
718
|
-
() => false
|
|
719
|
-
);
|
|
720
|
-
await environment.store.remove(apiUrl);
|
|
721
|
-
environment.out(
|
|
722
|
-
ended ? `Signed out of ${apiUrl}.` : `Forgot the login for ${apiUrl} on this machine, but could not reach the CMS to end it there. It ends by itself after 30 days unused; a super admin can also end it from the Sessions screen.`
|
|
3
|
+
// src/cli/bin.ts
|
|
4
|
+
var [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
5
|
+
if (major < 22 || major === 22 && minor < 12) {
|
|
6
|
+
console.error(
|
|
7
|
+
`ace-kit needs Node 22.12 or newer, and this is Node ${process.versions.node}. If you use a version manager (mise, nvm, fnm), check which version it picks in this folder.`
|
|
723
8
|
);
|
|
724
|
-
|
|
725
|
-
}
|
|
726
|
-
async function whoamiCommand(commandArguments, environment) {
|
|
727
|
-
const read = await readApiUrl(commandArguments, environment);
|
|
728
|
-
if (!read) return 1;
|
|
729
|
-
if ("help" in read) {
|
|
730
|
-
environment.out(loginUsage);
|
|
731
|
-
return 0;
|
|
732
|
-
}
|
|
733
|
-
const { apiUrl } = read;
|
|
734
|
-
const login = await resolveLogin({
|
|
735
|
-
apiUrl,
|
|
736
|
-
variables: environment.variables,
|
|
737
|
-
store: environment.store,
|
|
738
|
-
now: environment.now
|
|
739
|
-
});
|
|
740
|
-
if (!login) {
|
|
741
|
-
environment.out(`Not signed in to ${apiUrl}. Run: ace-kit login`);
|
|
742
|
-
return 1;
|
|
743
|
-
}
|
|
744
|
-
try {
|
|
745
|
-
const response = await environment.fetchImplementation(`${apiUrl}/auth/me`, {
|
|
746
|
-
headers: { Accept: "application/json", Authorization: `Bearer ${login.token}` },
|
|
747
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds3)
|
|
748
|
-
});
|
|
749
|
-
if (response.status === 401) {
|
|
750
|
-
environment.out(`The login from ${login.source} has ended. Run: ace-kit login`);
|
|
751
|
-
return 1;
|
|
752
|
-
}
|
|
753
|
-
if (!response.ok) {
|
|
754
|
-
environment.error(`The CMS answered with an error (${response.status}).`);
|
|
755
|
-
return 1;
|
|
756
|
-
}
|
|
757
|
-
const me = await response.json();
|
|
758
|
-
environment.out(`Signed in to ${apiUrl} as ${String(me.email)}, using the login in ${login.source}.`);
|
|
759
|
-
return 0;
|
|
760
|
-
} catch {
|
|
761
|
-
environment.error(`Could not reach the CMS at ${apiUrl}.`);
|
|
762
|
-
return 1;
|
|
763
|
-
}
|
|
9
|
+
process.exit(1);
|
|
764
10
|
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
var skippedFolders = /* @__PURE__ */ new Set([
|
|
774
|
-
"node_modules",
|
|
775
|
-
".git",
|
|
776
|
-
"dist",
|
|
777
|
-
"build",
|
|
778
|
-
".astro",
|
|
779
|
-
".react-router",
|
|
780
|
-
".output",
|
|
781
|
-
"coverage"
|
|
782
|
-
]);
|
|
783
|
-
async function findSchemaFiles(root, folder = "src") {
|
|
784
|
-
const start = join3(root, folder);
|
|
785
|
-
const found = [];
|
|
786
|
-
async function walk(directory) {
|
|
787
|
-
let entries;
|
|
788
|
-
try {
|
|
789
|
-
entries = await readdir(directory, { withFileTypes: true });
|
|
790
|
-
} catch {
|
|
791
|
-
return;
|
|
792
|
-
}
|
|
793
|
-
for (const entry of entries) {
|
|
794
|
-
const path = join3(directory, entry.name);
|
|
795
|
-
if (entry.isDirectory()) {
|
|
796
|
-
if (!skippedFolders.has(entry.name)) await walk(path);
|
|
797
|
-
} else if (entry.isFile() && schemaFilePattern.test(entry.name) && !entry.name.endsWith(".d.ts")) {
|
|
798
|
-
found.push(path);
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
}
|
|
802
|
-
await walk(start);
|
|
803
|
-
return found.sort((first, second) => {
|
|
804
|
-
const [firstName, secondName] = [relative(root, first), relative(root, second)];
|
|
805
|
-
return firstName < secondName ? -1 : firstName > secondName ? 1 : 0;
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// src/sections/load-schemas.ts
|
|
810
|
-
import { relative as relative2 } from "path";
|
|
811
|
-
|
|
812
|
-
// src/sections/payload.ts
|
|
813
|
-
var handlePattern = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
814
|
-
var maximumHandleLength = 64;
|
|
815
|
-
var maximumNameLength = 200;
|
|
816
|
-
var fieldTypes = [
|
|
817
|
-
"text",
|
|
818
|
-
"textarea",
|
|
819
|
-
"number",
|
|
820
|
-
"checkbox",
|
|
821
|
-
"select",
|
|
822
|
-
"image",
|
|
823
|
-
"richtext",
|
|
824
|
-
"date",
|
|
825
|
-
"link"
|
|
826
|
-
];
|
|
827
|
-
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
828
|
-
var isHandle = (value) => typeof value === "string" && value.length <= maximumHandleLength && handlePattern.test(value);
|
|
829
|
-
var handleRule = 'lowercase letters, numbers and hyphens (such as "call-to-action")';
|
|
830
|
-
function checkFields(fields, where, problems) {
|
|
831
|
-
if (fields === void 0) return;
|
|
832
|
-
if (!Array.isArray(fields)) {
|
|
833
|
-
problems.push(`${where}: fields must be a list.`);
|
|
834
|
-
return;
|
|
835
|
-
}
|
|
836
|
-
const seen = /* @__PURE__ */ new Set();
|
|
837
|
-
fields.forEach((field, index) => {
|
|
838
|
-
if (!isObject(field)) {
|
|
839
|
-
problems.push(`${where}: field ${index + 1} must be an object with a handle, a label and a type.`);
|
|
840
|
-
return;
|
|
841
|
-
}
|
|
842
|
-
const name = isHandle(field.handle) ? `field "${field.handle}"` : `field ${index + 1}`;
|
|
843
|
-
if (!isHandle(field.handle)) problems.push(`${where}: ${name} needs a handle of ${handleRule}.`);
|
|
844
|
-
else if (seen.has(field.handle)) problems.push(`${where}: ${name} is defined twice.`);
|
|
845
|
-
else seen.add(field.handle);
|
|
846
|
-
if (typeof field.label !== "string" || field.label.trim() === "" || field.label.length > maximumNameLength) {
|
|
847
|
-
problems.push(`${where}: ${name} needs a label.`);
|
|
848
|
-
}
|
|
849
|
-
if (typeof field.type !== "string" || !fieldTypes.includes(field.type)) {
|
|
850
|
-
const given = typeof field.type === "string" ? ` "${field.type}"` : "";
|
|
851
|
-
problems.push(`${where}: ${name} has a type${given} that isn't one of ${fieldTypes.join(", ")}.`);
|
|
852
|
-
} else if (field.type === "select") {
|
|
853
|
-
const { options } = field;
|
|
854
|
-
if (!Array.isArray(options) || options.length === 0 || options.some((option) => typeof option !== "string" || option === "")) {
|
|
855
|
-
problems.push(`${where}: ${name} is a select, so it needs options: a list of the choices, as text.`);
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
if (field.required !== void 0 && typeof field.required !== "boolean") {
|
|
859
|
-
problems.push(`${where}: ${name} has a required that isn't true or false.`);
|
|
860
|
-
}
|
|
861
|
-
});
|
|
11
|
+
try {
|
|
12
|
+
const { createRealEnvironment } = await import("./environment-T5K5ZJ2M.js");
|
|
13
|
+
const { runCli } = await import("./main-YRQQWLHX.js");
|
|
14
|
+
const environment = await createRealEnvironment();
|
|
15
|
+
process.exit(await runCli(process.argv.slice(2), environment));
|
|
16
|
+
} catch (error) {
|
|
17
|
+
console.error(error instanceof Error ? error.message : error);
|
|
18
|
+
process.exit(1);
|
|
862
19
|
}
|
|
863
|
-
function checkSectionDefinition(definition, where = "this section") {
|
|
864
|
-
const problems = [];
|
|
865
|
-
if (!isObject(definition)) {
|
|
866
|
-
return [`${where}: the default export must be the result of defineSection({ ... }).`];
|
|
867
|
-
}
|
|
868
|
-
if (!isHandle(definition.handle)) {
|
|
869
|
-
problems.push(`${where}: needs a handle of ${handleRule}.`);
|
|
870
|
-
}
|
|
871
|
-
if (typeof definition.name !== "string" || definition.name.trim() === "" || definition.name.length > maximumNameLength) {
|
|
872
|
-
problems.push(`${where}: needs a name.`);
|
|
873
|
-
}
|
|
874
|
-
checkFields(definition.fields, where, problems);
|
|
875
|
-
if (definition.blocks !== void 0) {
|
|
876
|
-
if (!isObject(definition.blocks)) {
|
|
877
|
-
problems.push(`${where}: blocks must be an object of the kinds of block, by handle.`);
|
|
878
|
-
} else {
|
|
879
|
-
for (const [handle, block] of Object.entries(definition.blocks)) {
|
|
880
|
-
const blockWhere = `${where}, block "${handle}"`;
|
|
881
|
-
if (!isHandle(handle)) problems.push(`${blockWhere}: the handle must be ${handleRule}.`);
|
|
882
|
-
if (!isObject(block)) {
|
|
883
|
-
problems.push(`${blockWhere}: must be an object with a name and fields.`);
|
|
884
|
-
continue;
|
|
885
|
-
}
|
|
886
|
-
if (typeof block.name !== "string" || block.name.trim() === "") problems.push(`${blockWhere}: needs a name.`);
|
|
887
|
-
checkFields(block.fields, blockWhere, problems);
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
return problems;
|
|
892
|
-
}
|
|
893
|
-
function apiFields(fields) {
|
|
894
|
-
return (fields ?? []).map((field) => ({
|
|
895
|
-
handle: field.handle,
|
|
896
|
-
label: field.label,
|
|
897
|
-
component_key: field.type,
|
|
898
|
-
config: {
|
|
899
|
-
...field.required ? { required: true } : {},
|
|
900
|
-
...field.type === "select" ? { options: [...field.options] } : {}
|
|
901
|
-
}
|
|
902
|
-
}));
|
|
903
|
-
}
|
|
904
|
-
function sectionTypesPayload(definitions) {
|
|
905
|
-
return {
|
|
906
|
-
sections: definitions.map((definition) => ({
|
|
907
|
-
handle: definition.handle,
|
|
908
|
-
name: definition.name,
|
|
909
|
-
fields: apiFields(definition.fields),
|
|
910
|
-
blocks: Object.entries(definition.blocks ?? {}).map(([handle, block]) => ({
|
|
911
|
-
handle,
|
|
912
|
-
name: block.name,
|
|
913
|
-
fields: apiFields(block.fields)
|
|
914
|
-
}))
|
|
915
|
-
}))
|
|
916
|
-
};
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
// src/sections/load-schemas.ts
|
|
920
|
-
async function loadSchemas(files, root, importModule2) {
|
|
921
|
-
const definitions = [];
|
|
922
|
-
const problems = [];
|
|
923
|
-
const handleToFile = /* @__PURE__ */ new Map();
|
|
924
|
-
for (const file of files) {
|
|
925
|
-
const name = relative2(root, file);
|
|
926
|
-
let exported;
|
|
927
|
-
try {
|
|
928
|
-
const module = await importModule2(file);
|
|
929
|
-
exported = module.default;
|
|
930
|
-
} catch (error) {
|
|
931
|
-
problems.push(`${name}: could not be loaded: ${error instanceof Error ? error.message : String(error)}`);
|
|
932
|
-
continue;
|
|
933
|
-
}
|
|
934
|
-
const fileProblems = checkSectionDefinition(exported, name);
|
|
935
|
-
if (fileProblems.length > 0) {
|
|
936
|
-
problems.push(...fileProblems);
|
|
937
|
-
continue;
|
|
938
|
-
}
|
|
939
|
-
const definition = exported;
|
|
940
|
-
const earlier = handleToFile.get(definition.handle);
|
|
941
|
-
if (earlier) {
|
|
942
|
-
problems.push(`${name}: the handle "${definition.handle}" is already used by ${earlier}.`);
|
|
943
|
-
continue;
|
|
944
|
-
}
|
|
945
|
-
handleToFile.set(definition.handle, name);
|
|
946
|
-
definitions.push({ file, definition });
|
|
947
|
-
}
|
|
948
|
-
return { definitions, problems };
|
|
949
|
-
}
|
|
950
|
-
|
|
951
|
-
// src/sections/sync.ts
|
|
952
|
-
var requestTimeoutMilliseconds4 = 2e4;
|
|
953
|
-
async function readMessage2(response, fallback) {
|
|
954
|
-
try {
|
|
955
|
-
const body = await response.json();
|
|
956
|
-
if (typeof body.error === "string") return body.error;
|
|
957
|
-
} catch {
|
|
958
|
-
}
|
|
959
|
-
return fallback;
|
|
960
|
-
}
|
|
961
|
-
async function syncSectionTypes(options) {
|
|
962
|
-
const { apiUrl, siteDomain, token, payload, fetchImplementation } = options;
|
|
963
|
-
const headers = { Accept: "application/json", Authorization: `Bearer ${token}` };
|
|
964
|
-
let sitesResponse;
|
|
965
|
-
try {
|
|
966
|
-
sitesResponse = await fetchImplementation(`${apiUrl}/sites`, {
|
|
967
|
-
headers,
|
|
968
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds4)
|
|
969
|
-
});
|
|
970
|
-
} catch {
|
|
971
|
-
return { kind: "unreachable" };
|
|
972
|
-
}
|
|
973
|
-
if (sitesResponse.status === 401) return { kind: "login-ended" };
|
|
974
|
-
if (!sitesResponse.ok)
|
|
975
|
-
return {
|
|
976
|
-
kind: "rejected",
|
|
977
|
-
message: await readMessage2(sitesResponse, `The CMS answered with an error (${sitesResponse.status}).`)
|
|
978
|
-
};
|
|
979
|
-
const sites = await sitesResponse.json().catch(() => []);
|
|
980
|
-
const wanted = siteDomain.trim().toLowerCase();
|
|
981
|
-
const site = sites.find((candidate) => candidate.domain.toLowerCase() === wanted);
|
|
982
|
-
if (!site)
|
|
983
|
-
return { kind: "site-not-found", domain: siteDomain, available: sites.map((candidate) => candidate.domain) };
|
|
984
|
-
let response;
|
|
985
|
-
try {
|
|
986
|
-
response = await fetchImplementation(`${apiUrl}/sites/${site.id}/section-types`, {
|
|
987
|
-
method: "PUT",
|
|
988
|
-
headers: { ...headers, "Content-Type": "application/json" },
|
|
989
|
-
body: JSON.stringify(payload),
|
|
990
|
-
signal: AbortSignal.timeout(requestTimeoutMilliseconds4)
|
|
991
|
-
});
|
|
992
|
-
} catch {
|
|
993
|
-
return { kind: "unreachable" };
|
|
994
|
-
}
|
|
995
|
-
if (response.status === 401) return { kind: "login-ended" };
|
|
996
|
-
if (response.status === 403) {
|
|
997
|
-
return {
|
|
998
|
-
kind: "forbidden",
|
|
999
|
-
message: "Your account can't change this site's sections: only a site's owners and super admins can."
|
|
1000
|
-
};
|
|
1001
|
-
}
|
|
1002
|
-
if (!response.ok)
|
|
1003
|
-
return {
|
|
1004
|
-
kind: "rejected",
|
|
1005
|
-
message: await readMessage2(response, `The CMS answered with an error (${response.status}).`)
|
|
1006
|
-
};
|
|
1007
|
-
const body = await response.json().catch(() => null);
|
|
1008
|
-
return {
|
|
1009
|
-
kind: "synced",
|
|
1010
|
-
site: { id: site.id, domain: site.domain },
|
|
1011
|
-
sections: (body?.sections ?? []).map((section) => ({
|
|
1012
|
-
handle: section.handle,
|
|
1013
|
-
name: section.name,
|
|
1014
|
-
retired: section.retired_at !== void 0
|
|
1015
|
-
})),
|
|
1016
|
-
warnings: body?.warnings ?? []
|
|
1017
|
-
};
|
|
1018
|
-
}
|
|
1019
|
-
|
|
1020
|
-
// src/cli/sync-command.ts
|
|
1021
|
-
var syncUsage = `ace-kit sync: send the section types your code defines to CMS Ace.
|
|
1022
|
-
|
|
1023
|
-
Usage:
|
|
1024
|
-
ace-kit sync [--site <domain>] [--api-url <address>] [--dir <folder>]
|
|
1025
|
-
|
|
1026
|
-
It finds every *.schema.ts file in the folder (src by default), checks them, and makes the CMS's section types for your
|
|
1027
|
-
site match. The dev server does this for you whenever a schema file is saved; run it yourself for a one-off sync, or on a
|
|
1028
|
-
build server (with ACE_TOKEN set).
|
|
1029
|
-
|
|
1030
|
-
Nothing is deleted: a section type, block or field you take out of your code is kept in the CMS, hidden, so the content
|
|
1031
|
-
written in it survives. If any schema file can't be loaded, nothing is synced.
|
|
1032
|
-
|
|
1033
|
-
Options:
|
|
1034
|
-
--site The domain your site has in the CMS, e.g. example.com (default: ACE_SITE_DOMAIN, else localhost).
|
|
1035
|
-
(--domain means the same.)
|
|
1036
|
-
--api-url Where the CMS Ace API lives (default: ACE_API_URL, else the hosted CMS Ace). Only for a CMS on your own machine.
|
|
1037
|
-
--dir The folder to look in (default: src).
|
|
1038
|
-
--help Show this message.
|
|
1039
|
-
`;
|
|
1040
|
-
var isSwitchedOff = (value) => ["false", "off", "no", "0"].includes((value ?? "").trim().toLowerCase());
|
|
1041
|
-
async function syncCommand(commandArguments, environment) {
|
|
1042
|
-
const { values } = parseArgs3({
|
|
1043
|
-
// eslint-disable-next-line id-denylist -- "args" is the name node's parseArgs gives this option.
|
|
1044
|
-
args: commandArguments,
|
|
1045
|
-
options: {
|
|
1046
|
-
"api-url": { type: "string" },
|
|
1047
|
-
site: { type: "string" },
|
|
1048
|
-
domain: { type: "string" },
|
|
1049
|
-
dir: { type: "string" },
|
|
1050
|
-
// Set by the dev server, which syncs on its own: it stays quiet when there is nothing to do, and keeps to a
|
|
1051
|
-
// local CMS unless told otherwise.
|
|
1052
|
-
automatic: { type: "boolean" },
|
|
1053
|
-
help: { type: "boolean" }
|
|
1054
|
-
}
|
|
1055
|
-
});
|
|
1056
|
-
if (values.help) {
|
|
1057
|
-
environment.out(syncUsage);
|
|
1058
|
-
return 0;
|
|
1059
|
-
}
|
|
1060
|
-
const automatic = values.automatic === true;
|
|
1061
|
-
if (automatic && isSwitchedOff(environment.variables.ACE_SYNC_SECTIONS)) return 0;
|
|
1062
|
-
let apiUrl;
|
|
1063
|
-
try {
|
|
1064
|
-
apiUrl = normaliseApiUrl(values["api-url"] ?? environment.variables.ACE_API_URL ?? hostedApiUrl);
|
|
1065
|
-
} catch (error) {
|
|
1066
|
-
environment.error(error instanceof Error ? error.message : String(error));
|
|
1067
|
-
return 1;
|
|
1068
|
-
}
|
|
1069
|
-
const given = values.site ?? values.domain ?? environment.variables.ACE_SITE_DOMAIN;
|
|
1070
|
-
const siteDomain = given ? domainFromSite(given) : "localhost";
|
|
1071
|
-
const aimedAtDevSite = environment.variables.ACE_DEV_SITE_ACTIVE === "1";
|
|
1072
|
-
if (automatic && !aimedAtDevSite && !isLocalApiUrl(apiUrl) && environment.variables.ACE_SYNC_SECTIONS?.trim().toLowerCase() !== "remote") {
|
|
1073
|
-
environment.out(
|
|
1074
|
-
`Section sync is off while ${apiUrl} is a hosted CMS, so a half-written change can't reach a live site. To sync on every save to it anyway, set ACE_SYNC_SECTIONS=remote. (npx ace-kit sync always works.)`
|
|
1075
|
-
);
|
|
1076
|
-
return 0;
|
|
1077
|
-
}
|
|
1078
|
-
const files = await findSchemaFiles(environment.workingDirectory, values.dir ?? "src");
|
|
1079
|
-
if (files.length === 0) {
|
|
1080
|
-
if (!automatic) {
|
|
1081
|
-
environment.out(
|
|
1082
|
-
`No *.schema.ts files found in ${values.dir ?? "src"}, so nothing was synced (syncing none would retire every section).`
|
|
1083
|
-
);
|
|
1084
|
-
}
|
|
1085
|
-
return 0;
|
|
1086
|
-
}
|
|
1087
|
-
const login = await resolveLogin({
|
|
1088
|
-
apiUrl,
|
|
1089
|
-
variables: environment.variables,
|
|
1090
|
-
store: environment.store,
|
|
1091
|
-
now: environment.now
|
|
1092
|
-
});
|
|
1093
|
-
if (!login) {
|
|
1094
|
-
environment.out(`Section sync is waiting for you to sign in. Run: npx ace-kit login --api-url ${apiUrl}`);
|
|
1095
|
-
return automatic ? 0 : 1;
|
|
1096
|
-
}
|
|
1097
|
-
const loaded = await loadSchemas(files, environment.workingDirectory, environment.importModule);
|
|
1098
|
-
if (loaded.problems.length > 0) {
|
|
1099
|
-
for (const problem of loaded.problems) environment.error(problem);
|
|
1100
|
-
environment.error("Nothing was synced, because syncing only some of your sections would retire the rest.");
|
|
1101
|
-
return 1;
|
|
1102
|
-
}
|
|
1103
|
-
const outcome = await syncSectionTypes({
|
|
1104
|
-
apiUrl,
|
|
1105
|
-
siteDomain,
|
|
1106
|
-
token: login.token,
|
|
1107
|
-
payload: sectionTypesPayload(loaded.definitions.map((entry) => entry.definition)),
|
|
1108
|
-
fetchImplementation: environment.fetchImplementation
|
|
1109
|
-
});
|
|
1110
|
-
switch (outcome.kind) {
|
|
1111
|
-
case "synced": {
|
|
1112
|
-
const defined = outcome.sections.filter((section) => !section.retired).map((section) => section.handle);
|
|
1113
|
-
const retired = outcome.sections.filter((section) => section.retired).map((section) => section.handle);
|
|
1114
|
-
environment.out(
|
|
1115
|
-
`Synced ${defined.length} section type${defined.length === 1 ? "" : "s"} (${defined.join(", ")}) to ${outcome.site.domain} (${apiUrl}).` + (retired.length > 0 ? ` No longer in your code, kept but hidden: ${retired.join(", ")}.` : "")
|
|
1116
|
-
);
|
|
1117
|
-
for (const warning of outcome.warnings) environment.error(`Warning: ${warning}`);
|
|
1118
|
-
return 0;
|
|
1119
|
-
}
|
|
1120
|
-
case "login-ended":
|
|
1121
|
-
environment.out(`Your login has ended. Run: npx ace-kit login --api-url ${apiUrl}`);
|
|
1122
|
-
return automatic ? 0 : 1;
|
|
1123
|
-
case "site-not-found":
|
|
1124
|
-
environment.error(
|
|
1125
|
-
`The CMS at ${apiUrl} has no site with the domain "${outcome.domain}" that you can see` + (outcome.available.length > 0 ? ` (your sites: ${outcome.available.join(", ")})` : "") + ". Set ACE_SITE_DOMAIN or pass --site."
|
|
1126
|
-
);
|
|
1127
|
-
return 1;
|
|
1128
|
-
case "forbidden":
|
|
1129
|
-
case "rejected":
|
|
1130
|
-
environment.error(outcome.message);
|
|
1131
|
-
return 1;
|
|
1132
|
-
case "unreachable":
|
|
1133
|
-
environment.error(`Could not reach the CMS at ${apiUrl}.`);
|
|
1134
|
-
return 1;
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
// src/cli/main.ts
|
|
1139
|
-
var usage = `ace-kit: tools for sites built on CMS Ace.
|
|
1140
|
-
|
|
1141
|
-
Commands:
|
|
1142
|
-
ace-kit generate Write TypeScript types for your content types.
|
|
1143
|
-
ace-kit sync Send the section types your code defines to the CMS.
|
|
1144
|
-
ace-kit login Sign in from the command line (opens the admin app).
|
|
1145
|
-
ace-kit logout Sign out.
|
|
1146
|
-
ace-kit whoami Say who you are signed in as.
|
|
1147
|
-
|
|
1148
|
-
Run a command with --help for more.
|
|
1149
|
-
`;
|
|
1150
|
-
async function runCli(commandArguments, environment) {
|
|
1151
|
-
const [command, ...rest] = commandArguments;
|
|
1152
|
-
switch (command) {
|
|
1153
|
-
case "generate":
|
|
1154
|
-
return generateCommand(rest, environment);
|
|
1155
|
-
case "sync":
|
|
1156
|
-
return syncCommand(rest, environment);
|
|
1157
|
-
case "login":
|
|
1158
|
-
return loginCommand(rest, environment);
|
|
1159
|
-
case "logout":
|
|
1160
|
-
return logoutCommand(rest, environment);
|
|
1161
|
-
case "whoami":
|
|
1162
|
-
return whoamiCommand(rest, environment);
|
|
1163
|
-
case "--help":
|
|
1164
|
-
case "-h":
|
|
1165
|
-
case "help":
|
|
1166
|
-
case void 0:
|
|
1167
|
-
environment.out(usage);
|
|
1168
|
-
return command === void 0 ? 1 : 0;
|
|
1169
|
-
default:
|
|
1170
|
-
environment.error(`Unknown command "${command}".
|
|
1171
|
-
|
|
1172
|
-
${usage}`);
|
|
1173
|
-
return 1;
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
// src/cli/bin.ts
|
|
1178
|
-
createRealEnvironment().then((environment) => runCli(process.argv.slice(2), environment)).then(
|
|
1179
|
-
(code) => process.exit(code),
|
|
1180
|
-
(error) => {
|
|
1181
|
-
console.error(error instanceof Error ? error.message : error);
|
|
1182
|
-
process.exit(1);
|
|
1183
|
-
}
|
|
1184
|
-
);
|