pinggy 0.6.4 → 0.6.6

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 (32) hide show
  1. package/ARCHITECTURE.md +126 -57
  2. package/CLAUDE.md +25 -12
  3. package/README.md +5 -5
  4. package/dist/{TunnelManager-NGSUBZYI.js → TunnelManager-JRVEADS4.js} +4 -3
  5. package/dist/{TunnelTui-UCG2YSLX.js → TunnelTui-6H4NPUNF.js} +4 -3
  6. package/dist/{chunk-Y435RMHQ.js → chunk-2GIJXE4K.js} +3 -2
  7. package/dist/{chunk-QNUVQ6KD.js → chunk-3WMTTJHI.js} +11 -299
  8. package/dist/chunk-4XXAHYCJ.js +927 -0
  9. package/dist/{chunk-PD7HXVQ3.js → chunk-CZOKR73F.js} +18 -1
  10. package/dist/chunk-FQ22KFVV.js +882 -0
  11. package/dist/{chunk-UVJYL2ZN.js → chunk-HAFTH5MX.js} +933 -576
  12. package/dist/chunk-HTIWY3O5.js +293 -0
  13. package/dist/{chunk-MV56U3E6.js → chunk-LWCVB42S.js} +2 -2
  14. package/dist/{chunk-AFMTIELL.js → chunk-MAK5R4WQ.js} +20 -0
  15. package/dist/{chunk-7EQKHVQX.js → chunk-MHQ3CVEB.js} +4 -51
  16. package/dist/chunk-MKGD2QAI.js +51 -0
  17. package/dist/{chunk-CIOYQU7F.js → chunk-Q5NCTGNS.js} +49 -233
  18. package/dist/{configStore-RR5ZU4E3.js → configStore-JJUWT2YO.js} +3 -3
  19. package/dist/{daemonChild-WHS676G4.js → daemonChild-Q6WGYKYX.js} +14 -14
  20. package/dist/daemonConfig-VWK4TXVS.js +17 -0
  21. package/dist/index.cjs +3214 -935
  22. package/dist/index.d.cts +150 -129
  23. package/dist/index.d.ts +150 -129
  24. package/dist/index.js +18 -13
  25. package/dist/{ipcClient-XGF2KCQO.js → ipcClient-IZ5R6TPN.js} +2 -1
  26. package/dist/{main-JRVKAIHH.js → main-BI7ACRHS.js} +19 -14
  27. package/dist/updateChild-Z3SIRYO5.js +237 -0
  28. package/dist/workers/file_serve_worker.js +1 -1
  29. package/package.json +2 -1
  30. package/scripts/install/install.ps1 +49 -5
  31. package/scripts/install/install.sh +99 -12
  32. package/dist/daemonConfig-QVXQ47XH.js +0 -9
package/CLAUDE.md CHANGED
@@ -25,11 +25,12 @@ node test/e2e/run.cjs out/pinggy-<platform>
25
25
 
26
26
  ### Two-process model
27
27
 
28
- The CLI binary has 3 entry modes, dispatched in `src/main.ts`:
28
+ The CLI binary has 4 entry modes, dispatched in `src/main.ts`:
29
29
 
30
30
  1. **Daemon child** (`--_daemon-child` flag). Calls `runDaemonChild()` in `src/daemon/daemonChild.ts`. The CLI re-execs itself with this flag when it needs to spawn a daemon; users never invoke it directly.
31
- 2. **Subcommand** (`config`, `start`, `stop`, `ps`, `attach`, `daemon`, `d`, `device`, `devices`). Routes to `handleSubcommand()` in `src/cli/subcommands.ts`.
31
+ 2. **Subcommand** (`config`, `start`, `stop`, `ps`, `attach`, `daemon`, `d`, `device`, `devices`, `update`). Routes to `handleSubcommand()` in `src/cli/subcommands.ts`.
32
32
  3. **Legacy single-tunnel** (no subcommand). Routes to `buildAndStartTunnel()` for flags like `-l 3000` or `-R0:localhost:3000`.
33
+ 4. **Update child** (`--_update-child` flag). Calls `runUpdateChild()` in `src/update/updateChild.ts`. A command starts it at most once a day, detached, to check for a release and install it.
33
34
 
34
35
  The daemon owns the `TunnelManager` singleton, the `@pinggy/pinggy` SDK, the web debugger server, and any `--serve` file servers. The CLI owns argument parsing, the TUI, the remote-management WebSocket client, and the IPC client to the daemon.
35
36
 
@@ -44,15 +45,18 @@ CLI code calls `TunnelClient` (`src/daemon/tunnelClient.ts`), the public facade
44
45
 
45
46
  ### Daemon discovery and lifecycle
46
47
 
47
- `getDaemonInfo()` in `src/daemon/daemonManager.ts` reads `daemon.json`, validates the PID with `process.kill(pid, 0)`, deletes the file if stale, and returns `null` if no live daemon is found. `startDaemon()` spawns a detached daemon child and polls `daemon.json` for up to 8s.
48
+ `getDaemonInfo()` in `src/daemon/daemonManager.ts` reads `daemon.json`, validates the PID with `process.kill(pid, 0)`, deletes the file if stale (dead PID, or `startedAt` before the last boot), and returns `null` if no live daemon is found. `startDaemon()` spawns a detached daemon child and polls `daemon.json` for up to 8s.
48
49
 
