@reticlehq/next 3.2.0 → 3.4.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.
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
@@ -12,6 +12,15 @@ const crypto = require('node:crypto');
12
12
  // Kept in sync with @reticlehq/core (ReticleDir / ReticleEnv). This package is plain CJS tooling and
13
13
  // deliberately has no ESM/TS dependency on core, so the two constants are mirrored here.
14
14
  const PAIRING_TOKEN_DIR_ENV = 'RETICLE_PAIRING_TOKEN_DIR';
15
+ /**
16
+ * Instrument anyway, whatever NODE_ENV says — for `NODE_ENV=production next dev`.
17
+ *
18
+ * Named here rather than imported: this package is plain CJS tooling that deliberately depends on
19
+ * nothing, which is why `RETICLE_PAIRING_TOKEN_DIR` above is a local constant too.
20
+ */
21
+ const DEV_OVERRIDE_ENV = 'RETICLE_DEV';
22
+ /** Next's own marker on the server process `next dev` forks. See the production gate below. */
23
+ const NEXT_DEV_WORKER_ENV = 'NEXT_PRIVATE_WORKER';
15
24
  const PAIRING_TOKEN_FILE = 'pairing-token';
16
25
  const RETICLE_CONFIG_FILE = '.reticle.json';
17
26
  const RETICLE_HOME_DIR = '.reticle';
@@ -78,9 +87,12 @@ function readPairingToken() {
78
87
  *
79
88
  * The rule is core's, mirrored rather than imported for the same reason the constants above are: this
80
89
  * package is plain CJS tooling with no ESM/TS dependency on core. Kept deliberately identical:
81
- * 1. drop dead daemons (crashed, or a stale entry left by a kill -9);
82
- * 2. among the living, prefer a projectId match, lowest port on a tie;
83
- * 3. return undefined when nothing matches, so the app falls back to the default port rather than
90
+ * 1. the port in `.reticle.json` wins whenever a live daemon not serving ANOTHER project is
91
+ * registered on it — `init --port`
92
+ * used to leave the old daemon alive, and discovery took the lower port and dialled it;
93
+ * 2. drop dead daemons (crashed, or a stale entry left by a kill -9);
94
+ * 3. among the living, prefer a projectId match, lowest port on a tie;
95
+ * 4. return undefined when nothing matches, so the app falls back to the default port rather than
84
96
  * auto-connecting to a daemon serving a DIFFERENT project — a wrong connect is worse than an
85
97
  * honest default, because it reports another app's state as this one's.
86
98
  *
@@ -113,16 +125,44 @@ function defaultIsAlive(pid) {
113
125
  }
114
126
  }
115
127
 
