playcanvas-agent-bridge-cli 0.2.2 → 0.3.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.
@@ -0,0 +1,191 @@
1
+ import { createReadStream } from "node:fs";
2
+ import http from "node:http";
3
+ import { realpath, stat } from "node:fs/promises";
4
+ import { extname, relative, resolve, sep } from "node:path";
5
+ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, } from "../config.js";
6
+ import { getFrontendStatus } from "./store.js";
7
+ const MIME_TYPES = {
8
+ ".avif": "image/avif",
9
+ ".bin": "application/octet-stream",
10
+ ".css": "text/css; charset=utf-8",
11
+ ".gif": "image/gif",
12
+ ".html": "text/html; charset=utf-8",
13
+ ".ico": "image/x-icon",
14
+ ".jpeg": "image/jpeg",
15
+ ".jpg": "image/jpeg",
16
+ ".js": "text/javascript; charset=utf-8",
17
+ ".json": "application/json; charset=utf-8",
18
+ ".map": "application/json; charset=utf-8",
19
+ ".mjs": "text/javascript; charset=utf-8",
20
+ ".mp3": "audio/mpeg",
21
+ ".ogg": "audio/ogg",
22
+ ".png": "image/png",
23
+ ".svg": "image/svg+xml",
24
+ ".ttf": "font/ttf",
25
+ ".wasm": "application/wasm",
26
+ ".wav": "audio/wav",
27
+ ".webp": "image/webp",
28
+ ".woff": "font/woff",
29
+ ".woff2": "font/woff2",
30
+ };
31
+ function writeHeaders(res, statusCode, headers = {}) {
32
+ res.writeHead(statusCode, {
33
+ "Access-Control-Allow-Origin": "*",
34
+ "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
35
+ "Cache-Control": "no-cache, must-revalidate",
36
+ "Cross-Origin-Resource-Policy": "cross-origin",
37
+ "X-Content-Type-Options": "nosniff",
38
+ ...headers,
39
+ });
40
+ }
41
+ function writeJson(res, statusCode, body, headOnly = false) {
42
+ const payload = Buffer.from(`${JSON.stringify(body)}\n`);
43
+ writeHeaders(res, statusCode, {
44
+ "Content-Length": payload.length,
45
+ "Content-Type": "application/json; charset=utf-8",
46
+ });
47
+ res.end(headOnly ? undefined : payload);
48
+ }
49
+ function hostAllowed(hostHeader) {
50
+ if (!hostHeader)
51
+ return false;
52
+ try {
53
+ const hostname = new URL(`http://${hostHeader}`).hostname;
54
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ }
60
+ async function resolveStaticFile(root, pathname) {
61
+ let decoded;
62
+ try {
63
+ decoded = decodeURIComponent(pathname);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (decoded.includes("\0"))
69
+ return null;
70
+ const rootPath = await realpath(root);
71
+ const candidate = resolve(rootPath, `.${decoded}`);
72
+ const relation = relative(rootPath, candidate);
73
+ if (relation === ".." || relation.startsWith(`..${sep}`))
74
+ return null;
75
+ const filePath = await realpath(candidate).catch(() => null);
76
+ if (!filePath)
77
+ return null;
78
+ const realRelation = relative(rootPath, filePath);
79
+ if (realRelation === ".." || realRelation.startsWith(`..${sep}`))
80
+ return null;
81
+ const info = await stat(filePath).catch(() => null);
82
+ return info?.isFile() ? filePath : null;
83
+ }
84
+ export function createFrontendServer(options = {}) {
85
+ const host = options.host || DEFAULT_HOST;
86
+ const requestedPort = options.port ?? DEFAULT_FRONTEND_PORT;
87
+ const rootDir = options.rootDir || CONFIG_DIR;
88
+ const log = options.log || (() => undefined);
89
+ let actualPort = requestedPort;
90
+ let listening = false;
91
+ let runtimeError = null;
92
+ const runtime = () => ({
93
+ host,
94
+ port: actualPort,
95
+ listening,
96
+ error: runtimeError,
97
+ });
98
+ const status = async () => ({
99
+ ...(await getFrontendStatus({ rootDir })),
100
+ server: runtime(),
101
+ });
102
+ const server = http.createServer(async (req, res) => {
103
+ try {
104
+ const headOnly = req.method === "HEAD";
105
+ if (!hostAllowed(req.headers.host)) {
106
+ writeJson(res, 403, { ready: false, error: "Invalid Host header." }, headOnly);
107
+ return;
108
+ }
109
+ if (req.method === "OPTIONS") {
110
+ writeHeaders(res, 204);
111
+ res.end();
112
+ return;
113
+ }
114
+ if (req.method !== "GET" && !headOnly) {
115
+ writeJson(res, 405, { ready: false, error: "Method not allowed." });
116
+ return;
117
+ }
118
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
119
+ if (url.pathname === "/__pcbridge_frontend__/health") {
120
+ const current = await status();
121
+ writeJson(res, current.ready ? 200 : 503, current, headOnly);
122
+ return;
123
+ }
124
+ const current = await getFrontendStatus({ rootDir });
125
+ if (!current.activePath) {
126
+ writeJson(res, 503, {
127
+ ready: false,
128
+ error: "No active PlayCanvas Editor frontend is installed.",
129
+ }, headOnly);
130
+ return;
131
+ }
132
+ const filePath = await resolveStaticFile(current.activePath, url.pathname);
133
+ if (!filePath) {
134
+ writeJson(res, 404, { ready: false, error: "Frontend asset not found." }, headOnly);
135
+ return;
136
+ }
137
+ const info = await stat(filePath);
138
+ writeHeaders(res, 200, {
139
+ "Content-Length": info.size,
140
+ "Content-Type": MIME_TYPES[extname(filePath).toLowerCase()] || "application/octet-stream",
141
+ });
142
+ if (headOnly) {
143
+ res.end();
144
+ return;
145
+ }
146
+ createReadStream(filePath).on("error", () => res.destroy()).pipe(res);
147
+ }
148
+ catch (error) {
149
+ writeJson(res, 500, { ready: false, error: String(error) });
150
+ }
151
+ });
152
+ return {
153
+ status,
154
+ listen: () => new Promise((resolveListen, reject) => {
155
+ const onError = (error) => {
156
+ runtimeError = error.message;
157
+ server.off("listening", onListening);
158
+ reject(error);
159
+ };
160
+ const onListening = () => {
161
+ server.off("error", onError);
162
+ const address = server.address();
163
+ if (address && typeof address !== "string")
164
+ actualPort = address.port;
165
+ listening = true;
166
+ runtimeError = null;
167
+ log(`frontend server listening on http://${host}:${actualPort}`);
168
+ resolveListen();
169
+ };
170
+ server.once("error", onError);
171
+ server.once("listening", onListening);
172
+ server.listen(requestedPort, host);
173
+ }),
174
+ close: () => new Promise((resolveClose, reject) => {
175
+ if (!server.listening) {
176
+ listening = false;
177
+ resolveClose();
178
+ return;
179
+ }
180
+ server.close((error) => {
181
+ listening = false;
182
+ if (error) {
183
+ reject(error);
184
+ }
185
+ else {
186
+ resolveClose();
187
+ }
188
+ });
189
+ }),
190
+ };
191
+ }
@@ -0,0 +1,369 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, readdir, rename, rm, stat, writeFile, } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { t as inspectTar, x as extractTar } from "tar";
5
+ import { CONFIG_DIR, DEFAULT_FRONTEND_REPOSITORY, VERSION, } from "../config.js";
6
+ const RELEASE_PATTERN = /^playcanvas-editor-v\d+\.\d+\.\d+-r\d+$/;
7
+ const SHA256_PATTERN = /^[a-f0-9]{64}$/;
8
+ const COMMIT_PATTERN = /^[a-f0-9]{40}$/;
9
+ const MAX_ARCHIVE_SIZE = 250 * 1024 * 1024;
10
+ const MAX_EXTRACTED_SIZE = 1024 * 1024 * 1024;
11
+ const MAX_ARCHIVE_ENTRIES = 100_000;
12
+ const REQUIRED_FILES = [
13
+ "dist/js/editor.js",
14
+ "dist/js/editor-empty.js",
15
+ "dist/js/code-editor.js",
16
+ "dist/js/launch.js",
17
+ "dist/css/editor.css",
18
+ "dist/css/code-editor.css",
19
+ "dist/css/launch.css",
20
+ ];
21
+ export class FrontendError extends Error {
22
+ code;
23
+ constructor(code, message) {
24
+ super(message);
25
+ this.name = "FrontendError";
26
+ this.code = code;
27
+ }
28
+ }
29
+ function storePaths(rootDir = CONFIG_DIR) {
30
+ const frontendsDir = join(rootDir, "frontends");
31
+ return {
32
+ rootDir,
33
+ frontendsDir,
34
+ stateFile: join(rootDir, "frontend-state.json"),
35
+ };
36
+ }
37
+ function isObject(value) {
38
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
39
+ }
40
+ function assertReleaseName(release) {
41
+ if (!RELEASE_PATTERN.test(release)) {
42
+ throw new FrontendError("INVALID_FRONTEND_RELEASE", `Invalid frontend release name: ${release}`);
43
+ }
44
+ }
45
+ function parseVersion(version) {
46
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
47
+ if (!match) {
48
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", `Invalid version: ${version}`);
49
+ }
50
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
51
+ }
52
+ function compareVersions(left, right) {
53
+ const a = parseVersion(left);
54
+ const b = parseVersion(right);
55
+ for (let index = 0; index < a.length; index += 1) {
56
+ if (a[index] !== b[index])
57
+ return a[index] - b[index];
58
+ }
59
+ return 0;
60
+ }
61
+ export function validateFrontendManifest(value) {
62
+ if (!isObject(value) || value.schemaVersion !== 1) {
63
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Unsupported frontend manifest.");
64
+ }
65
+ const archive = value.archive;
66
+ if (!isObject(archive)) {
67
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive metadata is missing.");
68
+ }
69
+ const manifest = value;
70
+ assertReleaseName(manifest.release);
71
+ if (typeof manifest.editorVersion !== "string" ||
72
+ typeof manifest.sourceRepository !== "string" ||
73
+ typeof manifest.sourceCommit !== "string" ||
74
+ typeof manifest.builtAt !== "string" ||
75
+ typeof manifest.minPcbridgeVersion !== "string" ||
76
+ typeof manifest.archive.name !== "string" ||
77
+ typeof manifest.archive.url !== "string" ||
78
+ typeof manifest.archive.sha256 !== "string" ||
79
+ typeof manifest.archive.size !== "number") {
80
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend manifest fields are invalid.");
81
+ }
82
+ parseVersion(manifest.editorVersion);
83
+ parseVersion(manifest.minPcbridgeVersion);
84
+ if (!manifest.release.startsWith(`playcanvas-editor-v${manifest.editorVersion}-r`)) {
85
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend release name does not match the Editor version.");
86
+ }
87
+ if (Number.isNaN(Date.parse(manifest.builtAt))) {
88
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend build time is invalid.");
89
+ }
90
+ if (manifest.sourceRepository !== DEFAULT_FRONTEND_REPOSITORY) {
91
+ throw new FrontendError("UNTRUSTED_FRONTEND_SOURCE", `Unexpected frontend repository: ${manifest.sourceRepository}`);
92
+ }
93
+ if (!COMMIT_PATTERN.test(manifest.sourceCommit)) {
94
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend source commit is invalid.");
95
+ }
96
+ if (manifest.archive.name !== `${manifest.release}.tar.gz`) {
97
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive name is invalid.");
98
+ }
99
+ if (!SHA256_PATTERN.test(manifest.archive.sha256)) {
100
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive SHA-256 is invalid.");
101
+ }
102
+ if (!Number.isSafeInteger(manifest.archive.size) ||
103
+ manifest.archive.size <= 0 ||
104
+ manifest.archive.size > MAX_ARCHIVE_SIZE) {
105
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive size is invalid.");
106
+ }
107
+ let archiveUrl;
108
+ try {
109
+ archiveUrl = new URL(manifest.archive.url);
110
+ }
111
+ catch {
112
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend archive URL is invalid.");
113
+ }
114
+ const expectedPath = `/${DEFAULT_FRONTEND_REPOSITORY}/releases/download/` +
115
+ `${manifest.release}/${manifest.archive.name}`;
116
+ if (archiveUrl.protocol !== "https:" ||
117
+ archiveUrl.hostname !== "github.com" ||
118
+ archiveUrl.pathname !== expectedPath ||
119
+ archiveUrl.search ||
120
+ archiveUrl.hash) {
121
+ throw new FrontendError("UNTRUSTED_FRONTEND_SOURCE", "Frontend archive URL is not trusted.");
122
+ }
123
+ if (compareVersions(VERSION, manifest.minPcbridgeVersion) < 0) {
124
+ throw new FrontendError("FRONTEND_REQUIRES_NEWER_CLI", `Frontend ${manifest.release} requires pcbridge ${manifest.minPcbridgeVersion} or newer.`);
125
+ }
126
+ return manifest;
127
+ }
128
+ export function frontendManifestUrl(release = "latest") {
129
+ if (release === "latest") {
130
+ return `https://github.com/${DEFAULT_FRONTEND_REPOSITORY}/releases/latest/download/release.json`;
131
+ }
132
+ assertReleaseName(release);
133
+ return (`https://github.com/${DEFAULT_FRONTEND_REPOSITORY}/releases/download/` +
134
+ `${release}/release.json`);
135
+ }
136
+ export async function fetchFrontendManifest(release = "latest", options = {}) {
137
+ const fetchImpl = options.fetch || fetch;
138
+ let response;
139
+ try {
140
+ response = await fetchImpl(frontendManifestUrl(release), {
141
+ headers: {
142
+ Accept: "application/json",
143
+ "User-Agent": `playcanvas-agent-bridge-cli/${VERSION}`,
144
+ },
145
+ redirect: "follow",
146
+ });
147
+ }
148
+ catch (error) {
149
+ throw new FrontendError("FRONTEND_MANIFEST_DOWNLOAD_FAILED", `Cannot download frontend manifest: ${String(error)}`);
150
+ }
151
+ if (!response.ok) {
152
+ throw new FrontendError("FRONTEND_MANIFEST_DOWNLOAD_FAILED", `Cannot download frontend manifest: HTTP ${response.status}.`);
153
+ }
154
+ try {
155
+ return validateFrontendManifest(await response.json());
156
+ }
157
+ catch (error) {
158
+ if (error instanceof FrontendError)
159
+ throw error;
160
+ throw new FrontendError("INVALID_FRONTEND_MANIFEST", "Frontend manifest is not valid JSON.");
161
+ }
162
+ }
163
+ async function readState(rootDir = CONFIG_DIR) {
164
+ const { stateFile } = storePaths(rootDir);
165
+ try {
166
+ const value = JSON.parse(await readFile(stateFile, "utf8"));
167
+ if (isObject(value) &&
168
+ (value.activeRelease === null || typeof value.activeRelease === "string") &&
169
+ typeof value.updatedAt === "string") {
170
+ if (typeof value.activeRelease === "string")
171
+ assertReleaseName(value.activeRelease);
172
+ return value;
173
+ }
174
+ }
175
+ catch {
176
+ // Missing or invalid state falls back to no active frontend.
177
+ }
178
+ return { activeRelease: null, updatedAt: "" };
179
+ }
180
+ async function writeState(state, rootDir = CONFIG_DIR) {
181
+ const { stateFile } = storePaths(rootDir);
182
+ await mkdir(rootDir, { recursive: true });
183
+ const temporary = `${stateFile}.${process.pid}.${randomUUID()}.tmp`;
184
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
185
+ await rename(temporary, stateFile);
186
+ }
187
+ async function validateInstalledFrontend(directory) {
188
+ for (const file of REQUIRED_FILES) {
189
+ const info = await stat(join(directory, file)).catch(() => null);
190
+ if (!info?.isFile()) {
191
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Frontend archive is missing ${file}.`);
192
+ }
193
+ }
194
+ const monaco = await stat(join(directory, "dist/js/monaco-editor")).catch(() => null);
195
+ const wasm = await stat(join(directory, "dist/wasm")).catch(() => null);
196
+ if (!monaco?.isDirectory() || !wasm?.isDirectory()) {
197
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", "Frontend archive is missing Monaco or WASM assets.");
198
+ }
199
+ }
200
+ function validateArchiveEntry(path, type) {
201
+ const normalized = path.replaceAll("\\", "/");
202
+ if (!normalized ||
203
+ normalized.startsWith("/") ||
204
+ normalized.split("/").some((part) => part === "..")) {
205
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unsafe frontend archive path: ${path}`);
206
+ }
207
+ if (normalized !== "LICENSE" &&
208
+ normalized !== "dist" &&
209
+ normalized !== "dist/" &&
210
+ !normalized.startsWith("dist/")) {
211
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unexpected frontend archive path: ${path}`);
212
+ }
213
+ if (!["File", "OldFile", "Directory"].includes(type)) {
214
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", `Unsupported frontend archive entry type: ${type}`);
215
+ }
216
+ }
217
+ async function installedManifest(directory) {
218
+ try {
219
+ const manifest = validateFrontendManifest(JSON.parse(await readFile(join(directory, "release.json"), "utf8")));
220
+ await validateInstalledFrontend(directory);
221
+ return manifest;
222
+ }
223
+ catch {
224
+ return null;
225
+ }
226
+ }
227
+ export async function installFrontend(release = "latest", options = {}) {
228
+ const rootDir = options.rootDir || CONFIG_DIR;
229
+ const fetchImpl = options.fetch || fetch;
230
+ const { frontendsDir } = storePaths(rootDir);
231
+ const manifest = await fetchFrontendManifest(release, { fetch: fetchImpl });
232
+ const targetDir = join(frontendsDir, manifest.release);
233
+ const existing = await installedManifest(targetDir);
234
+ if (existing?.archive.sha256 === manifest.archive.sha256) {
235
+ if (options.activate !== false) {
236
+ await useFrontend(manifest.release, { rootDir });
237
+ }
238
+ return { manifest: existing, path: targetDir, alreadyInstalled: true };
239
+ }
240
+ await mkdir(frontendsDir, { recursive: true });
241
+ const installId = `${manifest.release}.${process.pid}.${randomUUID()}`;
242
+ const archiveFile = join(frontendsDir, `.${installId}.tar.gz.part`);
243
+ const extractDir = join(frontendsDir, `.${installId}.extract`);
244
+ try {
245
+ let response;
246
+ try {
247
+ response = await fetchImpl(manifest.archive.url, {
248
+ headers: {
249
+ Accept: "application/gzip, application/octet-stream",
250
+ "User-Agent": `playcanvas-agent-bridge-cli/${VERSION}`,
251
+ },
252
+ redirect: "follow",
253
+ });
254
+ }
255
+ catch (error) {
256
+ throw new FrontendError("FRONTEND_DOWNLOAD_FAILED", `Cannot download frontend archive: ${String(error)}`);
257
+ }
258
+ if (!response.ok) {
259
+ throw new FrontendError("FRONTEND_DOWNLOAD_FAILED", `Cannot download frontend archive: HTTP ${response.status}.`);
260
+ }
261
+ const archive = Buffer.from(await response.arrayBuffer());
262
+ if (archive.length !== manifest.archive.size) {
263
+ throw new FrontendError("FRONTEND_SIZE_MISMATCH", `Frontend archive size mismatch: expected ${manifest.archive.size}, got ${archive.length}.`);
264
+ }
265
+ const digest = createHash("sha256").update(archive).digest("hex");
266
+ if (digest !== manifest.archive.sha256) {
267
+ throw new FrontendError("FRONTEND_CHECKSUM_MISMATCH", "Frontend archive SHA-256 verification failed.");
268
+ }
269
+ await writeFile(archiveFile, archive, { mode: 0o600 });
270
+ await mkdir(extractDir, { recursive: true });
271
+ let entryCount = 0;
272
+ let extractedSize = 0;
273
+ await inspectTar({
274
+ file: archiveFile,
275
+ onentry: (entry) => {
276
+ validateArchiveEntry(entry.path, entry.type);
277
+ entryCount += 1;
278
+ extractedSize += entry.size;
279
+ if (entryCount > MAX_ARCHIVE_ENTRIES ||
280
+ extractedSize > MAX_EXTRACTED_SIZE) {
281
+ throw new FrontendError("INVALID_FRONTEND_ARCHIVE", "Frontend archive expands beyond the safety limit.");
282
+ }
283
+ },
284
+ });
285
+ await extractTar({
286
+ cwd: extractDir,
287
+ file: archiveFile,
288
+ preservePaths: false,
289
+ strict: true,
290
+ });
291
+ await validateInstalledFrontend(extractDir);
292
+ await writeFile(join(extractDir, "release.json"), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });
293
+ await rm(targetDir, { force: true, recursive: true });
294
+ await rename(extractDir, targetDir);
295
+ if (options.activate !== false) {
296
+ await useFrontend(manifest.release, { rootDir });
297
+ }
298
+ return { manifest, path: targetDir, alreadyInstalled: false };
299
+ }
300
+ finally {
301
+ await rm(archiveFile, { force: true });
302
+ await rm(extractDir, { force: true, recursive: true });
303
+ }
304
+ }
305
+ export async function listFrontends(options = {}) {
306
+ const rootDir = options.rootDir || CONFIG_DIR;
307
+ const { frontendsDir } = storePaths(rootDir);
308
+ const state = await readState(rootDir);
309
+ const entries = await readdir(frontendsDir, { withFileTypes: true }).catch(() => []);
310
+ const installed = [];
311
+ for (const entry of entries) {
312
+ if (!entry.isDirectory() || entry.name.startsWith("."))
313
+ continue;
314
+ const path = join(frontendsDir, entry.name);
315
+ const manifest = await installedManifest(path);
316
+ if (!manifest)
317
+ continue;
318
+ installed.push({
319
+ release: manifest.release,
320
+ editorVersion: manifest.editorVersion,
321
+ sourceCommit: manifest.sourceCommit,
322
+ builtAt: manifest.builtAt,
323
+ path,
324
+ active: state.activeRelease === manifest.release,
325
+ });
326
+ }
327
+ return installed.sort((left, right) => right.release.localeCompare(left.release));
328
+ }
329
+ export async function getFrontendStatus(options = {}) {
330
+ const rootDir = options.rootDir || CONFIG_DIR;
331
+ const state = await readState(rootDir);
332
+ const installed = await listFrontends({ rootDir });
333
+ const active = installed.find((item) => item.release === state.activeRelease) || null;
334
+ return {
335
+ ready: Boolean(active),
336
+ activeRelease: active?.release || null,
337
+ activePath: active ? join(active.path, "dist") : null,
338
+ installed,
339
+ };
340
+ }
341
+ export async function useFrontend(release, options = {}) {
342
+ assertReleaseName(release);
343
+ const rootDir = options.rootDir || CONFIG_DIR;
344
+ const { frontendsDir } = storePaths(rootDir);
345
+ const directory = join(frontendsDir, release);
346
+ if (!(await installedManifest(directory))) {
347
+ throw new FrontendError("FRONTEND_NOT_INSTALLED", `Frontend ${release} is not installed.`);
348
+ }
349
+ await writeState({
350
+ activeRelease: release,
351
+ updatedAt: new Date().toISOString(),
352
+ }, rootDir);
353
+ return getFrontendStatus({ rootDir });
354
+ }
355
+ export async function removeFrontend(release, options = {}) {
356
+ assertReleaseName(release);
357
+ const rootDir = options.rootDir || CONFIG_DIR;
358
+ const { frontendsDir } = storePaths(rootDir);
359
+ const state = await readState(rootDir);
360
+ if (state.activeRelease === release) {
361
+ throw new FrontendError("FRONTEND_IS_ACTIVE", `Frontend ${release} is active. Select another version before removing it.`);
362
+ }
363
+ const directory = join(frontendsDir, release);
364
+ if (!(await installedManifest(directory))) {
365
+ throw new FrontendError("FRONTEND_NOT_INSTALLED", `Frontend ${release} is not installed.`);
366
+ }
367
+ await rm(directory, { force: true, recursive: true });
368
+ return getFrontendStatus({ rootDir });
369
+ }
package/dist/snippets.js CHANGED
@@ -865,6 +865,83 @@ return {
865
865
  };
866
866
  `;
867
867
  }
868
+ export function scriptUpsertSnippet() {
869
+ return `
870
+ ${assetReader}
871
+ ${assetFolderHelpers}
872
+ const args = command.args || {};
873
+ const globals = editor.api.globals;
874
+ const assets = globals.assets;
875
+ if (!args.filename) {
876
+ throw new Error("filename is required.");
877
+ }
878
+ const folderResult = await resolveFolder(assets, args);
879
+ const folderId = folderResult.folder ? folderResult.folder.get("id") : null;
880
+ function isInTargetFolder(asset) {
881
+ if (!folderId) return true;
882
+ const path = asset.get("path") || [];
883
+ return path[path.length - 1] === folderId;
884
+ }
885
+ let asset = assets.list().find((candidate) =>
886
+ candidate.get("type") === "script" &&
887
+ isInTargetFolder(candidate) &&
888
+ (
889
+ candidate.get("file.filename") === args.filename ||
890
+ candidate.get("name") === args.filename
891
+ )
892
+ );
893
+ let action = "updated";
894
+ if (!asset) {
895
+ asset = await assets.createScript({
896
+ filename: args.filename,
897
+ text: String(args.text || ""),
898
+ folder: folderResult.folder || undefined,
899
+ preload: args.preload !== false
900
+ });
901
+ action = "created";
902
+ } else {
903
+ const filename = asset.get("file.filename") || asset.get("name") || args.filename;
904
+ const form = new FormData();
905
+ form.append("filename", filename);
906
+ form.append("file", new Blob([String(args.text || "")], { type: "text/javascript" }), filename);
907
+ const branchId = window.config?.self?.branch?.id || window.config?.branch?.id;
908
+ if (branchId) {
909
+ form.append("branchId", String(branchId));
910
+ }
911
+ const headers = {};
912
+ if (globals.accessToken) {
913
+ headers.Authorization = "Bearer " + globals.accessToken;
914
+ }
915
+ const response = await fetch("/api/assets/" + asset.get("id"), {
916
+ method: "PUT",
917
+ headers,
918
+ body: form
919
+ });
920
+ const body = await response.json().catch(() => ({}));
921
+ if (!response.ok || body.error) {
922
+ throw new Error(body.error || "Failed to update script asset.");
923
+ }
924
+ }
925
+
926
+ let scripts = asset.get("data.scripts") || {};
927
+ if (args.parse) {
928
+ const [error, data] = await new Promise((resolve) => {
929
+ editor.call("scripts:parse", asset.observer, (...values) => resolve(values));
930
+ });
931
+ if (error) {
932
+ throw new Error(String(error));
933
+ }
934
+ scripts = data?.scripts || {};
935
+ }
936
+
937
+ return {
938
+ action,
939
+ asset: readAsset(asset),
940
+ scripts,
941
+ createdFolders: folderResult.created.map(readAsset)
942
+ };
943
+ `;
944
+ }
868
945
  export function scriptParseSnippet() {
869
946
  return `
870
947
  ${assetReader}