@pixelbyte-software/pixcode 1.50.3 → 1.50.5

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.
@@ -1,4 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
 
3
6
  /**
4
7
  * External-access service.
@@ -31,16 +34,62 @@ export const getUpnpState = () => UPNP_UNAVAILABLE;
31
34
  // stops the previous one to avoid dangling child processes.
32
35
  // ============================================================================
33
36
 
37
+ export const TUNNEL_PERSISTENCE_PATH = process.env.PIXCODE_TUNNEL_STATE_PATH
38
+ || path.join(os.homedir(), '.pixcode', 'external-access.json');
39
+
34
40
  let tunnelProc = null;
41
+ let suppressNextTunnelRestore = false;
42
+ let restoreTimer = null;
43
+ let restoreInFlight = null;
35
44
  let tunnelState = {
36
45
  running: false,
37
46
  binary: null, // 'cloudflared' | 'ngrok'
38
47
  url: null,
39
48
  error: null,
40
49
  installHint: null,
50
+ desired: false,
51
+ restoring: false,
41
52
  log: [],
42
53
  };
43
54
 
55
+ const DEFAULT_TUNNEL_PREFERENCE = Object.freeze({
56
+ desired: false,
57
+ port: null,
58
+ provider: null,
59
+ lastUrl: null,
60
+ lastStartedAt: null,
61
+ lastStoppedAt: null,
62
+ updatedAt: null,
63
+ });
64
+
65
+ const readTunnelPreference = async () => {
66
+ try {
67
+ const raw = await fs.readFile(TUNNEL_PERSISTENCE_PATH, 'utf8');
68
+ const parsed = JSON.parse(raw);
69
+ return {
70
+ ...DEFAULT_TUNNEL_PREFERENCE,
71
+ ...(parsed && typeof parsed === 'object' ? parsed : {}),
72
+ };
73
+ } catch (error) {
74
+ if (error?.code !== 'ENOENT') {
75
+ console.warn('[external-access] Failed to read tunnel preference:', error?.message || error);
76
+ }
77
+ return { ...DEFAULT_TUNNEL_PREFERENCE };
78
+ }
79
+ };
80
+
81
+ export const persistTunnelPreference = async (patch) => {
82
+ const current = await readTunnelPreference();
83
+ const next = {
84
+ ...current,
85
+ ...patch,
86
+ updatedAt: new Date().toISOString(),
87
+ };
88
+ await fs.mkdir(path.dirname(TUNNEL_PERSISTENCE_PATH), { recursive: true });
89
+ await fs.writeFile(TUNNEL_PERSISTENCE_PATH, `${JSON.stringify(next, null, 2)}\n`, 'utf8');
90
+ return next;
91
+ };
92
+
44
93
  const appendLog = (line) => {
45
94
  // Tunnels can be noisy. Cap the tail we retain so a long-running tunnel
46
95
  // doesn't grow the log into an OOM risk.
@@ -94,17 +143,34 @@ const extractUrl = (binary, text) => {
94
143
  return null;
95
144
  };
96
145
 
97
- export const startTunnel = async ({ port }) => {
146
+ export const startTunnel = async ({ port, persistPreference = false, restoring = false } = {}) => {
98
147
  if (tunnelProc) {
99
- // Already running — tell the caller to stop it first rather than silently
100
- // replacing, which would orphan the old child and lie about state.
101
- throw new Error('Tunnel already running; stop it first');
148
+ if (persistPreference) {
149
+ await persistTunnelPreference({
150
+ desired: true,
151
+ port,
152
+ provider: tunnelState.binary,
153
+ lastUrl: tunnelState.url,
154
+ });
155
+ tunnelState = { ...tunnelState, desired: true, restoring: false };
156
+ }
157
+ return tunnelState;
102
158
  }
159
+ suppressNextTunnelRestore = false;
103
160
 
104
161
  const binary = await detectBinary();
105
162
  if (!binary) {
106
163
  const installHint = createTunnelInstallHint();
107
- tunnelState = { running: false, binary: null, url: null, error: 'No tunnel binary found', installHint, log: [] };
164
+ tunnelState = {
165
+ running: false,
166
+ binary: null,
167
+ url: null,
168
+ error: 'No tunnel binary found',
169
+ installHint,
170
+ desired: Boolean(persistPreference || restoring),
171
+ restoring,
172
+ log: [],
173
+ };
108
174
  const err = new Error('No tunnel binary found (tried cloudflared, ngrok)');
109
175
  err.code = 'ENOENT_TUNNEL';
110
176
  err.installHint = installHint;
@@ -114,7 +180,16 @@ export const startTunnel = async ({ port }) => {
114
180
  const args = buildTunnelArgs(binary, port);
115
181
  const child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'] });
116
182
  tunnelProc = child;
117
- tunnelState = { running: true, binary, url: null, error: null, installHint: null, log: [] };
183
+ tunnelState = {
184
+ running: true,
185
+ binary,
186
+ url: null,
187
+ error: null,
188
+ installHint: null,
189
+ desired: Boolean(persistPreference || restoring),
190
+ restoring,
191
+ log: [],
192
+ };
118
193
 
119
194
  const handleChunk = (chunk) => {
120
195
  const text = chunk.toString();
@@ -135,8 +210,26 @@ export const startTunnel = async ({ port }) => {
135
210
  url: null,
136
211
  error: code === 0 ? null : `Tunnel exited with code ${code}`,
137
212
  installHint: null,
213
+ desired: tunnelState.desired,
214
+ restoring: false,
138
215
  log: tunnelState.log,
139
216
  };
217
+
218
+ if (suppressNextTunnelRestore) {
219
+ suppressNextTunnelRestore = false;
220
+ return;
221
+ }
222
+
223
+ void readTunnelPreference().then((preference) => {
224
+ if (!preference.desired) return;
225
+ if (restoreTimer) clearTimeout(restoreTimer);
226
+ restoreTimer = setTimeout(() => {
227
+ restoreTimer = null;
228
+ restoreRequestedTunnel({ port: Number(preference.port || port) || port }).catch((error) => {
229
+ console.warn('[external-access] Tunnel restore failed after exit:', error?.message || error);
230
+ });
231
+ }, 3000);
232
+ });
140
233
  });
141
234
 
142
235
  // Wait up to 15s for the public URL to appear in the log. We don't block
@@ -144,7 +237,19 @@ export const startTunnel = async ({ port }) => {
144
237
  // a clear failure instead of a spinner that never resolves.
145
238
  const start = Date.now();
146
239
  while (Date.now() - start < 15000) {
147
- if (tunnelState.url) return tunnelState;
240
+ if (tunnelState.url) {
241
+ if (persistPreference || restoring) {
242
+ await persistTunnelPreference({
243
+ desired: true,
244
+ port,
245
+ provider: binary,
246
+ lastUrl: tunnelState.url,
247
+ lastStartedAt: new Date().toISOString(),
248
+ });
249
+ tunnelState = { ...tunnelState, desired: true, restoring: false };
250
+ }
251
+ return tunnelState;
252
+ }
148
253
  if (!tunnelProc) break; // process died early
149
254
 
150
255
  await new Promise((r) => setTimeout(r, 250));
@@ -152,18 +257,40 @@ export const startTunnel = async ({ port }) => {
152
257
 
153
258
  if (!tunnelState.url) {
154
259
  // If we never captured a URL, kill the child so we don't leak it.
260
+ suppressNextTunnelRestore = true;
155
261
  try { child.kill(); } catch { /* ignore */ }