128
+ const MAX_TCP_PORT = 65535;
129
+
130
+ /** @param {number} port */
131
+ const bridgeUrl = (port) => `ws://${RETICLE_CLIENT_HOST}:${String(port)}${RETICLE_WS_PATH}`;
132
+
133
+ /**
134
+ * The same order the Vite plugin's `chooseDaemonPort` states: a live daemon registered for this
135
+ * project, then the `port` in `.reticle.json`, and only then the `url` literal `reticle init` wrote
136
+ * into the generated ReticleDev component (which this value overrides page-side). The file comes
137
+ * before the literal because it is what the daemon and the CLI read: a user who edited it moved the
138
+ * daemon, and the page kept dialling the old literal with nothing saying why.
139
+ */
116
140
  function discoverDaemonUrl(cwd = process.cwd(), home = reticleHomeDir(), alive = defaultIsAlive) {
117
141
  let projectId;
142
+ let configuredPort;
118
143
  try {
119
144
  const parsed = JSON.parse(fs.readFileSync(path.join(cwd, RETICLE_CONFIG_FILE), 'utf8'));
120
145
  projectId = typeof parsed?.projectId === 'string' ? parsed.projectId : undefined;
146
+ const port = parsed?.port;
147
+ configuredPort = Number.isInteger(port) && port > 0 && port <= MAX_TCP_PORT ? port : undefined;
121
148
  } catch {
122
149
  return undefined; // no .reticle.json: this project has not been through `reticle init`
123
150
  }
124
- if (projectId === undefined || projectId.length === 0) return undefined;
125
- const dir = home;
151
+ const discovered = discoverRegisteredPort(projectId, home, alive, configuredPort);
152
+ const port = discovered ?? configuredPort;
153
+ return port === undefined ? undefined : bridgeUrl(port);
154
+ }
155
+
156
+ /**
157
+ * The live daemon registered in `home` for `projectId`, lowest port on a tie — or the configured port,
158
+ * when a live daemon registered there is not another project's (core's `pickDaemonPort`, rule 1).
159
+ * @param {string | undefined} projectId
160
+ * @param {string} dir
161
+ * @param {(pid: number) => boolean} alive
162
+ * @param {number | undefined} configuredPort
163
+ * @returns {number | undefined}
164
+ */
165
+ function discoverRegisteredPort(projectId, dir, alive, configuredPort) {
126
166
  let files;
127
167
  try {
128
168
  files = fs.readdirSync(dir);
@@ -138,13 +178,15 @@ function discoverDaemonUrl(cwd = process.cwd(), home = reticleHomeDir(), alive =
138
178
  } catch {
139
179
  continue; // a half-written or corrupt entry is not a daemon
140
180
  }
141
- if (entry?.projectId !== projectId) continue;
142
- if (typeof entry.port !== 'number' || typeof entry.pid !== 'number') continue;
181
+ if (typeof entry?.port !== 'number' || typeof entry.pid !== 'number') continue;
143
182
  if (!alive(entry.pid)) continue;
183
+ const mine = entry.projectId === projectId;
184
+ const unnamed = entry.projectId === undefined || projectId === undefined;
185
+ if (entry.port === configuredPort && (mine || unnamed)) return configuredPort;
186
+ if (projectId === undefined || projectId.length === 0 || !mine) continue;
144
187
  ports.push(entry.port);
145
188
  }
146
- if (ports.length === 0) return undefined;
147
- return `ws://${RETICLE_CLIENT_HOST}:${String(Math.min(...ports))}${RETICLE_WS_PATH}`;
189
+ return ports.length === 0 ? undefined : Math.min(...ports);
148
190
  }
149
191
 
