freertc 0.1.33 → 0.5.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.
Files changed (60) hide show
  1. package/README.md +205 -13
  2. package/bin/freertc.mjs +38 -633
  3. package/migrations/0001_initial.sql +43 -0
  4. package/migrations/0002_kademlia_overlay.sql +32 -0
  5. package/migrations/0003_announcement_role.sql +4 -0
  6. package/package.json +44 -17
  7. package/public/app.js +746 -172
  8. package/public/icon-180.png +0 -0
  9. package/public/icon-192.png +0 -0
  10. package/public/index.html +200 -799
  11. package/public/pigeonlogo.svg +51 -0
  12. package/scripts/d1-schema.sql +36 -0
  13. package/scripts/deploy-cloudflare.mjs +190 -0
  14. package/scripts/dev-server.mjs +54 -7
  15. package/scripts/generate-relay-identity.mjs +14 -0
  16. package/scripts/name-setup.mjs +332 -0
  17. package/scripts/node-relay.mjs +1128 -0
  18. package/scripts/project-bootstrap.mjs +13 -6
  19. package/scripts/wrangler-install-wizard.mjs +21 -11
  20. package/src/client.js +3468 -0
  21. package/src/direct/cert.js +95 -0
  22. package/src/direct/common.js +187 -0
  23. package/src/direct/dial.js +47 -0
  24. package/src/direct/directory.js +230 -0
  25. package/src/direct/listener.js +201 -0
  26. package/src/direct/lookup.js +75 -0
  27. package/src/direct/names.js +150 -0
  28. package/src/direct/node-relay-direct.js +170 -0
  29. package/src/direct/portmap.js +214 -0
  30. package/src/direct/reachable.js +40 -0
  31. package/src/direct/record.js +188 -0
  32. package/src/index.js +1401 -199
  33. package/src/kademlia.js +133 -0
  34. package/src/node/account-sync.js +98 -0
  35. package/src/node/cost-meter.js +92 -0
  36. package/src/node/d1-sqlite.js +108 -0
  37. package/src/node/data-dir.js +66 -0
  38. package/src/node/durable-object.js +58 -0
  39. package/src/node/lan-beacon.js +55 -0
  40. package/src/node/link-crypto.js +99 -0
  41. package/src/node/relay-links.js +385 -0
  42. package/src/node/relay-name.js +193 -0
  43. package/src/node/relay-pq.js +68 -0
  44. package/src/node/relay-stats.js +276 -0
  45. package/src/node/stats-page.js +281 -0
  46. package/src/node/websocket-pair.js +117 -0
  47. package/src/punch/offer.js +143 -0
  48. package/src/punch/rendezvous.js +124 -0
  49. package/src/punch/transport.js +257 -0
  50. package/src/relay-fetch.js +131 -0
  51. package/src/relay-id.js +74 -0
  52. package/src/relay-identity.js +298 -0
  53. package/src/relay-overlay.js +857 -0
  54. package/src/tunnel/client.js +276 -0
  55. package/src/tunnel/frames.js +64 -0
  56. package/src/tunnel/home.js +271 -0
  57. package/wrangler.template.jsonc +34 -9
  58. package/wrangler.workers-dev.jsonc +20 -3
  59. package/scripts/non-cloudflare-server.mjs +0 -433
  60. package/scripts/postinstall-message.mjs +0 -133
package/bin/freertc.mjs CHANGED
@@ -4,13 +4,11 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { spawnSync } from 'node:child_process';
7
- import { ensureProjectFiles, resolveProjectRoot, resolveWranglerCommand } from '../scripts/project-bootstrap.mjs';
7
+ import { ensureProjectFiles, resolveProjectRoot } from '../scripts/project-bootstrap.mjs';
8
8
 
9
9
  const __filename = fileURLToPath(import.meta.url);
10
10
  const PACKAGE_ROOT = path.resolve(path.dirname(__filename), '..');
11
11
  const PROJECT_ROOT = resolveProjectRoot(process.cwd());
12
- const PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
13
- const CLI_VERSION = PACKAGE_JSON.version;
14
12
 
