@air-jam/server 0.9.2 → 1.0.0-beta.1

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.
Files changed (47) hide show
  1. package/bin/air-jam-server.mjs +43 -20
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/chunk-2BHF5ZCS.js +38 -0
  4. package/dist/chunk-2BHF5ZCS.js.map +1 -0
  5. package/dist/{chunk-5ZVGSYXC.js → chunk-5YSBR6YK.js} +1 -46
  6. package/dist/chunk-5YSBR6YK.js.map +1 -0
  7. package/dist/chunk-64G5AWIQ.js +1271 -0
  8. package/dist/chunk-64G5AWIQ.js.map +1 -0
  9. package/dist/chunk-GMZVQDC6.js +54 -0
  10. package/dist/chunk-GMZVQDC6.js.map +1 -0
  11. package/dist/chunk-ILYZVHYT.js +39 -0
  12. package/dist/chunk-ILYZVHYT.js.map +1 -0
  13. package/dist/chunk-INZKL5US.js +484 -0
  14. package/dist/chunk-INZKL5US.js.map +1 -0
  15. package/dist/chunk-JYI2GKLJ.js +334 -0
  16. package/dist/chunk-JYI2GKLJ.js.map +1 -0
  17. package/dist/cli.js +31 -112
  18. package/dist/cli.js.map +1 -1
  19. package/dist/index.d.ts +31 -0
  20. package/dist/index.js +15 -5972
  21. package/dist/index.js.map +1 -1
  22. package/dist/process-lifecycle-A55YCNJN.js +8 -0
  23. package/dist/room-server-4U4TBSS5.js +13 -0
  24. package/dist/room-server-4U4TBSS5.js.map +1 -0
  25. package/dist/room-server-BO0iOvhH.d.ts +144 -0
  26. package/dist/room-server.d.ts +7 -0
  27. package/dist/room-server.js +13 -0
  28. package/dist/room-server.js.map +1 -0
  29. package/dist/room.d.ts +360 -0
  30. package/dist/room.js +17 -0
  31. package/dist/room.js.map +1 -0
  32. package/package.json +42 -29
  33. package/dist/chunk-5ZVGSYXC.js.map +0 -1
  34. package/dist/chunk-RM7AMBDY.js +0 -831
  35. package/dist/chunk-RM7AMBDY.js.map +0 -1
  36. package/dist/game-dev-D3TEAHOD.js +0 -422
  37. package/dist/game-dev-D3TEAHOD.js.map +0 -1
  38. package/dist/local-dev-state-QT7H5GUA.js +0 -270
  39. package/dist/local-dev-state-QT7H5GUA.js.map +0 -1
  40. package/dist/secure-dev-HMOGLYVC.js +0 -39
  41. package/dist/topology-PM3PI753.js +0 -140
  42. package/dist/topology-PM3PI753.js.map +0 -1
  43. package/src/project-cli/vite-config.d.mts +0 -17
  44. package/src/project-cli/vite-config.mjs +0 -121
  45. package/src/project-cli/vite-https.d.mts +0 -14
  46. package/src/project-cli/vite-https.mjs +0 -39
  47. /package/dist/{secure-dev-HMOGLYVC.js.map → process-lifecycle-A55YCNJN.js.map} +0 -0
