freertc 0.1.32 → 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 +204 -12
  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 -169
  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
@@ -4,6 +4,8 @@
4
4
  // Default JS worker runtime (no Rust toolchain required).
5
5
  "main": "src/index.js",
6
6
  "compatibility_date": "2024-09-23",
7
+ // Keep variables set in the dashboard: a deploy must never remove them.
8
+ "keep_vars": true,
7
9
 
8
10
  // Serve static files from the public directory.
9
11
  "assets": {
@@ -11,15 +13,19 @@
11
13
  },
12
14
 
13
15
  "vars": {
14
- // Peer ID the relay server advertises as itself in PSP messages.
15
- "RELAY_PEER_ID": "bootstrap-relay",
16
16
 
17
17
  // Set automatically by the wizard from your domain (wss://<domain>/ws).
18
18
  "RELAY_URL": "wss://YOUR_DOMAIN/ws",
19
19
 
20
20
  // Set automatically by the wizard if you opt into the global network.
21
- // Remove this line to run standalone (no cross-relay peer discovery).
22
- "GLOBAL_RELAY_URL": "wss://peer.ooo/ws",
21
+ // Seeds for the Kademlia join: any relay can be one, and a seed answers with the relays
22
+ // closest to you. List several; the relay asks one at a time, in random order.
23
+ // Remove it to run standalone.
24
+ "KADEMLIA_BOOTSTRAP_URLS": "wss://peer.ooo/ws,wss://decentralize.ooo/ws",
25
+
26
+ // Deploy and local-dev scripts generate a stable private relay identity
27
+ // automatically. It is never stored in this configuration file.
28
+ // "RELAY_CAPACITY": "10000",
23
29
  "RELAY_NAME": "Your App Relay"
24
30
  },
25
31
 
@@ -31,10 +37,22 @@
31
37
  {
32
38
  "binding": "DB",
33
39
  "database_name": "freertc-signal-YOUR_DOMAIN",
34
- "database_id": "YOUR_D1_DATABASE_ID"
40
+ "database_id": "YOUR_D1_DATABASE_ID",
41
+ "migrations_dir": "migrations"
35
42
  }
36
43
  ],
37
44
 
45
+ "durable_objects": {
46
+ "bindings": [
47
+ { "name": "RELAY_COORDINATOR", "class_name": "RelayCoordinator" },
48
+ { "name": "RELAY_TUNNEL", "class_name": "RelayTunnel" }
49
+ ]
50
+ },
51
+ "migrations": [
52
+ { "tag": "relay-coordinator-v1", "new_sqlite_classes": ["RelayCoordinator"] },
53
+ { "tag": "relay-tunnel-v1", "new_sqlite_classes": ["RelayTunnel"] }
54
+ ],
55
+
38
56
  // ── Custom domain (OPTIONAL) ──────────────────────────────────────────────
39
57
  // If you have a domain on Cloudflare, uncomment and fill in:
40
58
  //
@@ -54,18 +72,25 @@
54
72
  "production": {
55
73
  "name": "freertc",
56
74
  "vars": {
57
- "RELAY_PEER_ID": "bootstrap-relay",
58
75
  "RELAY_URL": "wss://YOUR_DOMAIN/ws",
59
- "GLOBAL_RELAY_URL": "wss://peer.ooo/ws",
76
+ "KADEMLIA_BOOTSTRAP_URLS": "wss://peer.ooo/ws,wss://decentralize.ooo/ws",
77
+ // The deploy script installs the production relay identity secret.
60
78
  "RELAY_NAME": "Your App Relay"
61
79
  },
62
80
  "d1_databases": [
63
81
  {
64
82
  "binding": "DB",
65
83
  "database_name": "freertc-signal-YOUR_DOMAIN",
66
- "database_id": "YOUR_D1_DATABASE_ID"
84
+ "database_id": "YOUR_D1_DATABASE_ID",
85
+ "migrations_dir": "migrations"
67
86
  }
68
- ]
87
+ ],
88
+ "durable_objects": {
89
+ "bindings": [
90
+ { "name": "RELAY_COORDINATOR", "class_name": "RelayCoordinator" },
91
+ { "name": "RELAY_TUNNEL", "class_name": "RelayTunnel" }
92
+ ]
93
+ }
69
94
  }
70
95
  }
71
96
  }