15
13
  function printHelp() {
16
14
  console.log(`freertc CLI
@@ -21,16 +19,20 @@ Usage:
21
19
  freertc setup
22
20
  freertc init
23
21
  freertc install
22
+ freertc relay:keygen
24
23
  freertc deploy [-- <deploy-args>]
25
24
  freertc dev [-- <dev-args>]
26
25
  freertc dev:cf [-- <dev-args>]
26
+ freertc name [--domain example.com] [--worker <name>]
27
27
 
28
28
  Examples:
29
29
  npx freertc
30
30
  npx freertc wizard
31
31
  npx freertc setup
32
+ npx freertc relay:keygen
32
33
  freertc
33
34
  npx freertc deploy
35
+ npx freertc name --domain example.com (a name and Let's Encrypt certificate for this machine's relay)
34
36
  `);
35
37
  }
36
38
 
@@ -58,660 +60,63 @@ function runInProject(command, args, { bootstrap = false } = {}) {
58
60
  function requireWranglerConfig() {
59
61
  const configPath = path.join(PROJECT_ROOT, 'wrangler.jsonc');
60
62
  if (fs.existsSync(configPath)) {
61
- return configPath;
63
+ return;
62
64
  }
63
65
 
64
66
  console.error(`Missing ${configPath}. Run "npx freertc" or "npx freertc wizard" from this project directory first.`);
65
67
  process.exit(1);
66
68
  }
67
69
 
68
- function normalizeHost(value) {
69
- if (!value || typeof value !== 'string') return null;
70
- let host = value.trim().toLowerCase();
71
- if (!host) return null;
72
- host = host.replace(/^https?:\/\//, '');
73
- host = host.replace(/^wss?:\/\//, '');
74
- host = host.replace(/\/.*$/, '');
75
- host = host.replace(/:\d+$/, '');
76
- return host || null;
77
- }
78
-
79
- function isPlaceholderHost(host) {
80
- if (!host || typeof host !== 'string') return false;
81
- return /your-domain\.example|your[-_]?domain/i.test(host);
82
- }
83
-
84
- function sanitizeDomain(domain) {
85
- if (!domain || typeof domain !== 'string') return null;
86
- return domain
87
- .trim()
88
- .toLowerCase()
89
- .replace(/[^a-z0-9-]/g, '-')
90
- .replace(/-+/g, '-')
91
- .replace(/^-|-$/g, '') || null;
92
- }
93
-
94
- function patchJsoncVar(text, varName, value) {
95
- const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
96
- const re = new RegExp(`("${escaped}"\\s*:\\s*)"[^"]*"`, 'g');
97
- if (re.test(text)) {
98
- return text.replace(re, `$1"${value}"`);
99
- }
100
- return text;
101
- }
102
-
103
- function ensureRoutesForHost(configText, host) {
104
- const normalizedHost = normalizeHost(host);
105
- if (!normalizedHost || isPlaceholderHost(normalizedHost)) {
106
- return configText;
107
- }
108
-
109
- const pattern = `${normalizedHost}/*`;
110
- let text = configText;
111
-
112
- if (/^\s*"routes"\s*:\s*\[/m.test(text)) {
113
- text = text.replace(/^(\s*"pattern"\s*:\s*")([^"]*)(")/m, `$1${pattern}$3`);
114
- if (/^\s*"zone_name"\s*:\s*"[^"]*"/m.test(text)) {
115
- text = text.replace(/^(\s*"zone_name"\s*:\s*")([^"]*)(")/m, `$1${normalizedHost}$3`);
116
- }
117
- return text;
118
- }
119
-
120
- const routesBlock = [
121
- ' "routes": [',
122
- ' {',
123
- ` "pattern": "${pattern}",`,
124
- ` "zone_name": "${normalizedHost}"`,
125
- ' }',
126
- ' ]'
127
- ].join('\n');
128
-
129
- if (/\n\s*"env"\s*:\s*\{/.test(text)) {
130
- return text.replace(/\n\s*"env"\s*:\s*\{/, `\n${routesBlock},\n\n "env": {`);
131
- }
132
-
133
- return text.replace(/\n}\s*$/, `\n${routesBlock}\n}`);
134
- }
135
-
136
- function extractRouteHost(configText) {
137
- const routeMatch = configText.match(/^\s*"pattern"\s*:\s*"([^"]+)"/m);
138
- if (!routeMatch) return null;
139
- const pattern = routeMatch[1];
140
- const host = normalizeHost(pattern.split('/')[0]);
141
- if (!host || isPlaceholderHost(host)) return null;
142
- return host;
143
- }
144
-
145
- function extractCurrentWorkerName(configText) {
146
- const match = configText.match(/"name"\s*:\s*"([^"]+)"/);
147
- return match?.[1] || null;
148
- }
149
-
150
- function extractDeployHost(configPath) {
151
- const text = fs.readFileSync(configPath, 'utf8');
152
- return extractRouteHost(text) || extractDatabaseDomainHost(text) || extractRelayUrlHost(text) || extractGlobalRelayUrlHost(text);
153
- }
154
-
155
- function extractGlobalRelayUrlHost(configText) {
156
- const match = configText.match(/"GLOBAL_RELAY_URL"\s*:\s*"([^"]*)"/);
157
- if (!match) return null;
158
- const host = normalizeHost(match[1]);
159
- if (!host || isPlaceholderHost(host)) return null;
160
- return host;
161
- }
162
-
163
- function extractRelayUrlHost(configText) {
164
- const relayUrlMatch = configText.match(/"RELAY_URL"\s*:\s*"([^"]*)"/);
165
- if (!relayUrlMatch) return null;
166
- const raw = relayUrlMatch[1];
167
- const host = normalizeHost(raw);
168
- if (!host || isPlaceholderHost(host)) return null;
169
- return host;
170
- }
171
-
172
- function extractDatabaseDomainHost(configText) {
173
- const dbMatch = configText.match(/"database_name"\s*:\s*"([^"]+)"/);
174
- if (!dbMatch) return null;
175
- const dbName = dbMatch[1];
176
- const slugMatch = dbName.match(/^freertc-signal-(.+)$/i);
177
- if (!slugMatch) return null;
178
- const slug = (slugMatch[1] || '').trim();
179
- if (!slug || /your[-_]?domain/i.test(slug)) return null;
180
- return normalizeHost(slug.replace(/-/g, '.'));
181
- }
182
-
183
- function autoPatchWranglerConfig(configPath) {
184
- let text = fs.readFileSync(configPath, 'utf8');
185
-
186
- const dbDomainHost = extractDatabaseDomainHost(text);
187
- const routeHost = extractRouteHost(text);
188
- const relayUrlHost = extractRelayUrlHost(text);
189
- const globalRelayHost = extractGlobalRelayUrlHost(text);
190
- const publicHost = dbDomainHost || routeHost || relayUrlHost || globalRelayHost;
191
- const envDomainCandidate = normalizeHost(process.env.CF_DOMAIN || process.env.CLOUD_FLARE_DOMAIN || '');
192
- const envDomainHost = envDomainCandidate && !isPlaceholderHost(envDomainCandidate) ? envDomainCandidate : null;
193
- const baseRelayDomain = dbDomainHost || routeHost || envDomainHost || relayUrlHost || globalRelayHost;
194
-
195
- if (!baseRelayDomain) {
196
- return;
197
- }
198
-
199
- const relayHost = baseRelayDomain;
200
-
201
- const relayWsUrl = `wss://${relayHost}/ws`;
202
- const relayName = relayHost;
203
- const dbName = `freertc-signal-${sanitizeDomain(dbDomainHost || baseRelayDomain)}`;
204
-
205
- const before = text;
206
- text = patchJsoncVar(text, 'RELAY_URL', relayWsUrl);
207
- text = patchJsoncVar(text, 'RELAY_NAME', relayName);
208
- text = text.replace(/("database_name"\s*:\s*)"freertc-signal(?:-your[-_]?domain)?"/gi, `$1"${dbName}"`);
209
- text = ensureRoutesForHost(text, publicHost || relayHost);
210
-
211
- if (text !== before) {
212
- fs.writeFileSync(configPath, text, 'utf8');
213
- console.log(`Auto-patched wrangler.jsonc for deploy: RELAY_URL=${relayWsUrl}, RELAY_NAME=${relayName}`);
214
- }
215
- }
216
-
217
- function validateWranglerConfigForDeploy(configPath) {
218
- const configText = fs.readFileSync(configPath, 'utf8');
219
- const failures = [];
220
-
221
- const placeholderChecks = [
222
- { test: /YOUR_D1_DATABASE_ID/, message: 'Replace YOUR_D1_DATABASE_ID in wrangler.jsonc.' },
223
- { test: /Your App Relay/, message: 'Set vars.RELAY_NAME to your actual relay name.' },
224
- { test: /wss:\/\/(?:your-domain\.example|your[-_]?domain)\/ws/i, message: 'Set vars.RELAY_URL to your real deployed relay WebSocket URL.' },
225
- { test: /"database_name"\s*:\s*"freertc-signal(?:-your[-_]?domain)?"/i, message: 'Set d1_databases.database_name to a real database name (freertc-signal-<your-domain-slug>).' },
226
- { test: /"main"\s*:\s*"build\/worker\/shim\.mjs"/, message: 'Switch wrangler.jsonc main to src/index.js unless you intentionally use the Rust/WASM worker path.' },
227
- { test: /"command"\s*:\s*"worker-build --release"/, message: 'Remove the worker-build step unless you intentionally deploy the Rust/WASM worker path.' }
228
- ];
229
-
230
- for (const check of placeholderChecks) {
231
- if (check.test.test(configText)) {
232
- failures.push(check.message);
233
- }
234
- }
235
-
236
- const relayUrlMatch = configText.match(/"RELAY_URL"\s*:\s*"([^"]*)"/);
237
- if (!relayUrlMatch || !/^wss:\/\/[a-z0-9.-]+\/ws$/i.test(relayUrlMatch[1])) {
238
- failures.push('Set vars.RELAY_URL to a valid wss://<host>/ws URL.');
239
- }
240
-
241
- const relayNameMatch = configText.match(/"RELAY_NAME"\s*:\s*"([^"]*)"/);
242
- if (!relayNameMatch || !relayNameMatch[1].trim()) {
243
- failures.push('Set vars.RELAY_NAME to a non-empty relay name.');
244
- }
245
-
246
- if (failures.length > 0) {
247
- console.error(`Refusing to deploy with placeholder or invalid wrangler config: ${configPath}`);
248
- for (const failure of failures) {
249
- console.error(`- ${failure}`);
250
- }
251
- console.error('Run "npx freertc wizard" in the domain repo to patch wrangler.jsonc before deploying.');
252
- process.exit(1);
253
- }
254
- }
255
-
256
- function extractRouteConflictOwner(outputText) {
257
- if (!outputText) return null;
258
- const usedByMatch = outputText.match(/used by Worker:\s*([A-Za-z0-9._-]+)/i);
259
- if (usedByMatch?.[1]) return usedByMatch[1];
260
-
261
- const assignedMatch = outputText.match(/"([A-Za-z0-9._-]+)"\s+is already assigned to routes:/i);
262
- return assignedMatch?.[1] || null;
263
- }
264
-
265
- function patchWranglerScriptName(configPath, workerName) {
266
- if (!workerName) return false;
267
- const text = fs.readFileSync(configPath, 'utf8');
268
- const updated = text.replace(/^(\s*"name"\s*:\s*)"[^"]*"/gm, `$1"${workerName}"`);
269
- if (updated === text) return false;
270
- fs.writeFileSync(configPath, updated, 'utf8');
271
- return true;
272
- }
273
-
274
- function getApiToken() {
275
- return process.env.CLOUDFLARE_API_TOKEN || process.env.CF_API_TOKEN || '';
276
- }
277
-
278
- function getAccountId() {
279
- return process.env.CLOUDFLARE_ACCOUNT_ID || process.env.CF_ACCOUNT_ID || '';
280
- }
281
-
282
- function guessZoneCandidates(host) {
283
- const normalized = normalizeHost(host);
284
- if (!normalized) return [];
285
- const parts = normalized.split('.');
286
- const candidates = [];
287
- for (let i = 0; i <= Math.max(0, parts.length - 2); i += 1) {
288
- candidates.push(parts.slice(i).join('.'));
289
- }
290
- return Array.from(new Set(candidates));
291
- }
292
-
293
- function routePatternMatchesHost(pattern, host) {
294
- const normalizedHost = normalizeHost(host);
295
- if (!pattern || !normalizedHost) return false;
296
- const rawHost = normalizeHost(String(pattern).split('/')[0]);
297
- if (!rawHost) return false;
298
- if (rawHost === normalizedHost) return true;
299
- if (rawHost.startsWith('*.')) {
300
- const suffix = rawHost.slice(2);
301
- return normalizedHost === suffix || normalizedHost.endsWith(`.${suffix}`);
302
- }
303
- return false;
304
- }
305
-
306
- async function apiGetJson(url, token) {
307
- const response = await fetch(url, {
308
- headers: {
309
- Authorization: `Bearer ${token}`,
310
- Accept: 'application/json'
311
- }
312
- });
313
- if (!response.ok) {
314
- return null;
315
- }
316
-
317
- let payload;
318
- try {
319
- payload = await response.json();
320
- } catch {
321
- return null;
322
- }
323
-
324
- if (!payload?.success) {
325
- return null;
326
- }
327
-
328
- return payload.result;
329
- }
330
-
331
- async function apiMutateJson(url, token, method, body) {
332
- const response = await fetch(url, {
333
- method,
334
- headers: {
335
- Authorization: `Bearer ${token}`,
336
- Accept: 'application/json',
337
- 'Content-Type': 'application/json'
338
- },
339
- body: JSON.stringify(body)
340
- });
341
-
342
- let payload;
343
- try {
344
- payload = await response.json();
345
- } catch {
346
- return null;
347
- }
348
-
349
- if (!response.ok || !payload?.success) {
350
- return null;
351
- }
352
-
353
- return payload.result || {};
354
- }
355
-
356
- async function resolveZoneIdForHost(host, token) {
357
- const candidates = guessZoneCandidates(host);
358
- for (const candidate of candidates) {
359
- const result = await apiGetJson(`https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(candidate)}`, token);
360
- if (Array.isArray(result) && result.length > 0 && result[0]?.id) {
361
- return result[0].id;
362
- }
363
- }
364
- return null;
365
- }
366
-
367
- async function findRouteOwnerForHost(host) {
368
- const token = getApiToken();
369
- const accountId = getAccountId();
370
- if (!token || !accountId) {
371
- return null;
372
- }
373
-
374
- const zoneId = await resolveZoneIdForHost(host, token);
375
- if (!zoneId) {
376
- return null;
377
- }
378
-
379
- const routes = await apiGetJson(`https://api.cloudflare.com/client/v4/zones/${zoneId}/workers/routes`, token);
380
- if (!Array.isArray(routes)) {
381
- return null;
382
- }
70
+ const [, , subcommand, ...rest] = process.argv;
383
71
 
384
- // Prefer exact host matches over wildcard matches.
385
- const exact = routes.find((route) => {
386
- const patternHost = normalizeHost(String(route?.pattern || '').split('/')[0]);
387
- const scriptName = route?.script || route?.script_name;
388
- return patternHost === normalizeHost(host) && typeof scriptName === 'string' && scriptName.trim();
389
- });
390
- if (exact?.script || exact?.script_name) {
391
- return exact.script || exact.script_name;
392
- }
393
-
394
- const wildcard = routes.find((route) => {
395
- const scriptName = route?.script || route?.script_name;
396
- return routePatternMatchesHost(route?.pattern, host) && typeof scriptName === 'string' && scriptName.trim();
397
- });
398
- return wildcard ? (wildcard.script || wildcard.script_name) : null;
72
+ if (!subcommand) {
73
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both'], { bootstrap: true });
399
74
  }
400
75
 
401
- async function forceRouteBindingToWorker(host, workerName) {
402
- const normalizedHost = normalizeHost(host);
403
- const normalizedWorker = typeof workerName === 'string' ? workerName.trim() : '';
404
- const token = getApiToken();
405
- if (!normalizedHost || !normalizedWorker || !token) {
406
- return false;
407
- }
408
-
409
- const zoneId = await resolveZoneIdForHost(normalizedHost, token);
410
- if (!zoneId) {
411
- return false;
412
- }
413
-
414
- const routes = await apiGetJson(`https://api.cloudflare.com/client/v4/zones/${zoneId}/workers/routes`, token);
415
- if (!Array.isArray(routes)) {
416
- return false;
417
- }
418
-
419
- const exactPattern = `${normalizedHost}/*`;
420
- const matchingRoute = routes.find((route) => String(route?.pattern || '') === exactPattern)
421
- || routes.find((route) => routePatternMatchesHost(route?.pattern, normalizedHost));
422
-
423
- if (matchingRoute?.id) {
424
- const currentScript = matchingRoute.script || matchingRoute.script_name || '';
425
- if (currentScript === normalizedWorker) {
426
- return false;
427
- }
428
-
429
- const updated = await apiMutateJson(
430
- `https://api.cloudflare.com/client/v4/zones/${zoneId}/workers/routes/${matchingRoute.id}`,
431
- token,
432
- 'PUT',
433
- { pattern: matchingRoute.pattern || exactPattern, script: normalizedWorker }
434
- );
435
- return Boolean(updated);
436
- }
437
-
438
- const created = await apiMutateJson(
439
- `https://api.cloudflare.com/client/v4/zones/${zoneId}/workers/routes`,
440
- token,
441
- 'POST',
442
- { pattern: exactPattern, script: normalizedWorker }
443
- );
444
- return Boolean(created);
76
+ if (subcommand === '--help' || subcommand === '-h' || subcommand === 'help') {
77
+ printHelp();
78
+ process.exit(0);
445
79
  }
446
80
 
447
- async function maybeAlignWorkerNameToRouteOwner(configPath) {
448
- const text = fs.readFileSync(configPath, 'utf8');
449
- const host = extractRouteHost(text) || extractRelayUrlHost(text) || extractDatabaseDomainHost(text);
450
- if (!host) {
451
- return;
452
- }
453
-
454
- const routeOwner = await findRouteOwnerForHost(host);
455
- if (!routeOwner) {
456
- return;
457
- }
458
-
459
- const currentName = extractCurrentWorkerName(text);
460
- if (!currentName || currentName === routeOwner) {
461
- return;
462
- }
463
-
464
- const patched = patchWranglerScriptName(configPath, routeOwner);
465
- if (patched) {
466
- console.log(`Detected route owner worker "${routeOwner}" for ${host}. Auto-updated wrangler.jsonc name before deploy.`);
467
- }
81
+ if (subcommand === 'wizard') {
82
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), ...rest], { bootstrap: true });
468
83
  }
