@triflare/fx 2.3.0-alpha.2 → 2.3.0-alpha.4
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 +1 -1
- package/product.yml +1 -1
- package/src/cli/commands/index.js +2 -0
- package/src/cli/commands/open.js +141 -0
- package/src/cli/commands/vendor/add.js +32 -5
- package/src/cli/commands/vendor/outdated.js +22 -2
- package/src/cli/commands/vendor/update.js +28 -7
- package/src/editor.js +305 -0
- package/src/marketplace.js +167 -0
- package/src/vendor.js +124 -11
- package/vendor/pm-packager-dist/.fx-build.json +1 -1
- package/vendor/pm-vm-dist/.fx-build.json +1 -1
- package/vendor/pm-vm-dist/dist/iframe-extension-worker.js +1 -1
- package/vendor/pm-vm-dist/dist/js/extension-worker/extension-worker.40d7c84af034b84d9b3c.js +1 -0
- package/vendor/pm-vm-dist/dist/scratch-vm.js +6 -6
- package/vendor/pm-vm-dist/dist/js/extension-worker/extension-worker.0d57461eefdca9f130a6.js +0 -1
package/package.json
CHANGED
package/product.yml
CHANGED
|
@@ -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
|
+
};
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
isMarketplaceSource,
|
|
4
|
+
resolveMarketplaceExtension,
|
|
5
|
+
} from "../../../marketplace.js";
|
|
2
6
|
import { defaultVendorName, installVendorEntry } from "../../../vendor.js";
|
|
3
7
|
import { UsageError } from "../../errors.js";
|
|
4
8
|
import {
|
|
@@ -14,6 +18,7 @@ export async function addVendor({
|
|
|
14
18
|
cwd,
|
|
15
19
|
reporter,
|
|
16
20
|
product,
|
|
21
|
+
fetchImpl,
|
|
17
22
|
}) {
|
|
18
23
|
if (!source) throw new UsageError("vendor add requires a path or URL");
|
|
19
24
|
const configPath = requireConfigPath(cwd, product);
|
|
@@ -22,15 +27,24 @@ export async function addVendor({
|
|
|
22
27
|
|
|
23
28
|
if (typeof options.as === "string" && options.as.trim() === "")
|
|
24
29
|
throw new UsageError("--as needs a non-empty name");
|
|
30
|
+
const resolved = isMarketplaceSource(source)
|
|
31
|
+
? await resolveMarketplaceExtension({ source, fetchImpl })
|
|
32
|
+
: null;
|
|
25
33
|
const name =
|
|
26
|
-
typeof options.as === "string"
|
|
27
|
-
|
|
34
|
+
typeof options.as === "string"
|
|
35
|
+
? options.as
|
|
36
|
+
: (resolved?.id ?? defaultVendorName(source));
|
|
37
|
+
const configSource = resolved
|
|
38
|
+
? resolved.downloadUrl
|
|
39
|
+
: vendorConfigSource(source, configDir, cwd);
|
|
28
40
|
const existing = loaded.vendor.find((entry) => entry.name === name);
|
|
29
41
|
if (existing && existing.source !== configSource && !options.force)
|
|
30
42
|
throw new UsageError(
|
|
31
43
|
`A vendored extension named ${JSON.stringify(name)} already exists.`,
|
|
32
44
|
{
|
|
33
|
-
hint:
|
|
45
|
+
hint: resolved
|
|
46
|
+
? `pass --force to replace it with ${resolved.package}@${resolved.version}, or choose another name with --as`
|
|
47
|
+
: `run "${product.command} vendor update ${name}" or pass --force to replace it`,
|
|
34
48
|
},
|
|
35
49
|
);
|
|
36
50
|
|
|
@@ -50,8 +64,18 @@ export async function addVendor({
|
|
|
50
64
|
vendorDir: path.resolve(configDir, loaded.vendorDir || "extensions"),
|
|
51
65
|
unsandboxed: Boolean(options.unsandboxed) || Boolean(existing?.unsandboxed),
|
|
52
66
|
volatile: existingVolatile,
|
|
67
|
+
marketplace: resolved?.marketplace,
|
|
68
|
+
prefetched: resolved
|
|
69
|
+
? {
|
|
70
|
+
buffer: resolved.buffer,
|
|
71
|
+
etag: resolved.etag,
|
|
72
|
+
lastModified: resolved.lastModified,
|
|
73
|
+
}
|
|
74
|
+
: undefined,
|
|
53
75
|
});
|
|
54
76
|
|
|
77
|
+
if (resolved)
|
|
78
|
+
reporter.info(`Resolved ${source} to ${resolved.package}@${resolved.version}`);
|
|
55
79
|
reporter.success(
|
|
56
80
|
`Vendored ${name} -> ${result.file} (${result.lockEntry.sha256.slice(0, 12)}…)`,
|
|
57
81
|
);
|
|
@@ -64,15 +88,17 @@ export async function addVendor({
|
|
|
64
88
|
source: configSource,
|
|
65
89
|
file: result.file,
|
|
66
90
|
sha256: result.lockEntry.sha256,
|
|
91
|
+
marketplace: resolved?.marketplace ?? null,
|
|
67
92
|
replaced: Boolean(existing),
|
|
68
93
|
};
|
|
69
94
|
}
|
|
70
95
|
|
|
71
96
|
export const vendorAddCommand = {
|
|
72
97
|
name: "add",
|
|
73
|
-
summary: "Vendor an extension by URL or
|
|
98
|
+
summary: "Vendor an extension by URL, path, or Marketplace package",
|
|
74
99
|
description: `Copy an extension into the vendor directory, record its SHA-256 in
|
|
75
|
-
fx.lock, and add it to the project config
|
|
100
|
+
fx.lock, and add it to the project config. Marketplace sources are resolved to a
|
|
101
|
+
pinned download URL first.`,
|
|
76
102
|
arguments: ["<source>"],
|
|
77
103
|
options: [
|
|
78
104
|
{ flags: "--as <name>", description: "Name for the vendored extension" },
|
|
@@ -85,6 +111,7 @@ fx.lock, and add it to the project config.`,
|
|
|
85
111
|
examples: [
|
|
86
112
|
"fx vendor add https://example.com/signals.js --as signals",
|
|
87
113
|
"fx vendor add ./src/mything.js",
|
|
114
|
+
"fx vendor add marketplace:@handle/extension@latest",
|
|
88
115
|
],
|
|
89
116
|
run(context) {
|
|
90
117
|
return addVendor({
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { resolveMarketplaceExtension } from "../../../marketplace.js";
|
|
2
3
|
import { outdatedVendor } from "../../../vendor.js";
|
|
3
4
|
import { UsageError } from "../../errors.js";
|
|
4
5
|
import { outcome } from "../../define-command.js";
|
|
@@ -7,7 +8,8 @@ import { loadVendorConfig, requireConfigPath } from "./helpers.js";
|
|
|
7
8
|
export const vendorOutdatedCommand = {
|
|
8
9
|
name: "outdated",
|
|
9
10
|
summary: "Compare upstream sources with fx.lock",
|
|
10
|
-
description:
|
|
11
|
+
description:
|
|
12
|
+
"Check whether any vendored extension changed upstream or a Marketplace dist-tag points at a newer release.",
|
|
11
13
|
examples: ["fx vendor outdated"],
|
|
12
14
|
async run({ cwd, reporter, product }) {
|
|
13
15
|
const configPath = requireConfigPath(cwd, product);
|
|
@@ -16,7 +18,17 @@ export const vendorOutdatedCommand = {
|
|
|
16
18
|
if (loaded.vendor.length === 0)
|
|
17
19
|
throw new UsageError(`No vendor entries in ${path.basename(configPath)}`);
|
|
18
20
|
|
|
19
|
-
const results = await outdatedVendor({
|
|
21
|
+
const results = await outdatedVendor({
|
|
22
|
+
configDir,
|
|
23
|
+
config: loaded,
|
|
24
|
+
resolveEntry: async (entry, lockEntry) => {
|
|
25
|
+
const marketplace = lockEntry?.marketplace;
|
|
26
|
+
if (!marketplace) return null;
|
|
27
|
+
return resolveMarketplaceExtension({
|
|
28
|
+
source: `marketplace:${marketplace.package}@${marketplace.ref}`,
|
|
29
|
+
});
|
|
30
|
+
},
|
|
31
|
+
});
|
|
20
32
|
let outdated = 0;
|
|
21
33
|
let errors = 0;
|
|
22
34
|
for (const result of results) {
|
|
@@ -35,6 +47,14 @@ export const vendorOutdatedCommand = {
|
|
|
35
47
|
? "danger"
|
|
36
48
|
: "success";
|
|
37
49
|
reporter.item(result.name, label, { width: 24, tone });
|
|
50
|
+
if (
|
|
51
|
+
result.version &&
|
|
52
|
+
result.previousVersion &&
|
|
53
|
+
result.version !== result.previousVersion
|
|
54
|
+
)
|
|
55
|
+
reporter.info(
|
|
56
|
+
`${result.name}: ${result.previousVersion} -> ${result.version}`,
|
|
57
|
+
);
|
|
38
58
|
if (result.error) reporter.warn(result.error);
|
|
39
59
|
}
|
|
40
60
|
if (outdated > 0)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { resolveMarketplaceExtension } from "../../../marketplace.js";
|
|
2
3
|
import { updateVendor } from "../../../vendor.js";
|
|
3
4
|
import { UsageError } from "../../errors.js";
|
|
4
5
|
import { loadVendorConfig, requireConfigPath } from "./helpers.js";
|
|
@@ -7,7 +8,8 @@ export const vendorUpdateCommand = {
|
|
|
7
8
|
name: "update",
|
|
8
9
|
summary: "Update vendored extensions and show diffs",
|
|
9
10
|
description: `Re-fetch upstream sources, update the vendored copies, and show a
|
|
10
|
-
diff for each change.
|
|
11
|
+
diff for each change. Marketplace entries re-resolve the version or dist-tag
|
|
12
|
+
recorded in fx.lock. Use --dry-run to preview without writing.`,
|
|
11
13
|
arguments: ["[name]"],
|
|
12
14
|
options: [
|
|
13
15
|
{ flags: "--dry-run", description: "Show diffs without writing files" },
|
|
@@ -26,24 +28,43 @@ diff for each change. Use --dry-run to preview without writing.`,
|
|
|
26
28
|
config: loaded,
|
|
27
29
|
name: args[0],
|
|
28
30
|
write: !options.dryRun,
|
|
31
|
+
resolveEntry: async (entry, lockEntry) => {
|
|
32
|
+
const marketplace = lockEntry?.marketplace;
|
|
33
|
+
if (!marketplace || entry.source !== lockEntry.source) return null;
|
|
34
|
+
return resolveMarketplaceExtension({
|
|
35
|
+
source: `marketplace:${marketplace.package}@${marketplace.ref}`,
|
|
36
|
+
});
|
|
37
|
+
},
|
|
29
38
|
});
|
|
30
39
|
for (const entry of result.entries) {
|
|
40
|
+
if (entry.versionChanged)
|
|
41
|
+
reporter.info(
|
|
42
|
+
`${entry.name}: ${entry.previousVersion} -> ${entry.version}`,
|
|
43
|
+
);
|
|
31
44
|
if (!entry.changed) {
|
|
32
|
-
reporter.info(`${entry.name} is up to date`);
|
|
45
|
+
if (!entry.sourceChanged) reporter.info(`${entry.name} is up to date`);
|
|
33
46
|
continue;
|
|
34
47
|
}
|
|
35
48
|
reporter.text(entry.diff);
|
|
36
49
|
}
|
|
37
|
-
if (options.dryRun && result.
|
|
38
|
-
reporter.info(`Dry run: ${result.
|
|
39
|
-
else if (result.
|
|
40
|
-
reporter.success(`Updated ${result.
|
|
50
|
+
if (options.dryRun && result.updated > 0)
|
|
51
|
+
reporter.info(`Dry run: ${result.updated} extension(s) would change`);
|
|
52
|
+
else if (result.updated > 0)
|
|
53
|
+
reporter.success(`Updated ${result.updated} extension(s)`);
|
|
41
54
|
else reporter.success("Everything is up to date");
|
|
42
55
|
|
|
43
56
|
return {
|
|
44
57
|
dryRun: Boolean(options.dryRun),
|
|
58
|
+
updated: result.updated,
|
|
45
59
|
changed: result.changed,
|
|
46
|
-
entries: result.entries.map(
|
|
60
|
+
entries: result.entries.map(
|
|
61
|
+
({ name, changed, versionChanged, version }) => ({
|
|
62
|
+
name,
|
|
63
|
+
changed,
|
|
64
|
+
versionChanged,
|
|
65
|
+
version,
|
|
66
|
+
}),
|
|
67
|
+
),
|
|
47
68
|
};
|
|
48
69
|
},
|
|
49
70
|
};
|
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("&", "&")
|
|
65
|
+
.replaceAll("<", "<")
|
|
66
|
+
.replaceAll(">", ">")
|
|
67
|
+
.replaceAll('"', """);
|
|
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
|
+
}
|