playcanvas-agent-bridge-cli 0.2.1 → 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.
package/dist/config.js CHANGED
@@ -4,10 +4,14 @@ import { existsSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- export const VERSION = "0.2.1";
7
+ export const VERSION = "0.3.0";
8
8
  export const DEFAULT_HOST = "127.0.0.1";
9
9
  export const DEFAULT_PORT = 17329;
10
- export const CONFIG_DIR = join(homedir(), ".pcbridge");
10
+ export const DEFAULT_FRONTEND_PORT = 3487;
11
+ export const DEFAULT_FRONTEND_REPOSITORY = "Q-My99/playcanvas-editor";
12
+ export const CONFIG_DIR = process.env.PCBRIDGE_CONFIG_DIR
13
+ ? resolve(process.env.PCBRIDGE_CONFIG_DIR)
14
+ : join(homedir(), ".pcbridge");
11
15
  export const SESSION_FILE = join(CONFIG_DIR, "session.json");
12
16
  export const EXTENSION_INSTALL_DIR = join(CONFIG_DIR, "extension");
13
17
  export async function readOrCreateSession() {
@@ -1,7 +1,8 @@
1
1
  import http from "node:http";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { WebSocketServer } from "ws";
4
- import { DEFAULT_HOST, DEFAULT_PORT, VERSION } from "../config.js";
4
+ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, DEFAULT_PORT, VERSION, } from "../config.js";
5
+ import { createFrontendServer, } from "../frontend/server.js";
5
6
  import { TargetRegistry } from "./target-registry.js";
6
7
  import { fail, normalizeError, ok, } from "../shared/protocol.js";
7
8
  function readBody(req) {
@@ -38,10 +39,17 @@ function isJsonObject(value) {
38
39
  }
39
40
  export function createDaemonServer(options) {
40
41
  const host = options.host || DEFAULT_HOST;
41
- const port = Number(options.port || DEFAULT_PORT);
42
+ const port = Number(options.port ?? DEFAULT_PORT);
43
+ let actualPort = port;
42
44
  const registry = new TargetRegistry();
43
45
  const pending = new Map();
44
46
  const log = options.log || (() => undefined);
47
+ const frontend = createFrontendServer({
48
+ host,
49
+ port: options.frontendPort ?? DEFAULT_FRONTEND_PORT,
50
+ rootDir: options.frontendRootDir || CONFIG_DIR,
51
+ log,
52
+ });
45
53
  function requireToken(req) {
46
54
  return req.headers["x-pcbridge-token"] === options.token;
47
55
  }
@@ -94,14 +102,24 @@ export function createDaemonServer(options) {
94
102
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
95
103
  return;
96
104
  }
105
+ const frontendStatus = await frontend.status();
97
106
  writeJson(res, 200, ok({
98
107
  version: VERSION,
99
108
  host,
100
- port,
109
+ port: actualPort,
101
110
  targetCount: registry.list().filter((target) => target.connected).length,
111
+ frontend: frontendStatus,
102
112
  }));
103
113
  return;
104
114
  }
115
+ if (url.pathname === "/frontend/status" && req.method === "GET") {
116
+ if (!requireToken(req)) {
117
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
118
+ return;
119
+ }
120
+ writeJson(res, 200, ok(await frontend.status()));
121
+ return;
122
+ }
105
123
  if (url.pathname === "/targets" && req.method === "GET") {
106
124
  if (!requireToken(req)) {
107
125
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -149,7 +167,7 @@ export function createDaemonServer(options) {
149
167
  const message = JSON.parse(raw.toString());
150
168
  if (message.type === "target:update" && message.target?.clientId) {
151
169
  const info = registry.upsert(message.target, ws);
152
- log(`target ${info.id} ready=${info.ready} url=${info.url}`);
170
+ log(`target ${info.id} kind=${info.kind || "unknown"} ready=${info.ready} url=${info.url}`);
153
171
  return;
154
172
  }
155
173
  if (message.type === "response" && message.id) {
@@ -187,18 +205,35 @@ export function createDaemonServer(options) {
187
205
  });
188
206
  return {
189
207
  host,
190
- port,
208
+ get port() {
209
+ return actualPort;
210
+ },
191
211
  registry,
192
- listen: () => new Promise((resolve, reject) => {
193
- server.once("error", reject);
194
- server.listen(port, host, () => {
195
- server.off("error", reject);
196
- resolve();
212
+ frontend,
213
+ listen: async () => {
214
+ await new Promise((resolveListen, reject) => {
215
+ server.once("error", reject);
216
+ server.listen(port, host, () => {
217
+ server.off("error", reject);
218
+ const address = server.address();
219
+ if (address && typeof address !== "string")
220
+ actualPort = address.port;
221
+ resolveListen();
222
+ });
223
+ });
224
+ try {
225
+ await frontend.listen();
226
+ }
227
+ catch (error) {
228
+ log(`frontend server unavailable: ${String(error)}`);
229
+ }
230
+ },
231
+ close: async () => {
232
+ await frontend.close();
233
+ await new Promise((resolveClose) => {
234
+ wss.close();
235
+ server.close(() => resolveClose());
197
236
  });
198
- }),
199
- close: () => new Promise((resolve) => {
200
- wss.close();
201
- server.close(() => resolve());
202
- }),
237
+ },
203
238
  };
204
239
  }
@@ -10,11 +10,17 @@ export class TargetRegistry {
10
10
  clientId: info.clientId,
11
11
  tabId: info.tabId,
12
12
  windowId: info.windowId,
13
+ kind: info.kind || existing?.kind || "unknown",
13
14
  url: info.url || existing?.url || "",
14
15
  title: info.title || existing?.title,
15
16
  projectId: info.projectId || existing?.projectId,
16
17
  sceneId: info.sceneId || existing?.sceneId,
17
18
  branchId: info.branchId || existing?.branchId,
19
+ extensionVersion: info.extensionVersion || existing?.extensionVersion,
20
+ hasEditor: info.hasEditor ?? existing?.hasEditor,
21
+ hasPc: info.hasPc ?? existing?.hasPc,
22
+ hasRuntimeApp: info.hasRuntimeApp ?? existing?.hasRuntimeApp,
23
+ canvasCount: info.canvasCount ?? existing?.canvasCount,
18
24
  ready: Boolean(info.ready),
19
25
  connected: true,
20
26
  lastSeen: now,
@@ -47,7 +53,7 @@ export class TargetRegistry {
47
53
  return {
48
54
  ok: false,
49
55
  code: "NO_READY_TARGET",
50
- message: "No ready PlayCanvas Editor target is connected.",
56
+ message: "No ready PlayCanvas target is connected.",
51
57
  candidates: this.list(),
52
58
  };
53
59
  }
@@ -92,6 +98,19 @@ export class TargetRegistry {
92
98
  };
93
99
  }
94
100
  }
101
+ if ((kind === "editor" || kind === "launch") && value) {
102
+ const matches = targets.filter((target) => target.info.kind === kind && target.info.sceneId === value);
103
+ if (matches.length === 1)
104
+ return { ok: true, target: matches[0] };
105
+ if (matches.length > 1) {
106
+ return {
107
+ ok: false,
108
+ code: "AMBIGUOUS_TARGET",
109
+ message: `${selector} matches multiple connected targets.`,
110
+ candidates: matches.map((target) => target.info),
111
+ };
112
+ }
113
+ }
95
114
  return {
96
115
  ok: false,
97
116
  code: "TARGET_NOT_FOUND",
@@ -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
+ }