469
84
 
470
- function runDeployWithAutoRouteRecovery(wrangler, configPath, extraArgs = []) {
471
- const attemptedOwners = new Set();
472
-
473
- for (let attempt = 0; attempt < 2; attempt += 1) {
474
- const args = [...wrangler.baseArgs, 'deploy', '--config', configPath, '--env', 'production', ...extraArgs];
475
- const result = spawnSync(wrangler.command, args, {
476
- cwd: PROJECT_ROOT,
477
- stdio: 'pipe',
478
- encoding: 'utf8',
479
- env: {
480
- ...process.env,
481
- FREERTC_PACKAGE_ROOT: PACKAGE_ROOT
482
- }
483
- });
484
-
485
- if (result.stdout) process.stdout.write(result.stdout);
486
- if (result.stderr) process.stderr.write(result.stderr);
487
-
488
- if (typeof result.status === 'number' && result.status === 0) {
489
- return { ok: true, status: 0 };
490
- }
491
-
492
- const combinedOutput = `${result.stdout || ''}\n${result.stderr || ''}`;
493
- const conflictOwner = extractRouteConflictOwner(combinedOutput);
494
- if (!conflictOwner || attemptedOwners.has(conflictOwner)) {
495
- return { ok: false, status: typeof result.status === 'number' ? result.status : 1 };
496
- }
497
-
498
- attemptedOwners.add(conflictOwner);
499
- const patched = patchWranglerScriptName(configPath, conflictOwner);
500
- if (!patched) {
501
- return { ok: false, status: typeof result.status === 'number' ? result.status : 1 };
502
- }
503
-
504
- console.log(`Detected route owned by worker "${conflictOwner}". Retrying deploy with that worker name automatically.`);
505
- }
506
-
507
- return { ok: false, status: 1 };
85
+ if (subcommand === 'setup') {
86
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both', ...rest], { bootstrap: true });
508
87
  }
509
88
 
510
- async function fetchLiveHealthVersion(host) {
511
- const normalizedHost = normalizeHost(host);
512
- if (!normalizedHost) return null;
513
- try {
514
- const response = await fetch(`https://${normalizedHost}/health`, {
515
- headers: { Accept: 'application/json' }
516
- });
517
- if (!response.ok) return null;
518
- const payload = await response.json();
519
- const version = payload?.version;
520
- return typeof version === 'string' && version.trim() ? version.trim() : null;
521
- } catch {
522
- return null;
523
- }
89
+ if (subcommand === 'init' || subcommand === 'install') {
90
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both', ...rest], { bootstrap: true });
524
91
  }
525
92
 
526
- function compareVersions(left, right) {
527
- const leftParts = String(left).split('.').map((value) => Number.parseInt(value, 10) || 0);
528
- const rightParts = String(right).split('.').map((value) => Number.parseInt(value, 10) || 0);
529
- const length = Math.max(leftParts.length, rightParts.length);
530
-
531
- for (let index = 0; index < length; index += 1) {
532
- const leftValue = leftParts[index] ?? 0;
533
- const rightValue = rightParts[index] ?? 0;
534
- if (leftValue > rightValue) return 1;
535
- if (leftValue < rightValue) return -1;
536
- }
537
-
538
- return 0;
93
+ if (subcommand === 'relay:keygen' || subcommand === 'keygen') {
94
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'generate-relay-identity.mjs'), ...rest]);
539
95
  }
