@leadconnector/vite-tanstack-config 0.2.0-beta.0 → 0.3.0-beta.1

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/index.cjs CHANGED
@@ -34,12 +34,529 @@ __export(src_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(src_exports);
36
36
  var import_vibe_tagger = require("@leadconnector/vibe-tagger");
37
+ var import_node_path = require("path");
38
+ var import_vite2 = require("vite");
39
+
40
+ // src/bundledDev.ts
41
+ var import_node_module = require("module");
42
+ var BUNDLED_DEV_ENV_VAR = "VIBE_FEATURE_BUNDLED_DEV";
43
+ function bundledDevRequested() {
44
+ return process.env[BUNDLED_DEV_ENV_VAR] === "true";
45
+ }
46
+ function viteVersionSupportsBundledDev(version) {
47
+ if (!version || version.includes("-"))
48
+ return false;
49
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
50
+ if (!match)
51
+ return false;
52
+ const major = Number(match[1]);
53
+ const minor = Number(match[2]);
54
+ return major > 8 || major === 8 && minor >= 1;
55
+ }
56
+ function resolveInstalledViteVersion(cwd = process.cwd()) {
57
+ try {
58
+ const manifest = (0, import_node_module.createRequire)(`${cwd}/package.json`)(
59
+ "vite/package.json"
60
+ );
61
+ return typeof manifest.version === "string" ? manifest.version : void 0;
62
+ } catch {
63
+ return void 0;
64
+ }
65
+ }
66
+
67
+ // src/diagnostics.ts
68
+ var SSR_CAPTURE_KEY = "__VIBE_TANSTACK_CAPTURE_SSR_ERROR__";
69
+ var HANDLER_RAN_KEY = "__VIBE_TANSTACK_HANDLER_RAN__";
70
+ var SERVER_FN_SEND_KEY = "__VIBE_TANSTACK_SERVER_FN_HMR_SEND__";
71
+ var MAX_JSON_LENGTH = 6e3;
72
+ var MAX_STRING_LENGTH = 2e3;
73
+ var MAX_ITEMS = 20;
74
+ var MAX_DEPTH = 4;
75
+ var ERROR_FIELDS = [
76
+ "name",
77
+ "message",
78
+ "plugin",
79
+ "pluginCode",
80
+ "id",
81
+ "moduleId",
82
+ "hook",
83
+ "code",
84
+ "loc",
85
+ "frame",
86
+ "stack",
87
+ "cause"
88
+ ];
89
+ function truncate(value, max = MAX_STRING_LENGTH) {
90
+ return value.length > max ? `${value.slice(0, max)}...[truncated]` : value;
91
+ }
92
+ function readProperty(value, key) {
93
+ try {
94
+ return value[key];
95
+ } catch (error) {
96
+ return `[unreadable: ${error instanceof Error ? error.message : String(error)}]`;
97
+ }
98
+ }
99
+ function describePrimitive(value) {
100
+ if (typeof value === "symbol") {
101
+ return value.description ? `Symbol(${value.description})` : "Symbol()";
102
+ }
103
+ if (typeof value === "function") {
104
+ return `[function ${value.name || "anonymous"}]`;
105
+ }
106
+ return String(value);
107
+ }
108
+ function serializeDiagnosticValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
109
+ if (value == null)
110
+ return value;
111
+ if (typeof value === "string")
112
+ return truncate(value);
113
+ if (typeof value === "number" || typeof value === "boolean")
114
+ return value;
115
+ if (typeof value !== "object")
116
+ return describePrimitive(value);
117
+ if (seen.has(value))
118
+ return "[circular]";
119
+ if (depth >= MAX_DEPTH)
120
+ return "[max depth]";
121
+ seen.add(value);
122
+ try {
123
+ if (Array.isArray(value)) {
124
+ const entries = value.slice(0, MAX_ITEMS).map((entry) => serializeDiagnosticValue(entry, depth + 1, seen));
125
+ if (value.length > MAX_ITEMS) {
126
+ entries.push(`[${value.length - MAX_ITEMS} items truncated]`);
127
+ }
128
+ return entries;
129
+ }
130
+ const output = {};
131
+ for (const field of ERROR_FIELDS) {
132
+ if (!(field in value))
133
+ continue;
134
+ const nested = readProperty(value, field);
135
+ if (nested == null || nested === "")
136
+ continue;
137
+ output[field] = serializeDiagnosticValue(nested, depth + 1, seen);
138
+ }
139
+ const nestedErrors = readProperty(value, "errors");
140
+ if (nestedErrors != null && nestedErrors !== "") {
141
+ output.errors = serializeDiagnosticValue(
142
+ Array.isArray(nestedErrors) ? nestedErrors.slice(0, MAX_ITEMS) : nestedErrors,
143
+ depth + 1,
144
+ seen
145
+ );
146
+ }
147
+ if (Object.keys(output).length > 0)
148
+ return output;
149
+ const keys = Object.keys(value);
150
+ for (const key of keys.slice(0, MAX_ITEMS)) {
151
+ const nested = readProperty(value, key);
152
+ if (nested == null || nested === "")
153
+ continue;
154
+ output[truncate(key, 200)] = serializeDiagnosticValue(
155
+ nested,
156
+ depth + 1,
157
+ seen
158
+ );
159
+ }
160
+ if (keys.length > MAX_ITEMS) {
161
+ output.properties_truncated = keys.length - MAX_ITEMS;
162
+ }
163
+ return Object.keys(output).length > 0 ? output : Object.prototype.toString.call(value);
164
+ } catch (error) {
165
+ return `[unreadable object: ${error instanceof Error ? error.message : String(error)}]`;
166
+ } finally {
167
+ seen.delete(value);
168
+ }
169
+ }
170
+ function stringifyDiagnosticPayload(value) {
171
+ const serialized = serializeDiagnosticValue(value);
172
+ const full = JSON.stringify(serialized);
173
+ if (full.length <= MAX_JSON_LENGTH)
174
+ return full;
175
+ const compact = serializeDiagnosticValue(value, 2);
176
+ const compactPayload = compact && typeof compact === "object" && !Array.isArray(compact) ? { ...compact, diagnostics_truncated: true } : { diagnostics_truncated: true, value: compact };
177
+ const compactJson = JSON.stringify(compactPayload);
178
+ if (compactJson.length <= MAX_JSON_LENGTH)
179
+ return compactJson;
180
+ return JSON.stringify({
181
+ diagnostics_truncated: true,
182
+ message: "Diagnostic payload exceeded output budget."
183
+ });
184
+ }
185
+ function boundedData(value) {
186
+ try {
187
+ const parsed = JSON.parse(stringifyDiagnosticPayload(value));
188
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : { value: parsed };
189
+ } catch {
190
+ return { message: "Diagnostic payload could not be serialized." };
191
+ }
192
+ }
193
+ function createBuildErrorDiagnostics() {
194
+ let emitted = false;
195
+ const emit = (error) => {
196
+ if (!error || emitted)
197
+ return;
198
+ emitted = true;
199
+ try {
200
+ process.stderr.write(
201
+ `
202
+ [vibe-build-error-diagnostics]
203
+ ${stringifyDiagnosticPayload(
204
+ error
205
+ )}
206
+ [/vibe-build-error-diagnostics]
207
+ `
208
+ );
209
+ } catch {
210
+ }
211
+ };
212
+ return {
213
+ name: "vibe-build-error-diagnostics",
214
+ apply: "build",
215
+ buildEnd: emit,
216
+ renderError: emit
217
+ };
218
+ }
219
+ function isBuildError(error) {
220
+ const messagePattern = /transform failed with \d+ error|failed to parse source/i;
221
+ if (typeof error === "string")
222
+ return messagePattern.test(error);
223
+ if (!error || typeof error !== "object")
224
+ return false;
225
+ const record = error;
226
+ if (typeof record.plugin === "string" && (record.plugin.startsWith("vite:") || record.plugin.startsWith("esbuild:"))) {
227
+ return true;
228
+ }
229
+ if (record.frame != null && record.loc != null)
230
+ return true;
231
+ return typeof record.message === "string" && messagePattern.test(record.message);
232
+ }
233
+ function isRequestResponseModule(id) {
234
+ const normalized = id.replaceAll("\\", "/").split("?")[0];
235
+ return normalized.includes(
236
+ "/@tanstack/start-server-core/src/request-response.ts"
237
+ ) || normalized.includes(
238
+ "/@tanstack/start-server-core/dist/esm/request-response.js"
239
+ );
240
+ }
241
+ function isServerFunctionsHandlerModule(id) {
242
+ const normalized = id.replaceAll("\\", "/").split("?")[0];
243
+ return normalized.includes(
244
+ "/@tanstack/start-server-core/src/server-functions-handler.ts"
245
+ ) || normalized.includes(
246
+ "/@tanstack/start-server-core/dist/esm/server-functions-handler.js"
247
+ );
248
+ }
249
+ var runtimeGlobal = globalThis;
250
+ var ssrGlobalRegistrations = [];
251
+ var serverFnGlobalRegistrations = [];
252
+ var originalSsrCapture;
253
+ var originalSsrMark;
254
+ var originalServerFnSend;
255
+ function snapshotGlobal(key) {
256
+ return {
257
+ existed: Object.prototype.hasOwnProperty.call(runtimeGlobal, key),
258
+ value: runtimeGlobal[key]
259
+ };
260
+ }
261
+ function restoreGlobal(key, snapshot) {
262
+ if (snapshot.existed)
263
+ runtimeGlobal[key] = snapshot.value;
264
+ else
265
+ delete runtimeGlobal[key];
266
+ }
267
+ function registerSsrGlobals(registration) {
268
+ if (ssrGlobalRegistrations.length === 0) {
269
+ originalSsrCapture = snapshotGlobal(SSR_CAPTURE_KEY);
270
+ originalSsrMark = snapshotGlobal(HANDLER_RAN_KEY);
271
+ }
272
+ ssrGlobalRegistrations.push(registration);
273
+ runtimeGlobal[SSR_CAPTURE_KEY] = registration.capture;
274
+ runtimeGlobal[HANDLER_RAN_KEY] = registration.mark;
275
+ }
276
+ function unregisterSsrGlobals(registration) {
277
+ const index = ssrGlobalRegistrations.indexOf(registration);
278
+ if (index === -1)
279
+ return;
280
+ ssrGlobalRegistrations.splice(index, 1);
281
+ const active = ssrGlobalRegistrations.at(-1);
282
+ if (active) {
283
+ runtimeGlobal[SSR_CAPTURE_KEY] = active.capture;
284
+ runtimeGlobal[HANDLER_RAN_KEY] = active.mark;
285
+ return;
286
+ }
287
+ restoreGlobal(SSR_CAPTURE_KEY, originalSsrCapture);
288
+ restoreGlobal(HANDLER_RAN_KEY, originalSsrMark);
289
+ originalSsrCapture = void 0;
290
+ originalSsrMark = void 0;
291
+ }
292
+ function registerServerFnGlobal(registration) {
293
+ if (serverFnGlobalRegistrations.length === 0) {
294
+ originalServerFnSend = snapshotGlobal(SERVER_FN_SEND_KEY);
295
+ }
296
+ serverFnGlobalRegistrations.push(registration);
297
+ runtimeGlobal[SERVER_FN_SEND_KEY] = registration.dispatch;
298
+ }
299
+ function unregisterServerFnGlobal(registration) {
300
+ const index = serverFnGlobalRegistrations.indexOf(registration);
301
+ if (index === -1)
302
+ return;
303
+ serverFnGlobalRegistrations.splice(index, 1);
304
+ const active = serverFnGlobalRegistrations.at(-1);
305
+ if (active) {
306
+ runtimeGlobal[SERVER_FN_SEND_KEY] = active.dispatch;
307
+ return;
308
+ }
309
+ restoreGlobal(SERVER_FN_SEND_KEY, originalServerFnSend);
310
+ originalServerFnSend = void 0;
311
+ }
312
+ function createSsrErrorLogger() {
313
+ const handlerRan = Symbol("vibeHandlerRan");
314
+ const capturedError = Symbol("vibeCapturedSsrError");
315
+ const generations = [];
316
+ let globalsInstalled = false;
317
+ const responseFromEvent = (event) => {
318
+ const response = event?.node?.res;
319
+ return response && typeof response === "object" ? response : void 0;
320
+ };
321
+ const capture = (error, event) => {
322
+ const response = responseFromEvent(event);
323
+ if (!response)
324
+ return;
325
+ response[handlerRan] = true;
326
+ response[capturedError] = error;
327
+ };
328
+ const consumeCapture = (response) => {
329
+ const error = response[capturedError];
330
+ delete response[capturedError];
331
+ return error;
332
+ };
333
+ const markHandlerRan = (event) => {
334
+ const response = responseFromEvent(event);
335
+ if (response)
336
+ response[handlerRan] = true;
337
+ };
338
+ const registration = { capture, mark: markHandlerRan };
339
+ const installGlobals = () => {
340
+ if (globalsInstalled)
341
+ return;
342
+ registerSsrGlobals(registration);
343
+ globalsInstalled = true;
344
+ };
345
+ const restoreGlobals = () => {
346
+ if (!globalsInstalled || generations.length > 0)
347
+ return;
348
+ globalsInstalled = false;
349
+ unregisterSsrGlobals(registration);
350
+ };
351
+ const retireOldestDetached = () => {
352
+ generations.find((generation) => !generation.httpServer)?.close();
353
+ };
354
+ return {
355
+ name: "vibe-ssr-error-logger",
356
+ apply: "serve",
357
+ configureServer(server) {
358
+ installGlobals();
359
+ const httpServer = server.httpServer;
360
+ let closed = false;
361
+ const generation = {};
362
+ const cleanup = () => {
363
+ if (closed)
364
+ return;
365
+ closed = true;
366
+ httpServer?.off("close", cleanup);
367
+ const index = generations.indexOf(generation);
368
+ if (index !== -1)
369
+ generations.splice(index, 1);
370
+ restoreGlobals();
371
+ };
372
+ generation.close = cleanup;
373
+ generation.httpServer = httpServer ?? void 0;
374
+ generations.push(generation);
375
+ httpServer?.once("close", cleanup);
376
+ server.middlewares.use((request, response, next) => {
377
+ let handled = false;
378
+ const handleErrorResponse = () => {
379
+ if (handled || response.statusCode < 500)
380
+ return;
381
+ handled = true;
382
+ const responseRecord = response;
383
+ const captured = consumeCapture(responseRecord);
384
+ const ranHandler = Boolean(responseRecord[handlerRan]);
385
+ const source = !ranHandler ? "vite" : isBuildError(captured) ? "build" : "app";
386
+ if (!response.headersSent) {
387
+ try {
388
+ response.setHeader("x-vibe-error-source", source);
389
+ } catch {
390
+ }
391
+ }
392
+ const where = [request.method, request.url].filter(Boolean).join(" ") || "the request";
393
+ const data = captured !== void 0 ? boundedData(captured) : {
394
+ message: ranHandler ? `The app returned ${response.statusCode} while handling ${where}, but no stack was captured.` : `The dev server returned ${response.statusCode} for ${where} before the app handler ran.`
395
+ };
396
+ try {
397
+ server.ws.send({
398
+ type: "custom",
399
+ event: "vibe:server-ssr-error",
400
+ data
401
+ });
402
+ } catch {
403
+ }
404
+ };
405
+ const writeHead = response.writeHead.bind(response);
406
+ response.writeHead = (...args) => {
407
+ if (typeof args[0] === "number")
408
+ response.statusCode = args[0];
409
+ handleErrorResponse();
410
+ return writeHead(...args);
411
+ };
412
+ const end = response.end.bind(response);
413
+ response.end = (...args) => {
414
+ handleErrorResponse();
415
+ return end(...args);
416
+ };
417
+ next();
418
+ });
419
+ },
420
+ transform(code, id) {
421
+ if (!isRequestResponseModule(id))
422
+ return null;
423
+ if (code.includes(SSR_CAPTURE_KEY))
424
+ return null;
425
+ const needle = "handler(request, requestOpts)";
426
+ if (!code.includes(needle)) {
427
+ throw new Error(
428
+ `[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core request-response transform: expected ${JSON.stringify(needle)} in ${id}.`
429
+ );
430
+ }
431
+ return code.replace(
432
+ needle,
433
+ `(() => {
434
+ const __vibeSsrEvent = typeof h3Event === "undefined" ? undefined : h3Event
435
+ globalThis.${HANDLER_RAN_KEY}?.(__vibeSsrEvent)
436
+ try {
437
+ return Promise.resolve(${needle}).catch((err) => {
438
+ globalThis.${SSR_CAPTURE_KEY}?.(err, __vibeSsrEvent)
439
+ throw err
440
+ })
441
+ } catch (err) {
442
+ globalThis.${SSR_CAPTURE_KEY}?.(err, __vibeSsrEvent)
443
+ throw err
444
+ }
445
+ })()`
446
+ );
447
+ },
448
+ closeWatcher() {
449
+ },
450
+ closeBundle() {
451
+ retireOldestDetached();
452
+ }
453
+ };
454
+ }
455
+ function createServerFnErrorLogger() {
456
+ const generations = [];
457
+ let globalInstalled = false;
458
+ const dispatch = (data) => {
459
+ generations.at(-1)?.send(data);
460
+ };
461
+ const registration = { dispatch };
462
+ const installGlobal = () => {
463
+ if (globalInstalled)
464
+ return;
465
+ registerServerFnGlobal(registration);
466
+ globalInstalled = true;
467
+ };
468
+ const restoreGlobal2 = () => {
469
+ if (!globalInstalled || generations.length > 0)
470
+ return;
471
+ globalInstalled = false;
472
+ unregisterServerFnGlobal(registration);
473
+ };
474
+ const retireOldestDetached = () => {
475
+ generations.find((generation) => !generation.httpServer)?.close();
476
+ };
477
+ return {
478
+ name: "vibe-server-fn-error-logger",
479
+ apply: "serve",
480
+ enforce: "pre",
481
+ configureServer(server) {
482
+ installGlobal();
483
+ const send = (data) => {
484
+ try {
485
+ server.ws.send({
486
+ type: "custom",
487
+ event: "vibe:server-fn-error",
488
+ data: boundedData(data)
489
+ });
490
+ } catch {
491
+ }
492
+ };
493
+ const httpServer = server.httpServer;
494
+ let closed = false;
495
+ const generation = {};
496
+ const cleanup = () => {
497
+ if (closed)
498
+ return;
499
+ closed = true;
500
+ httpServer?.off("close", cleanup);
501
+ const index = generations.indexOf(generation);
502
+ if (index !== -1)
503
+ generations.splice(index, 1);
504
+ restoreGlobal2();
505
+ };
506
+ generation.close = cleanup;
507
+ generation.httpServer = httpServer ?? void 0;
508
+ generation.send = send;
509
+ generations.push(generation);
510
+ httpServer?.once("close", cleanup);
511
+ },
512
+ transform(code, id) {
513
+ if (!isServerFunctionsHandlerModule(id))
514
+ return null;
515
+ if (code.includes(SERVER_FN_SEND_KEY))
516
+ return null;
517
+ const needle = "const unwrapped = res.result || res.error";
518
+ if (!code.includes(needle)) {
519
+ throw new Error(
520
+ `[@leadconnector/vite-tanstack-config] unsupported @tanstack/start-server-core server-functions-handler transform: expected ${JSON.stringify(needle)} in ${id}.`
521
+ );
522
+ }
523
+ return code.replace(
524
+ needle,
525
+ `${needle}
526
+
527
+ if (res?.error) {
528
+ const err = res.error
529
+ const clipVibeDiagnostic = (value, max = 2000) => {
530
+ let text
531
+ try { text = String(value ?? "") } catch { text = "[unreadable]" }
532
+ return text.length > max ? text.slice(0, max) + "...[truncated]" : text
533
+ }
534
+ globalThis.${SERVER_FN_SEND_KEY}?.({
535
+ source: "tanstack",
536
+ type: "vibe:server-fn-error",
537
+ method: clipVibeDiagnostic(request.method, 32),
538
+ url: clipVibeDiagnostic(request.url, 1000),
539
+ name: clipVibeDiagnostic(err?.name ?? "Error", 200),
540
+ message: clipVibeDiagnostic(err?.message ?? err),
541
+ stack: typeof err?.stack === "string" ? clipVibeDiagnostic(err.stack) : undefined,
542
+ })
543
+ }`
544
+ );
545
+ },
546
+ closeWatcher() {
547
+ },
548
+ closeBundle() {
549
+ retireOldestDetached();
550
+ }
551
+ };
552
+ }
37
553
 