150
192
  /**
@@ -200,10 +242,78 @@ function turbopackConfig(existing) {
200
242
  // type here makes Turbopack rewrite the module id (./x.tsx → ./x.tsx.tsx) and every import breaks.
201
243
  '*.tsx': rule,
202
244
  '*.jsx': rule,
245
+ // A JavaScript Next project's pages are .js (#1081). `.js` also names every file in
246
+ // node_modules, so the rule is limited to the project's own code; `condition` is Next 16+,
247
+ // and an older Turbopack that does not know the key is left without the rule rather than
248
+ // handed one it would reject.
249
+ ...(supportsRuleConditions() ? { '*.js': { ...rule, condition: { not: 'foreign' } } } : {}),
203
250
  },
204
251
  };
205
252
  }
206
253
 
254
+ /**
255
+ * The loopback hosts a Reticle-opened tab may arrive on, in the form Next compares: the Origin's
256
+ * `hostname`, which keeps the brackets on IPv6. `localhost` is not listed because Next always
257
+ * allows it.
258
+ */
259
+ const LOOPBACK_DEV_ORIGINS = ['127.0.0.1', '[::1]'];
260
+
261
+ /**
262
+ * Whether this Next release accepts `allowedDevOrigins`. It arrived in 15.2.2 and was backported to
263
+ * 14.2.30; on anything older it is an unknown key, which Next reports as "Invalid next.config.js
264
+ * options detected" on every boot. An unreadable version is assumed modern, as elsewhere here.
265
+ * @param {string | undefined} version
266
+ * @returns {boolean}
267
+ */
268
+ function knowsAllowedDevOrigins(version) {
269
+ const [major, minor, patch] = String(version)
270
+ .split('.')
271
+ .map((n) => parseInt(n, 10));
272
+ if (!Number.isFinite(major)) return true;
273
+ const at = (m, p) => minor > m || (minor === m && patch >= p);
274
+ if (major > 15) return true;
275
+ if (major === 15) return at(2, 2);
276
+ if (major === 14) return at(2, 30);
277
+ return false;
278
+ }
279
+
280
+ /** The installed Next's version, read from the APP (see resolveFromApp), or undefined. */
281
+ function installedNextVersion() {
282
+ try {
283
+ return String(require(resolveFromApp('next/package.json')).version);
284
+ } catch {
285
+ return undefined;
286
+ }
287
+ }
288
+
289
+ /**
290
+ * The app's `allowedDevOrigins` plus the loopback hosts, or undefined when this Next does not know
291
+ * the key.
292
+ *
293
+ * Next 16 BLOCKS its dev resources (`/_next/*`, HMR) for an origin outside this list, and only
294
+ * `localhost` is allowed by default. A tab opened on 127.0.0.1 or [::1] — which is where a first
295
+ * run lands when `localhost` answers slowly on a cold compile — got the HTML and nothing else: no
296
+ * hydration, so the connect effect never ran and the SDK "never dialled the bridge".
297
+ * @param {string[] | undefined} existing
298
+ * @returns {string[] | undefined}
299
+ */
300
+ function devOrigins(existing) {
301
+ if (!knowsAllowedDevOrigins(installedNextVersion())) return undefined;
302
+ const mine = Array.isArray(existing) ? existing : [];
303
+ return [...mine, ...LOOPBACK_DEV_ORIGINS.filter((host) => !mine.includes(host))];
304
+ }
305
+
306
+ /** Whether this Next's Turbopack accepts a rule `condition` (added with Next 16). */
307
+ function supportsRuleConditions() {
308
+ try {
309
+ const { version } = require(resolveFromApp('next/package.json'));
310
+ const major = parseInt(String(version).split('.')[0] ?? '', 10);
311
+ return !Number.isFinite(major) || major >= 16;
312
+ } catch {
313
+ return true;
314
+ }
315
+ }
316
+
207
317
  /**
208
318
  * The React kit the host app imports the SDK from. Deliberately NOT a dependency of this package —
209
319
  * it is the user's own install, probed for its version and nothing else. Declaring it here would
@@ -275,14 +385,44 @@ function sdkPackageVersion() {
275
385
  * @returns {import('next').NextConfig}
276
386
  */