540
96
 
541
- async function fetchLatestCliVersion() {
542
- const response = await fetch('https://registry.npmjs.org/freertc/latest', {
543
- headers: { Accept: 'application/json' }
544
- });
545
- if (!response.ok) {
546
- throw new Error(`npm registry responded with ${response.status}`);
547
- }
548
-
549
- const payload = await response.json();
550
- const version = payload?.version;
551
- if (typeof version !== 'string' || !version.trim()) {
552
- throw new Error('npm registry response did not include a version');
553
- }
554
-
555
- return version;
97
+ if (subcommand === 'deploy') {
98
+ ensureProjectFiles(PROJECT_ROOT);
99
+ requireWranglerConfig();
100
+ runInProject(process.execPath, [
101
+ path.join(PACKAGE_ROOT, 'scripts', 'deploy-cloudflare.mjs'),
102
+ '--env',
103
+ 'production',
104
+ ...rest,
105
+ ]);
556
106
  }
557
107
 
558
- async function assertLatestCliForDeploy() {
559
- if (process.env.FREERTC_SKIP_LATEST_CHECK === '1') {
560
- return;
561
- }
562
-
563
- try {
564
- const latestVersion = await fetchLatestCliVersion();
565
- if (compareVersions(CLI_VERSION, latestVersion) < 0) {
566
- console.warn(`freertc ${CLI_VERSION} is older than npm latest ${latestVersion}.`);
567
- console.warn('Continuing deploy with current CLI and enforcing live /health verification.');
568
- }
569
- } catch (error) {
570
- console.warn(`Unable to verify freertc version before deploy: ${error?.message || String(error)}`);
571
- console.warn('Continuing deploy anyway and relying on live /health verification.');
572
- }
108
+ if (subcommand === 'name') {
109
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'name-setup.mjs'), ...rest]);
573
110
  }
