@revenexx/integrations-node-devkit 0.3.0 → 0.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.
package/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ CliError,
3
4
  DEVKIT_VERSION,
4
5
  DevStore,
5
6
  applySeeds,
@@ -10,31 +11,226 @@ import {
10
11
  loadSeedsFromDir,
11
12
  loadState,
12
13
  saveState
13
- } from "./chunk-PS3HCKE7.js";
14
+ } from "./chunk-YXIYTBOZ.js";
14
15
 
15
16
  // src/cli.ts
16
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, watch } from "fs";
17
- import { createServer } from "http";
17
+ import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync3, watch } from "fs";
18
+ import { createServer as createServer2 } from "http";
18
19
  import { createRequire } from "module";
19
- import { extname, join as join2, resolve as resolve2 } from "path";
20
+ import { basename as basename2, extname, join as join3, resolve as resolve3 } from "path";
20
21
  import { fileURLToPath as fileURLToPath2 } from "url";
21
22
 
23
+ // src/cli-args.ts
24
+ import { existsSync } from "fs";
25
+ import { resolve } from "path";
26
+
27
+ // src/ports.ts
28
+ import { createServer } from "net";
29
+ var DEFAULT_LIMIT = 20;
30
+ async function listenWithFallback(server, options) {
31
+ const limit = options.strict ? 1 : options.limit ?? DEFAULT_LIMIT;
32
+ const first = options.port;
33
+ for (let port = first; port < first + limit; port += 1) {
34
+ const bound = await bind(server, port);
35
+ if (bound !== null) {
36
+ return bound;
37
+ }
38
+ }
39
+ throw options.strict ? new CliError(`Port ${first} is already in use. Stop whatever is holding it, or pass a different --port.`) : new CliError(`No free port between ${first} and ${first + limit - 1}. Pass --port <n> to choose one explicitly.`);
40
+ }
41
+ function bind(server, port) {
42
+ return new Promise((resolvePort, reject) => {
43
+ const onError = (err) => {
44
+ server.removeListener("listening", onListening);
45
+ if (err.code === "EADDRINUSE") {
46
+ resolvePort(null);
47
+ return;
48
+ }
49
+ reject(err);
50
+ };
51
+ const onListening = () => {
52
+ server.removeListener("error", onError);
53
+ const address = server.address();
54
+ resolvePort(typeof address === "object" && address !== null ? address.port : port);
55
+ };
56
+ server.once("error", onError);
57
+ server.once("listening", onListening);
58
+ server.listen(port);
59
+ });
60
+ }
61
+ async function findFreePort(base, limit = DEFAULT_LIMIT) {
62
+ for (let port = base; port < base + limit; port += 1) {
63
+ if (await isFree(port)) {
64
+ return port;
65
+ }
66
+ }
67
+ throw new CliError(`No free port between ${base} and ${base + limit - 1} for the preview UI.`);
68
+ }
69
+ function isFree(port) {
70
+ return new Promise((resolveFree) => {
71
+ const probe = createServer();
72
+ probe.once("error", () => resolveFree(false));
73
+ probe.once("listening", () => probe.close(() => resolveFree(true)));
74
+ probe.listen(port);
75
+ });
76
+ }
77
+ function parsePort(value, flag) {
78
+ if (value === void 0 || value.startsWith("-")) {
79
+ throw new CliError(`${flag} needs a port number, e.g. \`${flag} 4000\`.`);
80
+ }
81
+ const port = Number(value);
82
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
83
+ throw new CliError(`${flag} expects an integer between 1 and 65535, got \`${value}\`.`);
84
+ }
85
+ return port;
86
+ }
87
+
88
+ // src/cli-args.ts
89
+ var DEFAULT_PORT = 3555;
90
+ function parseArgs(argv, env = process.env) {
91
+ const cwd = process.cwd();
92
+ const opts = {
93
+ entry: "",
94
+ seedDir: resolve(cwd, "dev/seeds"),
95
+ stateFile: resolve(cwd, ".revenexx-dev/state.json"),
96
+ persist: true,
97
+ port: env.PORT === void 0 ? DEFAULT_PORT : parsePort(env.PORT, "$PORT"),
98
+ portExplicit: env.PORT !== void 0,
99
+ uiDir: null,
100
+ serveUi: true,
101
+ open: false,
102
+ previewDir: null,
103
+ force: false,
104
+ parallel: false
105
+ };
106
+ let command = null;
107
+ for (let i = 0; i < argv.length; i++) {
108
+ const arg = argv[i];
109
+ switch (arg) {
110
+ case "reset":
111
+ command = "reset";
112
+ break;
113
+ case "init-preview":
114
+ command = "init-preview";
115
+ break;
116
+ case "preview":
117
+ command = "preview";
118
+ break;
119
+ case "--dir":
120
+ opts.previewDir = resolve(cwd, argv[++i] ?? "");
121
+ break;
122
+ case "--force":
123
+ opts.force = true;
124
+ break;
125
+ case "--parallel":
126
+ opts.parallel = true;
127
+ break;
128
+ case "--entry":
129
+ opts.entry = resolve(cwd, argv[++i] ?? "");
130
+ break;
131
+ case "--seed":
132
+ opts.seedDir = resolve(cwd, argv[++i] ?? "");
133
+ break;
134
+ case "--state":
135
+ opts.stateFile = resolve(cwd, argv[++i] ?? "");
136
+ break;
137
+ case "--no-persist":
138
+ opts.persist = false;
139
+ break;
140
+ case "--port":
141
+ opts.port = parsePort(argv[++i], "--port");
142
+ opts.portExplicit = true;
143
+ break;
144
+ case "--ui":
145
+ opts.uiDir = resolve(cwd, argv[++i] ?? "");
146
+ break;
147
+ case "--no-ui":
148
+ opts.serveUi = false;
149
+ break;
150
+ case "--open":
151
+ opts.open = true;
152
+ break;
153
+ // Both are consumed by loadEnvFile() before parsing; listed here so they
154
+ // do not fall through to the unknown-option branch. A repeated `--env`
155
+ // resolves to the last one, so each occurrence skips its own value.
156
+ case "--env":
157
+ i++;
158
+ break;
159
+ case "--no-env":
160
+ break;
161
+ case "--version":
162
+ case "-v":
163
+ command = "version";
164
+ break;
165
+ default:
166
+ if (arg?.startsWith("--env-file")) {
167
+ if (!arg.includes("=")) {
168
+ i++;
169
+ }
170
+ break;
171
+ }
172
+ if (arg?.startsWith("-")) {
173
+ throw new CliError(`Unknown option: ${arg}`);
174
+ }
175
+ }
176
+ }
177
+ if (!opts.entry) {
178
+ const src = resolve(cwd, "src/index.ts");
179
+ opts.entry = existsSync(src) ? src : resolve(cwd, "dist/index.js");
180
+ }
181
+ return { command, options: opts };
182
+ }
183
+
184
+ // src/preview/child-env.ts
185
+ function previewChildEnv(options) {
186
+ const env = { ...options.base };
187
+ delete env.PORT;
188
+ return {
189
+ ...env,
190
+ NUXT_PUBLIC_INTEGRATIONS_API: options.apiUrl,
191
+ NUXT_PUBLIC_DEV_TOKEN: options.base.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
192
+ NUXT_PUBLIC_DEV_TENANT: options.base.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
193
+ NUXT_PORT: String(options.uiPort),
194
+ DEVKIT_NUXT_BUILD_DIR: options.buildDir,
195
+ DEVKIT_VITE_CACHE_DIR: options.viteCacheDir
196
+ };
197
+ }
198
+
22
199
  // src/preview/host.ts
