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