574
111
 
575
- async function maybeHandoffToLatestCli(rawArgs = []) {
576
- if (process.env.FREERTC_NO_AUTO_HANDOFF === '1') {
577
- return;
578
- }
579
-
580
- // Avoid network checks for explicit help output.
581
- const firstArg = rawArgs[0];
582
- if (firstArg === '--help' || firstArg === '-h' || firstArg === 'help') {
583
- return;
584
- }
585
-
586
- try {
587
- const latestVersion = await fetchLatestCliVersion();
588
- if (compareVersions(CLI_VERSION, latestVersion) >= 0) {
589
- return;
590
- }
591
-
592
- console.log(`Detected newer freertc version ${latestVersion} (current ${CLI_VERSION}).`);
593
- console.log('Running command with latest CLI automatically...');
594
-
595
- const args = ['-y', `freertc@${latestVersion}`, ...rawArgs];
596
- const result = spawnSync('npx', args, {
597
- cwd: PROJECT_ROOT,
598
- stdio: 'inherit',
599
- env: {
600
- ...process.env,
601
- FREERTC_NO_AUTO_HANDOFF: '1'
602
- }
603
- });
604
-
605
- if (typeof result.status === 'number') {
606
- process.exit(result.status);
607
- }
608
- process.exit(1);
609
- } catch {
610
- // Offline or registry hiccup: continue with local CLI.
611
- }
112
+ if (subcommand === 'dev') {
113
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'node-relay.mjs'), ...rest], { bootstrap: true });
612
114
  }
