@reticlehq/next 2.11.0 → 2.13.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 (2) hide show
  1. package/index.cjs +134 -12
  2. package/package.json +6 -3
package/index.cjs CHANGED
@@ -7,29 +7,145 @@
7
7
  const fs = require('node:fs');
8
8
  const os = require('node:os');
9
9
  const path = require('node:path');
10
+ const crypto = require('node:crypto');
10
11
 
11
12
  // Kept in sync with @reticlehq/core (ReticleDir / ReticleEnv). This package is plain CJS tooling and
12
13
  // deliberately has no ESM/TS dependency on core, so the two constants are mirrored here.
13
14
  const PAIRING_TOKEN_DIR_ENV = 'RETICLE_PAIRING_TOKEN_DIR';
14
15
  const PAIRING_TOKEN_FILE = 'pairing-token';
16
+ const RETICLE_CONFIG_FILE = '.reticle.json';
17
+ const RETICLE_HOME_DIR = '.reticle';
18
+ // Mirrors core's daemonRegistryFileName: ~/.reticle/daemon-<port>.json.
19
+ const DAEMON_ENTRY_PREFIX = 'daemon-';
20
+ const DAEMON_ENTRY_SUFFIX = '.json';
21
+ // Mirrors core's RETICLE_CLIENT_HOST / RETICLE_WS_PATH. This package is plain CJS tooling with no
22
+ // ESM/TS dependency on core, so the values are duplicated here the way the constants above are — and
23
+ // pinned to core's by test, because a URL that drifts produces a silent no-connect rather than an
24
+ // error anybody sees.
25
+ const RETICLE_CLIENT_HOST = 'localhost';
26
+ const RETICLE_WS_PATH = '/reticle';
15
27
 