277
387
  function withReticle(nextConfig = {}, options = {}) {
278
- // Production builds are untouched — this is a dev-time aid only.
279
- if (process.env.NODE_ENV === 'production') return nextConfig;
388
+ /*
389
+ * Production builds are untouched — this is a dev-time aid only.
390
+ *
391
+ * NODE_ENV is the gate because it is the only signal available where this runs. `withReticle`
392
+ * receives no `phase`, and Next evaluates the config inside `start-server.js`, a child process
393
+ * whose argv carries no `dev` — MEASURED, after a first attempt read argv and was wrong on a real
394
+ * `next dev`. The webpack hook below does get Next's own `dev` flag, but the pairing token is
395
+ * injected at CONFIG level, and baking one into a production bundle is the thing this gate exists
396
+ * to prevent.
397
+ *
398
+ * What was actually broken is that it happened in SILENCE. `NODE_ENV=production next dev` is a
399
+ * real configuration — people use it to reproduce production behaviour locally — and the result
400
+ * was an app that looked instrumented, started cleanly and never connected, with no reason to
401
+ * suspect an env var set for something else. So it says why, once, and names both the variable
402
+ * responsible and the way out (#1069).
403
+ */
404
+ if (process.env.NODE_ENV === 'production' && process.env[DEV_OVERRIDE_ENV] !== '1') {
405
+ // Only on a dev server, where being off is the surprise. `next build` and `next typegen`
406
+ // evaluate this config under NODE_ENV=production too, and there off is simply correct: the
407
+ // line read as a fault in every build log. NEXT_PRIVATE_WORKER is set by `next dev` on the
408
+ // server process it forks (Next 13 through 16) and by no other command.
409
+ if (process.env[NEXT_DEV_WORKER_ENV] === '1') {
410
+ console.log(
411
+ `[reticle] instrumentation is OFF because NODE_ENV=production. ` +
412
+ `If this is a dev server you want instrumented, set ${DEV_OVERRIDE_ENV}=1 (or do not export ` +
413
+ `NODE_ENV=production for it) — nothing else about your config needs to change.`,
414
+ );
415
+ }
416
+ return nextConfig;
417
+ }
280
418
 
281
419
  const userWebpack = nextConfig.webpack;
282
420
  const token = readPairingToken();
283
421
  const daemonUrl = discoverDaemonUrl();
422
+ const allowedDevOrigins = devOrigins(nextConfig.allowedDevOrigins);
284
423
  return {
285
424
  ...nextConfig,
425
+ ...(allowedDevOrigins !== undefined ? { allowedDevOrigins } : {}),
286
426
  ...(supportsTurbopackKey() ? { turbopack: turbopackConfig(nextConfig.turbopack) } : {}),
287
427
  // Expose the token to the client bundle as process.env.NEXT_PUBLIC_RETICLE_TOKEN (Next's convention
288
428
  // for client-readable env), so a dev-only client connect can present it. Minted here if the file
@@ -308,7 +448,8 @@ function withReticle(nextConfig = {}, options = {}) {
308
448
  config.module = config.module || { rules: [] };
309
449
  config.module.rules = config.module.rules || [];
310
450
  config.module.rules.push({
311
- test: /\.(t|j)sx$/,
451
+ // .js as well: see the Turbopack rule above (#1081).
452
+ test: /\.(tsx|jsx|js)$/,
312
453
  exclude: /node_modules/,
313
454
  enforce: 'pre',
314
455
  use: [{ loader: require.resolve('./loader.cjs') }],
@@ -319,4 +460,4 @@ function withReticle(nextConfig = {}, options = {}) {
319
460
  };
320
461
  }
321
462
 
322
- module.exports = { withReticle, readPairingToken, discoverDaemonUrl };
463
+ module.exports = { withReticle, readPairingToken, discoverDaemonUrl, knowsAllowedDevOrigins };
package/loader.cjs CHANGED
@@ -10,7 +10,15 @@ module.exports = function reticleNextLoader(source, inputMap) {
10
10
  const callback = this.async();
11
11
  const filename = this.resourcePath;
12
12
 
13
- if (!/\.(t|j)sx$/.test(filename) || filename.includes('node_modules')) {
13
+ // `.js` too: create-next-app's JavaScript template writes every page as .js, and matching only
14
+ // .tsx/.jsx left those projects with no stamp anywhere (#1081). A .js file with no JSX in it is
15
+ // handed back untouched without being parsed, which is every config and route handler.
16
+ const isJs = /\.js$/.test(filename);
17
+ if (
18
+ !(/\.(t|j)sx$/.test(filename) || isJs) ||
19
+ filename.includes('node_modules') ||
20
+ (isJs && !/<[A-Za-z]/.test(source))
21
+ ) {
14
22
  callback(null, source, inputMap);
15
23
  return;
16
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/next",
3
- "version": "3.2.0",
3
+ "version": "3.4.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.2.0"
41
+ "@reticlehq/babel-plugin": "3.4.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "next": ">=13"