38
554
  // src/env.ts
39
555
  var SANDBOX_ENV_VAR = "DEV_SERVER__PROJECT_PATH";
556
+ var VIBE_SANDBOX_ENV_VAR = "VIBE_SANDBOX";
40
557
  var LOVABLE_SANDBOX_ENV_VAR = "LOVABLE_SANDBOX";
41
558
  function isSandboxEnvironment() {
42
- return process.env[LOVABLE_SANDBOX_ENV_VAR] === "1" || !!process.env[SANDBOX_ENV_VAR];
559
+ return process.env[VIBE_SANDBOX_ENV_VAR] === "1" || process.env[LOVABLE_SANDBOX_ENV_VAR] === "1" || !!process.env[SANDBOX_ENV_VAR];
43
560
  }
44
561
 
45
562
  // src/nitro.ts
@@ -58,8 +575,27 @@ function buildNitroOptions(nitroOpt, isSandbox) {
58
575
  }
59
576
  return opts;
60
577
  }
578
+ async function loadNitroPlugin(importer, requiredReason) {
579
+ let nitroModule;
580
+ try {
581
+ nitroModule = await importer();
582
+ } catch (error) {
583
+ throw new Error(
584
+ `[@leadconnector/vite-tanstack-config] ${requiredReason}, but the \`nitro\` package could not be loaded. Install \`nitro\` in devDependencies (peerDependency >=3.0.260603-beta). Original import error: ${error instanceof Error ? error.message : String(error)}`,
585
+ { cause: error }
586
+ );
587
+ }
588
+ const nitro = nitroModule.nitro;
589
+ if (typeof nitro !== "function") {
590
+ throw new Error(
591
+ `[@leadconnector/vite-tanstack-config] could not resolve the Nitro plugin (expected a named \`nitro\` export from \`nitro/vite\`). Installed exports: ${Object.keys(nitroModule).join(", ") || "(none)"}.`
592
+ );
593
+ }
594
+ return nitro;
595
+ }
61
596
 