23
200
  import { createHash } from "crypto";
24
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
201
+ import { cpSync, existsSync as existsSync2, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "fs";
25
202
  import { homedir } from "os";
26
- import { dirname, join, relative, resolve, sep } from "path";
203
+ import { dirname, join, relative, resolve as resolve2, sep } from "path";
27
204
  import { fileURLToPath } from "url";
205
+
206
+ // src/preview/pid.ts
207
+ function pidIsAlive(pid) {
208
+ if (!Number.isInteger(pid) || pid <= 0) {
209
+ return false;
210
+ }
211
+ try {
212
+ process.kill(pid, 0);
213
+ return true;
214
+ } catch (err) {
215
+ return err.code === "EPERM";
216
+ }
217
+ }
218
+
219
+ // src/preview/host.ts
28
220
  var INSTALL_MARKER = ".devkit-install-complete";
29
221
  var COPY_MARKER = ".devkit-copy-complete";
222
+ var INSTALL_LOCK = ".devkit-install.lock";
30
223
  var HOST_GITIGNORE = `node_modules/
31
224
  .nuxt/
32
225
  .nuxt-*/
226
+ .vite-*/
33
227
  .output/
34
228
  .data/
35
- .env
229
+ .env*
230
+ previews/
36
231
  ${COPY_MARKER}
37
232
  ${INSTALL_MARKER}
233
+ ${INSTALL_LOCK}
38
234
  `;
39
235
  function resolveHostDir(options) {
40
236
  const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache");
@@ -44,7 +240,7 @@ function shippedHostDir() {
44
240
  let dir = dirname(fileURLToPath(import.meta.url));
45
241
  for (let up = 0; up < 5; up += 1) {
46
242
  const candidate = join(dir, "preview-host");
47
- if (existsSync(join(candidate, "nuxt.config.ts"))) {
243
+ if (existsSync2(join(candidate, "nuxt.config.ts"))) {
48
244
  return candidate;
49
245
  }
50
246
  const parent = dirname(dir);
@@ -57,21 +253,22 @@ function materializeHost(options) {
57
253
  const log = options.log ?? (() => {
58
254
  });
59
255
  const source = options.sourceDir ?? shippedHostDir();
60
- const dir = resolve(options.targetDir);
256
+ const dir = resolve2(options.targetDir);
61
257
  const managed = options.managed ?? false;
62
- const intact = managed ? hostIsComplete(dir) : hostExists(dir);
258
+ const intact = managed ? hostIsComplete(dir) && copyIsCurrent(dir, source) : hostExists(dir);
63
259
  const alreadyIntact = intact && !options.force;
64
260
  if (!alreadyIntact) {
65
261
  mkdirSync(dir, { recursive: true });
66
262
  rmSync(join(dir, COPY_MARKER), { force: true });
67
263
  cpSync(source, dir, { recursive: true, filter: (src) => !isInsideNodeModules(source, src) });
68
- writeFileSync(join(dir, COPY_MARKER), `${(/* @__PURE__ */ new Date()).toISOString()}
264
+ writeFileSync(join(dir, COPY_MARKER), `${sourceFingerprint(source)}
265
+ ${(/* @__PURE__ */ new Date()).toISOString()}
69
266
  `, "utf-8");
70
267
  writeFileSync(join(dir, ".gitignore"), HOST_GITIGNORE, "utf-8");
71
268
  log(`Preview host ready in ${dir}`);
72
269
  }
73
- const envPath = join(dir, ".env");
74
- if (managed || !existsSync(envPath)) {
270
+ const envPath = join(dir, options.dotenvName ?? ".env");
271
+ if (managed || !existsSync2(envPath)) {
75
272
  writeFileSync(envPath, envFile(options), "utf-8");
76
273
  }
77
274
  return { dir, copied: !alreadyIntact };
@@ -80,28 +277,69 @@ function isInsideNodeModules(source, src) {
80
277
  const rel = relative(source, src);
81
278
  return rel !== "" && rel.split(sep).includes("node_modules");
82
279
  }
280
+ function sourceFingerprint(source) {
281
+ const hash = createHash("sha256");
282
+ for (const file of listFiles(source, source).sort()) {
283
+ hash.update(file);
284
+ hash.update(readFileSync(join(source, file)));
285
+ }
286
+ return hash.digest("hex").slice(0, 16);
287
+ }
288
+ function listFiles(root, dir) {
289
+ const files = [];
290
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
291
+ if (entry.name === "node_modules") {
292
+ continue;
293
+ }
294
+ const full = join(dir, entry.name);
295
+ if (entry.isDirectory()) {
296
+ files.push(...listFiles(root, full));
297
+ } else if (entry.isFile()) {
298
+ files.push(relative(root, full));
299
+ }
300
+ }
301
+ return files;
302
+ }
303
+ function copyIsCurrent(dir, source) {
304
+ try {
305
+ const recorded = readFileSync(join(dir, COPY_MARKER), "utf-8").split("\n")[0]?.trim();
306
+ return recorded === sourceFingerprint(source);
307
+ } catch {
308
+ return false;
309
+ }
310
+ }
83
311
  function envFile(options) {
312
+ const name = options.dotenvName ?? ".env";
313
+ const manual = name === ".env" ? "npm run dev" : `npm run dev -- --dotenv ${name}`;
84
314
  return `# Generated by integrations-devkit \u2014 overrides the Nuxt runtimeConfig.public.* values.
85
315
  # The \`preview\` command also passes these to the Nuxt child process; this file is
86
- # what makes a manual \`npm run dev\` in this directory work.
316
+ # what makes a manual \`${manual}\` in this directory work.
87
317
  NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
88
318
  NUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? "dev"}
89
319
  NUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? "dev-tenant"}
90
320
  `;
91
321
  }
322
+ function consumerKey(consumerDir) {
323
+ return createHash("sha256").update(consumerDir).digest("hex").slice(0, 12);
324
+ }
92
325
  function hostBuildDir(hostDir, consumerDir) {
93
- const key = createHash("sha256").update(consumerDir).digest("hex").slice(0, 12);
94
- return join(hostDir, `.nuxt-${key}`);
326
+ return join(hostDir, `.nuxt-${consumerKey(consumerDir)}`);
327
+ }
328
+ function hostViteCacheDir(hostDir, consumerDir) {
329
+ return join(hostDir, `.vite-${consumerKey(consumerDir)}`);
330
+ }
331
+ function hostDotenvName(consumerDir) {
332
+ return `.env.${consumerKey(consumerDir)}`;
95
333
  }
96
334
  function hostExists(dir) {
97
- return existsSync(join(dir, "package.json")) && existsSync(join(dir, "nuxt.config.ts"));
335
+ return existsSync2(join(dir, "package.json")) && existsSync2(join(dir, "nuxt.config.ts"));
98
336
  }
99
337
  function hostIsComplete(dir) {
100
- return hostExists(dir) && existsSync(join(dir, COPY_MARKER));
338
+ return hostExists(dir) && existsSync2(join(dir, COPY_MARKER));
101
339
  }
102
340
  function hostNeedsInstall(dir) {
103
341
  const marker = join(dir, INSTALL_MARKER);
104
- if (!existsSync(join(dir, "node_modules")) || !existsSync(marker)) {
342
+ if (!existsSync2(join(dir, "node_modules")) || !existsSync2(marker)) {
105
343
  return true;
106
344
  }
107
345
  try {
@@ -117,112 +355,144 @@ function markHostInstalled(dir) {
117
355
  function clearHostInstallMarker(dir) {
118
356
  rmSync(join(dir, INSTALL_MARKER), { force: true });
119
357
  }
358
+ async function withInstallLock(dir, install, options = {}) {
359
+ const isAlive = options.isAlive ?? pidIsAlive;
360
+ const log = options.log ?? (() => {
361
+ });
362
+ const timeoutMs = options.timeoutMs ?? 20 * 6e4;
363
+ const pollMs = options.pollMs ?? 500;
364
+ const lockPath = join(dir, INSTALL_LOCK);
365
+ const deadline = Date.now() + timeoutMs;
366
+ let waitingFor = null;
367
+ while (!acquire(lockPath)) {
368
+ const holder = lockHolder(lockPath);
369
+ if (holder === null || !isAlive(holder)) {
370
+ rmSync(lockPath, { force: true });
371
+ continue;
372
+ }
373
+ if (holder !== waitingFor) {
374
+ waitingFor = holder;
375
+ log(`Another devkit (PID ${holder}) is installing the preview host's dependencies \u2014 waiting for it to finish\u2026`);
376
+ }
377
+ if (Date.now() > deadline) {
378
+ throw new CliError(`Timed out after ${Math.round(timeoutMs / 6e4)} min waiting for PID ${holder} to finish installing in ${dir}. If that process is gone, delete ${lockPath}.`);
379
+ }
380
+ await new Promise((done) => setTimeout(done, pollMs));
381
+ }
382
+ try {
383
+ if (options.needsInstall && !options.needsInstall()) {
384
+ return null;
385
+ }
386
+ return await install();
387
+ } finally {
388
+ rmSync(lockPath, { force: true });
389
+ }
390
+ }
391
+ function acquire(lockPath) {
392
+ try {
393
+ mkdirSync(dirname(lockPath), { recursive: true });
394
+ writeFileSync(lockPath, `${process.pid}
395
+ ${(/* @__PURE__ */ new Date()).toISOString()}
396
+ `, { encoding: "utf-8", flag: "wx" });
397
+ return true;
398
+ } catch {
399
+ return false;
400
+ }
401
+ }
402
+ function lockHolder(lockPath) {
403
+ try {
404
+ const pid = Number.parseInt(readFileSync(lockPath, "utf-8").split("\n")[0] ?? "", 10);
405
+ return Number.isInteger(pid) ? pid : null;
406
+ } catch {
407
+ return null;
408
+ }
409
+ }
120
410
  function manifestFingerprint(dir) {
121
411
  const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf-8"));
122
412
  return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });
123
413
  }
124
414
 
125
- // src/cli.ts
126
- function parseArgs(argv) {
127
- const cwd = process.cwd();
128
- const opts = {
129
- entry: "",
130
- seedDir: resolve2(cwd, "dev/seeds"),
131
- stateFile: resolve2(cwd, ".revenexx-dev/state.json"),
132
- persist: true,
133
- port: Number.parseInt(process.env.PORT ?? "3555", 10),
134
- uiDir: null,
135
- serveUi: true,
136
- open: false,
137
- previewDir: null,
138
- force: false
139
- };
140
- let command = null;
141
- for (let i = 0; i < argv.length; i++) {
142
- const arg = argv[i];
143
- switch (arg) {
144
- case "reset":
145
- command = "reset";
146
- break;
147
- case "init-preview":
148
- command = "init-preview";
149
- break;
150
- case "preview":
151
- command = "preview";
152
- break;
153
- case "--dir":
154
- opts.previewDir = resolve2(cwd, argv[++i] ?? "");
155
- break;
156
- case "--force":
157
- opts.force = true;
158
- break;
159
- case "--entry":
160
- opts.entry = resolve2(cwd, argv[++i] ?? "");
161
- break;
162
- case "--seed":
163
- opts.seedDir = resolve2(cwd, argv[++i] ?? "");
164
- break;
165
- case "--state":
166
- opts.stateFile = resolve2(cwd, argv[++i] ?? "");
167
- break;
168
- case "--no-persist":
169
- opts.persist = false;
170
- break;
171
- case "--port":
172
- opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
173
- break;
174
- case "--ui":
175
- opts.uiDir = resolve2(cwd, argv[++i] ?? "");
176
- break;
177
- case "--no-ui":
178
- opts.serveUi = false;
179
- break;
180
- case "--open":
181
- opts.open = true;
182
- break;
183
- // Both are consumed by loadEnvFile() before parsing; listed here so they
184
- // do not fall through to the unknown-option branch. A repeated `--env`
185
- // resolves to the last one, so each occurrence skips its own value.
186
- case "--env":
187
- i++;
188
- break;
189
- case "--no-env":
190
- break;
191
- case "--version":
192
- case "-v":
193
- command = "version";
194
- break;
195
- default:
196
- if (arg?.startsWith("--env-file")) {
197
- if (!arg.includes("=")) {
198
- i++;
199
- }
200
- break;
201
- }
202
- if (arg?.startsWith("-")) {
203
- console.error(`Unknown option: ${arg}`);
204
- process.exit(1);
205
- }
415
+ // src/preview/registry.ts
416
+ import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync as readdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
417
+ import { basename, join as join2 } from "path";
418
+ var REGISTRY_DIR = "previews";
419
+ function readLivePreviews(hostDir, isAlive = pidIsAlive) {
420
+ const dir = join2(hostDir, REGISTRY_DIR);
421
+ if (!existsSync3(dir)) {
422
+ return [];
423
+ }
424
+ const live = [];
425
+ for (const file of readdirSync2(dir)) {
426
+ if (!file.endsWith(".json")) {
427
+ continue;
428
+ }
429
+ const path = join2(dir, file);
430
+ const entry = readEntry(path);
431
+ if (entry && isAlive(entry.pid)) {
432
+ live.push(entry);
433
+ } else {
434
+ rmSync2(path, { force: true });
206
435
  }
207
436
  }
208
- if (!opts.entry) {
209
- const src = resolve2(cwd, "src/index.ts");
210
- opts.entry = existsSync2(src) ? src : resolve2(cwd, "dist/index.js");
437
+ return live.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
438
+ }
439
+ function readEntry(path) {
440
+ try {
441
+ const parsed = JSON.parse(readFileSync2(path, "utf-8"));
442
+ return Number.isInteger(parsed?.pid) ? parsed : null;
443
+ } catch {
444
+ return null;
211
445
  }
212
- return { command, options: opts };
213
446
  }
447
+ function registerPreview(hostDir, entry) {
448
+ const dir = join2(hostDir, REGISTRY_DIR);
449
+ mkdirSync2(dir, { recursive: true });
450
+ writeFileSync2(join2(dir, `${entry.pid}.json`), `${JSON.stringify(entry, null, 2)}
451
+ `, "utf-8");
452
+ }
453
+ function unregisterPreview(hostDir, pid = process.pid) {
454
+ rmSync2(join2(hostDir, REGISTRY_DIR, `${pid}.json`), { force: true });
455
+ }
456
+ function describePreview(entry) {
457
+ return `${basename(entry.cwd)} (PID ${entry.pid}, mock :${entry.mockPort}, UI :${entry.uiPort}) \u2014 ${entry.cwd}`;
458
+ }
459
+ function previewConflict(running, options) {
460
+ const sameRepo = running.find((entry) => entry.cwd === options.cwd);
461
+ if (sameRepo) {
462
+ return [
463
+ `A preview of this very package is already running: ${describePreview(sameRepo)}`,
464
+ "",
465
+ "Two previews of one package share a build directory and would serve each other's",
466
+ "output, so this is refused even with --parallel. Stop that one first."
467
+ ].join("\n");
468
+ }
469
+ if (options.force && running.length > 0) {
470
+ return `--force reinstalls the host's dependencies, which would pull node_modules out from under the preview still running in ${running[0]?.cwd}. Stop it first.`;
471
+ }
472
+ if (running.length > 0 && !options.parallel) {
473
+ return [
474
+ `A preview is already running out of ${options.hostDir}:`,
475
+ ...running.map((entry) => ` ${describePreview(entry)}`),
476
+ "",
477
+ "Stop it (Ctrl-C in its terminal), or run this one alongside it with --parallel."
478
+ ].join("\n");
479
+ }
480
+ return null;
481
+ }
482
+
483
+ // src/cli.ts
214
484
  function loadSchemas() {
215
485
  const here = fileURLToPath2(new URL(".", import.meta.url));
216
- const schemasDir = resolve2(here, "..", "assets", "schemas");
486
+ const schemasDir = resolve3(here, "..", "assets", "schemas");
217
487
  const schemas = {};
218
- if (!existsSync2(schemasDir)) {
488
+ if (!existsSync4(schemasDir)) {
219
489
  return schemas;
220
490
  }
221
- for (const file of readdirSync(schemasDir)) {
491
+ for (const file of readdirSync3(schemasDir)) {
222
492
  if (extname(file) !== ".json") {
223
493
  continue;
224
494
  }
225
- const parsed = JSON.parse(readFileSync2(join2(schemasDir, file), "utf-8"));
495
+ const parsed = JSON.parse(readFileSync3(join3(schemasDir, file), "utf-8"));
226
496
  const base = file.replace(/\.json$/, "");
227
497
  const dash = base.indexOf("-");
228
498
  if (dash > 0) {
@@ -238,15 +508,15 @@ function loadSchemas() {
238
508
  }
239
509
  function resolveUiDir(explicit) {
240
510
  if (explicit) {
241
- return existsSync2(explicit) ? explicit : null;
511
+ return existsSync4(explicit) ? explicit : null;
242
512
  }
243
513
  const candidates = ["@revenexx/studio-integrations"];
244
514
  const req = createRequire(import.meta.url);
245
515
  for (const pkg of candidates) {
246
516
  try {
247
517
  const entry = req.resolve(`${pkg}/package.json`);
248
- const dist = resolve2(entry, "..", "dist");
249
- if (existsSync2(join2(dist, "index.html"))) {
518
+ const dist = resolve3(entry, "..", "dist");
519
+ if (existsSync4(join3(dist, "index.html"))) {
250
520
  return dist;
251
521
  }
252
522
  } catch {
@@ -268,16 +538,16 @@ var MIME = {
268
538
  function serveStatic(uiDir, req, res) {
269
539
  const url = new URL(req.url ?? "/", "http://localhost");
270
540
  const relative2 = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
271
- let filePath = resolve2(uiDir, relative2);
272
- if (!filePath.startsWith(uiDir) || !existsSync2(filePath)) {
273
- filePath = join2(uiDir, "index.html");
541
+ let filePath = resolve3(uiDir, relative2);
542
+ if (!filePath.startsWith(uiDir) || !existsSync4(filePath)) {
543
+ filePath = join3(uiDir, "index.html");
274
544
  }
275
- if (!existsSync2(filePath)) {
545
+ if (!existsSync4(filePath)) {
276
546
  res.writeHead(404).end("UI build not found");
277
547
  return;
278
548
  }
279
549
  res.writeHead(200, { "Content-Type": MIME[extname(filePath)] ?? "application/octet-stream" });
280
- res.end(readFileSync2(filePath));
550
+ res.end(readFileSync3(filePath));
281
551
  }
282
552
  async function startMock(options) {
283
553
  let loaded = await loadPackageFromEntry(options.entry);
@@ -299,7 +569,7 @@ async function startMock(options) {
299
569
  const schemas = loadSchemas();
300
570
  const apiListener = createRequestListener({ getPackage: () => loaded, store, schemas });
301
571
  const uiDir = options.serveUi ? resolveUiDir(options.uiDir) : null;
302
- const server = createServer((req, res) => {
572
+ const server = createServer2((req, res) => {
303
573
  const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
304
574
  if (pathname.startsWith("/api/") || pathname === "/health") {
305
575
  apiListener(req, res);
@@ -313,7 +583,10 @@ async function startMock(options) {
313
583
  );
314
584
  }
315
585
  });
316
- await new Promise((r) => server.listen(options.port, r));
586
+ const port = await listenWithFallback(server, { port: options.port, strict: options.portExplicit });
587
+ if (port !== options.port) {
588
+ console.log(`Port ${options.port} was taken \u2014 the mock is on ${port} instead.`);
589
+ }
317
590
  const stopWatch = watchAndReload(options.entry, async () => {
318
591
  try {
319
592
  loaded = await loadPackageFromEntry(options.entry);
@@ -324,6 +597,7 @@ async function startMock(options) {
324
597
  });
325
598
  return {
326
599
  uiDir,
600
+ port,
327
601
  dispose() {
328
602
  if (options.persist) {
329
603
  saveState(options.stateFile, store.toSnapshot());
@@ -335,7 +609,7 @@ async function startMock(options) {
335
609
  }
336
610
  async function run(options) {
337
611
  const mock = await startMock(options);
338
- const urlBase = `http://localhost:${options.port}`;
612
+ const urlBase = `http://localhost:${mock.port}`;
339
613
  console.log(`
340
614
  Mock Integrations API ${urlBase}/api/v1`);
341
615
  console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only \u2014 set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);
@@ -351,7 +625,7 @@ async function run(options) {
351
625
  process.on("SIGTERM", shutdown);
352
626
  }
353
627
  function watchAndReload(entry, onChange) {
354
- const dir = resolve2(entry, "..");
628
+ const dir = resolve3(entry, "..");
355
629
  let timer;
356
630
  try {
357
631
  const watcher = watch(dir, { recursive: true }, (_event, file) => {
@@ -375,63 +649,92 @@ async function runNpmInstall(dir) {
375
649
  });
376
650
  }
377
651
  function noteLegacyPreviewDir() {
378
- const legacy = resolve2(process.cwd(), ".revenexx-dev/preview");
379
- if (existsSync2(legacy)) {
652
+ const legacy = resolve3(process.cwd(), ".revenexx-dev/preview");
653
+ if (existsSync4(legacy)) {
380
654
  console.log(`Note: ${legacy} is no longer used \u2014 the preview host now lives in a shared cache. You can delete it to reclaim the space.`);
381
655
  }
382
656
  }
657
+ var UI_PORT = 3e3;
383
658
  async function preview(options) {
384
- const apiUrl = `http://localhost:${options.port}/api/v1`;
659
+ const cwd = process.cwd();
385
660
  const managed = options.previewDir === null;
386
- const targetDir = options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION });
387
- noteLegacyPreviewDir();
388
- const { dir } = materializeHost({
389
- targetDir,
390
- integrationsApiUrl: apiUrl,
391
- force: options.force,
392
- managed,
393
- log: (msg) => console.log(msg)
394
- });
395
- if (managed) {
396
- console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
397
- }
398
- if (options.force) {
399
- clearHostInstallMarker(dir);
400
- }
401
- if (hostNeedsInstall(dir)) {
402
- console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
403
- await runNpmInstall(dir);
404
- markHostInstalled(dir);
661
+ const hostDir = resolve3(options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION }));
662
+ const running = readLivePreviews(hostDir);
663
+ const conflict = previewConflict(running, { cwd, hostDir, parallel: options.parallel, force: options.force });
664
+ if (conflict) {
665
+ throw new CliError(conflict);
405
666
  }
667
+ noteLegacyPreviewDir();
406
668
  const mock = await startMock({ ...options, serveUi: false });
407
- console.log(`
408
- Mock Integrations API ${apiUrl}`);
409
- console.log(" Preview UI http://localhost:3000/integrations (Nuxt starting\u2026)\n");
410
- const { spawn } = await import("child_process");
411
- const child = spawn("npm", ["run", "dev"], {
412
- cwd: dir,
413
- stdio: "inherit",
414
- env: {
415
- ...process.env,
416
- NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
417
- NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
418
- NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
419
- // Keep the shared host's dependency install shared but its BUILD per repo,
420
- // so two node packages previewing at once do not compile over each other.
421
- DEVKIT_NUXT_BUILD_DIR: hostBuildDir(dir, process.cwd())
669
+ const apiUrl = `http://localhost:${mock.port}/api/v1`;
670
+ try {
671
+ const { dir } = materializeHost({
672
+ targetDir: hostDir,
673
+ integrationsApiUrl: apiUrl,
674
+ dotenvName: managed ? hostDotenvName(cwd) : void 0,
675
+ force: options.force,
676
+ managed,
677
+ log: (msg) => console.log(msg)
678
+ });
679
+ if (options.force) {
680
+ clearHostInstallMarker(dir);
422
681
  }
423
- });
424
- const shutdown = () => {
425
- child.kill("SIGTERM");
426
- mock.dispose();
427
- process.exit(0);
428
- };
429
- process.on("SIGINT", shutdown);
430
- process.on("SIGTERM", shutdown);
431
- child.on("exit", (code) => {
682
+ if (hostNeedsInstall(dir)) {
683
+ await withInstallLock(
684
+ dir,
685
+ async () => {
686
+ console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
687
+ await runNpmInstall(dir);
688
+ markHostInstalled(dir);
689
+ },
690
+ { needsInstall: () => hostNeedsInstall(dir), log: (msg) => console.log(msg) }
691
+ );
692
+ }
693
+ const uiPort = process.env.NUXT_PORT ? Number(process.env.NUXT_PORT) : await findFreePort(UI_PORT);
694
+ console.log(`
695
+ Previewing ${basename2(cwd)} (${cwd})`);
696
+ console.log(` Mock Integrations API ${apiUrl}`);
697
+ if (managed) {
698
+ console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
699
+ }
700
+ console.log(` Preview UI starting on port ${uiPort} \u2014 Nuxt prints the URL it got, below.`);
701
+ for (const entry of running) {
702
+ console.log(` Also running ${describePreview(entry)}`);
703
+ }
704
+ console.log("");
705
+ const { spawn } = await import("child_process");
706
+ const args = managed ? ["run", "dev", "--", "--dotenv", hostDotenvName(cwd)] : ["run", "dev"];
707
+ const child = spawn("npm", args, {
708
+ cwd: dir,
709
+ stdio: "inherit",
710
+ env: previewChildEnv({
711
+ base: process.env,
712
+ apiUrl,
713
+ uiPort,
714
+ buildDir: hostBuildDir(dir, cwd),
715
+ viteCacheDir: hostViteCacheDir(dir, cwd)
716
+ })
717
+ });
718
+ registerPreview(dir, { pid: process.pid, cwd, mockPort: mock.port, uiPort, startedAt: (/* @__PURE__ */ new Date()).toISOString() });
719
+ const cleanUp = () => {
720
+ unregisterPreview(dir);
721
+ mock.dispose();
722
+ };
723
+ const shutdown = () => {
724
+ child.kill("SIGTERM");
725
+ cleanUp();
726
+ process.exit(0);
727
+ };
728
+ process.on("SIGINT", shutdown);
729
+ process.on("SIGTERM", shutdown);
730
+ child.on("exit", (code) => {
731
+ cleanUp();
732
+ process.exit(code ?? 0);
733
+ });
734
+ } catch (err) {
432
735
  mock.dispose();
433
- process.exit(code ?? 0);
434
- });
736
+ throw err;
737
+ }
435
738
  }
436
739
  async function openBrowser(url) {
437
740
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
@@ -450,8 +753,8 @@ async function main() {
450
753
  console.log(`Loaded env from ${envFile2}`);
451
754
  }
452
755
  if (command === "reset") {
453
- const { rmSync: rmSync2 } = await import("fs");
454
- rmSync2(options.stateFile, { force: true });
756
+ const { rmSync: rmSync3 } = await import("fs");
757
+ rmSync3(options.stateFile, { force: true });
455
758
  console.log(`Removed ${options.stateFile}`);
456
759
  return;
457
760
  }
@@ -480,7 +783,7 @@ async function main() {
480
783
  await run(options);
481
784
  }
482
785
  main().catch((err) => {
483
- console.error(err);
786
+ console.error(err instanceof CliError ? err.message : err);
484
787
  process.exit(1);
485
788
  });
486
789
  //# sourceMappingURL=cli.js.map