16
28
  /**
17
- * Read the daemon's auto-provisioned pairing token (~/.reticle/pairing-token, or the
18
- * RETICLE_PAIRING_TOKEN_DIR override). Node-side only. Returns undefined if the daemon hasn't started
19
- * yet (start it before `next dev`); the client then connects without a token and the page reloads once
20
- * the daemon is up and the config is re-read.
29
+ * Read the pairing token, or create it — whichever process gets there first.
30
+ *
31
+ * The token used to be read ONCE, when next.config was evaluated. Start `next dev` before the
32
+ * daemon and that value was empty, every page was refused, and a reload could not help: there was
33
+ * no token page-side to pick up. The comment that claimed "the client then connects without a token
34
+ * and the page reloads once it has" was false for Next.
35
+ *
36
+ * Same mint as the daemon (24 random bytes, 0600 file, never overwrite). An existing token is
37
+ * reused so a plugin-injected page keeps working after the daemon bounces.
38
+ * @param {string} dir
39
+ * @returns {string | undefined}
40
+ */
41
+ function ensurePairingToken(dir) {
42
+ const file = path.join(dir, PAIRING_TOKEN_FILE);
43
+ try {
44
+ const existing = fs.readFileSync(file, 'utf8').trim();
45
+ if (existing.length > 0) return existing;
46
+ } catch {
47
+ /* missing or unreadable — fall through and create one */
48
+ }
49
+ try {
50
+ const token = crypto.randomBytes(24).toString('hex');
51
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
52
+ fs.writeFileSync(file, token, { encoding: 'utf8', mode: 0o600 });
53
+ fs.chmodSync(file, 0o600);
54
+ return token;
55
+ } catch {
56
+ return undefined;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Read or mint the daemon's auto-provisioned pairing token (~/.reticle/pairing-token, or the
62
+ * RETICLE_PAIRING_TOKEN_DIR override). Node-side only. Minting here is what makes `next dev` before
63
+ * the daemon still authenticate.
21
64
  * @returns {string | undefined}
22
65
  */
23
66
  function readPairingToken() {
67
+ return ensurePairingToken(reticleHomeDir());
68
+ }
69
+
70
+ /**
71
+ * Find the live daemon serving THIS project and return its websocket URL.
72
+ *
73
+ * The Vite plugin has always done this (`discoverDaemonPort`), and core's `pickDaemonPort` documents
74
+ * the rule as shared by "both the vite and next plugins" — but this package never implemented the
75
+ * next half. The consequence was a frozen port: `reticle init` baked `url: 'ws://localhost:<port>'`
76
+ * into the generated ReticleDev component at install time, and the app dialled that forever. Move the
77
+ * daemon and a Next app silently dials a port nothing is listening on, with no error anywhere except
78
+ * a console warning in a browser nobody is watching.
79
+ *
80
+ * The rule is core's, mirrored rather than imported for the same reason the constants above are: this
81
+ * package is plain CJS tooling with no ESM/TS dependency on core. Kept deliberately identical:
82
+ * 1. drop dead daemons (crashed, or a stale entry left by a kill -9);
83
+ * 2. among the living, prefer a projectId match, lowest port on a tie;
84
+ * 3. return undefined when nothing matches, so the app falls back to the default port rather than
85
+ * auto-connecting to a daemon serving a DIFFERENT project — a wrong connect is worse than an
86
+ * honest default, because it reports another app's state as this one's.
87
+ *
88
+ * The projectId is READ from `.reticle.json` rather than re-derived. Re-deriving would duplicate
89
+ * core's slug + hash rule in a third place, and a drift there does not fail loudly: it silently
90
+ * matches no daemon, which is the exact bug this function exists to remove.
91
+ * @returns {string | undefined}
92
+ */
93
+ /**
94
+ * Where Reticle keeps its per-user state: the pairing token AND the daemon registry.
95
+ *
96
+ * Honours the same RETICLE_PAIRING_TOKEN_DIR override the token reader uses, because it is the same
97
+ * directory. One override rather than two keeps a test (or a sandbox) from pointing the two halves at
98
+ * different places and getting a token from one daemon with the port of another.
99
+ */
100
+ function reticleHomeDir() {
24
101
  const override = process.env[PAIRING_TOKEN_DIR_ENV];
25
- const dir =
26
- override !== undefined && override.length > 0 ? override : path.join(os.homedir(), '.reticle');
102
+ return override !== undefined && override.length > 0
103
+ ? override
104
+ : path.join(os.homedir(), RETICLE_HOME_DIR);
105
+ }
106
+
107
+ /** process.kill(pid, 0) throws iff the process is gone: the same liveness probe the daemon uses. */
108
+ function defaultIsAlive(pid) {
27
109
  try {
28
- const token = fs.readFileSync(path.join(dir, PAIRING_TOKEN_FILE), 'utf8').trim();
29
- return token.length > 0 ? token : undefined;
110
+ process.kill(pid, 0);
111
+ return true;
30
112
  } catch {
31
- return undefined;
113
+ return false;
114
+ }
115
+ }
116
+
117
+ function discoverDaemonUrl(cwd = process.cwd(), home = reticleHomeDir(), alive = defaultIsAlive) {
118
+ let projectId;
119
+ try {
120
+ const parsed = JSON.parse(fs.readFileSync(path.join(cwd, RETICLE_CONFIG_FILE), 'utf8'));
121
+ projectId = typeof parsed?.projectId === 'string' ? parsed.projectId : undefined;
122
+ } catch {
123
+ return undefined; // no .reticle.json: this project has not been through `reticle init`
124
+ }
125
+ if (projectId === undefined || projectId.length === 0) return undefined;
126
+ const dir = home;
127
+ let files;
128
+ try {
129
+ files = fs.readdirSync(dir);
130
+ } catch {
131
+ return undefined; // no ~/.reticle yet: no daemon has ever run here
132
+ }
133
+ const ports = [];
134
+ for (const file of files) {
135
+ if (!file.startsWith(DAEMON_ENTRY_PREFIX) || !file.endsWith(DAEMON_ENTRY_SUFFIX)) continue;
136
+ let entry;
137
+ try {
138
+ entry = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));
139
+ } catch {
140
+ continue; // a half-written or corrupt entry is not a daemon
141
+ }
142
+ if (entry?.projectId !== projectId) continue;
143
+ if (typeof entry.port !== 'number' || typeof entry.pid !== 'number') continue;
144
+ if (!alive(entry.pid)) continue;
145
+ ports.push(entry.port);
32
146
  }