62
597
  // src/server.ts
598
+ var import_vite = require("vite");
63
599
  var TOOL_MANAGED_WATCH_IGNORES = [
64
600
  "**/.workspace/**",
65
601
  "**/.agents/**",
@@ -67,21 +603,252 @@ var TOOL_MANAGED_WATCH_IGNORES = [
67
603
  "**/.lovable/**",
68
604
  "**/.tanstack/tmp/**"
69
605
  ];
70
- function serverConfig(isSandbox) {
71
- if (isSandbox) {
72
- return { host: "::", port: 8080, strictPort: true, watch: { ignored: TOOL_MANAGED_WATCH_IGNORES } };
606
+ var MAX_WARNING_ITEMS = 8;
607
+ var MAX_WARNING_LENGTH = 800;
608
+ function logWarning(message) {
609
+ const bounded = message.length > MAX_WARNING_LENGTH ? `${message.slice(0, MAX_WARNING_LENGTH)}...[truncated]` : message;
610
+ console.warn(`[@leadconnector/vite-tanstack-config] ${bounded}`);
611
+ }
612
+ function boundedList(values) {
613
+ const shown = values.slice(0, MAX_WARNING_ITEMS);
614
+ const omitted = values.length - shown.length;
615
+ return `${shown.join(", ")}${omitted > 0 ? ` (+${omitted} more)` : ""}`;
616
+ }
617
+ function normalizeIgnored(value) {
618
+ if (typeof value === "string" || typeof value === "function" || value instanceof RegExp) {
619
+ return [value];
620
+ }
621
+ if (!Array.isArray(value))
622
+ return [];
623
+ return value.filter(
624
+ (entry) => typeof entry === "string" || typeof entry === "function" || entry instanceof RegExp
625
+ );
626
+ }
627
+ function previewAllowedHosts() {
628
+ const hosts = /* @__PURE__ */ new Set([".modal.host"]);
629
+ const addHost = (value) => {
630
+ const trimmed = value.trim();
631
+ if (!trimmed)
632
+ return;
633
+ try {
634
+ const parsed = new URL(
635
+ trimmed.includes("://") ? trimmed : `https://${trimmed}`
636
+ );
637
+ if (!["http:", "https:"].includes(parsed.protocol))
638
+ throw new Error();
639
+ if (parsed.username || parsed.password)
640
+ throw new Error();
641
+ const hostname = parsed.hostname.toLowerCase();
642
+ const hostnameBody = hostname.startsWith(".") ? hostname.slice(1) : hostname;
643
+ const validHostname = hostnameBody === "localhost" || /^\[[0-9a-f:]+\]$/i.test(hostnameBody) || hostnameBody.split(".").every(
644
+ (label) => label.length > 0 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label)
645
+ );
646
+ if (!validHostname || hostname === "*")
647
+ throw new Error();
648
+ hosts.add(hostname);
649
+ } catch {
650
+ logWarning(`Ignoring invalid preview host ${JSON.stringify(trimmed)}.`);
651
+ }
652
+ };
653
+ if (process.env.VIBE_PREVIEW_HOST)
654
+ addHost(process.env.VIBE_PREVIEW_HOST);
655
+ for (const host of (process.env.VIBE_PREVIEW_HOSTS ?? "").split(",")) {
656
+ addHost(host);
657
+ }
658
+ return [...hosts];
659
+ }
660
+ function warnAndStripUnsupportedServerFields(config) {
661
+ const server = config.server;
662
+ if (!server)
663
+ return config;
664
+ if (server.headers) {
665
+ logWarning(
666
+ `Sandbox mode removed unsupported server.headers: ${boundedList(
667
+ Object.keys(server.headers)
668
+ )}.`
669
+ );
670
+ }
671
+ if (server.cors !== void 0) {
672
+ logWarning("Sandbox mode removed unsupported custom server.cors.");
673
+ }
674
+ if (server.proxy) {
675
+ logWarning(
676
+ `Sandbox mode removed unsupported server.proxy routes: ${boundedList(
677
+ Object.keys(server.proxy)
678
+ )}.`
679
+ );
73
680
  }
74
- return { host: "::", port: 8080 };
681
+ if (server.headers === void 0 && server.cors === void 0 && server.proxy === void 0) {
682
+ return config;
683
+ }
684
+ const {
685
+ headers: _headers,
686
+ cors: _cors,
687
+ proxy: _proxy,
688
+ ...supportedServer
689
+ } = server;
690
+ return { ...config, server: supportedServer };
691
+ }
692
+ function applyNonSandboxWatchDefaults(config) {
693
+ if (config.server?.watch === null)
694
+ return config;
695
+ return (0, import_vite.mergeConfig)({
696
+ server: {
697
+ watch: {
698
+ awaitWriteFinish: {
699
+ stabilityThreshold: 1e3,
700
+ pollInterval: 100
701
+ }
702
+ }
703
+ }
704
+ }, config);
705
+ }
706
+ function applySandboxServerInvariants(config) {
707
+ const userWatch = config.server?.watch ?? {};
708
+ const ignored = [
709
+ ...normalizeIgnored(userWatch.ignored),
710
+ ...TOOL_MANAGED_WATCH_IGNORES
711
+ ];
712
+ const dedupedIgnored = [...new Set(ignored)];
713
+ const allowedHosts = previewAllowedHosts();
714
+ const userHmr = config.server?.hmr;
715
+ const sandboxHmr = userHmr === false ? false : {
716
+ ...typeof userHmr === "object" ? userHmr : {},
717
+ overlay: false
718
+ };
719
+ const merged = (0, import_vite.mergeConfig)(config, {
720
+ server: {
721
+ host: "::",
722
+ port: 8080,
723
+ strictPort: true,
724
+ allowedHosts,
725
+ watch: { ...userWatch, ignored: dedupedIgnored },
726
+ hmr: sandboxHmr
727
+ }
728
+ });
729
+ const mergedServer = merged.server ?? {};
730
+ const invariantConfig = {
731
+ ...merged,
732
+ server: {
733
+ ...mergedServer,
734
+ host: "::",
735
+ port: 8080,
736
+ strictPort: true,
737
+ allowedHosts,
738
+ watch: {
739
+ ...mergedServer.watch,
740
+ ignored: dedupedIgnored
741
+ },
742
+ hmr: sandboxHmr
743
+ }
744
+ };
745
+ return warnAndStripUnsupportedServerFields(invariantConfig);
75
746
  }
76
747
 
77
748
  // src/index.ts
78
- function defineConfig(options = {}) {
79
- return async ({ command, mode }) => {
749
+ var OPTION_KEYS = /* @__PURE__ */ new Set([
750
+ "vite",
751
+ "nitro",
752
+ "tanstackStart",
753
+ "react",
754
+ "envDefine",
755
+ "hmrGate",
756
+ "devServerBridge",
757
+ "ssrErrorLogger",
758
+ "serverFnErrorLogger"
759
+ ]);
760
+ var DEFAULT_IMPORT_PROTECTION = {
761
+ behavior: "error",
762
+ client: {
763
+ files: ["**/server/**"],
764
+ specifiers: ["server-only"]
765
+ }
766
+ };
767
+ var DEFAULT_DEDUPE = [
768
+ "react",
769
+ "react-dom",
770
+ "react/jsx-runtime",
771
+ "react/jsx-dev-runtime",
772
+ "@tanstack/react-query",
773
+ "@tanstack/query-core"
774
+ ];
775
+ var DEFAULT_OPTIMIZE_DEPS = [
776
+ "react",
777
+ "react-dom",
778
+ "react-dom/client",
779
+ "react/jsx-runtime",
780
+ "react/jsx-dev-runtime"
781
+ ];
782
+ function logWarning2(message) {
783
+ console.warn(`[@leadconnector/vite-tanstack-config] ${message}`);
784
+ }
785
+ function isPromiseLike(value) {
786
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
787
+ }
788
+ function isExplicitOptions(value) {
789
+ return Object.keys(value).some((key) => OPTION_KEYS.has(key));
790
+ }
791
+ async function normalizeOptions(input, env) {
792
+ if (typeof input === "function") {
793
+ return { vite: await Promise.resolve(input(env)) };
794
+ }
795
+ if (isPromiseLike(input))
796
+ return { vite: await input };
797
+ const object = input && typeof input === "object" ? input : {};
798
+ return isExplicitOptions(object) ? object : { vite: object };
799
+ }
800
+ function pluginEnabled(option, isSandbox) {
801
+ return isSandbox ? option !== false : option === true || !!option;
802
+ }
803
+ function pluginOptions(option) {
804
+ return option && typeof option === "object" ? option : {};
805
+ }
806
+ function withUserAliasPrecedence(config, userConfig) {
807
+ const userAlias = userConfig.resolve?.alias;
808
+ if (!userAlias)
809
+ return config;
810
+ if (Array.isArray(userAlias)) {
811
+ const userAtAliases = userAlias.filter((entry) => entry.find === "@");
812
+ if (userAtAliases.length === 0)
813
+ return config;
814
+ const merged = Array.isArray(config.resolve?.alias) ? config.resolve.alias : Object.entries(config.resolve?.alias ?? {}).map(
815
+ ([find, replacement]) => ({ find, replacement })
816
+ );
817
+ return {
818
+ ...config,
819
+ resolve: {
820
+ ...config.resolve,
821
+ alias: [
822
+ ...userAtAliases,
823
+ ...merged.filter((entry) => entry.find !== "@")
824
+ ]
825
+ }
826
+ };
827
+ }
828
+ const userAliasRecord = userAlias;
829
+ if (!Object.prototype.hasOwnProperty.call(userAliasRecord, "@"))
830
+ return config;
831
+ const mergedAlias = Array.isArray(config.resolve?.alias) ? config.resolve.alias.filter((entry) => entry.find !== "@") : config.resolve?.alias;
832
+ return {
833
+ ...config,
834
+ resolve: {
835
+ ...config.resolve,
836
+ alias: Array.isArray(mergedAlias) ? [
837
+ { find: "@", replacement: userAliasRecord["@"] },
838
+ ...mergedAlias
839
+ ] : { ...mergedAlias, "@": userAliasRecord["@"] }
840
+ }
841
+ };
842
+ }
843
+ function defineConfig(configOrOptions = {}) {
844
+ return async (env) => {
845
+ const { command, mode } = env;
80
846
  const isSandbox = isSandboxEnvironment();
81
- const plugins = [];
847
+ const options = await normalizeOptions(configOrOptions, env);
848
+ const internalPlugins = [];
82
849
  if (mode === "development") {
83
850
  const { devtools } = await import("@tanstack/devtools-vite");
84
- plugins.push(
851
+ internalPlugins.push(
85
852
  devtools({
86
853
  logging: false,
87
854
  eventBusConfig: { enabled: false },
@@ -93,35 +860,110 @@ function defineConfig(options = {}) {
93
860
  );
94
861
  }
95
862
  if (command === "serve" && mode === "development") {
96
- plugins.push(
863
+ internalPlugins.push(
97
864
  (0, import_vibe_tagger.componentTagger)({ jsxSource: true, sourceInjection: false, tailwindConfig: true })
98
865
  );
99
866
  }
100
867
  const tailwindcss = (await import("@tailwindcss/vite")).default;
101
868
  const tsConfigPaths = (await import("vite-tsconfig-paths")).default;
869
+ internalPlugins.push(tailwindcss());
870
+ internalPlugins.push(tsConfigPaths({ projects: ["./tsconfig.json"] }));
871
+ if (options.serverFnErrorLogger !== false) {
872
+ internalPlugins.push(createServerFnErrorLogger());
873
+ }
874
+ if (options.ssrErrorLogger !== false) {
875
+ internalPlugins.push(createSsrErrorLogger());
876
+ }
877
+ if (command === "build" && isSandbox) {
878
+ internalPlugins.push(createBuildErrorDiagnostics());
879
+ }
102
880
  const { tanstackStart } = await import("@tanstack/react-start/plugin/vite");
103
- const viteReact = (await import("@vitejs/plugin-react")).default;
104
- plugins.push(tailwindcss());
105
- plugins.push(tsConfigPaths({ projects: ["./tsconfig.json"] }));
106
- plugins.push(tanstackStart(options.tanstackStart ?? {}));
881
+ const tanstackStartOptions = (0, import_vite2.mergeConfig)(
882
+ { importProtection: DEFAULT_IMPORT_PROTECTION },
883
+ options.tanstackStart ?? {}
884
+ );
885
+ internalPlugins.push(tanstackStart(tanstackStartOptions));
107
886
  if (shouldRunNitro(command, options.nitro, isSandbox)) {
108
- const nitroMod = await import("nitro/vite");
109
- const nitroFn = nitroMod.nitro ?? nitroMod.default;
110
- if (typeof nitroFn !== "function") {
111
- throw new Error(
112
- `[@leadconnector/vite-tanstack-config] could not resolve the \`nitro\` plugin function from \`nitro/vite\` (expected a named \`nitro\` export). Installed nitro exports: ${Object.keys(nitroMod).join(", ") || "(none)"}. Check the installed \`nitro\` version (peerDependency >=3.0.260603-beta).`
113
- );
887
+ const requiredReason = options.nitro === true || typeof options.nitro === "object" && options.nitro !== null ? "an explicit `nitro` option was set" : "running inside a Vibe sandbox";
888
+ const nitroFn = await loadNitroPlugin(
889
+ // nitro is an optional peer dependency, so keep the import dynamic.
890
+ // @ts-expect-error -- optional peer types are intentionally unavailable.
891
+ () => import("nitro/vite"),
892
+ requiredReason
893
+ );
894
+ internalPlugins.push(
895
+ nitroFn(buildNitroOptions(options.nitro, isSandbox))
896
+ );
897
+ }
898
+ const viteReact = (await import("@vitejs/plugin-react")).default;
899
+ internalPlugins.push(viteReact(options.react ?? {}));
900
+ if (command === "serve" && pluginEnabled(options.hmrGate, isSandbox)) {
901
+ const { hmrGatePlugin } = await import("@leadconnector/vite-plugin-hmr-gate");
902
+ internalPlugins.push(
903
+ hmrGatePlugin(pluginOptions(options.hmrGate))
904
+ );
905
+ }
906
+ if (command === "serve" && pluginEnabled(options.devServerBridge, isSandbox)) {
907
+ const { devServerBridgePlugin } = await import("@leadconnector/vite-plugin-dev-server-bridge");
908
+ internalPlugins.push(
909
+ devServerBridgePlugin(
910
+ pluginOptions(options.devServerBridge)
911
+ )
912
+ );
913
+ }
914
+ const userConfig = options.vite ?? {};
915
+ const projectRoot = (0, import_node_path.resolve)(process.cwd(), userConfig.root ?? ".");
916
+ const envDirectory = userConfig.envDir === false ? void 0 : (0, import_node_path.resolve)(projectRoot, userConfig.envDir ?? ".");
917
+ const envDefine = {};
918
+ if (options.envDefine !== false && envDirectory) {
919
+ const loadedEnv = (0, import_vite2.loadEnv)(mode, envDirectory, "VITE_");
920
+ for (const [key, value] of Object.entries(loadedEnv)) {
921
+ envDefine[`import.meta.env.${key}`] = JSON.stringify(value);
114
922
  }
115
- plugins.push(nitroFn(buildNitroOptions(options.nitro, isSandbox)));
116
923
  }
117
- plugins.push(viteReact(options.react ?? {}));
118
- const { plugins: extraPlugins, server: extraServer, ...restVite } = options.vite ?? {};
119
- return {
120
- plugins: [...plugins, ...options.plugins ?? [], ...extraPlugins ? Array.isArray(extraPlugins) ? extraPlugins : [extraPlugins] : []],
121
- server: { ...serverConfig(isSandbox), ...extraServer },
924
+ const isDevBuild = command === "build" && mode === "development";
925
+ const baseConfig = {
926
+ define: {
927
+ ...envDefine,
928
+ ...isDevBuild ? {
929
+ "process.env.NODE_ENV": JSON.stringify("development")
930
+ } : {}
931
+ },
932
+ ...isDevBuild ? {
933
+ environments: {
934
+ client: {
935
+ define: {
936
+ "process.env.NODE_ENV": JSON.stringify("development")
937
+ }
938
+ }
939
+ },
940
+ esbuild: { keepNames: true }
941
+ } : {},
122
942
  css: { transformer: "lightningcss" },
123
- ...restVite
943
+ resolve: {
944
+ alias: { "@": (0, import_node_path.resolve)(projectRoot, "src") },
945
+ dedupe: DEFAULT_DEDUPE
946
+ },
947
+ optimizeDeps: {
948
+ include: DEFAULT_OPTIMIZE_DEPS,
949
+ ignoreOutdatedRequests: true
950
+ },
951
+ plugins: [...internalPlugins, ...options.plugins ?? []],
952
+ server: { host: "::", port: 8080 }
124
953
  };
954
+ let config = (0, import_vite2.mergeConfig)(baseConfig, userConfig);
955
+ config = withUserAliasPrecedence(config, userConfig);
956
+ if (command === "serve" && isSandbox && bundledDevRequested()) {
957
+ const viteVersion = resolveInstalledViteVersion(projectRoot);
958
+ if (viteVersionSupportsBundledDev(viteVersion)) {
959
+ config = (0, import_vite2.mergeConfig)(config, { experimental: { bundledDev: true } });
960
+ } else {
961
+ logWarning2(
962
+ `Bundled dev requested (${BUNDLED_DEV_ENV_VAR}=true), but installed Vite ${viteVersion ?? "unresolved"} is missing, prerelease, or below 8.1. Starting classic dev.`
963
+ );
964
+ }
965
+ }
966
+ return isSandbox ? applySandboxServerInvariants(config) : applyNonSandboxWatchDefaults(config);
125
967
  };
126
968
  }
127
969
  // Annotate the CommonJS export names for ESM import in node: