@triflare/fx 2.3.0-beta.1 → 2.3.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triflare/fx",
3
- "version": "2.3.0-beta.1",
3
+ "version": "2.3.0-beta.3",
4
4
  "description": "Code PenguinMod projects with text.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
package/product.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  # Identity
2
2
  name: "Triflare Fx"
3
3
  command: "fx"
4
- version: "2.3.0-beta.1"
4
+ version: "2.3.0-beta.3"
5
5
  tagline: "Code PenguinMod projects with text."
6
6
  author: "Triflare"
7
7
  homepage: "https://github.com/triflare/fx"
@@ -9,6 +9,7 @@ import { featureCommand } from "./feature.js";
9
9
  import { fmtCommand } from "./fmt.js";
10
10
  import { initCommand } from "./init.js";
11
11
  import { lintCommand } from "./lint.js";
12
+ import { openCommand } from "./open.js";
12
13
  import { packageCommand } from "./package.js";
13
14
  import { registerSprite } from "./sprite/index.js";
14
15
  import { runCommand } from "./run.js";
@@ -19,6 +20,7 @@ import { defineCommand } from "../define-command.js";
19
20
  const TOP_LEVEL = [
20
21
  buildCommand,
21
22
  devCommand,
23
+ openCommand,
22
24
  packageCommand,
23
25
  decompileCommand,
24
26
  checkCommand,
@@ -0,0 +1,141 @@
1
+ import path from "node:path";
2
+ import { build } from "../../build.js";
3
+ import { sourceExtension } from "../../brand.js";
4
+ import { openBrowser, startEditorServer } from "../../editor.js";
5
+ import { slugify } from "../../package.js";
6
+ import { loadProjectState, resolveInput } from "../context.js";
7
+ import { EXIT, UsageError } from "../errors.js";
8
+ import { formatDuration } from "../format.js";
9
+
10
+ const EXTENSION = sourceExtension();
11
+
12
+ export const openCommand = {
13
+ name: "open",
14
+ aliases: ["o"],
15
+ group: "Core Commands:",
16
+ summary: "Serve a build and open it in the PenguinMod editor",
17
+ description: `Compile the project, serve the .pmp from a local HTTP server, and
18
+ open the PenguinMod editor on it through "?project_url=". The server keeps
19
+ serving the build from when it started, so restart the command to see changes.`,
20
+ arguments: [`[input${EXTENSION}|dir]`],
21
+ options: [
22
+ { flags: "--host [host]", description: "Server host" },
23
+ { flags: "--lan", description: "Listen on all interfaces" },
24
+ { flags: "--port <port>", description: "Server port (default 3000)" },
25
+ {
26
+ flags: "--strict-port",
27
+ description: "Fail instead of choosing the next free port",
28
+ },
29
+ {
30
+ flags: "--no-open",
31
+ description: "Print the editor link without a browser",
32
+ },
33
+ ],
34
+ examples: ["fx open", "fx open --port 4000", "fx open --no-open --json"],
35
+ jsonEvents: true,
36
+ async run({ args, options, cwd, reporter, prompts }) {
37
+ const target = resolveInput(args[0], cwd);
38
+ if (target.file && path.extname(target.file).toLowerCase() === ".pmp")
39
+ throw new UsageError(
40
+ "fx open needs .tfx sources or a directory, not a .pmp archive",
41
+ );
42
+
43
+ let host = "127.0.0.1";
44
+ if (options.lan) host = "0.0.0.0";
45
+ else if (options.host === true) host = "0.0.0.0";
46
+ else if (typeof options.host === "string") host = options.host;
47
+
48
+ if (options.port === true) throw new UsageError("--port needs a number");
49
+ const port = options.port === undefined ? 3000 : Number(options.port);
50
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
51
+ throw new UsageError("--port must be an integer between 0 and 65535");
52
+
53
+ const started = performance.now();
54
+ const state = await loadProjectState({
55
+ input: args[0],
56
+ cwd,
57
+ options,
58
+ reporter,
59
+ prompts,
60
+ });
61
+ const result = build({
62
+ ...state.target,
63
+ projectConfig: state.loaded.project,
64
+ fxConfig: state.loaded.fx,
65
+ catalog: state.catalog,
66
+ extensionUrls: state.extensionUrls,
67
+ useConfigFile: false,
68
+ });
69
+ for (const warning of result.warnings) reporter.warn(warning);
70
+
71
+ const filename = `${slugify(
72
+ result.config.name || path.basename(state.configDir),
73
+ )}.pmp`;
74
+ const server = await startEditorServer({
75
+ data: result.sb3,
76
+ filename,
77
+ host,
78
+ port,
79
+ strictPort: Boolean(options.strictPort),
80
+ log: { warn: (message) => reporter.warn(message) },
81
+ });
82
+
83
+ const startup = {
84
+ url: server.projectUrl,
85
+ projectUrls: server.projectUrls,
86
+ editorUrl: server.editorUrl,
87
+ editorUrls: server.editorUrls,
88
+ host,
89
+ port: server.port ?? port,
90
+ };
91
+ reporter.event("start", startup);
92
+
93
+ const durationMs = Math.round(performance.now() - started);
94
+ if (!reporter.json) {
95
+ reporter.success(`Serving ${filename} (${formatDuration(durationMs)})`);
96
+ reporter.text("");
97
+ reporter.detail("Project", server.projectUrl, { width: 9 });
98
+ server.editorUrls.forEach((link, index) => {
99
+ const label =
100
+ index < server.localUrls.length
101
+ ? index === 0
102
+ ? "Editor"
103
+ : "Local"
104
+ : "Network";
105
+ reporter.detail(label, link, { width: 9 });
106
+ });
107
+ if (state.unsandboxed.length)
108
+ reporter.detail(
109
+ "Unsandboxed",
110
+ `${state.unsandboxed.join(", ")} (must be allowed in the editor)`,
111
+ { width: 9 },
112
+ );
113
+ reporter.text(
114
+ ` ${reporter.muted("Restart to pick up changes. Press Ctrl+C to stop.")}`,
115
+ );
116
+ }
117
+
118
+ if (options.open !== false) {
119
+ const opened = await openBrowser(server.editorUrl);
120
+ if (!opened)
121
+ reporter.note(
122
+ "Could not launch a browser; open the editor link above.",
123
+ );
124
+ }
125
+
126
+ let stopping = false;
127
+ const shutdown = (signal) => {
128
+ if (stopping) return;
129
+ stopping = true;
130
+ server
131
+ .close()
132
+ .finally(() =>
133
+ process.exit(signal === "SIGINT" ? EXIT.INTERRUPTED : EXIT.OK),
134
+ );
135
+ };
136
+ process.once("SIGINT", () => shutdown("SIGINT"));
137
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
138
+
139
+ return startup;
140
+ },
141
+ };
@@ -94,6 +94,11 @@ it with "fx feature tests enable".`,
94
94
  flags: "--allow-external-io",
95
95
  description: "Allow network access (fetch and WebSocket) during tests",
96
96
  },
97
+ {
98
+ flags: "--slow",
99
+ description:
100
+ "Run tests asynchronously so async extension blocks can finish",
101
+ },
97
102
  ],
98
103
  examples: [
99
104
  "fx test",
@@ -141,6 +146,7 @@ it with "fx feature tests enable".`,
141
146
  timeout: validateNumber(options.timeout, "--timeout"),
142
147
  allowProjectExtensions: Boolean(options.allowProjectExtensions),
143
148
  allowExternalIO: Boolean(options.allowExternalIO),
149
+ slow: options.slow ? true : undefined,
144
150
  onEvent: testReporter.onEvent,
145
151
  });