613
115
 
614
- async function main() {
615
- const [, , subcommand, ...rest] = process.argv;
616
- const rawArgs = process.argv.slice(2);
617
-
618
- await maybeHandoffToLatestCli(rawArgs);
619
-
620
- if (!subcommand) {
621
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both'], { bootstrap: true });
622
- }
623
-
624
- if (subcommand === '--help' || subcommand === '-h' || subcommand === 'help') {
625
- printHelp();
626
- process.exit(0);
627
- }
628
-
629
- if (subcommand === 'wizard') {
630
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), ...rest], { bootstrap: true });
631
- }
632
-
633
- if (subcommand === 'setup') {
634
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both', ...rest], { bootstrap: true });
635
- }
636
-
637
- if (subcommand === 'init' || subcommand === 'install') {
638
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'wrangler-install-wizard.mjs'), '--mode', 'both', ...rest], { bootstrap: true });
639
- }
640
-
641
- if (subcommand === 'deploy') {
642
- await assertLatestCliForDeploy();
643
- ensureProjectFiles(PROJECT_ROOT);
644
- const configPath = requireWranglerConfig();
645
- autoPatchWranglerConfig(configPath);
646
- await maybeAlignWorkerNameToRouteOwner(configPath);
647
- validateWranglerConfigForDeploy(configPath);
648
- const wrangler = resolveWranglerCommand(PROJECT_ROOT);
649
- const firstDeploy = runDeployWithAutoRouteRecovery(wrangler, configPath, rest);
650
- if (!firstDeploy.ok) {
651
- process.exit(firstDeploy.status);
652
- }
653
-
654
- const deployHost = extractDeployHost(configPath);
655
- if (!deployHost) {
656
- process.exit(0);
657
- }
658
-
659
- let liveVersion = await fetchLiveHealthVersion(deployHost);
660
- if (liveVersion && compareVersions(liveVersion, CLI_VERSION) >= 0) {
661
- process.exit(0);
662
- }
663
-
664
- // If live version is still stale, force-resolve route owner and redeploy once.
665
- const routeOwner = await findRouteOwnerForHost(deployHost);
666
- if (routeOwner) {
667
- const currentText = fs.readFileSync(configPath, 'utf8');
668
- const currentName = extractCurrentWorkerName(currentText);
669
- if (currentName !== routeOwner) {
670
- patchWranglerScriptName(configPath, routeOwner);
671
- console.log(`Live health still stale on ${deployHost}. Retrying deploy against route-owner worker "${routeOwner}".`);
672
- } else {
673
- console.log(`Live health still stale on ${deployHost}. Retrying deploy once for route-owner worker "${routeOwner}".`);
674
- }
675
-
676
- const secondDeploy = runDeployWithAutoRouteRecovery(wrangler, configPath, rest);
677
- if (!secondDeploy.ok) {
678
- process.exit(secondDeploy.status);
679
- }
680
- liveVersion = await fetchLiveHealthVersion(deployHost);
681
- if (liveVersion && compareVersions(liveVersion, CLI_VERSION) >= 0) {
682
- process.exit(0);
683
- }
684
- }
685
-
686
- const finalText = fs.readFileSync(configPath, 'utf8');
687
- const finalWorkerName = extractCurrentWorkerName(finalText);
688
- if (finalWorkerName) {
689
- const rebound = await forceRouteBindingToWorker(deployHost, finalWorkerName);
690
- if (rebound) {
691
- console.log(`Live health still stale on ${deployHost}. Rebound Cloudflare route to worker "${finalWorkerName}" and rechecking health.`);
692
- liveVersion = await fetchLiveHealthVersion(deployHost);
693
- if (liveVersion && compareVersions(liveVersion, CLI_VERSION) >= 0) {
694
- process.exit(0);
695
- }
696
- }
697
- }
698
-
699
- console.error(`Deploy completed but live health on https://${deployHost}/health is still stale (version=${liveVersion || 'unknown'}, expected>=${CLI_VERSION}).`);
700
- console.error('Refusing silent success. Please rerun deploy after Cloudflare route cache settles.');
701
- process.exit(1);
702
- }
703
-
704
- if (subcommand === 'dev') {
705
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'non-cloudflare-server.mjs'), ...rest], { bootstrap: true });
706
- }
707
-
708
- if (subcommand === 'dev:cf' || subcommand === 'dev-cf') {
709
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'dev-server.mjs'), ...rest], { bootstrap: true });
710
- }
711
-
712
- console.error(`Unknown command: ${subcommand}\n`);
713
- printHelp();
714
- process.exit(1);
116
+ if (subcommand === 'dev:cf' || subcommand === 'dev-cf') {
117
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'dev-server.mjs'), ...rest], { bootstrap: true });
715
118
  }
716
119
 
717
- await main();
120
+ console.error(`Unknown command: ${subcommand}\n`);
121
+ printHelp();
122
+ process.exit(1);