156
262
  tunnelProc = null;
157
- tunnelState = { ...tunnelState, running: false, error: 'Tunnel did not report a public URL', installHint: null };
263
+ tunnelState = { ...tunnelState, running: false, error: 'Tunnel did not report a public URL', installHint: null, restoring: false };
158
264
  throw new Error(tunnelState.error);
159
265
  }
160
266
 
161
267
  return tunnelState;
162
268
  };
163
269
 
164
- export const stopTunnel = async () => {
270
+ export const stopTunnel = async ({ persistPreference = true } = {}) => {
271
+ suppressNextTunnelRestore = Boolean(tunnelProc);
272
+ if (restoreTimer) {
273
+ clearTimeout(restoreTimer);
274
+ restoreTimer = null;
275
+ }
276
+ if (persistPreference) {
277
+ await persistTunnelPreference({
278
+ desired: false,
279
+ lastStoppedAt: new Date().toISOString(),
280
+ });
281
+ }
165
282
  if (!tunnelProc) {
166
- tunnelState = { running: false, binary: null, url: null, error: null, installHint: null, log: [] };
283
+ suppressNextTunnelRestore = false;
284
+ tunnelState = {
285
+ running: false,
286
+ binary: null,
287
+ url: null,
288
+ error: null,
289
+ installHint: null,
290
+ desired: false,
291
+ restoring: false,
292
+ log: [],
293
+ };
167
294
  return tunnelState;
168
295
  }
169
296
  try {
@@ -172,10 +299,71 @@ export const stopTunnel = async () => {
172
299
  // already dead
173
300
  }
174
301
  tunnelProc = null;
175
- tunnelState = { running: false, binary: null, url: null, error: null, installHint: null, log: [] };
302
+ tunnelState = {
303
+ running: false,
304
+ binary: null,
305
+ url: null,
306
+ error: null,
307
+ installHint: null,
308
+ desired: false,
309
+ restoring: false,
310
+ log: [],
311
+ };
176
312
  return tunnelState;
177
313
  };
178
314
 
315
+ export const restoreRequestedTunnel = async ({ port } = {}) => {
316
+ if (restoreInFlight) return restoreInFlight;
317
+
318
+ restoreInFlight = (async () => {
319
+ const preference = await readTunnelPreference();
320
+ if (!preference.desired) {
321
+ tunnelState = { ...tunnelState, desired: false, restoring: false };
322
+ return tunnelState;
323
+ }
324
+ if (tunnelProc) {
325
+ tunnelState = { ...tunnelState, desired: true, restoring: false };
326
+ return tunnelState;
327
+ }
328
+
329
+ const restorePort = Number(port || preference.port);
330
+ if (!Number.isFinite(restorePort) || restorePort <= 0) {
331
+ tunnelState = {
332
+ ...tunnelState,
333
+ running: false,
334
+ desired: true,
335
+ restoring: false,
336
+ error: 'Tunnel restore skipped: no valid server port',
337
+ };
338
+ return tunnelState;
339
+ }
340
+
341
+ try {
342
+ return await startTunnel({
343
+ port: restorePort,
344
+ persistPreference: true,
345
+ restoring: true,
346
+ });
347
+ } catch (error) {
348
+ tunnelState = {
349
+ ...tunnelState,
350
+ running: false,
351
+ desired: true,
352
+ restoring: false,
353
+ error: `Tunnel restore failed: ${error?.message || error}`,
354
+ installHint: error?.installHint || tunnelState.installHint || null,
355
+ };
356
+ return tunnelState;
357
+ }
358
+ })();
359
+
360
+ try {
361
+ return await restoreInFlight;
362
+ } finally {
363
+ restoreInFlight = null;
364
+ }
365
+ };
366
+
179
367
  export const getTunnelState = () => tunnelState;
180
368
 
181
369
  // Explicit cleanup so the server process can shut down without leaking the