@@ -1,19 +1,36 @@
1
1
  {
2
- "name": "peer-ooo-worker-devtest",
2
+ "name": "freertc-worker-dev",
3
3
  "main": "src/index.js",
4
4
  "compatibility_date": "2024-09-23",
5
+ // Keep variables set in the dashboard: a deploy must never remove them.
6
+ "keep_vars": true,
5
7
  "workers_dev": true,
6
8
  "assets": {
7
9
  "directory": "public"
8
10
  },
9
11
  "vars": {
10
- "RELAY_PEER_ID": "bootstrap-relay"
12
+ // npm run dev:cf creates the private relay identity in .dev.vars.
13
+ // Seeds: any relay can be one. List several; the relay asks one at a time, in random order.
14
+ "KADEMLIA_BOOTSTRAP_URLS": "wss://peer.ooo/ws,wss://decentralize.ooo/ws"
11
15
  },
12
16
  "d1_databases": [
13
17
  {
14
18
  "binding": "DB",
15
19
  "database_name": "freertc-signal",
16
- "database_id": "52acefe2-e810-4b81-8225-1ca87d0205cc"
20
+ // Local development uses isolated D1 state. Replace this placeholder
21
+ // before using this config with a remote D1 database.
22
+ "database_id": "00000000-0000-0000-0000-000000000000",
23
+ "migrations_dir": "migrations"
17
24
  }
25
+ ],
26
+ "durable_objects": {
27
+ "bindings": [
28
+ { "name": "RELAY_COORDINATOR", "class_name": "RelayCoordinator" },
29
+ { "name": "RELAY_TUNNEL", "class_name": "RelayTunnel" }
30
+ ]
31
+ },
32
+ "migrations": [
33
+ { "tag": "relay-coordinator-v1", "new_sqlite_classes": ["RelayCoordinator"] },
34
+ { "tag": "relay-tunnel-v1", "new_sqlite_classes": ["RelayTunnel"] }
18
35
  ]
19
36
  }