147
+ if (ports.length === 0) return undefined;
148
+ return `ws://${RETICLE_CLIENT_HOST}:${String(Math.min(...ports))}${RETICLE_WS_PATH}`;
33
149
  }
34
150
 
35
151
  /**
@@ -152,12 +268,14 @@ function withReticle(nextConfig = {}) {
152
268
 
153
269
  const userWebpack = nextConfig.webpack;
154
270
  const token = readPairingToken();
271
+ const daemonUrl = discoverDaemonUrl();
155
272
  return {
156
273
  ...nextConfig,
157
274
  ...(supportsTurbopackKey() ? { turbopack: turbopackConfig(nextConfig.turbopack) } : {}),
158
275
  // Expose the token to the client bundle as process.env.NEXT_PUBLIC_RETICLE_TOKEN (Next's convention
159
- // for client-readable env), so a dev-only client connect can present it. Omitted when the daemon
160
- // hasn't provisioned one yet — the client then connects without it and the page reloads once it has.
276
+ // for client-readable env), so a dev-only client connect can present it. Minted here if the file
277
+ // is missing: Next evaluates this once, so an empty value is frozen and a reload cannot pick a
278
+ // later token up. Omitted only when the directory is unwritable.
161
279
  env: {
162
280
  ...nextConfig.env,
163
281
  ...(token !== undefined ? { NEXT_PUBLIC_RETICLE_TOKEN: token } : {}),
@@ -166,6 +284,10 @@ function withReticle(nextConfig = {}) {
166
284
  // Next 16 default — never runs the webpack branch, and a source pointer that only works on one
167
285
  // of the two bundlers is worse than one that works on neither.
168
286
  NEXT_PUBLIC_RETICLE_ROOT: process.cwd(),
287
+ // The daemon serving THIS project, discovered on every dev-server start rather than baked in
288
+ // at install time. Without it the generated connect keeps whatever port `init` happened to see,
289
+ // and a daemon that later moves is unreachable with no error the user ever sees.
290
+ ...(daemonUrl !== undefined ? { NEXT_PUBLIC_RETICLE_URL: daemonUrl } : {}),
169
291
  // So a version-skewed pair can name itself instead of surfacing as a bare -32000.
170
292
  NEXT_PUBLIC_RETICLE_SDK_VERSION: sdkPackageVersion(),
171
293
  },
@@ -183,4 +305,4 @@ function withReticle(nextConfig = {}) {
183
305
  };
184
306
  }
185
307
 
186
- module.exports = { withReticle, readPairingToken };
308
+ module.exports = { withReticle, readPairingToken, discoverDaemonUrl };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/next",
3
- "version": "2.11.0",
3
+ "version": "2.13.0",
4
4
  "description": "Next.js helper for Reticle: keeps SWC, adds source-file mapping via a dev-only webpack pre-loader (data-reticle-source).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Reticle contributors",
@@ -38,7 +38,7 @@
38
38
  ],
39
39
  "dependencies": {
40
40
  "@babel/core": "^7.26.0",
41
- "@reticlehq/babel-plugin": "2.11.0"
41
+ "@reticlehq/babel-plugin": "2.13.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "next": ">=13"
@@ -50,5 +50,8 @@
50
50
  "engines": {
51
51
  "node": ">=20.0.0"
52
52
  },
53
- "bugs": "https://github.com/reticlehq/reticle/issues"
53
+ "bugs": "https://github.com/reticlehq/reticle/issues",
54
+ "scripts": {
55
+ "test:unit": "vitest run loader.test.mjs index.test.mjs"
56
+ }
54
57
  }