49
50
  Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or `%APPDATA%/pinggy/` on Windows (helper: `src/utils/configDir.ts`):
50
51
 
51
- - `daemon.json`: `{pid, port, startedAt, host, ipcVersion}`. `ipcVersion` is `IPC_VERSION` from `src/daemon/ipc/ipcRoutes.ts`. `ensureDaemonRunning()` refuses a live daemon whose version differs and tells the user to run `pinggy daemon stop`. Bump `IPC_VERSION` on any incompatible IPC or WebSocket change.
52
- - `daemon-state.json`: detached tunnel configs, and the background device agent (`deviceAgent`), for crash recovery (`src/daemon/stateStore.ts`). Deleted on clean shutdown; replayed on next start.
52
+ - `daemon.json`: `{pid, port, startedAt, host, ipcVersion, cliVersion}`. `cliVersion` is the version the daemon started with, and never follows the installed binary. `ipcVersion` is `IPC_VERSION` from `src/daemon/ipc/ipcRoutes.ts`. `ensureDaemonRunning()` refuses a live daemon whose version differs and tells the user to run `pinggy daemon stop`. Bump `IPC_VERSION` on any incompatible IPC or WebSocket change. After an update the CLI is newer than the daemon, often for weeks, so a new IPC route or WebSocket frame needs a capability check or an `IPC_VERSION` bump.
53
+ - `daemon.lock`: `{pid, started_at}` of the running daemon (`src/daemon/lifecycle/daemonLock.ts`). Each daemon takes it before it opens its IPC port, and a daemon that finds a live holder exits 0. systemd and launchd run `--_daemon-child` directly, and 2 CLIs can spawn at once, so the CLI's `daemon.json` check alone does not keep 1 daemon.
54
+ - `daemon-state.json`: detached tunnel configs, for crash recovery (`src/daemon/lifecycle/stateStore.ts`). Deleted on clean shutdown; replayed on next start.
55
+ - `daemon-config.json`: settings that survive a clean shutdown (`src/daemon/lifecycle/daemonConfig.ts`): the log level, and `deviceAgent`, set while the background device agent should run. Every daemon start runs that agent. `pinggy device remove` deletes it. `pinggy device stop` keeps it, so the agent starts again with the next daemon.
53
56
  - `daemon.log`: SDK + daemon logs. CLI logs stay separate.
54
57
  - `tunnels/<name>_<configId>.json`: saved tunnel configs from `pinggy config save`.
55
58
  - `device.json`: device agent id and token from `pinggy device connect` (`src/devices/deviceIdentity.ts`). Written 0600, unlike the tunnel configs beside it.
59
+ - `device-agent.json`: `{pid, started_at}` of a device agent started with `--foreground`, while it runs (`src/devices/foregroundAgent.ts`). `pinggy device remove` deletes it, and the agent stops within 1 s. No credential.
56
60
 
57
61
  ### Foreground vs detached tunnels
58
62
 
@@ -69,15 +73,15 @@ Single daemon per user. State lives under `~/.config/pinggy/` on Linux/macOS or
69
73
 
70
74
  `pinggy devices`, the old spelling, stays a subcommand that prints the new one and exits 1 (`refuseDevicesSpelling()`). Do not remove `Subcommand.Devices`: without it `devices` falls to legacy tunnel mode, where `--token` is the tunnel token, so `pinggy devices connect --token pga_...` would send the device token to the tunnel server.
71
75
 
72
- It owns no tunnel. Since slice 09 it reads the daemon's `GET /tunnels` through `IPCClient` and the saved configs, to send `device/tunnels` (`src/devices/tunnels/tunnelList.ts`), and listing never starts a daemon. Since slice 10 it stops, restarts and starts tunnels when the dashboard asks (`src/devices/tunnels/tunnelActions.ts`), through `IPCClient` with the `device` origin; only a start of a config may call `ensureDaemonRunning()`. Since slice 10b it also applies an updated dashboard config to the tunnel running it, through the daemon's `update-config-v2`, and it rewrites a saved config's file when the dashboard edits it (`upsertConfig()`, no daemon). Since slice 12 `pinggy device login` signs the machine in by email over plain HTTPS (`src/devices/login/`), writes `device.json`, then runs the same agent; since slice 13 the sign-in can also be approved from the email's link, and the poll collects it. No `TunnelManager`. It also does not reuse `src/remote_management/`, which is a tunnel controller keyed by an API key rather than the machine keyed by a device token. Frames use a versioned envelope (`src/devices/envelope.ts`) validated with zod (`src/devices/device_schema.ts`); an unknown `ch` or `op` is ignored, never fatal.
76
+ It owns no tunnel. It reads the daemon's `GET /tunnels` through `IPCClient` and the saved configs, to send `device/tunnels` (`src/devices/tunnels/tunnelList.ts`), and listing never starts a daemon. It stops, restarts and starts tunnels when the dashboard asks (`src/devices/tunnels/tunnelActions.ts`), through `IPCClient` with the `device` origin; only a start of a config may call `ensureDaemonRunning()`. It also applies an updated dashboard config to the tunnel running it, through the daemon's `update-config-v2`, and it rewrites a saved config's file when the dashboard edits it (`upsertConfig()`, no daemon). `pinggy device login` signs the machine in by email over plain HTTPS (`src/devices/login/`), writes `device.json`, then runs the same agent; the sign-in can also be approved from the email's link, and the poll collects it. No `TunnelManager`. It also does not reuse `src/remote_management/`, which is a tunnel controller keyed by an API key rather than the machine keyed by a device token. Frames use a versioned envelope (`src/devices/envelope.ts`) validated with zod (`src/devices/device_schema.ts`); an unknown `ch` or `op` is ignored, never fatal.
73
77
 