146
152
  };
package/src/config.js CHANGED
@@ -38,6 +38,7 @@ export const DEFAULT_TESTS = {
38
38
  ticksPerSecond: 30,
39
39
  failOnRuntimeError: true,
40
40
  parallel: false,
41
+ slow: false,
41
42
  };
42
43
 
43
44
  /**
@@ -129,6 +130,7 @@ export function normalizeTestConfig(value) {
129
130
  if (value.failOnRuntimeError != null)
130
131
  tests.failOnRuntimeError = Boolean(value.failOnRuntimeError);
131
132
  if (value.parallel != null) tests.parallel = Boolean(value.parallel);
133
+ if (value.slow != null) tests.slow = Boolean(value.slow);
132
134
  return tests;
133
135
  }
134
136
 
package/src/editor.js ADDED
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Local project server for `fx open`.
3
+ *
4
+ * PenguinMod can load a project straight from a URL (`?project_url=`), but the
5
+ * editor fetches that URL from its own origin, so the server has to answer with
6
+ * CORS headers — including the private-network preflight Chrome sends when a
7
+ * public page reaches for a loopback address.
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ import http from "node:http";
11
+ import { formatDevUrls } from "./dev.js";
12
+
13
+ /** Editor page that accepts a `project_url` query parameter. */
14
+ export const PENGUINMOD_EDITOR = "https://studio.penguinmod.com/editor.html";
15
+
16
+ /**
17
+ * CORS headers for the editor origin. Same-origin access (the landing page) is
18
+ * not subject to CORS, so restricting the header does not affect it.
19
+ * @param {string} origin
20
+ * @returns {Record<string, string>}
21
+ */
22
+ function corsHeaders(origin) {
23
+ return {
24
+ "Access-Control-Allow-Origin": origin,
25
+ "Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
26
+ "Access-Control-Allow-Headers": "*",
27
+ // Chrome asks before a public page may read a loopback address.
28
+ "Access-Control-Allow-Private-Network": "true",
29
+ };
30
+ }
31
+
32
+ /**
33
+ * Origin the visitor used to reach this server, taken from a validated `Host`
34
+ * header. Returns null when the header is missing or malformed.
35
+ * @param {import("node:http").IncomingMessage} request
36
+ * @returns {string | null}
37
+ */
38
+ function requestOrigin(request) {
39
+ const host = request.headers.host;
40
+ if (!host) return null;
41
+ try {
42
+ const url = new URL(`http://${host}`);
43
+ if (url.host.toLowerCase() !== host.toLowerCase()) return null;
44
+ return url.origin;
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Editor link that loads `projectUrl` directly into the editor.
52
+ * @param {string} projectUrl
53
+ * @param {string} [base]
54
+ * @returns {string}
55
+ */
56
+ export function editorUrl(projectUrl, base = PENGUINMOD_EDITOR) {
57
+ const url = new URL(base);
58
+ url.searchParams.set("project_url", projectUrl);
59
+ return url.href;
60
+ }
61
+
62
+ function escapeHtml(text) {
63
+ return String(text)
64
+ .replaceAll("&", "&amp;")
65
+ .replaceAll("<", "&lt;")
66
+ .replaceAll(">", "&gt;")
67
+ .replaceAll('"', "&quot;");
68
+ }
69
+
70
+ function indexPage({ filename, link }) {
71
+ return `<!doctype html>
72
+ <html>
73
+ <head><meta charset="utf-8"><title>${escapeHtml(filename)}</title></head>
74
+ <body style="margin:0;padding:24px;background:#0e0e12;color:#ddd;font:14px/1.5 ui-monospace,monospace">
75
+ <p>${escapeHtml(filename)} is served at <a style="color:#3cc6ab" href="/${escapeHtml(filename)}">/${escapeHtml(filename)}</a>.</p>
76
+ <p><a style="color:#3cc6ab" href="${escapeHtml(link)}">Open it in the PenguinMod editor</a></p>
77
+ </body>
78
+ </html>`;
79
+ }
80
+
81
+ /**
82
+ * Serve one project archive over HTTP until closed.
83
+ *
84
+ * @param {object} options
85
+ * @param {Buffer|Uint8Array} options.data Archive bytes.
86
+ * @param {string} options.filename Name the archive is served under.
87
+ * @param {string} [options.host="127.0.0.1"]
88
+ * @param {number} [options.port=3000] Port 0 asks the OS for a free port.
89
+ * @param {boolean} [options.strictPort=false]
90
+ * @param {string} [options.editorBase] Editor page to link to.
91
+ * @param {object} [options.log]
92
+ * @returns {Promise<object>}
93
+ */
94
+ export async function startEditorServer(options = {}) {
95
+ if (!options.data) throw new Error("startEditorServer requires project data");
96
+ if (!options.filename)
97
+ throw new Error("startEditorServer requires a filename");
98
+
99
+ const data = Buffer.from(options.data);
100
+ const filename = String(options.filename);
101
+ const host =
102
+ options.host === true || options.host == null
103
+ ? "127.0.0.1"
104
+ : String(options.host);
105
+ const requestedPort = options.port == null ? 3000 : Number(options.port);
106
+ if (
107
+ !Number.isInteger(requestedPort) ||
108
+ requestedPort < 0 ||
109
+ requestedPort > 65535
110
+ )
111
+ throw new Error(`Invalid port: ${options.port}`);
112
+ const strictPort = Boolean(options.strictPort);
113
+ const log = options.log || {};
114
+ const editorBase = options.editorBase
115
+ ? String(options.editorBase)
116
+ : PENGUINMOD_EDITOR;
117
+ const editorOrigin = new URL(editorBase).origin;
118
+ if (editorOrigin === "null")
119
+ throw new Error(`Invalid editor base: ${editorBase}`);
120
+ const cors = corsHeaders(editorOrigin);
121
+
122
+ let closed = false;
123
+ let currentUrl = null;
124
+ const projectPath = `/${encodeURIComponent(filename)}`;
125
+
126
+ const server = http.createServer((request, response) => {
127
+ let url;
128
+ try {
129
+ url = new URL(request.url || "/", "http://localhost");
130
+ } catch {
131
+ response.writeHead(400, {
132
+ ...cors,
133
+ "Content-Type": "text/plain; charset=utf-8",
134
+ });
135
+ response.end("Bad request\n");
136
+ return;
137
+ }
138
+
139
+ // Preflight, including Chrome's private-network request.
140
+ if (request.method === "OPTIONS") {
141
+ response.writeHead(204, cors);
142
+ response.end();
143
+ return;
144
+ }
145
+
146
+ if (request.method !== "GET" && request.method !== "HEAD") {
147
+ response.writeHead(405, {
148
+ ...cors,
149
+ Allow: "GET, HEAD, OPTIONS",
150
+ "Content-Type": "text/plain; charset=utf-8",
151
+ });
152
+ response.end("Method not allowed\n");
153
+ return;
154
+ }
155
+
156
+ const head = request.method === "HEAD";
157
+
158
+ if (url.pathname === projectPath) {
159
+ response.writeHead(200, {
160
+ ...cors,
161
+ "Content-Type": "application/octet-stream",
162
+ "Content-Length": data.length,
163
+ "Cache-Control": "no-store",
164
+ });
165
+ response.end(head ? undefined : data);
166
+ return;
167
+ }
168
+
169
+ if (url.pathname === "/" || url.pathname === "/index.html") {
170
+ response.writeHead(200, {
171
+ ...cors,
172
+ "Content-Type": "text/html; charset=utf-8",
173
+ "Cache-Control": "no-store",
174
+ });
175
+ // Link to the archive on the address the visitor actually reached, so
176
+ // remote visitors are not sent to their own loopback address.
177
+ const origin = requestOrigin(request);
178
+ const projectUrl = origin
179
+ ? `${origin}${projectPath}`
180
+ : currentUrl || projectPath;
181
+ response.end(
182
+ head
183
+ ? undefined
184
+ : indexPage({
185
+ filename,
186
+ link: editorUrl(projectUrl, editorBase),
187
+ }),
188
+ );
189
+ return;
190
+ }
191
+
192
+ if (url.pathname === "/favicon.ico") {
193
+ response.writeHead(204, cors);
194
+ response.end();
195
+ return;
196
+ }
197
+
198
+ response.writeHead(404, {
199
+ ...cors,
200
+ "Content-Type": "text/plain; charset=utf-8",
201
+ });
202
+ response.end(head ? undefined : `Not found: ${filename}\n`);
203
+ });
204
+
205
+ let port;
206
+ for (let attempt = 0; ; attempt += 1) {
207
+ try {
208
+ port = await new Promise((resolve, reject) => {
209
+ const onError = (error) => {
210
+ server.off("listening", onListening);
211
+ reject(error);
212
+ };
213
+ const onListening = () => {
214
+ server.off("error", onError);
215
+ resolve(server.address().port);
216
+ };
217
+ server.once("error", onError);
218
+ server.once("listening", onListening);
219
+ server.listen(requestedPort === 0 ? 0 : requestedPort + attempt, host);
220
+ });
221
+ break;
222
+ } catch (error) {
223
+ if (
224
+ error.code !== "EADDRINUSE" ||
225
+ strictPort ||
226
+ requestedPort === 0 ||
227
+ attempt >= 20
228
+ )
229
+ throw error;
230
+ log.warn?.(
231
+ `Port ${requestedPort + attempt} is in use, trying ${
232
+ requestedPort + attempt + 1
233
+ }…`,
234
+ );
235
+ }
236
+ }
237
+
238
+ const urls = formatDevUrls({ host, port });
239
+ const projectUrls = [...urls.local, ...urls.network].map(
240
+ (base) => `${base}${filename}`,
241
+ );
242
+ const editorUrls = projectUrls.map((projectUrl) =>
243
+ editorUrl(projectUrl, editorBase),
244
+ );
245
+ currentUrl = projectUrls[0];
246
+
247
+ return {
248
+ server,
249
+ host,
250
+ port,
251
+ data,
252
+ filename,
253
+ projectUrl: projectUrls[0],
254
+ projectUrls,
255
+ editorUrl: editorUrls[0],
256
+ editorUrls,
257
+ localUrls: urls.local,
258
+ networkUrls: urls.network,
259
+ async close() {
260
+ if (closed) return;
261
+ closed = true;
262
+ const finished = new Promise((resolve) => server.close(resolve));
263
+ server.closeIdleConnections?.();
264
+ // Stalled transfers must not hold shutdown open forever.
265
+ const force = setTimeout(() => server.closeAllConnections?.(), 2000);
266
+ force.unref?.();
267
+ await finished;
268
+ clearTimeout(force);
269
+ },
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Open `url` in the platform browser. Resolves false when no opener is
275
+ * available, which is the normal case on servers and in containers.
276
+ * @param {string} url
277
+ * @returns {Promise<boolean>}
278
+ */
279
+ export function openBrowser(url) {
280
+ const [command, ...args] =
281
+ process.platform === "darwin"
282
+ ? ["open", url]
283
+ : process.platform === "win32"
284
+ ? ["cmd", "/c", "start", "", url]
285
+ : ["xdg-open", url];
286
+
287
+ return new Promise((resolve) => {
288
+ let settled = false;
289
+ const done = (opened) => {
290
+ if (settled) return;
291
+ settled = true;
292
+ resolve(opened);
293
+ };
294
+ try {
295
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
296
+ child.once("error", () => done(false));
297
+ child.once("spawn", () => {
298
+ child.unref();
299
+ done(true);
300
+ });
301
+ } catch {
302
+ done(false);
303
+ }
304
+ });
305
+ }