@@ -1,433 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import { createServer } from 'node:http';
6
- import { fileURLToPath } from 'node:url';
7
- import { WebSocketServer } from 'ws';
8
-
9
- const PSP_VERSION = '1.0';
10
- const WORKER_VERSION = '0.1.32';
11
- const DEFAULT_TTL_MS = 30_000;
12
- const MAX_TTL_MS = 120_000;
13
- const MAX_MESSAGE_SIZE = 64 * 1024;
14
- const MAX_BATCH = 50;
15
-
16
- const DISCOVERY_TYPES = new Set(['announce', 'withdraw', 'discover', 'peer_list', 'redirect']);
17
- const NEGOTIATION_TYPES = new Set(['connect_request', 'connect_accept', 'connect_reject', 'offer', 'answer', 'ice_candidate', 'ice_end', 'renegotiate']);
18
- const CONTROL_TYPES = new Set(['ping', 'pong', 'bye', 'error', 'ack']);
19
- const EXTENSION_TYPES = new Set(['ext']);
20
- const MESSAGE_TYPES = new Set([...DISCOVERY_TYPES, ...NEGOTIATION_TYPES, ...CONTROL_TYPES, ...EXTENSION_TYPES]);
21
-
22
- const RELAY_TYPES = new Set([
23
- 'connect_request', 'connect_accept', 'connect_reject',
24
- 'offer', 'answer', 'ice_candidate', 'ice_end', 'renegotiate',
25
- 'bye', 'error', 'ack', 'ext', 'peer_list', 'redirect'
26
- ]);
27
-
28
- const __filename = fileURLToPath(import.meta.url);
29
- const __dirname = path.dirname(__filename);
30
- const ROOT = path.resolve(__dirname, '..');
31
- const PUBLIC_DIR = path.join(ROOT, 'public');
32
- const HOST = process.env.HOST || '127.0.0.1';
33
- const PORT = Number(process.env.PORT || 8788);
34
-
35
- const livePeers = new Map(); // network:peerId -> { socket, peerId, network, lastSeen }
36
- const networkSubscribers = new Map(); // network -> Set<WebSocket>
37
- const announcements = new Map(); // network:peerId -> { sessionId, expiresAtMs, updatedAtMs }
38
- const relayQueue = new Map(); // network:toPeerId -> [{ id, message, expiresAtMs, createdAtMs }]
39
-
40
- let relayMessageId = 1;
41
-
42
- function makePeerKey(network, peerId) {
43
- return `${network}:${peerId}`;
44
- }
45
-
46
- function normalizeTtl(ttlMs) {
47
- const value = Number(ttlMs);
48
- if (!Number.isFinite(value) || value <= 0) {
49
- return DEFAULT_TTL_MS;
50
- }
51
- return Math.min(value, MAX_TTL_MS);
52
- }
53
-
54
- function json(res, body, status = 200) {
55
- const payload = JSON.stringify(body);
56
- res.writeHead(status, {
57
- 'Content-Type': 'application/json; charset=utf-8',
58
- 'Access-Control-Allow-Origin': '*',
59
- 'Content-Length': Buffer.byteLength(payload)
60
- });
61
- res.end(payload);
62
- }
63
-
64
- function validEnvelope(msg) {
65
- return (
66
- typeof msg === 'object' && msg !== null &&
67
- msg.psp_version === PSP_VERSION &&
68
- typeof msg.type === 'string' && MESSAGE_TYPES.has(msg.type) &&
69
- typeof msg.from === 'string' && msg.from.trim() &&
70
- typeof msg.network === 'string' && msg.network.trim() &&
71
- typeof msg.message_id === 'string' &&
72
- typeof msg.timestamp === 'number'
73
- );
74
- }
75
-
76
- function cleanExpired() {
77
- const now = Date.now();
78
-
79
- for (const [key, row] of announcements.entries()) {
80
- if (row.expiresAtMs <= now) {
81
- announcements.delete(key);
82
- livePeers.delete(key);
83
- }
84
- }
85
-
86
- for (const [queueKey, entries] of relayQueue.entries()) {
87
- const remaining = entries.filter((item) => item.expiresAtMs > now);
88
- if (remaining.length === 0) {
89
- relayQueue.delete(queueKey);
90
- } else {
91
- relayQueue.set(queueKey, remaining);
92
- }
93
- }
94
- }
95
-
96
- function listPeers(network, requesterPeerId = null) {
97
- const now = Date.now();
98
- const out = [];
99
- for (const [key, row] of announcements.entries()) {
100
- const [rowNetwork, rowPeerId] = key.split(':');
101
- if (rowNetwork !== network || row.expiresAtMs <= now) {
102
- continue;
103
- }
104
- if (requesterPeerId && rowPeerId === requesterPeerId) {
105
- continue;
106
- }
107
- out.push({
108
- peer_id: rowPeerId,
109
- session_id: row.sessionId,
110
- timestamp: row.updatedAtMs
111
- });
112
- if (out.length >= MAX_BATCH) {
113
- break;
114
- }
115
- }
116
- out.sort((a, b) => a.peer_id.localeCompare(b.peer_id));
117
- return out;
118
- }
119
-
120
- function sendSafe(socket, payloadObj) {
121
- try {
122
- socket.send(JSON.stringify(payloadObj));
123
- return true;
124
- } catch {
125
- return false;
126
- }
127
- }
128
-
129
- function sendPeerList(network) {
130
- const sockets = networkSubscribers.get(network);
131
- if (!sockets || sockets.size === 0) {
132
- return;
133
- }
134
- const peers = listPeers(network);
135
- const message = {
136
- psp_version: PSP_VERSION,
137
- type: 'peer_list',
138
- network,
139
- from: 'bootstrap-relay',
140
- to: null,
141
- message_id: crypto.randomUUID(),
142
- timestamp: Date.now(),
143
- ttl_ms: DEFAULT_TTL_MS,
144
- body: { peers }
145
- };
146
-
147
- for (const socket of sockets) {
148
- if (socket.readyState !== socket.OPEN) {
149
- sockets.delete(socket);
150
- continue;
151
- }
152
- sendSafe(socket, message);
153
- }
154
- }
155
-
156
- function queueRelayMessage(message) {
157
- const key = makePeerKey(message.network, message.to);
158
- const now = Date.now();
159
- const ttl = normalizeTtl(message.ttl_ms);
160
- const list = relayQueue.get(key) || [];
161
- list.push({
162
- id: relayMessageId++,
163
- message,
164
- createdAtMs: now,
165
- expiresAtMs: now + ttl
166
- });
167
- relayQueue.set(key, list);
168
- }
169
-
170
- function deliverQueued(network, peerId, socket) {
171
- const key = makePeerKey(network, peerId);
172
- const queue = relayQueue.get(key) || [];
173
- if (queue.length === 0) {
174
- return 0;
175
- }
176
-
177
- const now = Date.now();
178
- const fresh = [];
179
- let delivered = 0;
180
- for (const item of queue) {
181
- if (item.expiresAtMs <= now) {
182
- continue;
183
- }
184
- if (delivered < MAX_BATCH && sendSafe(socket, item.message)) {
185
- delivered += 1;
186
- } else {
187
- fresh.push(item);
188
- }
189
- }
190
-
191
- if (fresh.length === 0) {
192
- relayQueue.delete(key);
193
- } else {
194
- relayQueue.set(key, fresh);
195
- }
196
-
197
- return delivered;
198
- }
199
-
200
- function upsertAnnouncement(message) {
201
- const key = makePeerKey(message.network, message.from);
202
- const now = Date.now();
203
- const ttl = normalizeTtl(message.ttl_ms);
204
- announcements.set(key, {
205
- sessionId: message.session_id || null,
206
- expiresAtMs: now + ttl,
207
- updatedAtMs: now
208
- });
209
- }
210
-
211
- function cleanupSocketState(socket) {
212
- const state = socket.__peerState;
213
- if (!state?.network || !state.peerId) {
214
- return;
215
- }
216
-
217
- const { network, peerId } = state;
218
- const key = makePeerKey(network, peerId);
219
- announcements.delete(key);
220
- livePeers.delete(key);
221
-
222
- const sockets = networkSubscribers.get(network);
223
- if (sockets) {
224
- sockets.delete(socket);
225
- if (sockets.size === 0) {
226
- networkSubscribers.delete(network);
227
- }
228
- }
229
-
230
- socket.__peerState = null;
231
- sendPeerList(network);
232
- }
233
-
234
- function subscribeSocket(socket, network) {
235
- const previous = socket.__peerState?.network;
236
- if (previous && previous !== network) {
237
- const oldSet = networkSubscribers.get(previous);
238
- if (oldSet) {
239
- oldSet.delete(socket);
240
- if (oldSet.size === 0) {
241
- networkSubscribers.delete(previous);
242
- }
243
- }
244
- }
245
-
246
- if (!networkSubscribers.has(network)) {
247
- networkSubscribers.set(network, new Set());
248
- }
249
- networkSubscribers.get(network).add(socket);
250
- }
251
-
252
- function attachSocketHandlers(socket) {
253
- socket.__peerState = null;
254
-
255
- socket.on('message', (raw) => {
256
- cleanExpired();
257
-
258
- const rawString = raw.toString();
259
- if (!rawString || rawString.length > MAX_MESSAGE_SIZE) {
260
- return;
261
- }
262
-
263
- let message;
264
- try {
265
- message = JSON.parse(rawString);
266
- } catch {
267
- sendSafe(socket, {
268
- psp_version: PSP_VERSION,
269
- type: 'error',
270
- from: 'relay',
271
- to: 'client',
272
- body: { error: 'Invalid JSON' }
273
- });
274
- return;
275
- }
276
-
277
- if (!validEnvelope(message)) {
278
- sendSafe(socket, {
279
- psp_version: PSP_VERSION,
280
- type: 'error',
281
- from: 'relay',
282
- to: message?.from || 'unknown',
283
- body: { error: 'Invalid PSP envelope' }
284
- });
285
- return;
286
- }
287
-
288
- const { network, from: peerId, type } = message;
289
- const key = makePeerKey(network, peerId);
290
- const previousKey = socket.__peerState ? makePeerKey(socket.__peerState.network, socket.__peerState.peerId) : null;
291
-
292
- subscribeSocket(socket, network);
293
- socket.__peerState = { network, peerId };
294
- livePeers.set(key, { socket, network, peerId, lastSeen: Date.now() });
295
-
296
- if (type === 'announce') {
297
- upsertAnnouncement(message);
298
- deliverQueued(network, peerId, socket);
299
-
300
- const isHeartbeat = previousKey === key;
301
- if (!isHeartbeat) {
302
- sendPeerList(network);
303
- }
304
- return;
305
- }
306
-
307
- if (type === 'withdraw' || type === 'bye') {
308
- announcements.delete(key);
309
- livePeers.delete(key);
310
- sendPeerList(network);
311
- return;
312
- }
313
-
314
- if (type === 'discover') {
315
- sendPeerList(network);
316
- return;
317
- }
318
-
319
- if (type === 'ping') {
320
- sendSafe(socket, {
321
- psp_version: PSP_VERSION,
322
- type: 'pong',
323
- network,
324
- from: 'relay',
325
- to: peerId,
326
- message_id: crypto.randomUUID(),
327
- timestamp: Date.now(),
328
- ttl_ms: DEFAULT_TTL_MS,
329
- body: {}
330
- });
331
- deliverQueued(network, peerId, socket);
332
- return;
333
- }
334
-
335
- if (RELAY_TYPES.has(type) && message.to) {
336
- const targetKey = makePeerKey(network, message.to);
337
- const live = livePeers.get(targetKey);
338
- if (live && live.socket.readyState === live.socket.OPEN && sendSafe(live.socket, message)) {
339
- return;
340
- }
341
- queueRelayMessage(message);
342
- }
343
- });
344
-
345
- socket.on('close', () => cleanupSocketState(socket));
346
- socket.on('error', () => cleanupSocketState(socket));
347
- }
348
-
349
- function contentType(filePath) {
350
- const ext = path.extname(filePath).toLowerCase();
351
- if (ext === '.html') return 'text/html; charset=utf-8';
352
- if (ext === '.js') return 'application/javascript; charset=utf-8';
353
- if (ext === '.css') return 'text/css; charset=utf-8';
354
- if (ext === '.json') return 'application/json; charset=utf-8';
355
- if (ext === '.svg') return 'image/svg+xml';
356
- if (ext === '.png') return 'image/png';
357
- if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
358
- return 'application/octet-stream';
359
- }
360
-
361
- function serveStatic(req, res) {
362
- const reqUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
363
- let pathname = decodeURIComponent(reqUrl.pathname);
364
- if (pathname === '/') {
365
- pathname = '/index.html';
366
- }
367
-
368
- const requested = path.normalize(path.join(PUBLIC_DIR, pathname));
369
- if (!requested.startsWith(PUBLIC_DIR)) {
370
- res.writeHead(403);
371
- res.end('Forbidden');
372
- return;
373
- }
374
-
375
- if (!fs.existsSync(requested) || fs.statSync(requested).isDirectory()) {
376
- res.writeHead(404);
377
- res.end('Not Found');
378
- return;
379
- }
380
-
381
- const body = fs.readFileSync(requested);
382
- res.writeHead(200, { 'Content-Type': contentType(requested), 'Content-Length': body.length });
383
- res.end(body);
384
- }
385
-
386
- const server = createServer((req, res) => {
387
- cleanExpired();
388
-
389
- const reqUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
390
- if (reqUrl.pathname === '/health') {
391
- json(res, {
392
- ok: true,
393
- version: WORKER_VERSION,
394
- protocol_version: PSP_VERSION,
395
- peers: livePeers.size,
396
- }, 200);
397
- return;
398
- }
399
-
400
- if (reqUrl.pathname === '/ws') {
401
- json(res, { ok: false, error: 'Expected WebSocket upgrade on /ws' }, 426);
402
- return;
403
- }
404
-
405
- if (req.method !== 'GET' && req.method !== 'HEAD') {
406
- json(res, { ok: false, error: 'Method not allowed' }, 405);
407
- return;
408
- }
409
-
410
- serveStatic(req, res);
411
- });
412
-
413
- const wss = new WebSocketServer({ noServer: true });
414
- wss.on('connection', (socket) => attachSocketHandlers(socket));
415
-
416
- server.on('upgrade', (req, socket, head) => {
417
- const reqUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
418
- if (reqUrl.pathname !== '/ws') {
419
- socket.destroy();
420
- return;
421
- }
422
-
423
- wss.handleUpgrade(req, socket, head, (ws) => {
424
- wss.emit('connection', ws, req);
425
- });
426
- });
427
-
428
- setInterval(cleanExpired, 5000).unref();
429
-
430
- server.listen(PORT, HOST, () => {
431
- console.log(`[node-relay] listening on http://${HOST}:${PORT}`);
432
- console.log(`[node-relay] ws endpoint ws://${HOST}:${PORT}/ws`);
433
- });
@@ -1,133 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import { fileURLToPath } from 'node:url';
6
- import { spawnSync } from 'node:child_process';
7
-
8
- const __filename = fileURLToPath(import.meta.url);
9
- const PACKAGE_ROOT = path.resolve(path.dirname(__filename), '..');
10
- const PACKAGE_JSON = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
11
- const CLI_VERSION = PACKAGE_JSON.version;
12
-
13
- const isGlobalInstall = process.env.npm_config_global === 'true';
14
-
15
- function compareVersions(left, right) {
16
- const leftParts = String(left).split('.').map((value) => Number.parseInt(value, 10) || 0);
17
- const rightParts = String(right).split('.').map((value) => Number.parseInt(value, 10) || 0);
18
- const length = Math.max(leftParts.length, rightParts.length);
19
-
20
- for (let index = 0; index < length; index += 1) {
21
- const leftValue = leftParts[index] ?? 0;
22
- const rightValue = rightParts[index] ?? 0;
23
- if (leftValue > rightValue) return 1;
24
- if (leftValue < rightValue) return -1;
25
- }
26
-
27
- return 0;
28
- }
29
-
30
- async function fetchLatestCliVersion() {
31
- const response = await fetch('https://registry.npmjs.org/freertc/latest', {
32
- headers: { Accept: 'application/json' }
33
- });
34
- if (!response.ok) {
35
- throw new Error(`npm registry responded with ${response.status}`);
36
- }
37
-
38
- const payload = await response.json();
39
- const version = payload?.version;
40
- if (typeof version !== 'string' || !version.trim()) {
41
- throw new Error('npm registry response did not include a version');
42
- }
43
-
44
- return version;
45
- }
46
-
47
- async function maybeSelfHealInstall() {
48
- if (isGlobalInstall) return;
49
- if (process.env.FREERTC_POSTINSTALL_SELF_HEAL === '0') return;
50
- if (process.env.FREERTC_POSTINSTALL_RUNNING === '1') return;
51
-
52
- const projectRoot = process.env.INIT_CWD ? path.resolve(process.env.INIT_CWD) : null;
53
- if (!projectRoot) return;
54
- if (projectRoot === PACKAGE_ROOT) return;
55
- const projectPackagePath = path.join(projectRoot, 'package.json');
56
- if (!fs.existsSync(projectPackagePath)) return;
57
-
58
- let hostPackage;
59
- try {
60
- hostPackage = JSON.parse(fs.readFileSync(projectPackagePath, 'utf8'));
61
- } catch {
62
- return;
63
- }
64
-
65
- let latestVersion;
66
- try {
67
- latestVersion = await fetchLatestCliVersion();
68
- } catch {
69
- return;
70
- }
71
-
72
- const localAheadOfRegistry = compareVersions(CLI_VERSION, latestVersion) > 0;
73
- if (localAheadOfRegistry) {
74
- console.log(`freertc postinstall detected local ${CLI_VERSION} ahead of npm latest ${latestVersion}; skipping self-heal to avoid downgrade.`);
75
- return;
76
- }
77
-
78
- let dependencyRewritten = false;
79
- for (const section of ['dependencies', 'devDependencies', 'optionalDependencies']) {
80
- const table = hostPackage?.[section];
81
- if (table && typeof table === 'object' && Object.prototype.hasOwnProperty.call(table, 'freertc') && table.freertc !== 'latest') {
82
- table.freertc = 'latest';
83
- dependencyRewritten = true;
84
- }
85
- }
86
-
87
- if (dependencyRewritten) {
88
- fs.writeFileSync(projectPackagePath, `${JSON.stringify(hostPackage, null, 2)}\n`, 'utf8');
89
- console.log('freertc postinstall updated host package.json dependency to "latest".');
90
- }
91
-
92
- const needsUpgrade = compareVersions(CLI_VERSION, latestVersion) < 0;
93
- if (!needsUpgrade && !dependencyRewritten) {
94
- return;
95
- }
96
-
97
- console.log(`freertc postinstall syncing host project to latest (${latestVersion})...`);
98
-
99
- const installResult = spawnSync(
100
- 'npm',
101
- ['install'],
102
- {
103
- cwd: projectRoot,
104
- stdio: 'inherit',
105
- env: {
106
- ...process.env,
107
- FREERTC_POSTINSTALL_RUNNING: '1'
108
- }
109
- }
110
- );
111
-
112
- if (installResult.status !== 0) {
113
- console.warn('freertc postinstall self-heal failed; continuing with current install.');
114
- }
115
- }
116
-
117
- await maybeSelfHealInstall();
118
-
119
- const lines = [
120
- '',
121
- 'freertc installed.',
122
- 'Run commands from the project directory where you want the worker files created.',
123
- '',
124
- 'Quick start:',
125
- isGlobalInstall ? ' 1) freertc' : ' 1) npx freertc',
126
- isGlobalInstall ? ' 2) freertc deploy' : ' 2) npx freertc deploy',
127
- '',
128
- 'Need full control? Use:',
129
- isGlobalInstall ? ' freertc wizard' : ' npx freertc wizard',
130
- ''
131
- ];
132
-
133
- console.log(lines.join('\n'));