74
- `pinggy device connect` and `login` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal (slice 17). `--foreground` runs it in the CLI process instead, until Ctrl+C. `-b` still parses and changes nothing; `-b` with `--foreground` exits 1. `--foreground` sits hidden in `cliOptions`, because `main.ts` parses the whole command line with it, strict, before it dispatches. Whoever hosts the daemon, the CLI's child or the Pinggy app, hosts the agent (`src/daemon/deviceAgentHost.ts`, `src/devices/backgroundAgent.ts`). `GET /device`, `POST /device/start` and `POST /device/stop` reach it, and `TunnelClient` exposes them for the app. No IPC route takes or returns a token or a server: the daemon reads both from `device.json`, and a new token is checked in the CLI with 1 handshake before the daemon sees it. Once the daemon starts the agent, the CLI prints the commands that manage it (`status`, `stop`, `connect`, `remove`). `pinggy device stop` stops it. A `--foreground` `connect` or `login` refuses while it runs. The loop prints nothing itself: it calls a `DeviceAgentReporter`, and the foreground's prints the same lines as before.
78
+ `pinggy device connect` and `login` run the agent in the daemon, as `pinggy start -b` runs a tunnel there, so it outlives the terminal. `--foreground` runs it in the CLI process instead, until Ctrl+C. `-b` still parses and changes nothing; `-b` with `--foreground` exits 1. `--foreground` sits hidden in `cliOptions`, because `main.ts` parses the whole command line with it, strict, before it dispatches. Whoever hosts the daemon, the CLI's child or the Pinggy app, hosts the agent (`src/daemon/deviceAgentHost.ts`, `src/devices/backgroundAgent.ts`). `GET /device`, `POST /device/start` and `POST /device/stop` reach it, and `TunnelClient` exposes them for the app. No IPC route takes or returns a token or a server: the daemon reads both from `device.json`, and a new token is checked in the CLI with 1 handshake before the daemon sees it. Once the daemon starts the agent, the CLI prints the commands that manage it (`status`, `stop`, `connect`, `remove`). `pinggy device stop` stops it. A `--foreground` `connect` or `login` refuses while it runs. The loop prints nothing itself: it calls a `DeviceAgentReporter`, and the foreground's prints the same lines as before.
75
79
 
76
80
  1 invocation runs 1 subcommand: `isSubcommand()` reads `rawArgs[0]` only, so `pinggy device connect start my-tunnel` runs the agent and drops the rest, and tunnel flags on a `device` line parse and are ignored, except `-b` and `--foreground`.
77
81
 
78
- Since slice 14, `scripts/install/install.sh` and `install.ps1` install or update the binary, put it on PATH, and run `pinggy device login -b`. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. pinggy.io serves copies that `website-cli-download-links-pr.yml` writes at each release tag. Renaming a release asset, changing the `Pinggy CLI version:` line, or changing `device login`'s `--manage` or `-b` flag means changing both scripts in the same commit. Since slice 16, `DEVICE_AGENT_TOKEN` on either script updates without asking and runs `pinggy device connect -b` instead, with the token in the environment, never on a command line. `handleDevice()` deletes the variable from `process.env` before any verb runs, so no shell or daemon the agent starts inherits it. Renaming the variable or `connect`'s `--manage` or `-b` flag also changes both scripts in the same commit.
82
+ `scripts/install/install.sh` installs into `~/.pinggy/versions/<version>/` and points the link `~/.pinggy/bin/pinggy` at it. `install.sh` and `install.ps1` install or update the binary, put it on PATH, then ask "Connect this device to Pinggy? [Y/n]" and run `pinggy device login -b` unless the answer starts with `n`. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. pinggy.io serves copies that `website-cli-download-links-pr.yml` writes at each release tag. Renaming a release asset, changing the `Pinggy CLI version:` line, or changing `device login`'s `--manage` or `-b` flag means changing both scripts in the same commit. `DEVICE_AGENT_TOKEN` on either script updates without asking and runs `pinggy device connect -b` instead, with the token in the environment, never on a command line. `handleDevice()` deletes the variable from `process.env` before any verb runs, so no shell or daemon the agent starts inherits it. Renaming the variable or `connect`'s `--manage` or `-b` flag also changes both scripts in the same commit. `pinggy daemon service-install` runs only from the path the scripts install to (`installerBinaryPath()` in `src/daemon/lifecycle/serviceInstaller.ts`), so changing either script's install directory changes that function in the same commit. Once the device connects, both scripts offer `pinggy daemon service-install` unless the service exists. They look for the task name, plist or unit file that `serviceInstaller.ts` writes, and the installed binary's path in it, so renaming any of them changes both scripts in the same commit.
79
83
 
80
- Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome table, the `device.json` rules, and the full composition table. The design docs are in the `pinggy_backend` repo under `docs/pinggy-devices/`; read `cli.md` and `api-websocket.md` there before changing anything in `src/devices/`.
84
+ Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome table, the `device.json` rules, and the full composition table. The design docs are in the `pinggy_backend` repo under `docs/pinggy-devices/`; read `cli.md` there before changing anything in `src/devices/`.
81
85
 
82
86
  **Core types** are in `src/types.ts`: `TunnelStatus`, `Status`, `TunnelStateType` enum (`idle/starting/running/live/closed/exited`), `FinalConfig` (extends SDK's `TunnelConfigurationV1`). Browse `src/daemon/` and `src/cli/` for the rest of the module layout.
83
87
 
@@ -90,14 +94,23 @@ Section 17 of `ARCHITECTURE.md` has the protocol, the retry and terminal outcome
90
94
  | `pinggy stop <name\|id>` | Stop running tunnel(s) by name or ID prefix |
91
95
  | `pinggy ps` | Table of running tunnels (ID, name, status, local, URL) |
92
96
  | `pinggy attach <name\|id>` | Re-attach TUI to a running tunnel |
93
- | `pinggy daemon start \| stop \| status \| install-service \| uninstall-service` (alias `d`) | Daemon lifecycle and system-service installation |
94
- | `pinggy device login \| connect [--foreground] \| stop \| status \| remove` | Sign this machine in by email, or enrol it with a token, as a Pinggy device; the agent runs in the daemon, or in this terminal with `--foreground`, and `stop` stops the daemon's; show the enrolment and the background agent; forget the credential |
97
+ | `pinggy daemon start \| stop \| status \| service-install \| service-uninstall` (alias `d`) | Daemon lifecycle and system-service installation |
98
+ | `pinggy update [--check \| --rollback]` | Update to the latest release now, print the latest version and change nothing, or go back to the previous version. A background check starts on its own; `PINGGY_AUTO_UPDATE=false` turns it off |
99
+ | `pinggy device login \| connect [--foreground] \| stop \| status \| remove [-f]` | Sign this machine in by email, or enrol it with a token, as a Pinggy device; the agent runs in the daemon, or in this terminal with `--foreground`, and `stop` stops the daemon's; show the enrolment and the background agent; show the device and its connection, ask, then stop every agent and forget the credential (`-f` skips the question) |
100
+
101
+ ### Auto-update
102
+
103
+ `src/update/` updates the CLI from GitHub releases. Section 20 of `ARCHITECTURE.md` has the flow. 3 rules hold for every change:
104
+
105
+ - Each installed copy keeps the updater it shipped with, so these never change: the `/releases/latest` redirect, the tag format `vX.Y.Z`, the 6 asset names, `SHA256SUMS` and its format, the `Pinggy CLI version: <x.y.z>` line, the `--_ipc-version` output, and the `update.json` field names.
106
+ - A rollback runs older code against `daemon-state.json`, `device.json` and saved configs, so they change by adding fields only.
107
+ - `SHA256SUMS` is the last upload of a release. A release that has it counts as complete.
95
108
 
96
109
  ## Build System
97
110
 
98
111
  tsup bundles to `dist/` (CJS + ESM). tsc type-checks only (`npm run build:tsc`). pkg builds standalone platform binaries (`out/pinggy-<platform>`). ts-jest with the ESM preset for unit tests (`jest.config.cjs`).
99
112
 
100
- pkg packs every file in a dependency's `files` list and every package in its `dependencies`, whether the code loads it or not. The `pkg.ignore` list in `package.json` keeps out what the binary never loads: node-pty's `.pdb` debug symbols and C++ source, the SDK's unlinked `libcrypto.dylib` and `libssl.dylib` copies, the SDK's install-time `node-gyp` and `@mapbox/node-pre-gyp`, and zod's `src/` and `v3/`. A new glob must not match node-pty's `package.json`, `lib/`, or any file under `prebuilds/` other than a `.pdb`: `resolveNodePtyRoot()` copies those out of the snapshot at runtime. The `**` in these globs does not match a folder whose name starts with a dot, so a checkout under such a path (`~/.work/cli-js`) ignores nothing and builds the full-size binary. `"compress": "Brotli"` compresses the snapshot: on macOS arm64 the binary drops from 83 MB to 59 MB, and each run starts about 80ms later.
113
+ pkg packs every file in a dependency's `files` list and every package in its `dependencies`, whether the code loads it or not. The `pkg.ignore` list in `package.json` keeps out what the binary never loads: node-pty's `.pdb` debug symbols and C++ source, the SDK's unlinked `libcrypto.dylib` and `libssl.dylib` copies, the SDK's install-time `node-gyp` and `@mapbox/node-pre-gyp`, and zod's `src/` and `v3/`. A new glob must not match node-pty's `package.json`, `lib/`, `build/Release/pty.node`, or any file under `prebuilds/` other than a `.pdb`: `resolveNodePtyRoot()` copies those out of the snapshot at runtime. node-pty has no Linux prebuild, so on Linux `npm ci` compiles `build/Release/pty.node`. Its `files` list leaves `build/` out, so `pkg.assets` names that file. Without it the Linux binary offers no terminal. The `**` in these globs does not match a folder whose name starts with a dot, so a checkout under such a path (`~/.work/cli-js`) ignores nothing and builds the full-size binary. `"compress": "Brotli"` compresses the snapshot: on macOS arm64 the binary drops from 83 MB to 59 MB, and each run starts about 80ms later.
101
114
 
102
115
  ## Testing
103
116
 
package/README.md CHANGED
@@ -275,7 +275,7 @@ Prints the device id, server, masked token, and enrolment time from the local fi
275
275
  pinggy device remove
276
276
  ```
277
277
 
278
- Deletes the local credential only. The device still exists in the dashboard. Delete it there to revoke it, because a machine that has lost its credential cannot authenticate the delete.
278
+ Prints the device id and whether the device is connected now, in the background or with `--foreground` in another terminal, then asks "Remove this device from this machine? [y/N]". Only `y` removes it: the command stops the device agent, then deletes the local credential. With no terminal, it refuses unless you add `-f`, which removes without asking. The device still exists in the dashboard. Delete it there to revoke it, because a machine that has lost its credential cannot authenticate the delete.
279
279
 
280
280
  ### Reconnect and stop conditions
281
281
 
@@ -314,11 +314,11 @@ It enrols, learns its device id and heartbeat interval from the dashboard, and s
314
314
 
315
315
  ### Devices, tunnels, and the daemon
316
316
 
317
- - By default the daemon runs the agent. `pinggy device connect` and `login` start a daemon when none runs. `pinggy daemon stop` stops the agent with every tunnel, and so does a reboot. `pinggy device connect` starts it again.
317
+ - By default the daemon runs the agent. `pinggy device connect` and `login` start a daemon when none runs. `pinggy daemon stop` stops the agent with every tunnel, and so does a reboot. Every daemon start runs it again, until `pinggy device remove`. `pinggy device stop` stops it until the daemon starts again. With `pinggy daemon service-install`, the daemon starts at sign-in, so the device comes back online after a reboot. `pinggy device connect` starts it again after a stop.
318
318
  - With `--foreground` the agent is its own process. It never starts the daemon, `pinggy daemon stop` leaves it running, and Ctrl+C on it leaves every tunnel running.
319
319
  - 1 enrolment per machine. The newest successful connect overwrites `device.json`, and a `--token` on the command line beats the stored one.
320
- - 1 agent per machine. `--foreground` is refused while the daemon runs an agent. Stop it first with `pinggy device stop`.
321
- - `pinggy device remove` stops the daemon's agent, then deletes the credential file. It does not stop a `--foreground` agent, which rewrites the file the next time it connects. Stop that one first with Ctrl+C.
320
+ - 1 agent per machine. `connect` and `login` refuse while another terminal runs a `--foreground` agent. `--foreground` is refused while the daemon runs an agent. Stop that one first with `pinggy device stop`.
321
+ - `pinggy device remove` stops a running agent, in the background or with `--foreground` in another terminal, before it deletes the credential file.
322
322
 
323
323
 
324
324
  ## Usage
@@ -498,7 +498,7 @@ Config dir varies by OS:
498
498
  - Linux/macOS: `~/.config/pinggy/`
499
499
  - Windows: `%APPDATA%\pinggy\`
500
500
 
501
- It holds `daemon.json` (discovery), `daemon-config.json` (persisted settings), `daemon-state.json` (crash recovery), `tunnels/` (saved configs), and `device.json` (the Pinggy Devices credential, written `0600`).
501
+ It holds `daemon.json` (discovery), `daemon-config.json` (persisted settings), `daemon-state.json` (crash recovery), `tunnels/` (saved configs), `device.json` (the Pinggy Devices credential, written `0600`), and `device-agent.json` (the PID of a device agent running in a terminal).
502
502
 
503
503
  Log dir varies by OS:
504
504
  - Linux: `~/.local/state/pinggy-cli/logs/` (honors `$XDG_STATE_HOME`)
@@ -2,10 +2,11 @@ import {
2
2
  TunnelAlreadyRunningError,
3
3
  TunnelManager,
4
4
  TunnelRebuildInProgressError
5
- } from "./chunk-QNUVQ6KD.js";
5
+ } from "./chunk-3WMTTJHI.js";
6
6
  import "./chunk-UB26QJ4T.js";
7
- import "./chunk-MV56U3E6.js";
8
- import "./chunk-AFMTIELL.js";
7
+ import "./chunk-HTIWY3O5.js";
8
+ import "./chunk-LWCVB42S.js";
9
+ import "./chunk-MAK5R4WQ.js";
9
10
  export {
10
11
  TunnelAlreadyRunningError,
11
12
  TunnelManager,
@@ -3,12 +3,13 @@ import {
3
3
  } from "./chunk-XZ64ZAGO.js";
4
4
  import {
5
5
  TunnelManager
6
- } from "./chunk-QNUVQ6KD.js";
6
+ } from "./chunk-3WMTTJHI.js";
7
7
  import "./chunk-UB26QJ4T.js";
8
+ import "./chunk-HTIWY3O5.js";
8
9
  import {
9
10
  logger
10
- } from "./chunk-MV56U3E6.js";
11
- import "./chunk-AFMTIELL.js";
11
+ } from "./chunk-LWCVB42S.js";
12
+ import "./chunk-MAK5R4WQ.js";
12
13
 
13
14
  // src/tui/blessed/TunnelTui.ts
14
15
  import blessed3 from "blessed";
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  logger
3
- } from "./chunk-MV56U3E6.js";
3
+ } from "./chunk-LWCVB42S.js";
4
4
  import {
5
5
  ensureTunnelConfigDir,
6
6
  getTunnelConfigDir
7
- } from "./chunk-AFMTIELL.js";
7
+ } from "./chunk-MAK5R4WQ.js";
8
8
 
9
9
  // src/cli/configStore.ts
10
10
  import fs from "fs";
@@ -36,6 +36,7 @@ var Subcommand = {
36
36
  Log: "log",
37
37
  Restart: "restart",
38
38
  Device: "device",
39
+ Update: "update",
39
40
  // The old spelling, refused with a hint. As a subcommand it never reaches tunnel mode, where `--token` is the
40
41
  // tunnel token and a device token would go to the tunnel server.
41
42
  Devices: "devices"
@@ -1,13 +1,18 @@
1
1
  import {
2
2
  FileServerMessage
3
3
  } from "./chunk-UB26QJ4T.js";
4
+ import {
5
+ errorMessage,
6
+ getRandomId,
7
+ printer_default
8
+ } from "./chunk-HTIWY3O5.js";
4
9
  import {
5
10
  getLogLevel,
6
11
  logger
7
- } from "./chunk-MV56U3E6.js";
12
+ } from "./chunk-LWCVB42S.js";
8
13
  import {
9
14
  getTunnelLogPath
10
- } from "./chunk-AFMTIELL.js";
15
+ } from "./chunk-MAK5R4WQ.js";
11
16
 
12
17
  // src/tunnel_manager/TunnelManager.ts
13
18
  import { TunnelInstance, LogLevel as SdkLogLevel } from "@pinggy/pinggy";
@@ -94,288 +99,12 @@ function maybeRotate(file, maxBytes = DEFAULT_MAX_BYTES, maxArchives = DEFAULT_M
94
99
  }
95
100
  }
96
101
 
97
- // src/types.ts
98
- var TunnelStateType = /* @__PURE__ */ ((TunnelStateType2) => {
99
- TunnelStateType2["New"] = "idle";
100
- TunnelStateType2["Starting"] = "starting";
101
- TunnelStateType2["Running"] = "running";
102
- TunnelStateType2["Live"] = "live";
103
- TunnelStateType2["Closed"] = "closed";
104
- TunnelStateType2["Exited"] = "exited";
105
- return TunnelStateType2;
106
- })(TunnelStateType || {});
107
- var TunnelErrorCodeType = /* @__PURE__ */ ((TunnelErrorCodeType2) => {
108
- TunnelErrorCodeType2["NonResponsive"] = "non_responsive";
109
- TunnelErrorCodeType2["FailedToConnect"] = "failed_to_connect";
110
- TunnelErrorCodeType2["ErrorInAdditionalForwarding"] = "additional_forwarding_error";
111
- TunnelErrorCodeType2["WebdebuggerError"] = "webdebugger_error";
112
- TunnelErrorCodeType2["NoError"] = "";
113
- return TunnelErrorCodeType2;
114
- })(TunnelErrorCodeType || {});
115
- var TunnelWarningCode = /* @__PURE__ */ ((TunnelWarningCode3) => {
116
- TunnelWarningCode3["InvalidTunnelServePath"] = "INVALID_TUNNEL_SERVE_PATH";
117
- TunnelWarningCode3["UnknownWarning"] = "UNKNOWN_WARNING";
118
- return TunnelWarningCode3;
119
- })(TunnelWarningCode || {});
120
- var ErrorCode = {
121
- InvalidRequestMethodError: "INVALID_REQUEST_METHOD",
122
- InvalidRequestBodyError: "COULD_NOT_READ_BODY",
123
- InternalServerError: "INTERNAL_SERVER_ERROR",
124
- InvalidBodyFormatError: "INVALID_DATA_FORMAT",
125
- ErrorStartingTunnel: "ERROR_STARTING_TUNNEL",
126
- TunnelNotFound: "TUNNEL_WITH_ID_OR_CONFIG_ID_NOT_FOUND",
127
- TunnelAlreadyRunningError: "TUNNEL_WITH_ID_OR_CONFIG_ID_ALREADY_RUNNING",
128
- WebsocketUpgradeFailError: "WEBSOCKET_UPGRADE_FAILED",
129
- RemoteManagementAlreadyRunning: "REMOTE_MANAGEMENT_ALREADY_RUNNING",
130
- RemoteManagementNotRunning: "REMOTE_MANAGEMENT_NOT_RUNNING",
131
- RemoteManagementDeserializationFailed: "REMOTE_MANAGEMENT_DESERIALIZATION_FAILED",
132
- DeviceNotEnrolled: "DEVICE_NOT_ENROLLED"
133
- };
134
- function isErrorResponse(obj) {
135
- return typeof obj === "object" && obj !== null && "code" in obj && "message" in obj && typeof obj.message === "string" && Object.values(ErrorCode).includes(obj.code);
136
- }
137
- function newErrorResponse(codeOrError, message) {
138
- if (typeof codeOrError === "object") {
139
- return codeOrError;
140
- }
141
- return {
142
- code: codeOrError,
143
- message
144
- };
145
- }
146
- function NewResponseObject(data) {
147
- const encoder = new TextEncoder();
148
- const bytes = encoder.encode(JSON.stringify(data));
149
- return {
150
- response: bytes,
151
- requestid: "",
152
- command: "",
153
- error: false,
154
- errorresponse: {}
155
- };
156
- }
157
- function NewErrorResponseObject(errorResponse) {
158
- return {
159
- response: new Uint8Array(),
160
- requestid: "",
161
- command: "",
162
- error: true,
163
- errorresponse: errorResponse
164
- };
165
- }
166
- function newStatus(tunnelState, errorCode, errorMsg) {
167
- let assignedState = tunnelState;
168
- if (tunnelState === "live" /* Live */) {
169
- assignedState = "running" /* Running */;
170
- } else if (tunnelState === "idle" /* New */) {
171
- assignedState = "idle" /* New */;
172
- } else if (tunnelState === "closed" /* Closed */) {
173
- assignedState = "exited" /* Exited */;
174
- }
175
- const now = (/* @__PURE__ */ new Date()).toISOString();
176
- return {
177
- state: assignedState,
178
- errorcode: errorCode,
179
- errormsg: errorMsg,
180
- createdtimestamp: now,
181
- starttimestamp: now,
182
- endtimestamp: now,
183
- warnings: []
184
- };
185
- }
186
- function newStats() {
187
- return {
188
- numLiveConnections: 0,
189
- numTotalConnections: 0,
190
- numTotalReqBytes: 0,
191
- numTotalResBytes: 0,
192
- numTotalTxBytes: 0,
193
- elapsedTime: 0
194
- };
195
- }
196
- var RemoteManagementStatus = {
197
- Connecting: "CONNECTING",
198
- Disconnecting: "DISCONNECTING",
199
- Reconnecting: "RECONNECTING",
200
- Running: "RUNNING",
201
- NotRunning: "NOT_RUNNING",
202
- Error: "ERROR"
203
- };
204
-
205
102
  // src/tunnel_manager/TunnelManager.ts
206
103
  import path2 from "path";
207
104
  import { Worker } from "worker_threads";
208
- import { fileURLToPath as fileURLToPath2 } from "url";
209
-
210
- // src/utils/printer.ts
211
- import pico2 from "picocolors";
212
-
213
- // src/tui/spinner/spinner.ts
214
- import pico from "picocolors";
215
- var spinners = {
216
- dots: {
217
- interval: 80,
218
- frames: ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"]
219
- }
220
- };
221
- var currentTimer = null;
222
- var currentText = "";
223
- function startSpinner(name = "dots", text = "Loading") {
224
- const spinner = spinners[name];
225
- let i = 0;
226
- currentText = text;
227
- if (currentTimer) {
228
- clearInterval(currentTimer);
229
- }
230
- currentTimer = setInterval(() => {
231
- const frame = spinner.frames[i = ++i % spinner.frames.length];
232
- process.stdout.write(`\r${pico.cyan(frame)} ${text}\x1B[K`);
233
- }, spinner.interval);
234
- return () => stopSpinner();
235
- }
236
- function stopSpinner() {
237
- if (currentTimer) {
238
- clearInterval(currentTimer);
239
- currentTimer = null;
240
- process.stdout.write("\r\x1B[K");
241
- }
242
- }
243
- function stopSpinnerSuccess(message) {
244
- if (currentTimer) {
245
- clearInterval(currentTimer);
246
- currentTimer = null;
247
- const finalMessage = message || currentText;
248
- process.stdout.write(`\r${pico.green("\u2714")} ${finalMessage}\x1B[K
249
- `);
250
- }
251
- }
252
- function stopSpinnerFail(message) {
253
- if (currentTimer) {
254
- clearInterval(currentTimer);
255
- currentTimer = null;
256
- const finalMessage = message || currentText;
257
- process.stdout.write(`\r${pico.red("\u2716")} ${finalMessage}\x1B[K
258
- `);
259
- }
260
- }
261
-
262
- // src/utils/printer.ts
263
- var _CLIPrinter = class _CLIPrinter {
264
- static isCLIError(err) {
265
- return err instanceof Error;
266
- }
267
- static print(message, ...args) {
268
- console.log(message, ...args);
269
- }
270
- static error(err) {
271
- const def = this.errorDefinitions.find((d) => d.match(err));
272
- const msg = def.message(err);
273
- console.error(pico2.red(pico2.bold("\u2716 Error:")), pico2.red(msg));
274
- }
275
- static fatal(err) {
276
- const def = this.errorDefinitions.find((d) => d.match(err));
277
- const msg = def.message(err);
278
- console.error(pico2.red(pico2.bold("\u2716 Fatal Error:")), pico2.red(msg));
279
- process.exit(1);
280
- }
281
- static red(message) {
282
- return pico2.red(message);
283
- }
284
- static warn(message) {
285
- console.warn(pico2.yellow(pico2.bold("\u26A0 Warning:")), pico2.yellow(message));
286
- }
287
- static warnTxt(message) {
288
- console.warn(pico2.yellow(pico2.bold("\u26A0 Warning:")), pico2.yellow(message));
289
- }
290
- static success(message) {
291
- console.log(pico2.green(pico2.bold(" \u2714 Success:")), pico2.green(message));
292
- }
293
- static info(message) {
294
- console.log(pico2.blue(message));
295
- }
296
- static startSpinner(message) {
297
- startSpinner("dots", message);
298
- }
299
- static stopSpinnerSuccess(message) {
300
- stopSpinnerSuccess(message);
301
- }
302
- static stopSpinnerFail(message) {
303
- stopSpinnerFail(message);
304
- }
305
- };
306
- _CLIPrinter.errorDefinitions = [
307
- {
308
- match: (err) => _CLIPrinter.isCLIError(err) && err.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION",
309
- message: (err) => {
310
- const match = /Unknown option '(.+?)'/.exec(err.message);
311
- const option = match ? match[1] : "(unknown)";
312
- return `Unknown option '${option}'. Please check your command or use pinggy -h for guidance.`;
313
- }
314
- },
315
- {
316
- match: (err) => _CLIPrinter.isCLIError(err) && err.code === "ERR_PARSE_ARGS_MISSING_OPTION_VALUE",
317
- message: (err) => `Missing required argument for option '${err.option}'.`
318
- },
319
- {
320
- match: (err) => _CLIPrinter.isCLIError(err) && err.code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE",
321
- message: (err) => `Invalid argument'${err.message}'.`
322
- },
323
- {
324
- match: (err) => _CLIPrinter.isCLIError(err) && err.code === "ENOENT",
325
- message: (err) => `File or directory not found: ${err.message}`
326
- },
327
- {
328
- match: () => true,
329
- // fallback
330
- message: (err) => _CLIPrinter.isCLIError(err) ? err.message : String(err)
331
- }
332
- ];
333
- var CLIPrinter = _CLIPrinter;
334
- var printer_default = CLIPrinter;
335
-
336
- // src/utils/util.ts
337
- import { readFileSync } from "fs";
338
- import { randomUUID } from "crypto";
339
105
  import { fileURLToPath } from "url";
340
- import { dirname, join } from "path";
341
- function getRandomId() {
342
- return randomUUID();
343
- }
344
- function isValidPort(p) {
345
- return Number.isInteger(p) && p > 0 && p < 65536;
346
- }
347
- function errorMessage(err) {
348
- return err instanceof Error ? err.message : String(err);
349
- }
350
106
  var __filename2 = fileURLToPath(import.meta.url);
351
- var __dirname2 = dirname(__filename2);
352
- function getVersion() {
353
- try {
354
- const packageJsonPath = join(__dirname2, "../package.json");
355
- const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
356
- return pkg.version ?? "";
357
- } catch (error) {
358
- printer_default.error("Error reading version info");
359
- return "";
360
- }
361
- }
362
- function getLocalAddress(config) {
363
- if (!config) return "-";
364
- if (config.forwarding) {
365
- if (typeof config.forwarding === "string") return config.forwarding;
366
- if (Array.isArray(config.forwarding) && config.forwarding.length > 0) {
367
- const f = config.forwarding[0];
368
- if (f.address) return f.address;
369
- if (f.localDomain && f.localPort) return `${f.localDomain}:${f.localPort}`;
370
- }
371
- }
372
- if (config.localAddress) return config.localAddress;
373
- return "-";
374
- }
375
-
376
- // src/tunnel_manager/TunnelManager.ts
377
- var __filename3 = fileURLToPath2(import.meta.url);
378
- var __dirname3 = path2.dirname(__filename3);
107
+ var __dirname2 = path2.dirname(__filename2);
379
108
  var START_FAILED_MESSAGE = "Failed to start tunnel";
380
109
  function mapToSdkLogLevel(level) {
381
110
  if (level === "debug") return SdkLogLevel.DEBUG;
@@ -1862,9 +1591,9 @@ var TunnelManager = class _TunnelManager {
1862
1591
  }
1863
1592
  startStaticFileServer(managed) {
1864
1593
  try {
1865
- const __filename4 = fileURLToPath2(import.meta.url);
1866
- const __dirname4 = path2.dirname(__filename4);
1867
- const fileServerWorkerPath = path2.join(__dirname4, "workers", "file_serve_worker.cjs");
1594
+ const __filename3 = fileURLToPath(import.meta.url);
1595
+ const __dirname3 = path2.dirname(__filename3);
1596
+ const fileServerWorkerPath = path2.join(__dirname3, "workers", "file_serve_worker.cjs");
1868
1597
  logger.info("Starting static file server worker", {
1869
1598
  dir: managed.serve,
1870
1599
  forwarding: JSON.stringify(managed.tunnelConfig?.forwarding),
@@ -1905,26 +1634,9 @@ var TunnelManager = class _TunnelManager {
1905
1634
  };
1906
1635
 
1907
1636
  export {
1908
- printer_default,
1909
1637
  setTunnelLoggingEnabled,
1910
1638
  isTunnelLoggingEnabled,
1911
1639
  detachAllTunnelLoggers,
1912
- TunnelStateType,
1913
- TunnelErrorCodeType,
1914
- TunnelWarningCode,
1915
- ErrorCode,
1916
- isErrorResponse,
1917
- newErrorResponse,
1918
- NewResponseObject,
1919
- NewErrorResponseObject,
1920
- newStatus,
1921
- newStats,
1922
- RemoteManagementStatus,
1923
- getRandomId,
1924
- isValidPort,
1925
- errorMessage,
1926
- getVersion,
1927
- getLocalAddress,
1928
1640
  TunnelAlreadyRunningError,
1929
1641
  TunnelRebuildInProgressError,
1930
1642
  TunnelManager