@reticlehq/next 3.3.0 → 3.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 (3) hide show
  1. package/README.md +1 -1
  2. package/index.cjs +127 -26
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Next.js helper for [Reticle](https://github.com/reticlehq/reticle). Gives you **source-file mapping on Next.js without disabling SWC**.
4
4
 
5
- React 19 removed `_debugSource`, and Next compiles with SWC (not Babel), so the `@reticlehq/babel-plugin` route doesn't apply. `@reticlehq/next` adds a **dev-only webpack pre-loader** that stamps `data-reticle-source="file:line:col"` on your JSX _before_ SWC compiles it — so `reticle_inspect` returns the component's source file, and SWC stays on (next/font, fast refresh, etc. all keep working).
5
+ React 19 removed `_debugSource`, and Next compiles with SWC (not Babel), so the `@reticlehq/babel-plugin` route doesn't apply. `@reticlehq/next` adds a **dev-only webpack pre-loader** that stamps `data-reticle-source="file:line:col"` on your JSX _before_ SWC compiles it — so `reticle_look { action: "element" }` returns the component's source file, and SWC stays on (next/font, fast refresh, etc. all keep working).
6
6
 
7
7
  ```bash
8
8
  npm i -D @reticlehq/next
package/index.cjs CHANGED
@@ -10,8 +10,10 @@ const path = require('node:path');
10
10
  const crypto = require('node:crypto');
11
11
 
12
12
  // Kept in sync with @reticlehq/core (ReticleDir / ReticleEnv). This package is plain CJS tooling and
13
- // deliberately has no ESM/TS dependency on core, so the two constants are mirrored here.
13
+ // deliberately has no ESM/TS dependency on core, so these values are mirrored here.
14
14
  const PAIRING_TOKEN_DIR_ENV = 'RETICLE_PAIRING_TOKEN_DIR';
15
+ const STATE_DIR_ENV = 'RETICLE_STATE_DIR';
16
+ const PORT_ENV = 'RETICLE_PORT';
15
17
  /**
16
18
  * Instrument anyway, whatever NODE_ENV says — for `NODE_ENV=production next dev`.
17
19
  *
@@ -19,6 +21,8 @@ const PAIRING_TOKEN_DIR_ENV = 'RETICLE_PAIRING_TOKEN_DIR';
19
21
  * nothing, which is why `RETICLE_PAIRING_TOKEN_DIR` above is a local constant too.
20
22
  */
21
23
  const DEV_OVERRIDE_ENV = 'RETICLE_DEV';
24
+ /** Next's own marker on the server process `next dev` forks. See the production gate below. */
25
+ const NEXT_DEV_WORKER_ENV = 'NEXT_PRIVATE_WORKER';
22
26
  const PAIRING_TOKEN_FILE = 'pairing-token';
23
27
  const RETICLE_CONFIG_FILE = '.reticle.json';
24
28
  const RETICLE_HOME_DIR = '.reticle';
@@ -85,9 +89,12 @@ function readPairingToken() {
85
89
  *
86
90
  * The rule is core's, mirrored rather than imported for the same reason the constants above are: this
87
91
  * package is plain CJS tooling with no ESM/TS dependency on core. Kept deliberately identical:
88
- * 1. drop dead daemons (crashed, or a stale entry left by a kill -9);
89
- * 2. among the living, prefer a projectId match, lowest port on a tie;
90
- * 3. return undefined when nothing matches, so the app falls back to the default port rather than
92
+ * 1. the port in `.reticle.json` wins whenever a live daemon not serving ANOTHER project is
93
+ * registered on it — `init --port`
94
+ * used to leave the old daemon alive, and discovery took the lower port and dialled it;
95
+ * 2. drop dead daemons (crashed, or a stale entry left by a kill -9);
96
+ * 3. among the living, prefer a projectId match, lowest port on a tie;
97
+ * 4. return undefined when nothing matches, so the app falls back to the default port rather than
91
98
  * auto-connecting to a daemon serving a DIFFERENT project — a wrong connect is worse than an
92
99
  * honest default, because it reports another app's state as this one's.
93
100
  *
@@ -96,15 +103,9 @@ function readPairingToken() {
96
103
  * matches no daemon, which is the exact bug this function exists to remove.
97
104
  * @returns {string | undefined}
98
105
  */
99
- /**
100
- * Where Reticle keeps its per-user state: the pairing token AND the daemon registry.
101
- *
102
- * Honours the same RETICLE_PAIRING_TOKEN_DIR override the token reader uses, because it is the same
103
- * directory. One override rather than two keeps a test (or a sandbox) from pointing the two halves at
104
- * different places and getting a token from one daemon with the port of another.
105
- */
106
- function reticleHomeDir() {
107
- const override = process.env[PAIRING_TOKEN_DIR_ENV];
106
+ /** Pairing token and registry locations have separate overrides, matching the daemon. */
107
+ function reticleHomeDir(envKey = PAIRING_TOKEN_DIR_ENV) {
108
+ const override = process.env[envKey];
108
109
  return override !== undefined && override.length > 0
109
110
  ? override
110
111
  : path.join(os.homedir(), RETICLE_HOME_DIR);
@@ -120,16 +121,54 @@ function defaultIsAlive(pid) {
120
121
  }
121
122
  }
122
123
 
123
- function discoverDaemonUrl(cwd = process.cwd(), home = reticleHomeDir(), alive = defaultIsAlive) {
124
+ const MAX_TCP_PORT = 65535;
125
+
126
+ /** @param {number} port */
127
+ const bridgeUrl = (port) => `ws://${RETICLE_CLIENT_HOST}:${String(port)}${RETICLE_WS_PATH}`;
128
+
129
+ /**
130
+ * RETICLE_PORT overrides discovery. Otherwise, follow the Vite plugin's order: a live daemon for this
131
+ * project, then the `port` in `.reticle.json`, and only then the `url` literal `reticle init` wrote
132
+ * into the generated ReticleDev component (which this value overrides page-side). The file comes
133
+ * before the literal because it is what the daemon and the CLI read: a user who edited it moved the
134
+ * daemon, and the page kept dialling the old literal with nothing saying why.
135
+ */
136
+ function discoverDaemonUrl(
137
+ cwd = process.cwd(),
138
+ home = reticleHomeDir(STATE_DIR_ENV),
139
+ alive = defaultIsAlive,
140
+ env = process.env,
141
+ ) {
142
+ const requested = env[PORT_ENV];
143
+ if (requested !== undefined && /^\d+$/.test(requested)) {
144
+ const port = Number(requested);
145
+ if (Number.isInteger(port) && port > 0 && port <= MAX_TCP_PORT) return bridgeUrl(port);
146
+ }
124
147
  let projectId;
148
+ let configuredPort;
125
149
  try {
126
150
  const parsed = JSON.parse(fs.readFileSync(path.join(cwd, RETICLE_CONFIG_FILE), 'utf8'));
127
151
  projectId = typeof parsed?.projectId === 'string' ? parsed.projectId : undefined;
152
+ const port = parsed?.port;
153
+ configuredPort = Number.isInteger(port) && port > 0 && port <= MAX_TCP_PORT ? port : undefined;
128
154
  } catch {
129
155
  return undefined; // no .reticle.json: this project has not been through `reticle init`
130
156
  }
131
- if (projectId === undefined || projectId.length === 0) return undefined;
132
- const dir = home;
157
+ const discovered = discoverRegisteredPort(projectId, home, alive, configuredPort);
158
+ const port = discovered ?? configuredPort;
159
+ return port === undefined ? undefined : bridgeUrl(port);
160
+ }
161
+
162
+ /**
163
+ * The live daemon registered in `home` for `projectId`, lowest port on a tie — or the configured port,
164
+ * when a live daemon registered there is not another project's (core's `pickDaemonPort`, rule 1).
165
+ * @param {string | undefined} projectId
166
+ * @param {string} dir
167
+ * @param {(pid: number) => boolean} alive
168
+ * @param {number | undefined} configuredPort
169
+ * @returns {number | undefined}
170
+ */
171
+ function discoverRegisteredPort(projectId, dir, alive, configuredPort) {
133
172
  let files;
134
173
  try {
135
174
  files = fs.readdirSync(dir);
@@ -145,13 +184,15 @@ function discoverDaemonUrl(cwd = process.cwd(), home = reticleHomeDir(), alive =
145
184
  } catch {
146
185
  continue; // a half-written or corrupt entry is not a daemon
147
186
  }
148
- if (entry?.projectId !== projectId) continue;
149
- if (typeof entry.port !== 'number' || typeof entry.pid !== 'number') continue;
187
+ if (typeof entry?.port !== 'number' || typeof entry.pid !== 'number') continue;
150
188
  if (!alive(entry.pid)) continue;
189
+ const mine = entry.projectId === projectId;
190
+ const unnamed = entry.projectId === undefined || projectId === undefined;
191
+ if (entry.port === configuredPort && (mine || unnamed)) return configuredPort;
192
+ if (projectId === undefined || projectId.length === 0 || !mine) continue;
151
193
  ports.push(entry.port);
152
194
  }
153
- if (ports.length === 0) return undefined;
154
- return `ws://${RETICLE_CLIENT_HOST}:${String(Math.min(...ports))}${RETICLE_WS_PATH}`;
195
+ return ports.length === 0 ? undefined : Math.min(...ports);
155
196
  }
156
197
 
157
198
  /**
@@ -216,6 +257,58 @@ function turbopackConfig(existing) {
216
257
  };
217
258
  }
218
259
 
260
+ /**
261
+ * The loopback hosts a Reticle-opened tab may arrive on, in the form Next compares: the Origin's
262
+ * `hostname`, which keeps the brackets on IPv6. `localhost` is not listed because Next always
263
+ * allows it.
264
+ */
265
+ const LOOPBACK_DEV_ORIGINS = ['127.0.0.1', '[::1]'];
266
+
267
+ /**
268
+ * Whether this Next release accepts `allowedDevOrigins`. It arrived in 15.2.2 and was backported to
269
+ * 14.2.30; on anything older it is an unknown key, which Next reports as "Invalid next.config.js
270
+ * options detected" on every boot. An unreadable version is assumed modern, as elsewhere here.
271
+ * @param {string | undefined} version
272
+ * @returns {boolean}
273
+ */
274
+ function knowsAllowedDevOrigins(version) {
275
+ const [major, minor, patch] = String(version)
276
+ .split('.')
277
+ .map((n) => parseInt(n, 10));
278
+ if (!Number.isFinite(major)) return true;
279
+ const at = (m, p) => minor > m || (minor === m && patch >= p);
280
+ if (major > 15) return true;
281
+ if (major === 15) return at(2, 2);
282
+ if (major === 14) return at(2, 30);
283
+ return false;
284
+ }
285
+
286
+ /** The installed Next's version, read from the APP (see resolveFromApp), or undefined. */
287
+ function installedNextVersion() {
288
+ try {
289
+ return String(require(resolveFromApp('next/package.json')).version);
290
+ } catch {
291
+ return undefined;
292
+ }
293
+ }
294
+
295
+ /**
296
+ * The app's `allowedDevOrigins` plus the loopback hosts, or undefined when this Next does not know
297
+ * the key.
298
+ *
299
+ * Next 16 BLOCKS its dev resources (`/_next/*`, HMR) for an origin outside this list, and only
300
+ * `localhost` is allowed by default. A tab opened on 127.0.0.1 or [::1] — which is where a first
301
+ * run lands when `localhost` answers slowly on a cold compile — got the HTML and nothing else: no
302
+ * hydration, so the connect effect never ran and the SDK "never dialled the bridge".
303
+ * @param {string[] | undefined} existing
304
+ * @returns {string[] | undefined}
305
+ */
306
+ function devOrigins(existing) {
307
+ if (!knowsAllowedDevOrigins(installedNextVersion())) return undefined;
308
+ const mine = Array.isArray(existing) ? existing : [];
309
+ return [...mine, ...LOOPBACK_DEV_ORIGINS.filter((host) => !mine.includes(host))];
310
+ }
311
+
219
312
  /** Whether this Next's Turbopack accepts a rule `condition` (added with Next 16). */
220
313
  function supportsRuleConditions() {
221
314
  try {
@@ -315,19 +408,27 @@ function withReticle(nextConfig = {}, options = {}) {
315
408
  * responsible and the way out (#1069).
316
409
  */
317
410
  if (process.env.NODE_ENV === 'production' && process.env[DEV_OVERRIDE_ENV] !== '1') {
318
- console.log(
319
- `[reticle] instrumentation is OFF because NODE_ENV=production. That is correct for a build. ` +
320
- `If this is a dev server you want instrumented, set ${DEV_OVERRIDE_ENV}=1 (or do not export ` +
321
- `NODE_ENV=production for it) — nothing else about your config needs to change.`,
322
- );
411
+ // Only on a dev server, where being off is the surprise. `next build` and `next typegen`
412
+ // evaluate this config under NODE_ENV=production too, and there off is simply correct: the
413
+ // line read as a fault in every build log. NEXT_PRIVATE_WORKER is set by `next dev` on the
414
+ // server process it forks (Next 13 through 16) and by no other command.
415
+ if (process.env[NEXT_DEV_WORKER_ENV] === '1') {
416
+ console.log(
417
+ `[reticle] instrumentation is OFF because NODE_ENV=production. ` +
418
+ `If this is a dev server you want instrumented, set ${DEV_OVERRIDE_ENV}=1 (or do not export ` +
419
+ `NODE_ENV=production for it) — nothing else about your config needs to change.`,
420
+ );
421
+ }
323
422
  return nextConfig;
324
423
  }
325
424
 
326
425
  const userWebpack = nextConfig.webpack;
327
426
  const token = readPairingToken();
328
427
  const daemonUrl = discoverDaemonUrl();
428
+ const allowedDevOrigins = devOrigins(nextConfig.allowedDevOrigins);
329
429
  return {
330
430
  ...nextConfig,
431
+ ...(allowedDevOrigins !== undefined ? { allowedDevOrigins } : {}),
331
432
  ...(supportsTurbopackKey() ? { turbopack: turbopackConfig(nextConfig.turbopack) } : {}),
332
433
  // Expose the token to the client bundle as process.env.NEXT_PUBLIC_RETICLE_TOKEN (Next's convention
333
434
  // for client-readable env), so a dev-only client connect can present it. Minted here if the file
@@ -365,4 +466,4 @@ function withReticle(nextConfig = {}, options = {}) {
365
466
  };
366
467
  }
367
468
 
368
- module.exports = { withReticle, readPairingToken, discoverDaemonUrl };
469
+ module.exports = { withReticle, readPairingToken, discoverDaemonUrl, knowsAllowedDevOrigins };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/next",
3
- "version": "3.3.0",
3
+ "version": "3.5.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": "3.3.0"
41
+ "@reticlehq/babel-plugin": "3.5.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "next": ">=13"