@@ -1,831 +0,0 @@
1
- // src/project-cli/secure-dev.mjs
2
- import { execFileSync as execFileSync2 } from "child_process";
3
- import fs3 from "fs";
4
- import path from "path";
5
-
6
- // src/project-cli/dev-utils.mjs
7
- import { execFileSync, spawn } from "child_process";
8
- import fs from "fs";
9
- import net from "net";
10
- import os from "os";
11
- var isPortOpen = (port) => new Promise((resolve) => {
12
- const socket = net.createConnection({ port, host: "127.0.0.1" });
13
- const done = (value) => {
14
- socket.removeAllListeners();
15
- socket.destroy();
16
- resolve(value);
17
- };
18
- socket.setTimeout(400);
19
- socket.on("connect", () => done(true));
20
- socket.on("timeout", () => done(false));
21
- socket.on("error", () => done(false));
22
- });
23
- var waitForPort = (port, timeoutMs) => new Promise((resolve, reject) => {
24
- const start = Date.now();
25
- const tryConnect = () => {
26
- const socket = net.createConnection({ port, host: "127.0.0.1" });
27
- socket.on("connect", () => {
28
- socket.end();
29
- resolve(true);
30
- });
31
- socket.on("error", () => {
32
- socket.destroy();
33
- if (Date.now() - start > timeoutMs) {
34
- reject(new Error(`Timed out waiting for localhost:${port}`));
35
- return;
36
- }
37
- setTimeout(tryConnect, 300);
38
- });
39
- };
40
- tryConnect();
41
- });
42
- var loadEnvFile = (filePath, env = process.env) => {
43
- if (!fs.existsSync(filePath)) {
44
- return;
45
- }
46
- const content = fs.readFileSync(filePath, "utf8");
47
- for (const rawLine of content.split("\n")) {
48
- const line = rawLine.trim();
49
- if (!line || line.startsWith("#")) {
50
- continue;
51
- }
52
- const eq = line.indexOf("=");
53
- if (eq <= 0) {
54
- continue;
55
- }
56
- const key = line.slice(0, eq).trim();
57
- const value = line.slice(eq + 1).trim();
58
- if (!env[key]) {
59
- env[key] = value;
60
- }
61
- }
62
- };
63
- var isPrivateIpv4 = (ip) => ip.startsWith("10.") || ip.startsWith("192.168.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
64
- var isVirtualInterface = (name) => /^(lo|docker|br-|veth|vbox|vmnet|utun|gif|stf|awdl|llw)/i.test(name);
65
- var scoreIp = (ip) => {
66
- if (ip.startsWith("192.168.")) {
67
- const parts = ip.split(".");
68
- const third = Number(parts[2] ?? "0");
69
- return third < 64 ? 300 - third : 200 - third;
70
- }
71
- if (ip.startsWith("10.")) {
72
- return 150;
73
- }
74
- if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
75
- return 100;
76
- }
77
- return 0;
78
- };
79
- var detectLocalIpv4 = () => {
80
- const networks = os.networkInterfaces();
81
- const candidates = [];
82
- for (const [name, entries] of Object.entries(networks)) {
83
- if (!entries || isVirtualInterface(name)) {
84
- continue;
85
- }
86
- for (const entry of entries) {
87
- if (!entry || entry.internal || entry.family !== "IPv4") {
88
- continue;
89
- }
90
- const ip = entry.address;
91
- if (!isPrivateIpv4(ip) || ip.startsWith("169.254.")) {
92
- continue;
93
- }
94
- candidates.push({ ip, score: scoreIp(ip) });
95
- }
96
- }
97
- candidates.sort((a, b) => b.score - a.score);
98
- return candidates[0]?.ip ?? null;
99
- };
100
- var getFlagValue = (argv, flag) => {
101
- const inlineArg = argv.find((arg) => arg.startsWith(`${flag}=`));
102
- if (inlineArg) {
103
- return inlineArg.slice(flag.length + 1);
104
- }
105
- const index = argv.indexOf(flag);
106
- return index === -1 ? null : argv[index + 1] ?? null;
107
- };
108
- var hasFlag = (argv, flag) => argv.includes(flag);
109
- var upsertEnv = (filePath, key, value) => {
110
- let content = "";
111
- if (fs.existsSync(filePath)) {
112
- content = fs.readFileSync(filePath, "utf8");
113
- }
114
- const nextLine = `${key}=${value}`;
115
- const pattern = new RegExp(`^${key}=.*$`, "m");
116
- if (pattern.test(content)) {
117
- content = content.replace(pattern, nextLine);
118
- } else {
119
- content += `${content.endsWith("\n") || content.length === 0 ? "" : "\n"}${nextLine}
120
- `;
121
- }
122
- fs.writeFileSync(filePath, content, "utf8");
123
- };
124
- var commandExists = (command, args = ["--version"]) => {
125
- try {
126
- execFileSync(command, args, {
127
- encoding: "utf8",
128
- stdio: ["ignore", "pipe", "pipe"]
129
- });
130
- return true;
131
- } catch {
132
- return false;
133
- }
134
- };
135
- var logChunk = (prefix, data) => {
136
- const text = data.toString();
137
- for (const line of text.split("\n")) {
138
- if (!line.trim()) {
139
- continue;
140
- }
141
- console.log(`[${prefix}] ${line}`);
142
- }
143
- };
144
- var createProcessGroup = () => {
145
- const children = [];
146
- let isShuttingDown = false;
147
- const shutdown = (code = 0) => {
148
- if (isShuttingDown) {
149
- return;
150
- }
151
- isShuttingDown = true;
152
- for (const child of children) {
153
- if (!child.killed) {
154
- child.kill("SIGTERM");
155
- }
156
- }
157
- setTimeout(() => process.exit(code), 100);
158
- };
159
- const run2 = (name, command, args, options = {}) => {
160
- const { fatal = true, ...spawnOptions } = options;
161
- const child = spawn(command, args, {
162
- stdio: ["inherit", "pipe", "pipe"],
163
- ...spawnOptions
164
- });
165
- child.stdout.on("data", (data) => logChunk(name, data));
166
- child.stderr.on("data", (data) => logChunk(name, data));
167
- child.on("exit", (code, signal) => {
168
- if (!fatal) {
169
- return;
170
- }
171
- if (code === 0 || signal === "SIGTERM") {
172
- return;
173
- }
174
- console.error(`[${name}] exited with code ${code ?? "null"}`);
175
- shutdown(code ?? 1);
176
- });
177
- children.push(child);
178
- return child;
179
- };
180
- const registerSignalHandlers = () => {
181
- process.on("SIGINT", () => shutdown(0));
182
- process.on("SIGTERM", () => shutdown(0));
183
- };
184
- return {
185
- run: run2,
186
- shutdown,
187
- registerSignalHandlers
188
- };
189
- };
190
-
191
- // src/project-cli/internal/env-validation.mjs
192
- var toEnvKey = (path2) => {
193
- if (!Array.isArray(path2) || path2.length === 0) {
194
- return "<root>";
195
- }
196
- const firstStringSegment = path2.find(
197
- (segment) => typeof segment === "string"
198
- );
199
- return typeof firstStringSegment === "string" ? firstStringSegment : "<root>";
200
- };
201
- var describeExpectedRule = (issue) => {
202
- switch (issue.code) {
203
- case "invalid_type":
204
- return `type ${String(issue.expected)}`;
205
- case "invalid_value":
206
- return issue.values && issue.values.length > 0 ? `one of: ${issue.values.join(", ")}` : "a valid value";
207
- case "too_small":
208
- return issue.minimum != null ? `at least ${issue.minimum}${issue.inclusive === false ? " (exclusive)" : ""}` : "a larger value";
209
- case "too_big":
210
- return issue.maximum != null ? `at most ${issue.maximum}${issue.inclusive === false ? " (exclusive)" : ""}` : "a smaller value";
211
- case "invalid_format":
212
- return issue.format ? `format ${issue.format}` : "a valid format";
213
- default:
214
- return "a valid value";
215
- }
216
- };
217
- var toReceivedValue = (env, envKey) => {
218
- if (!env || envKey === "<root>") {
219
- return void 0;
220
- }
221
- const value = env[envKey];
222
- if (typeof value === "undefined") {
223
- return void 0;
224
- }
225
- return String(value);
226
- };
227
- var normalizeIssues = ({ zodIssues, env, keyHints }) => zodIssues.map((issue) => {
228
- const envKey = toEnvKey(issue.path);
229
- return {
230
- envKey,
231
- expected: describeExpectedRule(issue),
232
- received: toReceivedValue(env, envKey),
233
- message: issue.message,
234
- fix: keyHints?.[envKey] ?? (envKey === "<root>" ? "Adjust the environment values so the schema constraints pass." : `Set ${envKey} to a valid value.`)
235
- };
236
- }).sort((a, b) => {
237
- if (a.envKey === b.envKey) {
238
- return a.message.localeCompare(b.message);
239
- }
240
- return a.envKey.localeCompare(b.envKey);
241
- });
242
- var EnvValidationError = class extends Error {
243
- constructor({ boundary, issues, docsHint }) {
244
- const count = issues.length;
245
- super(
246
- `${boundary}: invalid environment configuration (${count} issue${count === 1 ? "" : "s"})`
247
- );
248
- this.name = "EnvValidationError";
249
- this.boundary = boundary;
250
- this.issues = issues;
251
- this.docsHint = docsHint;
252
- }
253
- };
254
- var validateEnv = ({
255
- boundary,
256
- schema,
257
- env = process.env,
258
- docsHint,
259
- keyHints
260
- }) => {
261
- const result = schema.safeParse(env);
262
- if (result.success) {
263
- return result.data;
264
- }
265
- throw new EnvValidationError({
266
- boundary,
267
- docsHint,
268
- issues: normalizeIssues({
269
- zodIssues: result.error.issues,
270
- env,
271
- keyHints
272
- })
273
- });
274
- };
275
-
276
- // src/project-cli/runtime-env.mjs
277
- import { z } from "zod";
278
- var trimToUndefined = (value) => {
279
- if (typeof value !== "string") {
280
- return void 0;
281
- }
282
- const normalized = value.trim();
283
- return normalized.length > 0 ? normalized : void 0;
284
- };
285
- var optionalEnvValue = z.string().optional().transform((value) => trimToUndefined(value));
286
- var optionalEnumFromEnv = (envKey, values) => optionalEnvValue.transform((value, context) => {
287
- if (!value) {
288
- return void 0;
289
- }
290
- if (!values.includes(value)) {
291
- context.addIssue({
292
- code: "custom",
293
- message: `${envKey} must be one of: ${values.join(", ")}.`
294
- });
295
- return z.NEVER;
296
- }
297
- return value;
298
- });
299
- var positiveIntegerFromEnv = (envKey, fallback) => optionalEnvValue.transform((value, context) => {
300
- if (!value) {
301
- return fallback;
302
- }
303
- const parsed = Number.parseInt(value, 10);
304
- if (!Number.isInteger(parsed) || parsed <= 0) {
305
- context.addIssue({
306
- code: "custom",
307
- message: `${envKey} must be a positive integer.`
308
- });
309
- return z.NEVER;
310
- }
311
- return parsed;
312
- });
313
- var createAirJamRuntimeEnvSchema = z.object({
314
- VITE_PORT: positiveIntegerFromEnv("VITE_PORT", 5173),
315
- AIR_JAM_SECURE_MODE: optionalEnumFromEnv("AIR_JAM_SECURE_MODE", [
316
- "local",
317
- "tunnel"
318
- ]),
319
- AIR_JAM_MKCERT_TRUST_STORES: optionalEnvValue,
320
- AIR_JAM_SECURE_PUBLIC_HOST: optionalEnvValue,
321
- CLOUDFLARE_TUNNEL_NAME: optionalEnvValue,
322
- AIR_JAM_SECURE_ROOT: optionalEnvValue,
323
- VITE_AIR_JAM_SERVER_URL: optionalEnvValue,
324
- VITE_AIR_JAM_PUBLIC_HOST: optionalEnvValue,
325
- NEXT_PUBLIC_APP_URL: optionalEnvValue,
326
- HOME: optionalEnvValue
327
- });
328
- var loadCreateAirJamRuntimeEnv = ({
329
- env = process.env,
330
- boundary = "air-jam-server.runtime"
331
- } = {}) => validateEnv({
332
- boundary,
333
- schema: createAirJamRuntimeEnvSchema,
334
- env,
335
- docsHint: "Fix runtime env values in .env / .env.local before running Air Jam project runtime commands.",
336
- keyHints: {
337
- VITE_PORT: "Set a positive integer Vite port (for example: VITE_PORT=5173).",
338
- AIR_JAM_SECURE_MODE: "Use AIR_JAM_SECURE_MODE=local or AIR_JAM_SECURE_MODE=tunnel."
339
- }
340
- });
341
-
342
- // src/project-cli/runtime-topology.mjs
343
- import {
344
- resolveProjectRuntimeTopology,
345
- resolveRuntimeTopology,
346
- serializeRuntimeTopology
347
- } from "@air-jam/sdk/runtime-topology";
348
-
349
- // src/project-cli/vite-https.mjs
350
- import fs2 from "fs";
351
- var DEFAULT_AIR_JAM_DEV_BACKEND_URL = "http://127.0.0.1:4000";
352
-
353
- // src/project-cli/runtime-topology.mjs
354
- var buildStandaloneGameTopology = ({
355
- surfaceRole,
356
- publicHost,
357
- secureTransport = false,
358
- backendOrigin = DEFAULT_AIR_JAM_DEV_BACKEND_URL
359
- }) => resolveProjectRuntimeTopology({
360
- runtimeMode: secureTransport ? "standalone-secure" : "standalone-dev",
361
- surfaceRole,
362
- appOrigin: publicHost,
363
- backendOrigin,
364
- publicHost,
365
- secureTransport
366
- });
367
- var serializeResolvedTopology = (topology) => serializeRuntimeTopology(topology);
368
-
369
- // src/project-cli/secure-dev.mjs
370
- var SECURE_MODE_LOCAL = "local";
371
- var SECURE_MODE_TUNNEL = "tunnel";
372
- var DEFAULT_GAME_PORT = 5173;
373
- var DEFAULT_PLATFORM_PORT = 3e3;
374
- var SECURE_DEV_VERSION = 1;
375
- var SECURE_MODE_VALUES = /* @__PURE__ */ new Set([SECURE_MODE_LOCAL, SECURE_MODE_TUNNEL]);
376
- var resolveRequestedSecureMode = ({
377
- argv = [],
378
- env = process.env,
379
- defaultMode = SECURE_MODE_LOCAL
380
- } = {}) => {
381
- const flagValue = getFlagValue(argv, "--secure-mode");
382
- const envValue = env.AIR_JAM_SECURE_MODE;
383
- const rawValue = (flagValue ?? envValue ?? defaultMode).trim().toLowerCase();
384
- if (!SECURE_MODE_VALUES.has(rawValue)) {
385
- throw new Error(
386
- `Unsupported secure mode "${rawValue}". Use "local" or "tunnel".`
387
- );
388
- }
389
- return rawValue;
390
- };
391
- var parseSecureInitArgs = (argv = [], env = process.env) => ({
392
- mode: resolveRequestedSecureMode({ argv, env }),
393
- hostname: getFlagValue(argv, "--hostname")?.trim() ?? "",
394
- tunnel: getFlagValue(argv, "--tunnel")?.trim() ?? ""
395
- });
396
- var parseGameDevArgs = (argv = [], env = process.env) => {
397
- const runtimeEnv = typeof env.VITE_PORT === "number" ? env : loadCreateAirJamRuntimeEnv({
398
- env,
399
- boundary: "air-jam-server.dev"
400
- });
401
- return {
402
- secure: hasFlag(argv, "--secure"),
403
- secureMode: resolveRequestedSecureMode({ argv, env: runtimeEnv }),
404
- previewManaged: hasFlag(argv, "--preview-managed"),
405
- webOnly: hasFlag(argv, "--web-only"),
406
- serverOnly: hasFlag(argv, "--server-only"),
407
- allowExistingGame: hasFlag(argv, "--allow-existing-game"),
408
- port: runtimeEnv.VITE_PORT ?? DEFAULT_GAME_PORT
409
- };
410
- };
411
- var getSecurePaths = (cwd) => {
412
- const rootDir = cwd;
413
- const airJamDir = path.join(rootDir, ".airjam");
414
- const certDir = path.join(airJamDir, "certs");
415
- return {
416
- rootDir,
417
- airJamDir,
418
- certDir,
419
- secureDevStateFile: path.join(airJamDir, "secure-dev.json"),
420
- certFile: path.join(certDir, "local-dev.pem"),
421
- keyFile: path.join(certDir, "local-dev-key.pem"),
422
- cloudflaredDir: path.join(rootDir, ".cloudflared"),
423
- cloudflaredConfigFile: path.join(rootDir, ".cloudflared", "config.yml")
424
- };
425
- };
426
- var run = (command, args, options = {}) => execFileSync2(command, args, {
427
- encoding: "utf8",
428
- stdio: options.silent ? ["ignore", "pipe", "pipe"] : "inherit",
429
- cwd: options.cwd,
430
- env: options.env ?? process.env
431
- });
432
- var buildLocalCertificateHosts = (lanIp) => {
433
- const hosts = ["localhost", "127.0.0.1", "::1"];
434
- if (lanIp) {
435
- hosts.push(lanIp);
436
- }
437
- return hosts;
438
- };
439
- var resolveSecurePublicHost = ({ mode, port, lanIp, tunnelHost }) => {
440
- if (mode === SECURE_MODE_TUNNEL) {
441
- return tunnelHost;
442
- }
443
- const host = lanIp ?? "localhost";
444
- return `https://${host}:${port}`;
445
- };
446
- var resolveSecureLoopbackHost = (port) => `https://127.0.0.1:${port}`;
447
- var resolveSecurePlatformHost = ({
448
- mode,
449
- lanIp,
450
- tunnelHost,
451
- port = DEFAULT_PLATFORM_PORT
452
- }) => {
453
- if (mode === SECURE_MODE_TUNNEL) {
454
- return tunnelHost;
455
- }
456
- const host = lanIp ?? "localhost";
457
- return `https://${host}:${port}`;
458
- };
459
- var readSecureDevState = (filePath) => {
460
- if (!fs3.existsSync(filePath)) {
461
- return null;
462
- }
463
- return JSON.parse(fs3.readFileSync(filePath, "utf8"));
464
- };
465
- var writeSecureDevState = (filePath, state) => {
466
- fs3.mkdirSync(path.dirname(filePath), { recursive: true });
467
- fs3.writeFileSync(filePath, JSON.stringify(state, null, 2), "utf8");
468
- };
469
- var ensureMkcertInstalled = () => {
470
- if (!commandExists("mkcert", ["-help"])) {
471
- throw new Error(
472
- [
473
- "mkcert is required for local secure dev.",
474
- "Install it once, then rerun `air-jam-server secure:init`.",
475
- "macOS: brew install mkcert",
476
- "Windows: winget install FiloSottile.mkcert or choco install mkcert",
477
- "Linux: install mkcert from your package manager or https://github.com/FiloSottile/mkcert"
478
- ].join("\n")
479
- );
480
- }
481
- };
482
- var ensureCloudflaredInstalled = () => {
483
- if (!commandExists("cloudflared")) {
484
- throw new Error(
485
- [
486
- "cloudflared is required for tunnel secure mode.",
487
- "Install it once, then rerun `air-jam-server secure:init --mode=tunnel ...`."
488
- ].join("\n")
489
- );
490
- }
491
- };
492
- var ensureCloudflareLogin = (env = process.env) => {
493
- const certPath = path.join(env.HOME || "", ".cloudflared", "cert.pem");
494
- if (!fs3.existsSync(certPath)) {
495
- throw new Error(
496
- "Cloudflare login not found. Run: cloudflared tunnel login"
497
- );
498
- }
499
- };
500
- var ensureLocalCertificate = ({
501
- cwd,
502
- certFile,
503
- keyFile,
504
- lanIp,
505
- env,
506
- runtimeEnv
507
- }) => {
508
- ensureMkcertInstalled();
509
- fs3.mkdirSync(path.dirname(certFile), { recursive: true });
510
- const trustStores = runtimeEnv.AIR_JAM_MKCERT_TRUST_STORES || "system,nss";
511
- const mkcertEnv = {
512
- ...env,
513
- TRUST_STORES: trustStores
514
- };
515
- run("mkcert", ["-install"], {
516
- cwd,
517
- env: mkcertEnv
518
- });
519
- run(
520
- "mkcert",
521
- [
522
- "-cert-file",
523
- certFile,
524
- "-key-file",
525
- keyFile,
526
- ...buildLocalCertificateHosts(lanIp)
527
- ],
528
- { cwd, env: mkcertEnv }
529
- );
530
- };
531
- var configureCloudflareTunnel = ({
532
- cwd,
533
- cloudflaredConfigFile,
534
- hostname,
535
- tunnel,
536
- gamePort,
537
- env
538
- }) => {
539
- ensureCloudflaredInstalled();
540
- ensureCloudflareLogin(env);
541
- let tunnelExists = false;
542
- try {
543
- run("cloudflared", ["tunnel", "info", tunnel], { cwd, silent: true });
544
- tunnelExists = true;
545
- } catch {
546
- tunnelExists = false;
547
- }
548
- if (!tunnelExists) {
549
- console.log(`Creating tunnel ${tunnel}...`);
550
- run("cloudflared", ["tunnel", "create", tunnel], { cwd });
551
- } else {
552
- console.log(`Tunnel ${tunnel} already exists, reusing it.`);
553
- }
554
- console.log(`Routing DNS ${hostname} -> ${tunnel}...`);
555
- run("cloudflared", ["tunnel", "route", "dns", tunnel, hostname], { cwd });
556
- const tunnelInfoRaw = run("cloudflared", ["tunnel", "info", tunnel], {
557
- cwd,
558
- silent: true
559
- });
560
- const idMatch = tunnelInfoRaw.match(/[0-9a-f-]{36}/i);
561
- if (!idMatch) {
562
- throw new Error(
563
- "Could not resolve tunnel UUID from `cloudflared tunnel info`."
564
- );
565
- }
566
- const tunnelId = idMatch[0];
567
- const credentialsFile = path.join(
568
- env.HOME || "",
569
- ".cloudflared",
570
- `${tunnelId}.json`
571
- );
572
- fs3.mkdirSync(path.dirname(cloudflaredConfigFile), { recursive: true });
573
- fs3.writeFileSync(
574
- cloudflaredConfigFile,
575
- [
576
- `tunnel: ${tunnel}`,
577
- `credentials-file: ${credentialsFile}`,
578
- "",
579
- "ingress:",
580
- ` - hostname: ${hostname}`,
581
- ` service: https://127.0.0.1:${gamePort}`,
582
- " originRequest:",
583
- " noTLSVerify: true",
584
- " - service: http_status:404",
585
- ""
586
- ].join("\n"),
587
- "utf8"
588
- );
589
- };
590
- var initializeSecureDev = ({
591
- cwd,
592
- envFilePath,
593
- mode,
594
- hostname,
595
- tunnel,
596
- env = process.env,
597
- runtimeEnv = loadCreateAirJamRuntimeEnv({
598
- env,
599
- boundary: "air-jam-server.secure-init"
600
- }),
601
- gamePort = DEFAULT_GAME_PORT,
602
- nextStepMessage = "pnpm run dev -- --secure"
603
- } = {}) => {
604
- const paths = getSecurePaths(cwd);
605
- const lanIp = detectLocalIpv4();
606
- const tunnelHost = hostname ? `https://${hostname}` : null;
607
- ensureLocalCertificate({
608
- cwd,
609
- certFile: paths.certFile,
610
- keyFile: paths.keyFile,
611
- lanIp,
612
- env,
613
- runtimeEnv
614
- });
615
- if (mode === SECURE_MODE_TUNNEL) {
616
- if (!hostname || !tunnel) {
617
- throw new Error(
618
- "Tunnel mode requires both --hostname <dev.example.com> and --tunnel <tunnel-name>."
619
- );
620
- }
621
- configureCloudflareTunnel({
622
- cwd,
623
- cloudflaredConfigFile: paths.cloudflaredConfigFile,
624
- hostname,
625
- tunnel,
626
- gamePort,
627
- env
628
- });
629
- }
630
- const nextState = {
631
- version: SECURE_DEV_VERSION,
632
- mode,
633
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
634
- lanIp,
635
- certFile: paths.certFile,
636
- keyFile: paths.keyFile,
637
- hosts: buildLocalCertificateHosts(lanIp),
638
- publicHost: resolveSecurePublicHost({
639
- mode,
640
- port: gamePort,
641
- lanIp,
642
- tunnelHost
643
- }),
644
- tunnelHost,
645
- tunnelName: tunnel || null
646
- };
647
- writeSecureDevState(paths.secureDevStateFile, nextState);
648
- upsertEnv(envFilePath, "AIR_JAM_SECURE_MODE", mode);
649
- if (mode === SECURE_MODE_TUNNEL) {
650
- upsertEnv(envFilePath, "AIR_JAM_SECURE_PUBLIC_HOST", nextState.publicHost);
651
- upsertEnv(envFilePath, "CLOUDFLARE_TUNNEL_NAME", tunnel);
652
- }
653
- console.log("\nSecure dev setup complete.");
654
- console.log(`Mode: ${mode}`);
655
- console.log(`Public host: ${nextState.publicHost}`);
656
- console.log(`Certificate: ${paths.certFile}`);
657
- if (!lanIp) {
658
- console.log(
659
- "No LAN IPv4 address was detected. Secure dev will work on localhost, but phone-on-LAN testing is not configured."
660
- );
661
- }
662
- if (mode === SECURE_MODE_TUNNEL) {
663
- console.log(`Tunnel: ${tunnel}`);
664
- }
665
- console.log(`Next: ${nextStepMessage}`);
666
- return nextState;
667
- };
668
- var loadSecureDevState = ({
669
- cwd,
670
- mode,
671
- env = process.env,
672
- gamePort = DEFAULT_GAME_PORT
673
- } = {}) => {
674
- const runtimeEnv = loadCreateAirJamRuntimeEnv({
675
- env,
676
- boundary: "air-jam-server.secure-state"
677
- });
678
- const paths = getSecurePaths(cwd);
679
- const state = readSecureDevState(paths.secureDevStateFile);
680
- if (!state) {
681
- throw new Error(
682
- "Missing .airjam/secure-dev.json. Run `air-jam-server secure:init` first."
683
- );
684
- }
685
- if (!fs3.existsSync(state.certFile ?? "") || !fs3.existsSync(state.keyFile ?? "")) {
686
- throw new Error(
687
- "Missing local HTTPS certificate files. Run `pnpm secure:init` again."
688
- );
689
- }
690
- if (mode === SECURE_MODE_LOCAL) {
691
- const currentLanIp = detectLocalIpv4();
692
- if ((state.lanIp ?? null) !== (currentLanIp ?? null)) {
693
- throw new Error(
694
- "Your LAN IPv4 address changed since secure setup was created. Run `air-jam-server secure:init` again."
695
- );
696
- }
697
- }
698
- const publicHost = resolveSecurePublicHost({
699
- mode,
700
- port: gamePort,
701
- lanIp: state.lanIp ?? null,
702
- tunnelHost: runtimeEnv.AIR_JAM_SECURE_PUBLIC_HOST || state.tunnelHost || null
703
- });
704
- const tunnelName = runtimeEnv.CLOUDFLARE_TUNNEL_NAME || state.tunnelName || null;
705
- if (mode === SECURE_MODE_TUNNEL && !tunnelName) {
706
- throw new Error(
707
- "Missing CLOUDFLARE_TUNNEL_NAME for tunnel secure mode. Run `air-jam-server secure:init --mode=tunnel ...` again."
708
- );
709
- }
710
- return {
711
- ...state,
712
- mode,
713
- publicHost,
714
- tunnelName,
715
- certFile: state.certFile,
716
- keyFile: state.keyFile,
717
- loopbackHost: resolveSecureLoopbackHost(gamePort),
718
- platformHost: resolveSecurePlatformHost({
719
- mode,
720
- lanIp: state.lanIp ?? null,
721
- tunnelHost: runtimeEnv.AIR_JAM_SECURE_PUBLIC_HOST || state.tunnelHost || null,
722
- port: DEFAULT_PLATFORM_PORT
723
- })
724
- };
725
- };
726
- var buildSecureGameEnv = ({
727
- secureState,
728
- webOnly,
729
- env = process.env
730
- } = {}) => ({
731
- VITE_AIR_JAM_RUNTIME_TOPOLOGY: serializeResolvedTopology(
732
- buildStandaloneGameTopology({
733
- surfaceRole: "host",
734
- publicHost: secureState.publicHost,
735
- secureTransport: true
736
- })
737
- ),
738
- AIR_JAM_SECURE_MODE: secureState.mode,
739
- AIR_JAM_SECURE_PUBLIC_HOST: secureState.publicHost,
740
- AIR_JAM_DEV_CERT_FILE: secureState.certFile,
741
- AIR_JAM_DEV_KEY_FILE: secureState.keyFile,
742
- AIR_JAM_DEV_PROXY_BACKEND_URL: "http://127.0.0.1:4000",
743
- VITE_AIR_JAM_PUBLIC_HOST: secureState.publicHost,
744
- ...webOnly && env.VITE_AIR_JAM_SERVER_URL ? { VITE_AIR_JAM_SERVER_URL: env.VITE_AIR_JAM_SERVER_URL } : {}
745
- });
746
- var appendNextHttpsArgs = ({ env = process.env, args = [] } = {}) => {
747
- const certFile = env.AIR_JAM_DEV_CERT_FILE;
748
- const keyFile = env.AIR_JAM_DEV_KEY_FILE;
749
- if (!certFile || !keyFile) {
750
- return args;
751
- }
752
- return [
753
- ...args,
754
- "--experimental-https",
755
- "--experimental-https-key",
756
- keyFile,
757
- "--experimental-https-cert",
758
- certFile
759
- ];
760
- };
761
- var runSecureInitCli = async ({
762
- cwd = process.cwd(),
763
- argv = process.argv.slice(2),
764
- env = process.env,
765
- nextStepMessage = "pnpm run dev -- --secure"
766
- } = {}) => {
767
- if (hasFlag(argv, "--help") || hasFlag(argv, "-h")) {
768
- console.log(
769
- "Usage: air-jam-server secure:init [--mode=local|tunnel] [--hostname <dev.example.com>] [--tunnel <tunnel-name>]"
770
- );
771
- console.log("");
772
- console.log("Modes:");
773
- console.log(
774
- " local Generate trusted local HTTPS certs with mkcert (default)"
775
- );
776
- console.log(
777
- " tunnel Generate local HTTPS certs and configure the optional Cloudflare tunnel fallback"
778
- );
779
- return;
780
- }
781
- loadEnvFile(path.join(cwd, ".env"), env);
782
- loadEnvFile(path.join(cwd, ".env.local"), env);
783
- const runtimeEnv = loadCreateAirJamRuntimeEnv({
784
- env,
785
- boundary: "air-jam-server.secure-init"
786
- });
787
- const args = parseSecureInitArgs(argv, runtimeEnv);
788
- initializeSecureDev({
789
- cwd,
790
- envFilePath: path.join(cwd, ".env.local"),
791
- mode: args.mode,
792
- hostname: args.hostname,
793
- tunnel: args.tunnel,
794
- env,
795
- runtimeEnv,
796
- gamePort: runtimeEnv.VITE_PORT ?? DEFAULT_GAME_PORT,
797
- nextStepMessage
798
- });
799
- };
800
-
801
- export {
802
- isPortOpen,
803
- waitForPort,
804
- loadEnvFile,
805
- detectLocalIpv4,
806
- getFlagValue,
807
- hasFlag,
808
- createProcessGroup,
809
- loadCreateAirJamRuntimeEnv,
810
- DEFAULT_AIR_JAM_DEV_BACKEND_URL,
811
- buildStandaloneGameTopology,
812
- serializeResolvedTopology,
813
- SECURE_MODE_LOCAL,
814
- SECURE_MODE_TUNNEL,
815
- DEFAULT_GAME_PORT,
816
- DEFAULT_PLATFORM_PORT,
817
- resolveRequestedSecureMode,
818
- parseSecureInitArgs,
819
- parseGameDevArgs,
820
- getSecurePaths,
821
- buildLocalCertificateHosts,
822
- resolveSecurePublicHost,
823
- resolveSecureLoopbackHost,
824
- resolveSecurePlatformHost,
825
- initializeSecureDev,
826
- loadSecureDevState,
827
- buildSecureGameEnv,
828
- appendNextHttpsArgs,
829
- runSecureInitCli
830
- };
831
- //# sourceMappingURL=chunk-RM7AMBDY.js.map